nagasurendra commited on
Commit
3ac7c45
·
verified ·
1 Parent(s): ba43ee9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -63
app.py CHANGED
@@ -4,6 +4,9 @@ import os
4
  import tempfile
5
  import json
6
  import speech_recognition as sr
 
 
 
7
 
8
  # Store cart in a temporary storage
9
  cart = []
@@ -17,6 +20,9 @@ menu_items = {
17
  "Soda": 2.49
18
  }
19
 
 
 
 
20
  def generate_voice_response(text):
21
  tts = gTTS(text)
22
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
@@ -27,73 +33,78 @@ def generate_voice_response(text):
27
  def calculate_total(cart):
28
  return sum(menu_items[item] for item in cart)
29
 
30
- def restaurant_voice_assistant(audio, state_json):
31
- global cart
32
- state = json.loads(state_json) if state_json else {}
33
- response = ""
34
- voice_path = None
35
-
36
- # Convert audio input to text
37
- if audio:
38
- recognizer = sr.Recognizer()
39
- with sr.AudioFile(audio) as source:
40
- try:
41
- input_text = recognizer.recognize_google(recognizer.record(source))
42
- except sr.UnknownValueError:
43
- input_text = ""
44
- else:
45
- input_text = ""
46
-
47
- if not state.get("menu_shown", False):
48
- # Show menu dynamically
49
- response = "Welcome to our restaurant! Here is our menu:\n"
50
- for item, price in menu_items.items():
51
- response += f"{item}: ${price:.2f}\n"
52
- response += "\nPlease tell me the item you would like to add to your cart."
53
- state["menu_shown"] = True
54
- elif any(item.lower() in input_text.lower() for item in menu_items):
55
- # Check if input matches a menu item
56
- for item in menu_items:
57
- if item.lower() in input_text.lower():
58
- cart.append(item)
59
- total = calculate_total(cart)
60
- response = f"{item} has been added to your cart. Your current cart includes:\n"
61
- for cart_item in cart:
62
- response += f"- {cart_item}: ${menu_items[cart_item]:.2f}\n"
63
- response += f"\nTotal: ${total:.2f}. Would you like to add anything else?"
64
  break
65
- elif "menu" in input_text.lower():
66
- response = "Here is our menu again:\n"
67
- for item, price in menu_items.items():
68
- response += f"{item}: ${price:.2f}\n"
69
- response += "\nWhat would you like to add to your cart?"
70
- elif "final order" in input_text.lower() or "submit order" in input_text.lower():
71
- if cart:
72
- total = calculate_total(cart)
73
- response = "Your final order includes:\n"
74
- for item in cart:
75
- response += f"- {item}: ${menu_items[item]:.2f}\n"
76
- response += f"\nTotal: ${total:.2f}.\nThank you for ordering!"
77
- cart = [] # Clear cart after finalizing order
78
- else:
79
- response = "Your cart is empty. Would you like to order something?"
80
- else:
81
- response = "I didn’t quite catch that. Please tell me what you’d like to order."
82
 
83
- voice_path = generate_voice_response(response)
84
- return response, voice_path, json.dumps(state)
 
85
 
86
- with gr.Blocks() as demo:
87
- state = gr.State(value=json.dumps({}))
 
 
 
 
 
 
88
 
89
- with gr.Row():
90
- user_audio = gr.Audio(type="filepath", label="Your Voice Input")
91
- output_text = gr.Textbox(label="Response Text")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
- with gr.Row():
94
- voice_output = gr.Audio(label="Response Audio", autoplay=True)
 
95
 
96
- submit_btn = gr.Button("Submit")
97
- submit_btn.click(restaurant_voice_assistant, inputs=[user_audio, state], outputs=[output_text, voice_output, state])
 
 
98
 
99
- demo.launch()
 
 
4
  import tempfile
5
  import json
6
  import speech_recognition as sr
7
+ import threading
8
+ import time
9
+ from playsound import playsound
10
 
11
  # Store cart in a temporary storage
12
  cart = []
 
20
  "Soda": 2.49
21
  }
22
 
23
+ # To manage playback control
24
+ playback_control = {"stop": False, "pause": False}
25
+
26
  def generate_voice_response(text):
27
  tts = gTTS(text)
28
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
 
33
  def calculate_total(cart):
34
  return sum(menu_items[item] for item in cart)
35
 
36
+ def play_audio_with_control(audio_path):
37
+ global playback_control
38
+ playback_control["stop"] = False
39
+ playback_control["pause"] = False
40
+ try:
41
+ for _ in range(3): # Retry loop in case of interruptions
42
+ if playback_control["stop"]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  break
44
+ playsound(audio_path)
45
+ break
46
+ except Exception as e:
47
+ print("Error playing audio:", e)
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ def restaurant_voice_assistant():
50
+ global cart
51
+ recognizer = sr.Recognizer()
52
 
53
+ # Continuously listen for user commands
54
+ while True:
55
+ with sr.Microphone() as source:
56
+ print("Listening for input...")
57
+ try:
58
+ audio = recognizer.listen(source)
59
+ input_text = recognizer.recognize_google(audio)
60
+ print("You said:", input_text)
61
 
62
+ # Process input text
63
+ if "menu" in input_text.lower():
64
+ response = "Here is our menu:\n"
65
+ for item, price in menu_items.items():
66
+ response += f"{item}: ${price:.2f}\n"
67
+ response += "\nWhat would you like to add to your cart?"
68
+ elif any(item.lower() in input_text.lower() for item in menu_items):
69
+ for item in menu_items:
70
+ if item.lower() in input_text.lower():
71
+ cart.append(item)
72
+ total = calculate_total(cart)
73
+ response = f"{item} has been added to your cart. Your current cart includes:\n"
74
+ for cart_item in cart:
75
+ response += f"- {cart_item}: ${menu_items[cart_item]:.2f}\n"
76
+ response += f"\nTotal: ${total:.2f}. Would you like to add anything else?"
77
+ break
78
+ elif "final order" in input_text.lower() or "submit order" in input_text.lower():
79
+ if cart:
80
+ total = calculate_total(cart)
81
+ response = "Your final order includes:\n"
82
+ for item in cart:
83
+ response += f"- {item}: ${menu_items[item]:.2f}\n"
84
+ response += f"\nTotal: ${total:.2f}.\nThank you for ordering!"
85
+ cart = [] # Clear cart after finalizing order
86
+ else:
87
+ response = "Your cart is empty. Would you like to order something?"
88
+ elif "stop" in input_text.lower():
89
+ playback_control["stop"] = True
90
+ response = "Audio playback stopped."
91
+ elif "pause" in input_text.lower():
92
+ playback_control["pause"] = True
93
+ response = "Audio playback paused."
94
+ elif "resume" in input_text.lower():
95
+ playback_control["pause"] = False
96
+ response = "Resuming audio playback."
97
+ else:
98
+ response = "I didn’t quite catch that. Please tell me what you’d like to order."
99
 
100
+ # Generate and play audio response
101
+ audio_path = generate_voice_response(response)
102
+ threading.Thread(target=play_audio_with_control, args=(audio_path,)).start()
103
 
104
+ except sr.UnknownValueError:
105
+ print("Sorry, I didn’t catch that. Could you please repeat?")
106
+ except Exception as e:
107
+ print("Error occurred:", e)
108
 
109
+ # Run the assistant
110
+ threading.Thread(target=restaurant_voice_assistant).start()