nagasurendra commited on
Commit
af704d1
·
verified ·
1 Parent(s): 63c3e87

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -83
app.py CHANGED
@@ -1,97 +1,79 @@
1
- import os
2
- import time
3
- import threading
4
- import speech_recognition as sr
5
  from gtts import gTTS
6
- from tempfile import NamedTemporaryFile
 
 
7
 
8
- # Initialize the recognizer
9
- recognizer = sr.Recognizer()
10
 
11
- # Menu items and cart initialization
12
  menu_items = {
13
- "biryani": ["Chicken Biryani", "Mutton Biryani", "Vegetable Biryani", "Egg Biryani"],
14
- "starters": ["Chicken Tikka", "Paneer Tikka", "Fish Fry", "Veg Manchurian"],
15
- "drinks": ["Coke", "Pepsi", "Lemonade", "Mango Juice", "Water"]
 
 
16
  }
17
- cart = []
18
-
19
- # Helper Functions
20
- def text_to_speech(text):
21
- """Convert text to speech and play the response."""
22
- tts = gTTS(text=text, lang='en')
23
- audio_file = NamedTemporaryFile(delete=False, suffix=".mp3")
24
- tts.save(audio_file.name)
25
- os.system(f"mpg123 {audio_file.name}")
26
- return audio_file.name
27
 
28
- def read_menu():
29
- """Generate the menu text."""
30
- menu_text = "Here is the menu: "
31
- for category, items in menu_items.items():
32
- menu_text += f"{category.capitalize()}: " + ", ".join(items) + ". "
33
- menu_text += "Please tell me the items you want to add to your cart."
34
- return menu_text
35
 
36
- def process_audio_command(audio_path):
37
- """Process the user's audio command."""
38
  global cart
39
- try:
40
- with sr.AudioFile(audio_path) as source:
41
- audio = recognizer.record(source)
42
- command = recognizer.recognize_google(audio).lower()
43
- except Exception as e:
44
- return "Sorry, I couldn't understand that. Could you repeat?"
45
 
46
- # Menu Request
47
- if "menu" in command:
48
- return read_menu()
49
-
50
- # Adding Items to the Cart
51
- for category, items in menu_items.items():
52
- for item in items:
53
- if item.lower() in command:
54
- cart.append(item)
55
- return f"{item} has been added to your cart."
56
-
57
- # Cart Inquiry
58
- if "cart" in command:
59
- if not cart:
60
- return "Your cart is empty."
61
  else:
62
- return "Your cart contains: " + ", ".join(cart)
63
-
64
- # Submitting Order
65
- if "submit" in command or "finalize" in command:
66
- if not cart:
67
- return "Your cart is empty. Add some items before submitting."
 
 
 
 
 
 
 
68
  else:
69
- response = "Your final order is: " + ", ".join(cart) + ". Thank you for your order!"
70
- cart.clear()
71
- return response
 
 
 
72
 
73
- return "Sorry, I didn't understand that. Please try again."
 
 
 
 
 
 
 
 
74
 
75
- # Continuous Listening and Responding
76
- def continuous_conversation():
77
- """Continuously listen to and respond to user commands."""
78
- while True:
79
- with NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
80
- try:
81
- print("Listening...")
82
- with sr.Microphone() as source:
83
- recognizer.adjust_for_ambient_noise(source)
84
- audio = recognizer.listen(source)
85
- with open(temp_audio.name, "wb") as f:
86
- f.write(audio.get_wav_data())
87
- response = process_audio_command(temp_audio.name)
88
- print("Assistant:", response)
89
- text_to_speech(response)
90
- except Exception as e:
91
- print("Error processing audio input:", e)
92
- text_to_speech("I encountered an error. Please try again.")
93
 
94
- if __name__ == "__main__":
95
- print("Starting Voice-Activated Restaurant Menu System...")
96
- text_to_speech("Welcome to the voice-activated restaurant menu system. You can ask for the menu, add items to your cart, check your cart, or submit your order.")
97
- continuous_conversation()
 
1
+ import gradio as gr
 
 
 
2
  from gtts import gTTS
3
+ import os
4
+ import tempfile
5
+ import json
6
 
7
+ # Store cart in a temporary storage
8
+ cart = []
9
 
10
+ # Define the menu items dynamically
11
  menu_items = {
12
+ "Pizza": 10.99,
13
+ "Burger": 8.49,
14
+ "Pasta": 12.99,
15
+ "Salad": 7.99,
16
+ "Soda": 2.49
17
  }
 
 
 
 
 
 
 
 
 
 
18
 
19
+ def generate_voice_response(text):
20
+ tts = gTTS(text)
21
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
22
+ temp_file.close()
23
+ tts.save(temp_file.name)
24
+ return temp_file.name
 
25
 
26
+ def restaurant_voice_assistant(input_text, state_json):
 
27
  global cart
28
+ state = json.loads(state_json) if state_json else {}
29
+ response = ""
30
+ voice_path = None
 
 
 
31
 
32
+ if not state.get("menu_shown", False):
33
+ # Show menu dynamically
34
+ response = "Welcome to our restaurant! Here is our menu:\n"
35
+ for item, price in menu_items.items():
36
+ response += f"{item}: ${price:.2f}\n"
37
+ response += "\nPlease tell me the item you would like to add to your cart."
38
+ state["menu_shown"] = True
39
+ elif "add_to_cart" in input_text.lower():
40
+ item = input_text.replace("add to cart", "").strip()
41
+ if item in menu_items:
42
+ cart.append(item)
43
+ response = f"{item} has been added to your cart. Would you like to add anything else?"
 
 
 
44
  else:
45
+ response = f"Sorry, {item} is not on the menu. Please choose an item from the menu."
46
+ elif "menu" in input_text.lower():
47
+ response = "Here is our menu again:\n"
48
+ for item, price in menu_items.items():
49
+ response += f"{item}: ${price:.2f}\n"
50
+ response += "\nWhat would you like to add to your cart?"
51
+ elif "final order" in input_text.lower():
52
+ if cart:
53
+ response = "Your final order includes:\n"
54
+ for item in cart:
55
+ response += f"- {item}\n"
56
+ response += "\nThank you for ordering!"
57
+ cart = [] # Clear cart after finalizing order
58
  else:
59
+ response = "Your cart is empty. Would you like to order something?"
60
+ else:
61
+ response = "I didn’t quite catch that. Please tell me what you’d like to order."
62
+
63
+ voice_path = generate_voice_response(response)
64
+ return response, voice_path, json.dumps(state)
65
 
66
+ with gr.Blocks() as demo:
67
+ state = gr.State(value=json.dumps({}))
68
+
69
+ with gr.Row():
70
+ user_input = gr.Textbox(label="Your Voice Input", placeholder="Type here or use voice input.")
71
+ output_text = gr.Textbox(label="Response Text")
72
+
73
+ with gr.Row():
74
+ voice_output = gr.Audio(label="Response Audio")
75
 
76
+ submit_btn = gr.Button("Submit")
77
+ submit_btn.click(restaurant_voice_assistant, inputs=[user_input, state], outputs=[output_text, voice_output, state])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ demo.launch()