Create a Virtual Assistant with Python and Machine Learning

In this tutorial we will be building our own virtual assistant with Machine Learning and Python, with complete voice activation plus response to a our inquiries. From there, you can customize it to perform whatever tasks you need most.

Lets import the libraries we need for this task:

import speech_recognition as sr
import os
from gtts import gTTS
import datetime
import warnings
import calendar
import random
import wikipedia

To ignore any warnings

warnings.filterwarnings('ignore')

To Record audio and return it into a string

def recordAudio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("please say something")
        audio = r.listen(source)
    #use google speach recognition
    data = ''
    try:
        data = r.recognize_google(audio)
        print('you said '+ data)
    except sr.UnknownValueError:
        print("Sorry I failed to understand")
    except sr.RequestError as e:
        print("Request results from google" + e)
    return data

A function to get the virtual assistant respond

def assistant(text):
    print(text)
    # convert the text to speech
    myObject = gTTS(text=text, lang='en', slow=False)
    # save the converted audio to a file
    myObject.save('assistant.mp3')
    # play the converted file
    os.system('start assistant.mp3')
# A functions for wake words
def wakewords(text):
    wake = ['hey computer', 'okay computer', 'hey aman']
    text = text.lower() # converting the text to all lower case
    # check if the user command contains wake words
    for phrase in wake:
        if phrase in text:
            return True
    return False

A function to get the current date, time and month

def getDate():
    now = datetime.datetime.now()
    date = datetime.datetime.today()
    weekday = calendar.day_name[date.weekday()]
    month = now.month
    daynum = now.day
    # A list of months
    months = ["January", "February", "March",
              "April", "May", "June", "July",
              "August", "September", "October",
              "November", "December"]
    ordinal = ['1st', '2nd', '3rd',
               '4th', '5th', '6th',
               '7th', '8th','9th',
               '10th', '11th', '12th',
               '13th', '14th', '15th',
               '16th', '17th', '18th',
               '19th', '20th', '21st',
               '22nd', '23rd','24th',
               '25th', '26th', '27th',
               '28th', '29th', '30th','31st']
    return 'Today is '+weekday+' '+ months[month - 1]+ ' the '+ ordinal[daynum - 1] +'.'

A function to create Greetings

def greetings(text):
    greetings_input = ['hi', 'hey', 'hola', 'greetings', 'wassup', 'hello']
    greetings_response = ['howdy', 'whats up', 'hello', 'hey there']
    for word in text.split():
        if word.lower() in greetings_input:
            return random.choice(greetings_response) + "."
    return ''

A function to get a persons first and last name from the text

def getPerson(text):
    wordlist =  text.split()
    for i in range(0, len(wordlist)):
        if i + 3 <= len(wordlist) - 1 and wordlist[i].lower() == 'who' and wordlist[i+1].lower() == "is":
            return wordlist[i+2] + " " + wordlist[i+3]

Now let’s use these functions to build our Virtual Assistant :

while True:
    text = recordAudio()
    response = ' '
    if (wakewords(text) == True):
        response = response + greetings(text)
        if ('date' in text):
            get_Date = getDate()
            response = response + ' '+get_Date
        if ('who is' in text):
            person = getPerson(text)
            wiki = wikipedia.summary(person, sentences=2)
            response = response + ' '+ wiki
            assistant(response)

Your output will be running like this:

Please speak something

Follow us on Instagram for all your Queries

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1435

Leave a Reply