import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
# Initialize text-to-speech engine
engine = pyttsx3.init()
def speak(text):
"""Convert text to speech."""
engine.say(text)
engine.runAndWait()
def recognize_speech():
"""Capture voice input and convert it to text."""
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
print("Recognizing...")
query = recognizer.recognize_google(audio)
print(f"User said: {query}")
return query.lower()
except sr.UnknownValueError:
print("Sorry, I couldn't understand. Please try again.")
return ""
except sr.RequestError:
print("Network error. Please check your connection.")
return ""
def greet():
"""Greet the user based on the time of day."""
hour = datetime.datetime.now().hour
if hour < 12:
speak("Good morning!")
elif 12 <= hour < 18:
speak("Good afternoon!")
else:
speak("Good evening!")
speak("How can I assist you?")
def execute_command(command):
"""Execute commands based on user input."""
if "time" in command:
current_time = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"The current time is {current_time}")
elif "date" in command:
today_date = datetime.date.today().strftime("%B %d, %Y")
speak(f"Today's date is {today_date}")
elif "wikipedia" in command:
speak("Searching Wikipedia...")
command = command.replace("wikipedia", "")
try:
result = wikipedia.summary(command, sentences=2)
speak("According to Wikipedia, " + result)
except wikipedia.exceptions.PageError:
speak("I couldn't find any results.")
elif "open google" in command:
speak("Opening Google")
webbrowser.open("https://www.google.com")
elif "open youtube" in command:
speak("Opening YouTube")
webbrowser.open("https://www.youtube.com")
elif "play music" in command:
music_dir = "C:\\Users\\Public\\Music" # Change to your music folder path
songs = os.listdir(music_dir)
if songs:
os.startfile(os.path.join(music_dir, songs[0]))
else:
speak("No music found in the directory.")
elif "exit" in command or "stop" in command:
speak("Goodbye! Have a great day!")
exit()
else:
speak("I'm sorry, I didn't understand that.")
# Main loop
if __name__ == "__main__":
greet()
while True:
user_command = recognize_speech()
if user_command:
execute_command(user_command)