lokesh341 commited on
Commit
d1aea20
Β·
verified Β·
1 Parent(s): 4afd51c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -113
app.py CHANGED
@@ -1,73 +1,28 @@
1
- import torch # <-- Import the torch module
2
- from simple_salesforce import Salesforce
3
  from flask import Flask, render_template, request, jsonify
4
  import json
5
- import time
 
6
  from gtts import gTTS
7
  from pydub import AudioSegment
8
  from pydub.silence import detect_nonsilent
9
- from transformers import pipeline
10
- from transformers import AutoConfig # Import AutoConfig for the config object
11
  from waitress import serve
 
 
 
12
 
13
- # Initialize Flask App
14
  app = Flask(__name__, template_folder="templates")
15
  app.secret_key = os.urandom(24)
16
 
17
- # Use whisper-small for faster processing and better speed
18
- device = "cuda" if torch.cuda.is_available() else "cpu"
19
-
20
- # Create config object to set timeout and other parameters
21
- config = AutoConfig.from_pretrained("openai/whisper-small")
22
- config.update({"timeout": 60}) # Set timeout to 60 seconds
23
-
24
- # Function to generate audio prompts
25
- def generate_audio_prompt(text, filename):
26
- try:
27
- tts = gTTS(text)
28
- tts.save(os.path.join("static", filename))
29
- except Exception as e:
30
- print(f"Error: {e}")
31
- time.sleep(5) # Wait before retrying
32
- generate_audio_prompt(text, filename)
33
-
34
- # Generate required voice prompts
35
- prompts = {
36
- "welcome": "Welcome to Biryani Hub.",
37
- "ask_name": "Tell me your name.",
38
- "ask_email": "Please provide your email address.",
39
- "thank_you": "Thank you for registration."
40
- }
41
-
42
- for key, text in prompts.items():
43
- generate_audio_prompt(text, f"{key}.mp3")
44
-
45
- # Function to convert audio to WAV format
46
- def convert_to_wav(input_path, output_path):
47
- try:
48
- audio = AudioSegment.from_file(input_path)
49
- audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
50
- audio.export(output_path, format="wav")
51
- except Exception as e:
52
- raise Exception(f"Audio conversion failed: {str(e)}")
53
-
54
- # Function to check if audio contains actual speech
55
- def is_silent_audio(audio_path):
56
- audio = AudioSegment.from_wav(audio_path)
57
- nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
58
- return len(nonsilent_parts) == 0
59
-
60
- # Salesforce connection details (hardcoded)
61
- username = '[email protected]'
62
- password = 'Sati@1020'
63
- security_token = 'sSSjyhInIsUohKpG8sHzty2q'
64
-
65
  try:
66
  print("Attempting to connect to Salesforce...")
67
- sf = Salesforce(username=username, password=password, security_token=security_token)
68
- print("Connected to Salesforce successfully!")
69
  except Exception as e:
70
- print(f"Failed to connect to Salesforce: {str(e)}")
71
 
72
  # βœ… HOME ROUTE (Loads `index.html`)
73
  @app.route("/", methods=["GET"])
@@ -79,10 +34,25 @@ def index():
79
  def dashboard():
80
  return render_template("dashboard.html")
81
 
82
- # βœ… MENU PAGE ROUTE
83
  @app.route("/menu_page", methods=["GET"])
84
  def menu_page():
85
- return render_template("menu_page.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  # βœ… LOGIN API
88
  @app.route('/login', methods=['POST'])
@@ -126,68 +96,42 @@ def submit():
126
  except Exception as e:
127
  return jsonify({'error': str(e)}), 500
128
 
129
- # βœ… TRANSCRIBE AUDIO API
130
- @app.route("/transcribe", methods=["POST"])
131
- def transcribe():
132
- if "audio" not in request.files:
133
- return jsonify({"error": "No audio file provided"}), 400
 
 
 
134
 
135
- audio_file = request.files["audio"]
136
- input_audio_path = os.path.join("static", "temp_input.wav")
137
- output_audio_path = os.path.join("static", "temp.wav")
138
- audio_file.save(input_audio_path)
139
 
 
140
  try:
141
- convert_to_wav(input_audio_path, output_audio_path)
142
- if is_silent_audio(output_audio_path):
143
- return jsonify({"error": "No speech detected. Please try again."}), 400
144
-
145
- asr_pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
146
- result = asr_pipeline(output_audio_path)
147
-
148
- transcribed_text = result["text"].strip().capitalize()
149
-
150
- parts = transcribed_text.split()
151
- name = parts[0] if len(parts) > 0 else "Unknown Name"
152
- email = parts[1] if '@' in parts[1] else "[email protected]"
153
- phone_number = parts[2] if len(parts) > 2 else "0000000000"
154
-
155
- confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
156
- generate_audio_prompt(confirmation, "confirmation.mp3")
157
-
158
- salesforce_response = sf.Customer_Login__c.create({
159
- 'Name': name,
160
- 'Email__c': email,
161
- 'Phone_Number__c': phone_number
162
  })
163
 
164
- return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
165
-
166
- except Exception as e:
167
- return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
168
-
169
- # βœ… MENU API
170
- @app.route("/menu", methods=["GET"])
171
- def get_menu():
172
- try:
173
- # Fetch menu items from Salesforce
174
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
175
- result = sf.query(query)
176
-
177
- menu_items = []
178
- for item in result["records"]:
179
- menu_items.append({
180
- "name": item["Name"],
181
- "price": item["Price__c"],
182
- "ingredients": item["Ingredients__c"],
183
- "category": item["Category__c"]
184
  })
185
 
186
- # Pass the menu items to the template
187
- return render_template("menu_page.html", menu=menu_items)
188
-
189
  except Exception as e:
190
- return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
191
 
192
  # βœ… START PRODUCTION SERVER
193
  if __name__ == "__main__":
 
1
+ import torch
 
2
  from flask import Flask, render_template, request, jsonify
3
  import json
4
+ import os
5
+ from transformers import pipeline
6
  from gtts import gTTS
7
  from pydub import AudioSegment
8
  from pydub.silence import detect_nonsilent
9
+ from transformers import AutoConfig
10
+ import time
11
  from waitress import serve
12
+ from simple_salesforce import Salesforce
13
+ import requests
14
+ import datetime
15
 
 
16
  app = Flask(__name__, template_folder="templates")
17
  app.secret_key = os.urandom(24)
18
 
19
+ # βœ… Salesforce Connection Setup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  try:
21
  print("Attempting to connect to Salesforce...")
22
+ sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
23
+ print("βœ… Connected to Salesforce successfully!")
24
  except Exception as e:
25
+ print(f"❌ Failed to connect to Salesforce: {str(e)}")
26
 
27
  # βœ… HOME ROUTE (Loads `index.html`)
28
  @app.route("/", methods=["GET"])
 
34
  def dashboard():
35
  return render_template("dashboard.html")
36
 
37
+ # βœ… MENU PAGE ROUTE (NEWLY ADDED)
38
  @app.route("/menu_page", methods=["GET"])
39
  def menu_page():
40
+ try:
41
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
42
+ result = sf.query(query)
43
+
44
+ menu_items = []
45
+ for item in result["records"]:
46
+ menu_items.append({
47
+ "name": item["Name"],
48
+ "price": item["Price__c"],
49
+ "ingredients": item["Ingredients__c"],
50
+ "category": item["Category__c"]
51
+ })
52
+
53
+ return render_template("menu_page.html", menu=menu_items)
54
+ except Exception as e:
55
+ return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
56
 
57
  # βœ… LOGIN API
58
  @app.route('/login', methods=['POST'])
 
96
  except Exception as e:
97
  return jsonify({'error': str(e)}), 500
98
 
99
+ # βœ… PLACE ORDER API (Sends order data to Salesforce)
100
+ @app.route("/place_order", methods=["POST"])
101
+ def place_order():
102
+ data = request.json
103
+ order_items = data.get('order_items') # List of items added to the cart
104
+ total_price = data.get('total_price') # Total price of the order
105
+ customer_name = data.get('customer_name') # Customer details
106
+ customer_email = data.get('customer_email')
107
 
108
+ if not order_items or not total_price or not customer_name or not customer_email:
109
+ return jsonify({'error': 'Missing required fields'}), 400
 
 
110
 
111
+ # Creating order record in Salesforce
112
  try:
113
+ # Create Order record
114
+ order = sf.Order.create({
115
+ 'Customer_Name__c': customer_name,
116
+ 'Customer_Email__c': customer_email,
117
+ 'Total_Price__c': total_price,
118
+ 'Order_Date__c': str(datetime.datetime.now()), # Date when the order was placed
119
+ 'Status__c': 'New'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  })
121
 
122
+ # Create Order Line Items (for each item in the order)
123
+ for item in order_items:
124
+ sf.Order_Line_Item__c.create({
125
+ 'Order__c': order['id'], # Linking to the order
126
+ 'Item_Name__c': item['name'],
127
+ 'Price__c': item['price'],
128
+ 'Quantity__c': item['quantity'],
129
+ 'Total_Price__c': item['price'] * item['quantity']
 
 
 
 
 
 
 
 
 
 
 
 
130
  })
131
 
132
+ return jsonify({'success': True, 'order_id': order['id']}), 200
 
 
133
  except Exception as e:
134
+ return jsonify({'error': f'Failed to create order in Salesforce: {str(e)}'}), 500
135
 
136
  # βœ… START PRODUCTION SERVER
137
  if __name__ == "__main__":