Make Personal Assistant using Python, Like Jarvis

Ever thought about having a personal assistant like Jarvis while watching Marvel. If yes then this article is for you. In this article, I have shared the source code along with the step-wise installation process. From which, you can easily make your own personal assistant using Python.

personal assistant using python

Features

So, what you can make your assistant perform? The Source Code that I have provided you here renders the following features to your Personal Assistant.

  • Wishes you: You can have morning, evening, etc. wishes from your assitant. Afterall courtsey is a must for your assitant.
  • Takes command: Definitely the primary function of an Assistant is to obey your command. It will obey all the commands, you have programmed it for.
  • Wikipedia: It also can access to wikipedia for giving you the serach results.
  • Open Browser: Your assitant will also open browser fro you to surf quickly.
  • Email: Even if you wish to mail somebody, don’t worry your assitant will do it for you.

And lastly, you can add some more features into Personal Assistant by programming in Python.
So, now let’s begin looking at the steps of making our Assitant.

Step 1 : Install Python

Firstly you should install python from its official site. The link to download Python is hereunder:

Link: https://www.python.org/downloads/

If you want a proper guide to install and set up Python. Visit: Make Super Mario Game using Python.
After successfully installing the Python and setting up the pip, now you need to install the required python packages in order to run the code.

Step 2: Required Librarires

Following are the requirements to run the source code:

See also  Convert any eBook into Audiobook: 12 lines of Python

pyttsx3: pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline, and is compatible with both Python 2 and 3.

Speech recognition: Like it, the name suggests this python packages let help your computer to recognize that what you saying.

Wikipedia: this python library helps you to fetch information from Wikipedia for us. In this Jarvis assistant using python, it used to get information from Wikipedia whenever we give him a command.

PyAudio: Pyaudio is a library written in C++ used on cross-platform. It is required in Python to play and record audio on a variety of platforms. Undoubtedly, this is the most necessary element for our project as our program is based on interaction via audio and speech.

How To Download the required library?

To install the library or you can say modules you need to open your command prompt or terminal whichever you want and enter the below commands


pip install pyttsx3
pip install speechRecognition
pip install wikipedia
pip install PyAudio

Note: If you are facing an error while installing PyAudio, don’t worry it’s common. Instead, you can install PyAudio manually.

How to Install PyAudio manually?

Above is a Youtube Video that can help you. Otherwise, you can Google or search it on Youtube, you’ll find an abundance of Tutorials there.

Step 3: Source Code

Now, If you have successfully completed the previous steps, its time for you to finally get the Source Code:

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)


➡️

In this part of the code, I have initialized the voice of the assistant and set the voice engine property.

import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)


➡️

In this part of the code, I have initialized the voice of the assistant and set the voice engine property.


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

    elif hour>=12 and hour<18:
        speak("Good Afternoon!")   

    else:
        speak("Good Evening!")  

    speak("I am Jarvis Sir. Please tell me how may I help you")       

def takeCommand():
    #It takes microphone input from the user and returns string output

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        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")

    except Exception as e:
        # print(e)    
        print("Say that again please...")  
        return "None"
    return query

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password')
    server.sendmail('youremail@gmail.com', to, content)
    server.close()


➡️

Now I have set some commands. if some say the command then it will be responded to the command

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        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)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")   


        elif 'play music' in query:
            music_dir = 'D:\\Non Critical\\songs\\Favorite Songs2'
            songs = os.listdir(music_dir)
            print(songs)    
            os.startfile(os.path.join(music_dir, songs&#91;0]))

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")    
            speak(f"Sir, the time is {strTime}")

        elif 'open code' in query:
            codePath = "C:\\Users\\Haris\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)

        elif 'email to friend' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "yourfriendEmail@gmail.com"    
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry. I am not able to send this email")    </code></pre>
<!-- /wp:code -->


➡️

This part of code is for expectation like when anything is wrong or else condition for the code.

Here is the complete source

import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)


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

    elif hour>=12 and hour<18:
        speak("Good Afternoon!")   

    else:
        speak("Good Evening!")  

    speak("I am Jarvis Sir. Please tell me how may I help you")       

def takeCommand():
    #It takes microphone input from the user and returns string output

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        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")

    except Exception as e:
        # print(e)    
        print("Say that again please...")  
        return "None"
    return query

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password')
    server.sendmail('youremail@gmail.com', to, content)
    server.close()

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        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)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")   


        elif 'play music' in query:
            music_dir = 'D:\\Non Critical\\songs\\Favorite Songs2'
            songs = os.listdir(music_dir)
            print(songs)    
            os.startfile(os.path.join(music_dir, songs[0]))

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")    
            speak(f"Sir, the time is {strTime}")

        elif 'open code' in query:
            codePath = "C:\\Users\\Haris\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)

        elif 'email to friend' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "yourfriendEmail@gmail.com"    
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry. I am not able to send this email")    

Note: make sure you don’t make any indentation error while copying with the code. Also before running the program make sure you have installed the required modules.

Source Code Link =>

See also  Key Logger | Python

https://drive.google.com/file/d/1AmAZyG4KDx7962QTADlge7gWyJNsoyEF/view?usp=drivesdk

3 thoughts on “Make Personal Assistant using Python, Like Jarvis”

Leave a Comment

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock