You are on page 1of 9

import speech_recognition as sr

import pyttsx3

class DeviceController:
def __init__(self):
self.devices = {
"lights": {"status": "off"},
"fan": {"status": "off"},
# Add more devices as
needed
}
def control_device(self,
device_name, action):
if device_name in
self.devices:
if action == "turn on":
self.devices[device_name]
["status"] = "on"
print(f"{device_name.capitalize()}
turned on.")
elif action == "turn off":
self.devices[device_name]
["status"] = "off"
print(f"{device_name.capitalize()}
turned off.")
else:
print("Invalid action.
Use 'turn on' or 'turn off'.")
else:
print(f"Device
'{device_name}' not found.")
def listen():
recognizer = sr.Recognizer()

with sr.Microphone() as
source:
print("Listening...")
recognizer.adjust_for_ambient_n
oise(source)
audio =
recognizer.listen(source)

try:
print("Recognizing...")
return
recognizer.recognize_google(aud
io).lower()
except sr.UnknownValueError:
print("Sorry, could not
understand audio.")
return ""
except sr.RequestError as e:
print(f"Could not request
results from Google Speech
Recognition service; {e}")
return ""

def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def answer_question(question):
# Hypothetical function to
answer questions
if "who" in question:
return "I am an AI
assistant."
elif "what" in question:
return "I can perform
various tasks."
else:
return "I'm sorry, I don't
have information on that."

if __name__ == "__main__":
device_controller =
DeviceController()

while True:
command = listen()

if "turn on lights" in
command:
device_controller.control_device(
"lights", "turn on")
speak("Lights are on.")
elif "turn off lights" in
command:
device_controller.control_device(
"lights", "turn off")
speak("Lights are off.")
elif "answer" in command:
question =
command.replace("answer",
"").strip()
response =
answer_question(question)
speak(response)
elif "goodbye" in command:
speak("Goodbye!")
break
else:
speak("Sorry, I didn't
understand that command.")

You might also like