Creating A Virtual Assistant Using Python

Are you attempting to obtain a Python project that will familiarize you with particular Python libraries? A project that could undoubtedly help you with that is a virtual assistant.

The Python libraries used in this project can help you improve your Python programming skills. Working on this project is also enjoyable because having a virtual assistant is incredible.

Getting Started

Creating your virtual assistant can be simple or complex, depending on your desired features ( the tasks you would like your assistant to perform). This article will walk you through creating your JARVIS or ALEXA, and thus in this article, we'll be creating a virtual assistant that is capable of playing a song for you, telling you the date, and giving you information regarding a person or place.

Before proceeding, let's check out the libraries we will use for this project.

SpeechRecognition: This Python library, as the name implies, is in charge of recognizing and processing whatever command you're instructing your assistant to do through your voice. You can get this library installed by running the command:

pip install SpeechRecognition

Pyttsx3: This is a Python text-to-speech library that converts any text command you want to include in your program into speech. It's a Python cross-platform library that works flawlessly offline. install it by running the command:

pip install pyttsx3

Pywhatkit: This is an intriguing library with numerous features embedded within it. You could use this library to perform a Google search, send Whatsapp messages, or even play a YouTube video. You can install this by running the command.

pip install pywhatkit

Wikipedia: This is yet another fascinating Python library for accessing data from the Wikipedia website. With this library, you can tell your virtual assistant to look up any information on Wikipedia. Install this fantastic library by running this command on your terminal

pip install Wikipedia

DateTime: This is a Python library that lets you use dates and times in your code. This built-in Python library does not require any pip commands to install.

We begin coding now that we have a basic understanding of the libraries used in this exciting project. I will be giving the name of my virtual assistant Joan. You can name it what you want.

Steps Involved

First of all, import all the libraries the project needs

import speech_recognition as sr
import pyttsx3
import pywhatkit
import Wikipedia
import DateTime

The setup of these libraries comes next.

listener=sr.Recognizer
engine=pyttsx3.init()
voices= engine.getProperty("voices")
engine.setProproperty("voices", voices[1].id)

We set up the Recognizer and the pyttsx3 library above and modified our virtual assistant's voice to a female voice.

Next, we define a function that will say whatever component is passed to it whenever the function is called.

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

Now we'll define another function and use the try-except function. Within this defined function, we would implement the earlier setups and write codes that would allow our assistant to listen to whatever command we gave.

def take_command():
    try:
        with sr.Microphone() as source:
            print('I am listening')
            voice = listener.listen(source)
            order = listener.recognize_google(voice)
            if 'Joan' in order:
                order = order.replace('Joan', '')
                print(order)

    except:
        pass
    return order

Following this, we define another function where we will place all of the commands we want our assistant to perform.

def run_Joan():
    command = take_command()
    print(command)

With this run_Joan() function we've defined, we would place all commands that we wish our virtual assistant runs for us, and to do this, the if, elif, and 'else' statements will be used.

As we all know, the if, elif, and 'else' statements allow us to test for multiple expressions. If the condition for if is False, the condition of the next elif block is reviewed, and so on. If all of the conditions are False, the else body is implemented. We would insert the commands we want our assistant to perform with these statements.

For instance, if you want your assistant to tell you its name, you can achieve this using the if statement by placing your code indented right under the defined function you created earlier.

if 'tell me your name' in command:
  print('I am Joan....I am at your service')
  speak('I am Joan... I am at your service')

With this above program, when your virtual assistant hears the command " Tell me your name," it fulfills the task attached to it, which is to say its name.

Moving on, let's make it a bit interesting by asking our assistant to play a song for us and we use the pywhatkit library we installed earlier on. To do this, we simply run:

elif 'play' in command:
        song = command.replace('play', '')
        speak('Playing ' + song)
        pywhatkit.playonyt(song)

Notice how we've shifted from the if statement to the elif statement. This points out the explanations given earlier as regards if, elif, and else statements. We are arranging our codes in such a way that when the conditions for the if statements aren't fulfilled, it moves on to the elif statements to see if those ones can be fulfilled.

Like the previous command, when our assistant hears the word "play", it goes ahead to perform what it has been assigned to do.

Let's add a few more commands for our virtual assistant.

We want our JOAN to tell us the time, and we structure this as we've done the previous ones such that when she hears the command "time", she responds by giving the time. This is how we achieve this:

elif 'time' in command:
        time = datetime.datetime.now().strftime('%H:%M')
        print(time)
        speak('Current time is ' + time)

We've settled the time. Let us proceed to ask our JOAN to give us information regarding a place or a person. This will still be structured in the same manner as the previous codes;

elif 'who' or 'where' in command:
        answer = command.replace('who' or 'where', '')
        fact= wikipedia.summary(answer, 3)
        print(fact)
        speak(fact)

Let's also add a shutting-down command that will instruct it to turn off when it hears the word " Shut down:

elif 'Shut-down' in command:
        print('Shutting down')
        speak('Shutting down')
        quit()

The quit() function added is to make the code terminate at this point since we are asking it to turn off.

Now let's use the else statement so that whenever none of the conditions in the if and elif statements, respectively, aren't fulfilled, the conditions for the else statement would take effect.

else:
        print("I can't understand what you are saying, please come again")
        speak("I can't understand what you are saying, please come again")

For this project, the virtual assistant is only limited to performing tasks such as playing a song when you ask, telling you the date or time, or requesting information about a specific person or location.

We've put these commands in the if and elif statements, and when the assistant doesn't recognize any of the orders you give it, it executes the condition in the else statement.

The final step in this project is to put all of these codes in a while loop to ensure that your virtual assistant does not stop running commands for you unless you tell it to (if included in the commands at the if and elif statements).

To do this, add this code at the end.

while True:
    run_Joan()

We have now successfully created a personal virtual assistant.

Conclusion

The goal of this project was to become acquainted with some fascinating libraries available in Python and how to use them, and the project itself was enjoyable to work on. You can add other functions you want your assistant to perform now that you've gone over the fundamentals.

I hope you found this helpful.