dschandra commited on
Commit
fa7b884
·
verified ·
1 Parent(s): 893c04d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -51
app.py CHANGED
@@ -36,7 +36,6 @@ user_name = None # Will be set once the user provides their name
36
  def get_menu_items(category):
37
  category_filter = ''
38
 
39
- # Determine the category filter (Veg, Non-Veg, or All)
40
  if category == 'Veg':
41
  category_filter = 'Veg'
42
  elif category == 'Non-Veg':
@@ -44,33 +43,28 @@ def get_menu_items(category):
44
  elif category == 'All':
45
  category_filter = '' # No filter for 'All'
46
 
47
- # Query Salesforce based on the category filter
48
- if category_filter == '':
49
- query = "SELECT Id, Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c FROM Menu_Item__c"
50
- else:
51
- query = f"""
52
- SELECT Id, Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
53
- FROM Menu_Item__c
54
- WHERE Veg_NonVeg__c = '{category_filter}' OR Veg_NonVeg__c = 'both'
55
- """
56
-
57
- # Execute the query
58
  result = sf.query_all(query)
59
  return result['records']
60
 
61
- # Function to save cart and order details into Salesforce
62
  def save_order_to_salesforce(cart, user_email, total_amount):
63
- # Prepare the order object
64
  order_items = ", ".join([f"{item['Name']} x {item['Quantity']}" for item in cart])
65
  order = {
66
  'Customer_Email__c': user_email,
67
  'Order_Date_Time__c': datetime.now(),
68
  'Order_Items__c': order_items,
69
  'Total_Amount__c': total_amount,
70
- 'Status__c': 'Pending' # Assuming the status is 'Pending' initially
71
  }
72
 
73
- # Insert order record into Salesforce
74
  order_record = sf.Order__c.create(order)
75
  return order_record
76
 
@@ -122,7 +116,7 @@ html_code = """
122
  greetUser();
123
  }
124
  });
125
- // Greeting the user and asking for their name
126
  function greetUser() {
127
  const utterance = new SpeechSynthesisUtterance("Hi, welcome to Biryani Hub! Can I know your name so I can greet you personally?");
128
  speechSynthesis.speak(utterance);
@@ -131,7 +125,7 @@ html_code = """
131
  startListening();
132
  };
133
  }
134
- // Start listening for the user's response
135
  async function startListening() {
136
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
137
  const mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm;codecs=opus" });
@@ -151,7 +145,7 @@ html_code = """
151
  speechSynthesis.speak(utterance);
152
  utterance.onend = () => {
153
  if (!data.response.includes("Goodbye") && !data.response.includes("final order")) {
154
- startListening(); // Continue listening
155
  } else {
156
  status.textContent = "Conversation ended.";
157
  isListening = false;
@@ -196,11 +190,11 @@ def process_audio():
196
 
197
  recognizer = sr.Recognizer()
198
  with sr.AudioFile(converted_file.name) as source:
199
- recognizer.adjust_for_ambient_noise(source, duration=1) # Adjust for ambient noise
200
- audio_data = recognizer.record(source, duration=10) # Increase the duration
201
  try:
202
  command = recognizer.recognize_google(audio_data)
203
- logging.info(f"Recognized command: {command}") # Log the recognized command
204
  response = process_command(command)
205
  except sr.UnknownValueError:
206
  response = "Sorry, I couldn't understand your command. Could you please repeat?"
@@ -224,12 +218,10 @@ def process_command(command):
224
  logging.info(f"Processing command: {command}")
225
 
226
  try:
227
- # Step 1: Handle user name input (personalize the greeting)
228
  if user_name is None and "my name is" in command:
229
  user_name = command.replace("my name is", "").strip()
230
  return jsonify({"response": f"Hello {user_name}! Nice to meet you. Please choose your preference: Veg, Non-Veg, or All."})
231
 
232
- # Step 2: Handle preference (Veg/Non-Veg/All)
233
  if awaiting_preference:
234
  if "veg" in command:
235
  current_category = 'Veg'
@@ -241,12 +233,11 @@ def process_command(command):
241
  return jsonify({"response": "I didn't catch your preference. Please choose Veg, Non-Veg, or All."})
242
 
243
  awaiting_preference = False
244
- awaiting_item_selection = True # Now ready for item selection
245
  return jsonify({"response": f"Great! You've selected {current_category}. What would you like to order?"})
246
 
247
- # Step 3: Handle item selection
248
  if awaiting_item_selection:
249
- menu_items = get_menu_items(current_category) # Simulate fetching menu items
250
  selected_item = next((item for item in menu_items if item['Name'].lower() in command), None)
251
 
252
  if selected_item:
@@ -257,7 +248,6 @@ def process_command(command):
257
 
258
  return jsonify({"response": "I didn't catch that. Please say the name of the item you want to order."})
259
 
260
- # Step 4: Handle quantity selection
261
  if awaiting_quantity:
262
  try:
263
  quantity = int(command)
@@ -270,7 +260,6 @@ def process_command(command):
270
  except ValueError:
271
  return jsonify({"response": "Please provide a valid number for quantity."})
272
 
273
- # Step 5: Handle email input
274
  if "my email is" in command:
275
  email_part = command.replace("my email is", "").strip()
276
  email_command = email_part.replace(' at ', '@').replace(' dot ', '.').replace(' ', '')
@@ -285,7 +274,6 @@ def process_command(command):
285
  else:
286
  return jsonify({"response": "Sorry, that doesn't look like a valid email. Can you please provide it again?"})
287
 
288
- # Step 6: Handle order finalization commands
289
  if "final order" in command or "confirm my order" in command or "place the order" in command or "confirm order" in command:
290
  return place_order()
291
 
@@ -293,21 +281,16 @@ def process_command(command):
293
 
294
  except Exception as e:
295
  logging.error(f"An error occurred while processing the command: {str(e)}")
296
- logging.error(f"Stack Trace: {traceback.format_exc()}") # Log full error details
297
  return jsonify({"response": "Sorry, there was an error processing your request."}), 500
298
 
299
- # Function to place the order
300
  def place_order():
301
  global cart, user_email, user_name
302
 
303
  try:
304
- # Calculate the total amount for the order
305
  total_amount = sum([item['Price__c'] * item['Quantity'] for item in cart])
306
-
307
- # Step 1: Save the main order record to Salesforce
308
  order_record = save_order_to_salesforce(cart, user_email, total_amount)
309
-
310
- # Step 2: Query Salesforce for the order just placed using the user's email and name
311
  order_query = f"""
312
  SELECT Id, Name, Customer_Email__c
313
  FROM Order__c
@@ -315,27 +298,22 @@ def place_order():
315
  ORDER BY CreatedDate DESC LIMIT 1
316
  """
317
  order_result = sf.query_all(order_query)
318
-
319
- # Ensure the order was created successfully
320
  if not order_result['records']:
321
  return jsonify({"response": "Failed to retrieve the placed order. Please try again."})
322
-
323
  order_id = order_result['records'][0]['Id']
324
-
325
- # Step 3: Add the food items as related records to the Order__c
326
  for item in cart:
327
  order_item = {
328
- 'Order__c': order_id, # Link the item to the specific order
329
- 'Item_Name__c': item['Name'], # Item name
330
- 'Quantity__c': item['Quantity'], # Item quantity
331
- 'Price__c': item['Price__c'], # Item price
332
  }
333
- sf.Order_Item__c.create(order_item) # Assuming you have a custom Order_Item__c object for items
334
 
335
- # Step 4: Clear the cart after placing the order
336
  cart = [] # Clear the cart
337
-
338
- # Return the success message
339
  return jsonify({"response": f"Order placed successfully! Total amount: ₹{total_amount}"})
340
 
341
  except Exception as e:
@@ -343,4 +321,4 @@ def place_order():
343
 
344
 
345
  if __name__ == "__main__":
346
- app.run(host="0.0.0.0", port=7860)
 
36
  def get_menu_items(category):
37
  category_filter = ''
38
 
 
39
  if category == 'Veg':
40
  category_filter = 'Veg'
41
  elif category == 'Non-Veg':
 
43
  elif category == 'All':
44
  category_filter = '' # No filter for 'All'
45
 
46
+ query = f"""
47
+ SELECT Id, Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
48
+ FROM Menu_Item__c
49
+ WHERE Veg_NonVeg__c = '{category_filter}' OR Veg_NonVeg__c = 'both'
50
+ """ if category_filter else """
51
+ SELECT Id, Name, Price__c, Image1__c, Veg_NonVeg__c, Section__c
52
+ FROM Menu_Item__c
53
+ """
 
 
 
54
  result = sf.query_all(query)
55
  return result['records']
56
 
57
+ # Function to save order to Salesforce
58
  def save_order_to_salesforce(cart, user_email, total_amount):
 
59
  order_items = ", ".join([f"{item['Name']} x {item['Quantity']}" for item in cart])
60
  order = {
61
  'Customer_Email__c': user_email,
62
  'Order_Date_Time__c': datetime.now(),
63
  'Order_Items__c': order_items,
64
  'Total_Amount__c': total_amount,
65
+ 'Status__c': 'Pending'
66
  }
67
 
 
68
  order_record = sf.Order__c.create(order)
69
  return order_record
70
 
 
116
  greetUser();
117
  }
118
  });
119
+
120
  function greetUser() {
121
  const utterance = new SpeechSynthesisUtterance("Hi, welcome to Biryani Hub! Can I know your name so I can greet you personally?");
122
  speechSynthesis.speak(utterance);
 
125
  startListening();
126
  };
127
  }
128
+
129
  async function startListening() {
130
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
131
  const mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm;codecs=opus" });
 
145
  speechSynthesis.speak(utterance);
146
  utterance.onend = () => {
147
  if (!data.response.includes("Goodbye") && !data.response.includes("final order")) {
148
+ startListening();
149
  } else {
150
  status.textContent = "Conversation ended.";
151
  isListening = false;
 
190
 
191
  recognizer = sr.Recognizer()
192
  with sr.AudioFile(converted_file.name) as source:
193
+ recognizer.adjust_for_ambient_noise(source, duration=1)
194
+ audio_data = recognizer.record(source, duration=10)
195
  try:
196
  command = recognizer.recognize_google(audio_data)
197
+ logging.info(f"Recognized command: {command}")
198
  response = process_command(command)
199
  except sr.UnknownValueError:
200
  response = "Sorry, I couldn't understand your command. Could you please repeat?"
 
218
  logging.info(f"Processing command: {command}")
219
 
220
  try:
 
221
  if user_name is None and "my name is" in command:
222
  user_name = command.replace("my name is", "").strip()
223
  return jsonify({"response": f"Hello {user_name}! Nice to meet you. Please choose your preference: Veg, Non-Veg, or All."})
224
 
 
225
  if awaiting_preference:
226
  if "veg" in command:
227
  current_category = 'Veg'
 
233
  return jsonify({"response": "I didn't catch your preference. Please choose Veg, Non-Veg, or All."})
234
 
235
  awaiting_preference = False
236
+ awaiting_item_selection = True
237
  return jsonify({"response": f"Great! You've selected {current_category}. What would you like to order?"})
238
 
 
239
  if awaiting_item_selection:
240
+ menu_items = get_menu_items(current_category)
241
  selected_item = next((item for item in menu_items if item['Name'].lower() in command), None)
242
 
243
  if selected_item:
 
248
 
249
  return jsonify({"response": "I didn't catch that. Please say the name of the item you want to order."})
250
 
 
251
  if awaiting_quantity:
252
  try:
253
  quantity = int(command)
 
260
  except ValueError:
261
  return jsonify({"response": "Please provide a valid number for quantity."})
262
 
 
263
  if "my email is" in command:
264
  email_part = command.replace("my email is", "").strip()
265
  email_command = email_part.replace(' at ', '@').replace(' dot ', '.').replace(' ', '')
 
274
  else:
275
  return jsonify({"response": "Sorry, that doesn't look like a valid email. Can you please provide it again?"})
276
 
 
277
  if "final order" in command or "confirm my order" in command or "place the order" in command or "confirm order" in command:
278
  return place_order()
279
 
 
281
 
282
  except Exception as e:
283
  logging.error(f"An error occurred while processing the command: {str(e)}")
284
+ logging.error(f"Stack Trace: {traceback.format_exc()}")
285
  return jsonify({"response": "Sorry, there was an error processing your request."}), 500
286
 
 
287
  def place_order():
288
  global cart, user_email, user_name
289
 
290
  try:
 
291
  total_amount = sum([item['Price__c'] * item['Quantity'] for item in cart])
 
 
292
  order_record = save_order_to_salesforce(cart, user_email, total_amount)
293
+
 
294
  order_query = f"""
295
  SELECT Id, Name, Customer_Email__c
296
  FROM Order__c
 
298
  ORDER BY CreatedDate DESC LIMIT 1
299
  """
300
  order_result = sf.query_all(order_query)
301
+
 
302
  if not order_result['records']:
303
  return jsonify({"response": "Failed to retrieve the placed order. Please try again."})
304
+
305
  order_id = order_result['records'][0]['Id']
306
+
 
307
  for item in cart:
308
  order_item = {
309
+ 'Order__c': order_id,
310
+ 'Item_Name__c': item['Name'],
311
+ 'Quantity__c': item['Quantity'],
312
+ 'Price__c': item['Price__c'],
313
  }
314
+ sf.Order_Item__c.create(order_item)
315
 
 
316
  cart = [] # Clear the cart
 
 
317
  return jsonify({"response": f"Order placed successfully! Total amount: ₹{total_amount}"})
318
 
319
  except Exception as e:
 
321
 
322
 
323
  if __name__ == "__main__":
324
+ app.run(host="0.0.0.0", port=7860)