DSatishchandra commited on
Commit
3504920
·
verified ·
1 Parent(s): f65fa0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -95
app.py CHANGED
@@ -1,115 +1,79 @@
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
- # Finalize the order
75
- elif "no" in user_input.lower() or "that's it" in user_input.lower():
76
- response = f"Your final order is: {', '.join(context['order'])}. Thank you for your order. Your food will arrive shortly. Enjoy your meal!"
77
- conversation_history.append(f"Order Summary: {context['order']}")
78
- context["last_action"] = "final_order"
79
- context["order"] = [] # Reset the order
80
-
81
- # Mid-meal check
82
- elif "everything alright" in user_input.lower() or "anything else" in user_input.lower():
83
- response = "I hope you're enjoying your meal. Can I bring you anything else?"
84
- context["last_action"] = "check_meal"
85
-
86
- # Default response
87
  else:
88
- response = "I'm not sure what you meant. Could you clarify?"
89
- context["last_action"] = "clarify"
 
 
90
 
91
- conversation_history.append(f"AI: {response}")
92
- audio_response_path = speak_and_save(response)
93
- return response, audio_response_path
 
94
 
95
- # Save Conversation History
96
- def save_conversation():
97
- with open("conversation_history.txt", "w") as f:
98
- f.write("\n".join(conversation_history))
99
- return "Conversation history saved successfully!"
100
 
101
- # Gradio Interface
102
  iface = gr.Interface(
103
  fn=process_order,
104
  inputs=gr.Audio(type="filepath"),
105
  outputs=[gr.Textbox(label="Text Response"), gr.Audio(label="Audio Response")],
106
- title="Restaurant Voice Assistant",
107
- description="Talk to our voice assistant to place your order or ask about the menu!",
108
- live=True
109
  )
110
 
111
- if __name__ == "__main__":
112
- try:
113
- iface.launch()
114
- finally:
115
- save_conversation()
 
1
  import gradio as gr
2
+ import pandas as pd
 
 
3
 
4
+ # Load menu from the uploaded file
5
+ menu_file_path = "menu.xlsx"
6
+ menu_df = pd.read_excel(menu_file_path)
7
+
8
+ # Extract unique categories from the menu
9
+ categories = menu_df["Category"].unique()
 
 
10
 
 
11
  conversation_history = []
 
12
 
13
+ def get_menu_by_category(category):
14
+ """Retrieve dishes for a given category."""
15
+ dishes = menu_df[menu_df["Category"] == category]
16
+ return "\n".join([
17
+ f"{row['Dish Name']} (${row['Price ($)']}): {row['Description']}"
18
+ for _, row in dishes.iterrows()
19
+ ])
20
 
21
+ def recommend_items(dish_name):
22
+ """Get recommended items for a dish."""
23
+ recommendations = menu_df[menu_df["Dish Name"] == dish_name]["Recommended Items"].values
24
+ if recommendations:
25
+ return recommendations[0]
26
+ return "No specific recommendations."
 
 
 
 
 
 
27
 
28
+ def process_order(audio_file):
29
+ import speech_recognition as sr
30
+ recognizer = sr.Recognizer()
 
31
 
32
+ with sr.AudioFile(audio_file) as source:
33
+ audio_data = recognizer.record(source)
34
+ try:
35
+ user_input = recognizer.recognize_google(audio_data)
36
+ except sr.UnknownValueError:
37
+ return "I couldn't understand that. Could you please repeat?", ""
38
 
39
+ global conversation_history
 
40
 
41
+ # Initial greeting
42
+ if "menu" in user_input.lower():
43
+ response = "Our menu categories are: " + ", ".join(categories) + ". Which one would you like to hear about?"
44
+ elif any(category.lower() in user_input.lower() for category in categories):
45
+ category = next(cat for cat in categories if cat.lower() in user_input.lower())
46
+ response = f"Here are the dishes in {category}:\n" + get_menu_by_category(category)
47
+ elif "recommend" in user_input.lower():
48
+ words = user_input.split()
49
+ dish_name = next((word for word in words if word in menu_df["Dish Name"].values), None)
50
+ if dish_name:
51
+ response = f"I recommend: {recommend_items(dish_name)}."
52
+ else:
53
+ response = "Could you specify the dish you’d like recommendations for?"
54
+ elif "order" in user_input.lower():
55
+ response = "What would you like to order?"
56
+ elif "thank you" in user_input.lower() or "done" in user_input.lower():
57
+ response = "Thank you for ordering with us. Enjoy your meal!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  else:
59
+ response = "I didn’t quite catch that. Could you please repeat?"
60
+
61
+ # Save conversation
62
+ conversation_history.append((user_input, response))
63
 
64
+ # Save conversation history to a file
65
+ with open("conversation_history.txt", "w") as file:
66
+ for user, ai in conversation_history:
67
+ file.write(f"Customer: {user}\nAI: {ai}\n\n")
68
 
69
+ return response, ""
 
 
 
 
70
 
 
71
  iface = gr.Interface(
72
  fn=process_order,
73
  inputs=gr.Audio(type="filepath"),
74
  outputs=[gr.Textbox(label="Text Response"), gr.Audio(label="Audio Response")],
75
+ live=True,
76
+ allow_flagging="never"
 
77
  )
78
 
79
+ iface.launch()