nagasurendra commited on
Commit
2b6046a
·
verified ·
1 Parent(s): 756720b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -92
app.py CHANGED
@@ -1,14 +1,8 @@
1
  import gradio as gr
2
  from gtts import gTTS
3
- import os
4
  import tempfile
5
- import json
6
- import sounddevice as sd
7
- import queue
8
- import threading
9
- from scipy.io.wavfile import write
10
  import speech_recognition as sr
11
- import subprocess
12
 
13
  # Store cart in a temporary storage
14
  cart = []
@@ -22,9 +16,6 @@ menu_items = {
22
  "Soda": 2.49
23
  }
24
 
25
- # To manage playback control
26
- playback_control = {"stop": False, "pause": False}
27
-
28
  def generate_voice_response(text):
29
  tts = gTTS(text)
30
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
@@ -32,96 +23,69 @@ def generate_voice_response(text):
32
  tts.save(temp_file.name)
33
  return temp_file.name
34
 
35
- def play_audio(audio_path):
 
 
 
 
36
  try:
37
- subprocess.run(["ffplay", "-nodisp", "-autoexit", audio_path], check=True)
38
- except Exception as e:
39
- print("Error playing audio:", e)
 
40
 
41
- def calculate_total(cart):
42
- return sum(menu_items[item] for item in cart)
 
 
 
43
 
44
- # Audio recording setup
45
- q = queue.Queue()
46
- def audio_callback(indata, frames, time, status):
47
- if status:
48
- print(status)
49
- q.put(indata.copy())
 
 
 
 
50
 
51
- def record_audio():
52
- fs = 16000 # Sample rate
53
- seconds = 5 # Duration
54
- print("Recording...")
55
- audio_data = []
56
- with sd.InputStream(callback=audio_callback, samplerate=fs, channels=1):
57
- for _ in range(int(fs * seconds / 1024)):
58
- audio_data.append(q.get())
59
- print("Recording finished.")
60
- return b"".join(audio_data)
61
 
62
- def restaurant_voice_assistant():
63
- global cart
64
- recognizer = sr.Recognizer()
65
 
66
- # Continuously listen for user commands
67
- while True:
68
- try:
69
- audio_data = record_audio()
70
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
71
- temp_audio.write(audio_data)
72
- temp_audio_path = temp_audio.name
73
 
74
- with sr.AudioFile(temp_audio_path) as source:
75
- audio = recognizer.record(source)
76
- input_text = recognizer.recognize_google(audio)
77
- print("You said:", input_text)
78
 
79
- # Process input text
80
- if "menu" in input_text.lower():
81
- response = "Here is our menu:\n"
82
- for item, price in menu_items.items():
83
- response += f"{item}: ${price:.2f}\n"
84
- response += "\nWhat would you like to add to your cart?"
85
- elif any(item.lower() in input_text.lower() for item in menu_items):
86
- for item in menu_items:
87
- if item.lower() in input_text.lower():
88
- cart.append(item)
89
- total = calculate_total(cart)
90
- response = f"{item} has been added to your cart. Your current cart includes:\n"
91
- for cart_item in cart:
92
- response += f"- {cart_item}: ${menu_items[cart_item]:.2f}\n"
93
- response += f"\nTotal: ${total:.2f}. Would you like to add anything else?"
94
- break
95
- elif "final order" in input_text.lower() or "submit order" in input_text.lower():
96
- if cart:
97
- total = calculate_total(cart)
98
- response = "Your final order includes:\n"
99
- for item in cart:
100
- response += f"- {item}: ${menu_items[item]:.2f}\n"
101
- response += f"\nTotal: ${total:.2f}.\nThank you for ordering!"
102
- cart = [] # Clear cart after finalizing order
103
- else:
104
- response = "Your cart is empty. Would you like to order something?"
105
- elif "stop" in input_text.lower():
106
- playback_control["stop"] = True
107
- response = "Audio playback stopped."
108
- elif "pause" in input_text.lower():
109
- playback_control["pause"] = True
110
- response = "Audio playback paused."
111
- elif "resume" in input_text.lower():
112
- playback_control["pause"] = False
113
- response = "Resuming audio playback."
114
- else:
115
- response = "I didn’t quite catch that. Please tell me what you’d like to order."
116
 
117
- # Generate and play audio response
118
- audio_path = generate_voice_response(response)
119
- play_audio(audio_path)
 
 
 
 
120
 
121
- except sr.UnknownValueError:
122
- print("Sorry, I didn’t catch that. Could you please repeat?")
123
- except Exception as e:
124
- print("Error occurred:", e)
125
 
126
- # Run the assistant
127
- threading.Thread(target=restaurant_voice_assistant).start()
 
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
8
  cart = []
 
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")
 
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}.\nThank 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
+ else:
66
+ response = "I didn’t quite catch that. Please tell me what you’d like to order."
 
67
 
68
+ except sr.UnknownValueError:
69
+ response = "Sorry, I didn’t catch that. Could you please repeat?"
70
+ except Exception as e:
71
+ response = f"An error occurred: {str(e)}"
 
 
 
72
 
73
+ audio_response_path = generate_voice_response(response)
74
+ return response, audio_response_path
 
 
75
 
76
+ def run_assistant(audio):
77
+ transcription, audio_response_path = process_audio(audio)
78
+ return transcription, audio_response_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
+ # Gradio Interface
81
+ with gr.Blocks() as demo:
82
+ gr.Markdown("# Voice-Activated Restaurant Assistant")
83
+ with gr.Row():
84
+ audio_input = gr.Audio(source="microphone", type="filepath", label="Speak Now")
85
+ text_output = gr.Textbox(label="Transcription")
86
+ audio_output = gr.Audio(label="Assistant Response")
87
 
88
+ submit_button = gr.Button("Submit")
89
+ submit_button.click(run_assistant, inputs=[audio_input], outputs=[text_output, audio_output])
 
 
90
 
91
+ demo.launch()