Virtual Assistant: Fun Coding
Code for yourself.
Having your own Virtual assistant is really cool thing. But you will find it more interesting if you indulge in the process of making your own Virtual Assistant (or AI Assistant) with help of python libraries.
What’s Virtual Assistant?
It’s an application program that understands natural language voice commands and completes tasks for the user.
Today, we will be making a Virtual Assistant called “Steffi” with help of some great python libraries(Install the packages before starting the project).
This program will do specific tasks once it is activated with voice instructions.
Some tasks done by Steffi
- Wishes you after running the program.
- Asks your name.
- Search Wikipedia
- Play music
So on...
Start Coding with Importing the libraries:
import datetime
import speech_recognition as sr
import pyttsx3
import wikipedia
import webbrowser
import os
import shutil
import time
import pyjokes
- wikipedia: It is used to fetch a variety of information from the Wikipedia website
- speech-recognition: It allows us to convert audio into text.
- pyttsx3: It is a text-to-speech conversion.
- webbrowser: It provides a high-level interface that allows displaying Web-based documents to users.
- OS: The OS module in Python provides functions for interacting with the operating system.
Next part of the program that creates an engine which is used in speak( ) function,
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)
engine.setProperty('rate', 150)
print(type(engine))
print(engine)
SAPI5: Microsoft Speech API (SAPI5) is the technology for voice recognition and synthesis provided by Microsoft
In the third line, you can change the index to change voice
voice[1].id = For Female voice
voice[0].id = For Male voice
Functions to perform tasks
These functions are like the core part of your virtual assistant.
- To speak, Text to Speech
def speak(audio):
engine.say(audio)
engine.runAndWait()
- Wanna know the Day: This function is for telling the day of the week
def tellDay():
day = datetime.datetime.today().weekday() + 1
Day_dict = {1: 'Monday', 2: 'Tuesday',3: 'Wednesday', 4:'Thursday',5: 'Friday', 6: 'Saturday',7: 'Sunday'}
if day in Day_dict.keys():
day_of_the_week = Day_dict[day]
print(day_of_the_week)
speak("The day is " + day_of_the_week)
- Wish me: Steffi is gonna wish you
def wishMe():
hour=int(datetime.datetime.now().hour)
time_now = time.strftime("%H:%M:%p")
if (hour >= 0 and hour < 12):
speak(f"Good Morning Boss!, its {time_now}")
elif(hour >= 12 and hour < 18):
speak(f"Good Afternoon Boss, its {time_now}")
else:
speak(f"Good Evening Boss, its {time_now}")
speak("I am Steffi, Your Virtual Assistant ")
- Let Steffi know who are you…Okay
def usrname():
speak("What should i call you sir")
uname = takeCommand()
speak("Welcome Mister")
speak(uname)
columns = shutil.get_terminal_size().columns
- Take command: It takes microphone input from the user and returns the string output.
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source: print("Listening...")
r.pause_threshold = 1
r.energy_threshold =300
audio = r.listen(source) try: print("Recognising...")
query=r.recognize_google(audio,language="en-in")
print(f"User said: {query}\n") except Exception as e:
print(e)
print("Say that again please!")
#speak("Say that again please!") return "None" return query
r.pause_threshold = 1 It refers to the amount of time gap after which the audio is supposed to be complete.
audio=r.listen(source) Digital data of whatsoever has been spoken will be stored in the audio.
- Main function: This Function will clean any command before execution of this python file.
if __name__ == '__main__':
clear = lambda: os.system('cls') clear() wishMe() usrname()
Here comes the fun part. You can code here whatever you want that your Digital Assistant do for you with the voice instruction.
while True:#if 1: # To run Steffi only once query = takeCommand().lower()#logic for executing tasks 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)
Continue...
elif 'open facebook' in query: webbrowser.open("fb.com")
elif 'open youtube' in query: webbrowser.open("youtube.com")elif 'google' in query:\ query=query.replace("google","") query=query.replace("search","") webbrowser.open("https://google.com/search?q=%s" % query)elif 'open stack overflow' in query: webbrowser.open("stackoverflow.com")elif (('music' in query) or ("song" in query)):# music_dir = "path of music folder with \\ instead of using single \" music_dir = 'enter path here of music directory.' songs = os.listdir(music_dir) #print(songs)
os.startfile(os.path.join(music_dir,songs[0])) elif 'how are you' in query:
speak("I am fine, thank you") speak("how are you, sir")elif 'fine' in query in query or 'I am good' in query: speak("it's good to know, sir")elif 'who created you' in query: speak("I have been created by Sanchit")elif "which day it is" in query: tellDay()elif 'time' in query: time = datetime.datetime.now().strftime("%H:%M:%S") speak("Sir, the time is") speak(time) print(time)elif 'open notepad' in query:# path = " enter notepad path" path = "C:\\WINDOWS\\system32\\notepad.exe" os.startfile(path)elif 'tell me a joke' in query: speak(pyjokes.get_joke())elif 'open command prompt' in query: os.system("start cmd")
elif "time to sleep" in query or "stop listening" in query or "no thanks" in query: speak("Thanks for using me sir, Have a good day") #subprocess.call("shutdown / h") exit()speak("sir, do you have any other work!")
“Steffi” is a virtual assistant for basic works. However, you can enhance its functionality according to your needs.
Enjoy your personal Virtual Assistant Steffi.. Or name yours What you want!!
Any Suggestion, How we can enhance the Functionality ??
Comment below...