Ai_voice / Ai.py
Subbu1304's picture
Create Ai.py
2d07494 verified
import pyttsx3
import speech_recognition as sr
# Initialize Text-to-Speech engine
engine = pyttsx3.init()
def speak(text):
"""Convert text to speech."""
engine.say(text)
engine.runAndWait()
def listen():
"""Capture voice input and return as text."""
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
speak("I am listening. Please speak now.")
recognizer.adjust_for_ambient_noise(source)
try:
audio = recognizer.listen(source, timeout=5)
command = recognizer.recognize_google(audio)
return command.lower()
except sr.UnknownValueError:
speak("Sorry, I could not understand. Could you repeat?")
return None
except sr.RequestError:
speak("There seems to be an issue with the voice recognition service.")
return None
except sr.WaitTimeoutError:
speak("I did not hear anything. Please try again.")
return None
def read_menu():
"""Read the menu from a text file."""
try:
with open("menu.txt", "r") as file:
menu = file.readlines()
return menu
except FileNotFoundError:
speak("Menu file not found.")
return []
def process_order(order, menu):
"""Process the voice command to identify menu items."""
selected_items = []
for item in menu:
if any(word in order for word in item.lower().split(" - ")[0].split()): # Match keywords
selected_items.append(item.strip())
return selected_items
def main():
"""Main program logic."""
speak("Welcome to the restaurant voice assistant.")
speak("Would you like to hear the menu?")
response = listen()
if response and "yes" in response:
menu = read_menu()
if menu:
speak("Here is the menu.")
for item in menu:
speak(item)
else:
return
speak("What would you like to order?")
order = listen()
if not order:
speak("I couldn't hear your order. Please try again.")
return
menu = read_menu()
selected_items = process_order(order, menu)
if selected_items:
speak("You have ordered:")
for item in selected_items:
speak(item)
speak("Would you like to confirm this order?")
confirmation = listen()
if confirmation and "yes" in confirmation:
speak("Your order has been placed successfully. Thank you!")
else:
speak("Order cancelled. Please let me know if you'd like to order something else.")
else:
speak("I couldn't match your order with any menu items. Please try again.")
if __name__ == "__main__":
main()