Working 2
Working 2
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import requests
try:
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source, timeout=5, phrase_time_limit=5)
if audio:
print("Recognizing...")
query = recognizer.recognize_google(audio, language='en-US')
print(f"User: {query}\n")
return query.lower()
else:
print("No audio detected.")
speak("Sorry, I couldn't hear anything. Can you please repeat?")
return "None"
except sr.UnknownValueError:
print("Speech Recognition could not understand audio.")
speak("Sorry, I couldn't understand that. Can you please repeat?")
return "None"
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service;
{e}")
speak("Sorry, there was an error. Please check your internet connection.")
return "None"
except Exception as e:
print(f"An unexpected error occurred: {e}")
speak("Sorry, something went wrong. Can you please repeat?")
return "None"
base_url = f"http://api.openweathermap.org/data/2.5/weather?
q={city}&appid={openweathermap_api_key}&units=metric"
response = requests.get(base_url)
weather_data = response.json()
if weather_data["cod"] == "404":
speak("Sorry, I couldn't retrieve the weather information for that
location.")
return
try:
main_info = weather_data["main"]
temperature = main_info["temp"]
description = weather_data["weather"][0]["description"]
speak(f"The current temperature in {city} is {temperature} degrees Celsius
with {description}.")
except KeyError as e:
print(f"Error accessing weather data: {e}")
speak("Sorry, there was an issue retrieving the weather information.")
# Main program
while True:
query = take_command().lower()
if 'wikipedia' in query:
speak('Searching Wikipedia...')
query = query.replace("wikipedia", "")
get_wikipedia_summary(query)
elif 'open notepad' in query:
open_application("notepad")
elif 'open calculator' in query:
open_application("calculator")
elif 'open website' in query:
speak("Which website would you like to open?")
website = take_command()
open_website(website)
elif 'time' in query:
current_time = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"The current time is {current_time}")
elif 'date' in query:
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
speak(f"Today's date is {current_date}")
elif 'weather' in query:
speak("Sure, for which city?")
city = take_command()
get_weather(city)
elif 'exit' in query or 'bye' in query:
speak('Goodbye!')
exit()
else:
speak("Sorry, I didn't understand that command. Can you please repeat?")