nagasurendra commited on
Commit
716ff70
·
verified ·
1 Parent(s): 42f18a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -71
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import gradio as gr
2
  from gtts import gTTS
3
- import tempfile
4
  import os
 
 
5
  import speech_recognition as sr
6
 
7
  # Store cart in a temporary storage
@@ -23,84 +24,76 @@ def generate_voice_response(text):
23
  tts.save(temp_file.name)
24
  return temp_file.name
25
 
26
- def process_audio(audio_path):
 
 
 
27
  global cart
28
- recognizer = sr.Recognizer()
29
  response = ""
30
-
31
- try:
32
- with sr.AudioFile(audio_path) as source:
33
- audio = recognizer.record(source)
34
- input_text = recognizer.recognize_google(audio)
35
- print("User said:", input_text)
36
-
37
- if "menu" in input_text.lower():
38
- response = "Here is our menu:\n"
39
- for item, price in menu_items.items():
40
- response += f"{item}: ${price:.2f}\n"
41
- response += "\nWhat would you like to add to your cart?"
42
-
43
- elif any(item.lower() in input_text.lower() for item in menu_items):
44
- for item in menu_items:
45
- if item.lower() in input_text.lower():
46
- cart.append(item)
47
- total = sum(menu_items[cart_item] for cart_item in cart)
48
- response = f"{item} has been added to your cart. Your current cart includes:\n"
49
- for cart_item in cart:
50
- response += f"- {cart_item}: ${menu_items[cart_item]:.2f}\n"
51
- response += f"\nTotal: ${total:.2f}. Would you like to add anything else?"
52
- break
53
-
54
- elif "final order" in input_text.lower() or "submit order" in input_text.lower():
55
- if cart:
56
- total = sum(menu_items[cart_item] for cart_item in cart)
57
- response = "Your final order includes:\n"
58
- for item in cart:
59
- response += f"- {item}: ${menu_items[item]:.2f}\n"
60
- response += f"\nTotal: ${total:.2f}. Thank you for ordering!"
61
- cart = [] # Clear cart after finalizing order
62
- else:
63
- response = "Your cart is empty. Would you like to order something?"
64
-
65
- elif "stop" in input_text.lower():
66
- response = "Stopping voice assistant."
67
-
68
- else:
69
- response = "I didn’t quite catch that. Please tell me what you’d like to order."
70
-
71
- except sr.UnknownValueError:
72
- response = "Sorry, I didn’t catch that. Could you please repeat?"
73
- except Exception as e:
74
- response = f"An error occurred: {str(e)}"
75
-
76
- audio_response_path = generate_voice_response(response)
77
- return response, audio_response_path
78
-
79
- def run_voice_assistant(audio):
80
- response, audio_path = process_audio(audio)
81
- return response, (audio_path,)
82
-
83
- def javascript_autoplay():
84
- return """<script>
85
- document.querySelector("audio").addEventListener("loadeddata", function() {
86
- this.play();
87
- });
88
- </script>"""
89
 
90
  with gr.Blocks() as demo:
91
- gr.Markdown("### Voice-Activated Restaurant Assistant")
92
 
93
  with gr.Row():
94
- voice_input = gr.Audio(type="filepath", label="Speak Now")
95
- assistant_response = gr.Textbox(label="Assistant Response")
96
-
97
- gr.Markdown("Note: The audio will play automatically.")
98
 
99
  with gr.Row():
100
- audio_output = gr.Audio(label="Audio Response")
101
-
102
- voice_input.change(run_voice_assistant, inputs=voice_input, outputs=[assistant_response, audio_output])
103
 
104
- gr.HTML(javascript_autoplay())
 
105
 
106
  demo.launch()
 
1
  import gradio as gr
2
  from gtts import gTTS
 
3
  import os
4
+ import tempfile
5
+ import json
6
  import speech_recognition as sr
7
 
8
  # Store cart in a temporary storage
 
24
  tts.save(temp_file.name)
25
  return temp_file.name
26
 
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
+ # Automatically process audio when recording stops
97
+ user_audio.change(restaurant_voice_assistant, inputs=[user_audio, state], outputs=[output_text, voice_output, state])
98
 
99
  demo.launch()