DSatishchandra commited on
Commit
762e547
·
verified ·
1 Parent(s): 0cf33d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -89
app.py CHANGED
@@ -1,108 +1,126 @@
1
  import gradio as gr
2
- import pandas as pd
3
- import speech_recognition as sr
4
- import tempfile
5
  from gtts import gTTS
6
  import os
7
- import io
8
- import wave
9
- import numpy as np
10
-
11
- # Load menu from the uploaded file
12
- menu_file_path = "menu.xlsx"
13
- menu_df = pd.read_excel(menu_file_path)
14
 
15
- # Extract unique categories from the menu
16
- categories = menu_df["Category"].unique()
 
 
 
 
 
 
17
 
 
18
  conversation_history = []
 
19
 
20
- def get_menu_by_category(category):
21
- """Retrieve dishes for a given category."""
22
- dishes = menu_df[menu_df["Category"] == category]
23
- return "\n".join([
24
- f"{row['Dish Name']} (${row['Price ($)']}): {row['Description']}"
25
- for _, row in dishes.iterrows()
26
- ])
27
-
28
- def recommend_items(dish_name):
29
- """Get recommended items for a dish."""
30
- recommendations = menu_df[menu_df["Dish Name"] == dish_name]["Recommended Items"].values
31
- if recommendations:
32
- return recommendations[0]
33
- return "No specific recommendations."
34
-
35
- def process_order(audio_data):
36
- recognizer = sr.Recognizer()
37
-
38
- if audio_data is None:
39
- return "No audio data provided. Please try again.", None
40
 
 
 
 
41
  try:
42
- # Convert raw audio to WAV file in memory
43
- with io.BytesIO() as wav_file:
44
- with wave.open(wav_file, 'wb') as wf:
45
- wf.setnchannels(1) # Mono audio
46
- wf.setsampwidth(2) # Sample width: 2 bytes
47
- wf.setframerate(16000) # Sampling rate
48
- wf.writeframes(audio_data.tobytes()) # Write audio frames
49
- wav_file.seek(0) # Reset pointer to the beginning
50
-
51
- # Use SpeechRecognition with in-memory WAV file
52
- with sr.AudioFile(wav_file) as source:
53
- audio_data = recognizer.record(source)
54
- user_input = recognizer.recognize_google(audio_data)
55
  except sr.UnknownValueError:
56
- return "I couldn't understand that. Could you please repeat?", None
57
- except Exception as e:
58
- return f"Error processing audio: {e}", None
59
-
60
- global conversation_history
61
-
62
- # Initial greeting
63
- if "menu" in user_input.lower():
64
- response = "Our menu categories are: " + ", ".join(categories) + ". Which one would you like to hear about?"
65
- elif any(category.lower() in user_input.lower() for category in categories):
66
- category = next(cat for cat in categories if cat.lower() in user_input.lower())
67
- response = f"Here are the dishes in {category}:\n" + get_menu_by_category(category)
68
- elif "recommend" in user_input.lower():
69
- words = user_input.split()
70
- dish_name = next((word for word in words if word in menu_df["Dish Name"].values), None)
71
- if dish_name:
72
- response = f"I recommend: {recommend_items(dish_name)}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  else:
74
- response = "Could you specify the dish you’d like recommendations for?"
75
- elif "order" in user_input.lower():
76
- response = "What would you like to order?"
77
- elif "thank you" in user_input.lower() or "done" in user_input.lower():
78
- response = "Thank you for ordering with us. Enjoy your meal!"
 
 
 
 
 
 
 
 
 
 
 
79
  else:
80
- response = "I didn’t quite catch that. Could you please repeat?"
81
-
82
- # Save conversation
83
- conversation_history.append((user_input, response))
84
 
85
- # Save conversation history to a file
86
- with open("conversation_history.txt", "w") as file:
87
- for user, ai in conversation_history:
88
- file.write(f"Customer: {user}\nAI: {ai}\n\n")
89
 
90
- # Generate audio response using gTTS
91
- try:
92
- tts = gTTS(response)
93
- temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
94
- tts.save(temp_audio_file.name)
95
- temp_audio_file.close()
96
- return response, temp_audio_file.name
97
- except Exception as e:
98
- return f"Error generating audio response: {e}", None
99
 
 
100
  iface = gr.Interface(
101
  fn=process_order,
102
- inputs=gr.Audio(type="numpy"), # Accept raw audio data
103
- outputs=[gr.Textbox(label="Text Response"), gr.Audio(label="Audio Response")], # Handle audio response correctly
104
- live=True,
105
- allow_flagging="never"
 
106
  )
107
 
108
- iface.launch()
 
 
 
 
 
1
  import gradio as gr
 
 
 
2
  from gtts import gTTS
3
  import os
4
+ import speech_recognition as sr
 
 
 
 
 
 
5
 
6
+ # Menu for the restaurant
7
+ menu = {
8
+ "Starters": ["Soup", "Spring Rolls"],
9
+ "Main Course": ["Paneer Butter Masala", "Chicken Curry", "Veg Biryani"],
10
+ "Breads": ["Roti", "Naan", "Paratha"],
11
+ "Desserts": ["Gulab Jamun", "Ice Cream"],
12
+ "Drinks": ["Mango Lassi", "Soda", "Water"]
13
+ }
14
 
15
+ # Conversation history and context
16
  conversation_history = []
17
+ context = {"last_action": None, "order": []}
18
 
19
+ # Text-to-Speech Function
20
+ def speak_and_save(text, filename="response.mp3"):
21
+ tts = gTTS(text=text, lang='en')
22
+ tts.save(filename)
23
+ return filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # Speech Recognition Function
26
+ def recognize_speech(audio_file_path):
27
+ recognizer = sr.Recognizer()
28
  try:
29
+ with sr.AudioFile(audio_file_path) as source:
30
+ audio_data = recognizer.record(source)
31
+ text = recognizer.recognize_google(audio_data)
32
+ return text
 
 
 
 
 
 
 
 
 
33
  except sr.UnknownValueError:
34
+ return "I didn't catch that. Could you repeat?"
35
+ except sr.RequestError:
36
+ return "There was an issue processing your speech. Try again later."
37
+
38
+ # Voice Assistant Logic
39
+ def process_order(audio_file_path):
40
+ user_input = recognize_speech(audio_file_path)
41
+ conversation_history.append(f"Customer: {user_input}")
42
+
43
+ if user_input.startswith("Sorry") or user_input.startswith("I didn't"):
44
+ response = user_input
45
+ conversation_history.append(f"AI: {response}")
46
+ return response, speak_and_save(response)
47
+
48
+ global context
49
+ response = ""
50
+
51
+ # Greet the customer
52
+ if context["last_action"] is None:
53
+ response = "Welcome to our restaurant. How can I assist you today?"
54
+ context["last_action"] = "greet"
55
+
56
+ # Show menu
57
+ elif "menu" in user_input.lower():
58
+ response = "Here is our menu:\n"
59
+ for category, items in menu.items():
60
+ response += f"{category}: {', '.join(items)}\n"
61
+ response += "What would you like to order?"
62
+ context["last_action"] = "show_menu"
63
+
64
+ # Place an order
65
+ elif "order" in user_input.lower() or any(item.lower() in user_input.lower() for item in sum(menu.values(), [])):
66
+ for category, items in menu.items():
67
+ for item in items:
68
+ if item.lower() in user_input.lower():
69
+ context["order"].append(item)
70
+ break
71
+ response = f"I’ve added {', '.join(context['order'])} to your order. Would you like anything else?"
72
+ context["last_action"] = "place_order"
73
+
74
+ # Suggest complementary items
75
+ elif "recommend" in user_input.lower() or "suggest" in user_input.lower():
76
+ response = "Based on your order, I suggest:"
77
+ if "Paneer Butter Masala" in context["order"]:
78
+ response += " Mango Lassi or Roti."
79
+ elif "Chicken Curry" in context["order"]:
80
+ response += " Naan or Soda."
81
  else:
82
+ response += " Gulab Jamun for dessert."
83
+ context["last_action"] = "recommend"
84
+
85
+ # Finalize the order
86
+ elif "no" in user_input.lower() or "that’s it" in user_input.lower():
87
+ response = f"Your final order is: {', '.join(context['order'])}. Thank you for your order. Your food will arrive shortly. Enjoy your meal!"
88
+ conversation_history.append(f"Order Summary: {context['order']}")
89
+ context["last_action"] = "final_order"
90
+ context["order"] = [] # Reset the order
91
+
92
+ # Mid-meal check
93
+ elif "everything alright" in user_input.lower() or "anything else" in user_input.lower():
94
+ response = "I hope you’re enjoying your meal. Can I bring you anything else?"
95
+ context["last_action"] = "check_meal"
96
+
97
+ # Default response
98
  else:
99
+ response = "I’m not sure what you meant. Could you clarify?"
100
+ context["last_action"] = "clarify"
 
 
101
 
102
+ conversation_history.append(f"AI: {response}")
103
+ audio_response_path = speak_and_save(response)
104
+ return response, audio_response_path
 
105
 
106
+ # Save Conversation History
107
+ def save_conversation():
108
+ with open("conversation_history.txt", "w") as f:
109
+ f.write("\n".join(conversation_history))
110
+ return "Conversation history saved successfully!"
 
 
 
 
111
 
112
+ # Gradio Interface
113
  iface = gr.Interface(
114
  fn=process_order,
115
+ inputs=gr.Audio(type="filepath"),
116
+ outputs=[gr.Textbox(label="Text Response"), gr.Audio(label="Audio Response")],
117
+ title="Restaurant Voice Assistant",
118
+ description="Talk to our voice assistant to place your order or ask about the menu!",
119
+ live=True
120
  )
121
 
122
+ if __name__ == "__main__":
123
+ try:
124
+ iface.launch()
125
+ finally:
126
+ save_conversation()