0% found this document useful (0 votes)
30 views3 pages

Working 2

This Python code defines functions for a voice assistant to speak, take voice commands, open websites and applications, get information from Wikipedia, and retrieve weather data. It imports necessary libraries and initializes a text-to-speech engine. The main loop processes commands to search Wikipedia, open apps, get the time/date, check the weather for a city, and exit the program.

Uploaded by

jt332763
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views3 pages

Working 2

This Python code defines functions for a voice assistant to speak, take voice commands, open websites and applications, get information from Wikipedia, and retrieve weather data. It imports necessary libraries and initializes a text-to-speech engine. The main loop processes commands to search Wikipedia, open apps, get the time/date, check the weather for a city, and exit the program.

Uploaded by

jt332763
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import speech_recognition as sr

import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import requests

# Initialize text-to-speech engine


engine = pyttsx3.init()

# Function to speak text


def speak(text):
engine.say(text)
engine.runAndWait()

# Function to take user command through voice


def take_command():
recognizer = sr.Recognizer()

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"

# Function to open websites in the default web browser


def open_website(url):
speak(f"Opening {url}")
webbrowser.open(url)

# Function to open applications


def open_application(app_name):
app_name = app_name.lower()
if "notepad" in app_name:
speak('Opening Notepad...')
os.system("notepad.exe")
elif "calculator" in app_name:
speak('Opening Calculator...')
os.system("calc.exe")
else:
speak(f"Sorry, I don't know how to open {app_name}")

# Function to get information from Wikipedia


def get_wikipedia_summary(query):
try:
results = wikipedia.summary(query, sentences=2, srsearch=query)
speak("According to Wikipedia:")
speak(results)
except wikipedia.exceptions.WikipediaException as e:
print(f"Wikipedia Exception: {e}")
speak("Sorry, there was an issue retrieving information from Wikipedia.")

# Function to get the current weather


def get_weather(city):
# Replace 'YOUR_API_KEY' with your OpenWeatherMap API key
openweathermap_api_key = 'YOUR_API_KEY'

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?")

You might also like