DSatishchandra commited on
Commit
e21d37e
·
verified ·
1 Parent(s): e99e79e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -81
app.py CHANGED
@@ -21,7 +21,33 @@ device = "cuda" if torch.cuda.is_available() else "cpu"
21
  config = AutoConfig.from_pretrained("openai/whisper-small")
22
  config.update({"timeout": 60}) # Set timeout to 60 seconds
23
 
24
- # Your function where you generate and save the audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def generate_audio_prompt(text, filename):
26
  try:
27
  tts = gTTS(text)
@@ -32,31 +58,7 @@ def generate_audio_prompt(text, filename):
32
  time.sleep(5) # Wait for 5 seconds before retrying
33
  generate_audio_prompt(text, filename)
34
 
35
- # Generate required voice prompts
36
- prompts = {
37
- "welcome": "Welcome to Biryani Hub.",
38
- "ask_name": "Tell me your name.",
39
- "ask_email": "Please provide your email address.",
40
- "thank_you": "Thank you for registration."
41
- }
42
-
43
- for key, text in prompts.items():
44
- generate_audio_prompt(text, f"{key}.mp3")
45
-
46
- # Symbol mapping for proper recognition
47
- SYMBOL_MAPPING = {
48
- "at the rate": "@",
49
- "at": "@",
50
- "dot": ".",
51
- "underscore": "_",
52
- "hash": "#",
53
- "plus": "+",
54
- "dash": "-",
55
- "comma": ",",
56
- "space": " "
57
- }
58
-
59
- # Function to convert audio to WAV format
60
  def convert_to_wav(input_path, output_path):
61
  try:
62
  audio = AudioSegment.from_file(input_path)
@@ -66,45 +68,25 @@ def convert_to_wav(input_path, output_path):
66
  print(f"Error: {str(e)}")
67
  raise Exception(f"Audio conversion failed: {str(e)}")
68
 
69
- # Function to check if audio contains actual speech
70
  def is_silent_audio(audio_path):
71
  audio = AudioSegment.from_wav(audio_path)
72
  nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
73
  print(f"Detected nonsilent parts: {nonsilent_parts}")
74
  return len(nonsilent_parts) == 0 # If no speech detected
75
 
76
- # Salesforce connection details
77
- try:
78
- print("Attempting to connect to Salesforce...")
79
- sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
80
- print("Connected to Salesforce successfully!")
81
- print("User Info:", sf.UserInfo) # Log the user info to verify the connection
82
- except Exception as e:
83
- print(f"Failed to connect to Salesforce: {str(e)}")
84
-
85
- # Function to fetch menu items from Salesforce
86
- def get_menu_items():
87
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
88
- result = sf.query(query)
89
- return result['records']
90
-
91
- # Define the route for the index page
92
  @app.route("/")
93
  def index():
94
  return render_template("index.html")
95
 
96
- @app.route("/dashboard", methods=["GET"])
97
  def dashboard():
98
- # You can pass user-specific data to this page if needed
99
  return render_template("dashboard.html") # Render the dashboard template
100
 
101
- # Function to create Salesforce record
102
- # API endpoint to receive data from voice bot
103
  @app.route('/login', methods=['POST'])
104
  def login():
105
  # Get data from voice bot (name, email, phone number)
106
  data = request.json # Assuming voice bot sends JSON data
107
-
108
  name = data.get('name')
109
  email = data.get('email')
110
  phone_number = data.get('phone_number')
@@ -112,9 +94,8 @@ def login():
112
  if not name or not email or not phone_number:
113
  return jsonify({'error': 'Missing required fields'}), 400
114
 
115
- # Create a record in Salesforce
116
  try:
117
- customer_login = create_salesforce_record(sf, name, email, phone_number)
118
  return redirect("/menu") # Redirect to the menu page after successful login
119
  except Exception as e:
120
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
@@ -146,53 +127,30 @@ def submit():
146
  return jsonify({'error': str(e)}), 500
147
 
148
 
149
- # Route for the menu page
150
  @app.route("/menu", methods=["GET"])
151
  def menu_page():
152
- menu_items = get_menu_items() # Fetch menu items from Salesforce
153
- menu_data = []
154
- for item in menu_items:
155
- menu_data.append({
156
- "name": item['Name'],
157
- "price": item['Price__c'],
158
- "ingredients": item['Ingredients__c'],
159
- "category": item['Category__c'],
160
- })
161
-
162
- # Render the menu page template and pass the menu data to it
163
  return render_template("menu_page.html", menu_items=menu_data)
164
 
165
- # Route for handling order (you'll save the order to Salesforce here)
166
  @app.route("/order", methods=["POST"])
167
  def place_order():
168
- # Getting the item name from the POST request (you can customize this to get more data)
169
  item_name = request.json.get('item_name')
170
  quantity = request.json.get('quantity')
171
-
172
- # Logic to save the order details to Salesforce
173
- order_data = {
174
- "Item__c": item_name, # Assuming 'Item__c' is the field in your Order object
175
- "Quantity__c": quantity, # Assuming 'Quantity__c' is a field for the quantity
176
- # Add any other fields you need to capture, like customer, price, etc.
177
- }
178
-
179
- # Create the order record in Salesforce
180
  sf.Order__c.create(order_data)
181
-
182
- # Return a success response
183
  return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
184
 
185
- # Route to handle the cart (this can be expanded later)
186
  @app.route("/cart", methods=["GET"])
187
  def cart():
188
- # Logic to fetch cart items (this could be from a session or database)
189
  cart_items = [] # Placeholder for cart items
190
  return render_template("cart_page.html", cart_items=cart_items)
191
 
192
- # Route for the order summary page (this can be expanded later)
193
  @app.route("/order-summary", methods=["GET"])
194
  def order_summary():
195
- # Logic to fetch order summary (this could be from a session or database)
196
  order_details = [] # Placeholder for order details
197
  return render_template("order_summary.html", order_details=order_details)
198
 
@@ -246,7 +204,7 @@ def transcribe():
246
  confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
247
  generate_audio_prompt(confirmation, "confirmation.mp3")
248
 
249
- # Simulate confirmation via user action, in real case this should be handled via front-end
250
  user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
251
 
252
  if user_confirms:
@@ -261,7 +219,6 @@ def transcribe():
261
  print(f"Error creating record in Salesforce: {salesforce_response['error']}")
262
  return jsonify(salesforce_response), 500
263
 
264
- # If creation was successful, return the details
265
  return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
266
 
267
  except Exception as e:
 
21
  config = AutoConfig.from_pretrained("openai/whisper-small")
22
  config.update({"timeout": 60}) # Set timeout to 60 seconds
23
 
24
+ # Salesforce connection details
25
+ try:
26
+ print("Attempting to connect to Salesforce...")
27
+ sf = Salesforce(username='your_username', password='your_password', security_token='your_token')
28
+ print("Connected to Salesforce successfully!")
29
+ print("User Info:", sf.UserInfo) # Log the user info to verify the connection
30
+ except Exception as e:
31
+ print(f"Failed to connect to Salesforce: {str(e)}")
32
+
33
+ # Functions for Salesforce operations
34
+ def create_salesforce_record(sf, name, email, phone_number):
35
+ try:
36
+ customer_login = sf.Customer_Login__c.create({
37
+ 'Name': name,
38
+ 'Email__c': email,
39
+ 'Phone_Number__c': phone_number
40
+ })
41
+ return customer_login
42
+ except Exception as e:
43
+ raise Exception(f"Failed to create record: {str(e)}")
44
+
45
+ def get_menu_items(sf):
46
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
47
+ result = sf.query(query)
48
+ return result['records']
49
+
50
+ # Voice-related functions
51
  def generate_audio_prompt(text, filename):
52
  try:
53
  tts = gTTS(text)
 
58
  time.sleep(5) # Wait for 5 seconds before retrying
59
  generate_audio_prompt(text, filename)
60
 
61
+ # Utility functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def convert_to_wav(input_path, output_path):
63
  try:
64
  audio = AudioSegment.from_file(input_path)
 
68
  print(f"Error: {str(e)}")
69
  raise Exception(f"Audio conversion failed: {str(e)}")
70
 
 
71
  def is_silent_audio(audio_path):
72
  audio = AudioSegment.from_wav(audio_path)
73
  nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
74
  print(f"Detected nonsilent parts: {nonsilent_parts}")
75
  return len(nonsilent_parts) == 0 # If no speech detected
76
 
77
+ # Routes and Views
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  @app.route("/")
79
  def index():
80
  return render_template("index.html")
81
 
82
+ @app.route("/dashboard", methods=["GET"])
83
  def dashboard():
 
84
  return render_template("dashboard.html") # Render the dashboard template
85
 
 
 
86
  @app.route('/login', methods=['POST'])
87
  def login():
88
  # Get data from voice bot (name, email, phone number)
89
  data = request.json # Assuming voice bot sends JSON data
 
90
  name = data.get('name')
91
  email = data.get('email')
92
  phone_number = data.get('phone_number')
 
94
  if not name or not email or not phone_number:
95
  return jsonify({'error': 'Missing required fields'}), 400
96
 
 
97
  try:
98
+ customer_login = create_salesforce_record(sf, name, email, phone_number)
99
  return redirect("/menu") # Redirect to the menu page after successful login
100
  except Exception as e:
101
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
 
127
  return jsonify({'error': str(e)}), 500
128
 
129
 
 
130
  @app.route("/menu", methods=["GET"])
131
  def menu_page():
132
+ menu_items = get_menu_items(sf) # Fetch menu items from Salesforce
133
+ menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
 
 
 
 
 
 
 
 
 
134
  return render_template("menu_page.html", menu_items=menu_data)
135
 
136
+ # Route for handling order
137
  @app.route("/order", methods=["POST"])
138
  def place_order():
 
139
  item_name = request.json.get('item_name')
140
  quantity = request.json.get('quantity')
141
+ order_data = {"Item__c": item_name, "Quantity__c": quantity}
 
 
 
 
 
 
 
 
142
  sf.Order__c.create(order_data)
 
 
143
  return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
144
 
145
+ # Route to handle the cart
146
  @app.route("/cart", methods=["GET"])
147
  def cart():
 
148
  cart_items = [] # Placeholder for cart items
149
  return render_template("cart_page.html", cart_items=cart_items)
150
 
151
+ # Route for the order summary page
152
  @app.route("/order-summary", methods=["GET"])
153
  def order_summary():
 
154
  order_details = [] # Placeholder for order details
155
  return render_template("order_summary.html", order_details=order_details)
156
 
 
204
  confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
205
  generate_audio_prompt(confirmation, "confirmation.mp3")
206
 
207
+ # Simulate confirmation via user action
208
  user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
209
 
210
  if user_confirms:
 
219
  print(f"Error creating record in Salesforce: {salesforce_response['error']}")
220
  return jsonify(salesforce_response), 500
221
 
 
222
  return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
223
 
224
  except Exception as e: