Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

DEPARTMENT OF SOFTWARE ENGINEERING

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

# Rest of your code here...

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

engine.setProperty('voice', voices[0].id) # Set the voice to the first voice

def speak(audio):

engine.say(audio)

engine.runAndWait()

def wishMe():

hour = int(datetime.datetime.now().hour)

if hour>=0 and hour<12 :

speak("Good Morning buddy")


elif hour>=12 and hour<18:

speak("Good Afternoon buddy")

else:

speak("Good Evening")

speak("I m your virtual assissant. How can i help you ")

def takeCommand():

r = sr.Recognizer()

with sr.Microphone() as source:

print("\n\nListening....")

r.pause_threshold = 1

audio = r.listen(source)

try:

print("Recognizing.....🙂")

query = r.recognize_google(audio, language='en-in')

print(f"user said:🔊 {query}\n\n")

except Exception as e:

#print(e)

print("say that again please...")

return "None"

return query
if __name__ == "__main__":

# Get the currently active voice

active_voice = engine.getProperty('voice')

print("Active Voice ID:", active_voice)

wishMe()

while True:

query = takeCommand().lower()

#logic for executing task based on query

if 'wikipedia' in query:

speak('Searching Wikipedia....')

query = query.replace("wikipedia", "")

results = wikipedia.summary(query, sentences=2)

speak('According to Wikipedia')

print(results)

speak(results)

elif query == 'open youtube':

webbrowser.open("youtube.com")

elif query == 'open youtube':

webbrowser.open("youtube.com")

elif query == 'open google':

webbrowser.open("google.com")

elif query == 'open stackoverflow':

webbrowser.open("stackoverflow.com")

elif query == 'open whatsapp':

webbrowser.open("whatsapp.com")

elif query == 'open facebook':


webbrowser.open("facebook.com")

elif query == 'open gmail':

webbrowser.open("gmail.com")

elif query == 'open chrome':

webbrowser.open("chrome.com")

elif 'play music' in query:

music_dir = "F:\\mobile data\\Download\\MusicDownload"

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

# Initialize the speech synthesis engine

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()

# Function to greet the user based on the time of day

def greet_user():

hour = datetime.datetime.now().hour

# Determine the appropriate greeting based on the time

greeting = "Good Morning" if 0 <= hour < 12 else "Good Afternoon" if 12 <= hour < 18 else "Good
Evening"

# Speak the greeting and an introductory message

speak(f"{greeting} buddy")

speak("I'm your virtual assistant. How can I help you?")

# Function to listen to user commands via microphone input

def listen_to_command():

recognizer = sr.Recognizer()

with sr.Microphone() as source:

print("\n\nListening....")

recognizer.pause_threshold = 1

audio = recognizer.listen(source)

try:

print("Recognizing.....")

# Use Google's speech recognition to convert audio to text

query = recognizer.recognize_google(audio, language='en-in')

print(f"user said:🔊 {query}\n\n")


return query.lower()

except Exception as e:

print("Say that again please...")

return "None"

# Function to search Wikipedia based on user query

def search_wikipedia(query):

if 'wikipedia' in query:

speak('Searching Wikipedia....')

# Remove the word 'wikipedia' from the query for accurate search

query = query.replace("wikipedia", "")

# Get Wikipedia summary and speak the results

results = wikipedia.summary(query, sentences=2)

speak('According to Wikipedia')

print(results)

speak(results)

# Function to open specific websites based on user query

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'

for site in websites:


# Check if the query matches any of the predefined websites

if f"open {site}" == query:

# Open the corresponding website in a web browser

webbrowser.open(websites[site])

break

# Function to play music based on user query

def play_music(query):

if 'play music' in query:

music_dir = "F:\\mobile data\\Download\\MusicDownload"

songs = os.listdir(music_dir)

print(songs)

# Play the first music file in the specified directory

os.startfile(os.path.join(music_dir, songs[0]))

# Main program execution starts here

if __name__ == "__main__":

active_voice = engine.getProperty('voice')

print("Active Voice ID:", active_voice)

# Greet the user and introduce the virtual assistant

greet_user()

# Continuously listen to user commands and perform actions accordingly

while True:

user_query = listen_to_command()

# Perform actions based on recognized user query

search_wikipedia(user_query)
open_website(user_query)

play_music(user_query)

Changes Made:
Function Decomposition:

Introduced functions like greet_user(), listen_to_command(), search_wikipedia(), open_website(), and


play_music() to encapsulate specific functionalities.

Improved Variable Naming:

Renamed wishMe() to greet_user(), takeCommand() to listen_to_command().

Used descriptive function names for improved readability.

Error Handling Enhancement:

Added try-except block in listen_to_command() function for better error handling.

Use of Constants (Website Dictionary):

Created a dictionary websites to map user queries to website URLs for open_website() function.

Encapsulation and Readability:

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

from googleapiclient.discovery import build

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):

youtube = build('youtube', 'v3', developerKey=api_key)

# Perform a search for random music videos

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:

# Fetch a random music video

video_id = get_random_music_video(api_key)

video_url = f"https://www.youtube.com/watch?v={video_id}"

# Play the music using the default media player

os.system(f"start {video_url}")

except Exception as e:

print("Error playing the music:", str(e))

if __name__ == "__main__":

# Replace '<YOUR_API_KEY>' with your actual API key

api_key = 'AIzaSyDJzrFNJGfFmPMX06ivYsFLM63oertcKos'

speak("I am your virtual assistant. How can I help you?")

while True:

query = input("You: ").lower()

if 'play music' in query:

play_youtube_music(api_key)

elif 'exit' in query:

speak("Goodbye! Have a great day!")

break
Program Code:
# Import necessary libraries/modules

import os

import random

from googleapiclient.discovery import build

import pyttsx3

# Function to initialize the speech synthesis engine

def initialize_engine():

engine = pyttsx3.init('sapi5') # Initialize the speech synthesis engine

voices = engine.getProperty('voices') # Get available voices

engine.setProperty('voice', voices[0].id) # Set the voice to the first available one

return engine # Return the initialized engine

# Function to speak using the initialized engine

def speak(audio, engine):

engine.say(audio) # Speak the provided text

engine.runAndWait() # Wait for the speech to complete

# Function to get a random music video ID using YouTube API

def get_random_music_video(api_key, youtube):

# Search for random music videos using YouTube API

search_response = youtube.search().list(

q="random music",

type="video",

part="id",

maxResults=50

).execute()
# Extract video IDs from the search response

video_ids = [item['id']['videoId'] for item in search_response['items']]

# Choose a random video ID from the retrieved IDs

random_video_id = random.choice(video_ids)

return random_video_id # Return the randomly selected video ID

# Function to play a YouTube music video

def play_youtube_music(api_key, engine, youtube):

try:

# Get a random music video ID

video_id = get_random_music_video(api_key, youtube)

video_url = f"https://www.youtube.com/watch?v={video_id}" # Construct the video URL

os.system(f"start {video_url}") # Start playing the video using the default media player

except Exception as e:

print("Error playing the music:", str(e)) # Print error if there's an exception

if __name__ == "__main__":

api_key = '<YOUR_API_KEY>' # Replace with your actual YouTube API key

# Build the YouTube API service object

youtube = build('youtube', 'v3', developerKey=api_key)

# Initialize the speech synthesis engine

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

play_youtube_music(api_key, tts_engine, youtube)

elif 'exit' in query:

speak("Goodbye! Have a great day!", tts_engine) # Speak a farewell message

break

# Exit the loop and end the program if 'exit' command is received

Changes Made:
Function Segregation:

Created an initialize_engine() function to handle engine initialization for speech synthesis.

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.

Error Handling Improvement:

Moved the try-except block inside the play_youtube_music() function for better error handling.

Code Readability:

Used more descriptive variable names (engine, tts_engine) for clarity.

API Key Replacement:

Kept the API key as a variable (api_key) for easy replacement. Replace <YOUR_API_KEY> with your actual
API key.

Consistent Speech Synthesis:

Ensured consistent use of the speak() function for speech synthesis throughout the code.

You might also like