Sre Assignment
Sre Assignment
SRE ASSIGNMENT # 03
Submitted by:
Muhammad Hasher F-301039
Amna Arooj F-301055
Amna Shaukat F-301022
SE – 03
Instructor:
Engr. Saiqa Anjum
Date:
18 DEC 23
Module # 01:
Original Code:
import pyttsx3
import speech_recognition as sr
import datetime
import wikipediaapi
import wikipedia
import webbrowser
import os
wiki_wiki = wikipediaapi.Wikipedia(
language='en', user_agent='JarvisAssistant/1.0'
) # Use 'en' for English Wikipedia, or the appropriate language code for other languages.
engine = pyttsx3.init('sapi5')
voices = engine.getProperty("voices")
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
else:
speak("Good Evening")
def takeCommand():
r = sr.Recognizer()
print("\n\nListening....")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing.....🙂")
except Exception as e:
#print(e)
return "None"
return query
if __name__ == "__main__":
active_voice = engine.getProperty('voice')
wishMe()
while True:
query = takeCommand().lower()
if 'wikipedia' in query:
speak('Searching Wikipedia....')
speak('According to Wikipedia')
print(results)
speak(results)
webbrowser.open("youtube.com")
webbrowser.open("youtube.com")
webbrowser.open("google.com")
webbrowser.open("stackoverflow.com")
webbrowser.open("whatsapp.com")
webbrowser.open("gmail.com")
webbrowser.open("chrome.com")
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir,songs[0]))
This code piece essentially creates a virtual assistant capable of speech synthesis, listening to voice
commands, performing Wikipedia searches, and executing predefined actions like opening websites and
playing music based on recognized commands.
Program Code:
# Import necessary libraries/modules
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
engine = pyttsx3.init('sapi5')
voices = engine.getProperty("voices")
engine.setProperty('voice', voices[0].id)
# Function to speak using the initialized engine
def speak(audio):
engine.say(audio)
engine.runAndWait()
def greet_user():
hour = datetime.datetime.now().hour
greeting = "Good Morning" if 0 <= hour < 12 else "Good Afternoon" if 12 <= hour < 18 else "Good
Evening"
speak(f"{greeting} buddy")
def listen_to_command():
recognizer = sr.Recognizer()
print("\n\nListening....")
recognizer.pause_threshold = 1
audio = recognizer.listen(source)
try:
print("Recognizing.....")
except Exception as e:
return "None"
def search_wikipedia(query):
if 'wikipedia' in query:
speak('Searching Wikipedia....')
# Remove the word 'wikipedia' from the query for accurate search
speak('According to Wikipedia')
print(results)
speak(results)
def open_website(query):
websites = {
'youtube': 'youtube.com',
'google': 'google.com',
'stackoverflow': 'stackoverflow.com',
'whatsapp': 'whatsapp.com',
'facebook': 'facebook.com',
'gmail': 'gmail.com',
'chrome': 'chrome.com'
webbrowser.open(websites[site])
break
def play_music(query):
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir, songs[0]))
if __name__ == "__main__":
active_voice = engine.getProperty('voice')
greet_user()
while True:
user_query = listen_to_command()
search_wikipedia(user_query)
open_website(user_query)
play_music(user_query)
Changes Made:
Function Decomposition:
Created a dictionary websites to map user queries to website URLs for open_website() function.
Each function now performs a specific task, enhancing readability and maintainability of the code.
Commentary:
Provided comments for certain functions to clarify their purpose and functionality.
Module # 02:
This code essentially sets up a virtual assistant capable of speech synthesis, interacting with the YouTube
API to play random music videos, and responding to user commands entered through the console for
playing music or exiting the program.
Original Code:
import os
import random
import pyttsx3
def speak(audio):
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine.say(audio)
engine.runAndWait()
def get_random_music_video(api_key):
search_response = youtube.search().list(
q="random music",
type="video",
part="id",
maxResults=50
).execute()
video_ids = [item['id']['videoId'] for item in search_response['items']]
random_video_id = random.choice(video_ids)
return random_video_id
def play_youtube_music(api_key):
try:
video_id = get_random_music_video(api_key)
video_url = f"https://www.youtube.com/watch?v={video_id}"
os.system(f"start {video_url}")
except Exception as e:
if __name__ == "__main__":
api_key = 'AIzaSyDJzrFNJGfFmPMX06ivYsFLM63oertcKos'
while True:
play_youtube_music(api_key)
break
Program Code:
# Import necessary libraries/modules
import os
import random
import pyttsx3
def initialize_engine():
search_response = youtube.search().list(
q="random music",
type="video",
part="id",
maxResults=50
).execute()
# Extract video IDs from the search response
random_video_id = random.choice(video_ids)
try:
os.system(f"start {video_url}") # Start playing the video using the default media player
except Exception as e:
if __name__ == "__main__":
tts_engine = initialize_engine()
speak("I am your virtual assistant. How can I help you?", tts_engine) # Speak an introductory message
while True:
query = input("You: ").lower() # Get user input from the console and convert to lowercase
if 'play music' in query:
# Play a random music video using the YouTube API and speech synthesis engine
break
# Exit the loop and end the program if 'exit' command is received
Changes Made:
Function Segregation:
Separated the speak() function to solely handle speech synthesis using the initialized engine.
Parameter Passing:
Modified functions to accept the required parameters (engine, youtube) instead of relying on global
variables.
Moved the try-except block inside the play_youtube_music() function for better error handling.
Code Readability:
Kept the API key as a variable (api_key) for easy replacement. Replace <YOUR_API_KEY> with your actual
API key.
Ensured consistent use of the speak() function for speech synthesis throughout the code.