Spaces:
Sleeping
Sleeping
Create voice_assistant.py
Browse files
components/voice_assistant.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pyttsx3
|
| 3 |
+
import speech_recognition as sr
|
| 4 |
+
from utils.state_management import state
|
| 5 |
+
from utils.excel_operations import read_excel
|
| 6 |
+
|
| 7 |
+
def voice_assistant():
|
| 8 |
+
recognizer = sr.Recognizer()
|
| 9 |
+
engine = pyttsx3.init()
|
| 10 |
+
|
| 11 |
+
def speak_response(text):
|
| 12 |
+
engine.say(text)
|
| 13 |
+
engine.runAndWait()
|
| 14 |
+
|
| 15 |
+
def process_voice_command(audio):
|
| 16 |
+
try:
|
| 17 |
+
# Recognize speech
|
| 18 |
+
command = recognizer.recognize_google(audio)
|
| 19 |
+
if "menu" in command.lower():
|
| 20 |
+
return fetch_menu()
|
| 21 |
+
elif "cart" in command.lower():
|
| 22 |
+
return view_cart()
|
| 23 |
+
elif "place order" in command.lower():
|
| 24 |
+
return place_order()
|
| 25 |
+
else:
|
| 26 |
+
return "Sorry, I didn't understand that command."
|
| 27 |
+
except Exception as e:
|
| 28 |
+
return f"Error processing voice command: {str(e)}"
|
| 29 |
+
|
| 30 |
+
def fetch_menu():
|
| 31 |
+
if not state.get("user"):
|
| 32 |
+
return "Please log in first to view the menu."
|
| 33 |
+
menu = read_excel("data/menu.xlsx")
|
| 34 |
+
menu_list = "\n".join([f"{item['Name']} - {item['Price']} ₹" for item in menu])
|
| 35 |
+
speak_response(menu_list)
|
| 36 |
+
return menu_list
|
| 37 |
+
|
| 38 |
+
def view_cart():
|
| 39 |
+
cart = state.get("cart", [])
|
| 40 |
+
if not cart:
|
| 41 |
+
return "Your cart is empty."
|
| 42 |
+
cart_details = "\n".join([f"{item['Item']} - {item['Spice Level']}" for item in cart])
|
| 43 |
+
speak_response(cart_details)
|
| 44 |
+
return cart_details
|
| 45 |
+
|
| 46 |
+
def place_order():
|
| 47 |
+
if not state.get("cart"):
|
| 48 |
+
return "Your cart is empty."
|
| 49 |
+
speak_response("Your order has been placed successfully!")
|
| 50 |
+
state["cart"] = []
|
| 51 |
+
return "Order placed successfully!"
|
| 52 |
+
|
| 53 |
+
def record_and_process_voice():
|
| 54 |
+
with sr.Microphone() as source:
|
| 55 |
+
speak_response("Listening for your command...")
|
| 56 |
+
audio = recognizer.listen(source)
|
| 57 |
+
return process_voice_command(audio)
|
| 58 |
+
|
| 59 |
+
with gr.Group():
|
| 60 |
+
gr.Markdown("### Voice Assistant")
|
| 61 |
+
gr.Button("Start Listening").click(record_and_process_voice, outputs="Response")
|