Make Your Own Jarvis Using Python

ยท

6 min read

Make Your Own Jarvis Using Python

Hello, buddies! Do you remember Jarvis who helped Tony Stark? Sure you can remember that cool bot. What about your own Jarvis? Since Tony Stark is not with us anymore, we have to make our own Jarvis without any help! Haha, don't worry, I will show you how to make your Jarvis!

Prerequisites

  • Basic knowledge of Python.

  • And the modules,

Install

 pip install PackageName

Import

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

Coding Time!

Your favorite time! Let's go!

Speak() Function

The first and foremost thing for an A.I. assistant is that it should be able to speak. To make our JARVIS talk, we will make a function called speak(). This function will take audio as an argument, and then it will pronounce it.

def speak(audio):
       pass      #For now, we will write the conditions later.

Now, the next thing we need is audio. We must supply audio so that we can pronounce it using the speak() function we made. We are going to install a module called pyttsx3. To install pyttsx3 you can open the terminal and type

pip install pyttsx

After that, pyttsx is imported(Code in Prerequisites)!

import pyttsx3

engine = pyttsx3.init('sapi5')

voices= engine.getProperty('voices') #getting details of current voice

engine.setProperty('voice', voice[0].id)

What is sapi5?

  • Microsoft developed speech API.

  • Helps in synthesis and recognition of voice.

What Is VoiceId?

  • Voice id helps us to select different voices.

  • voice[0].id = Male voice

  • voice[1].id = Female voice

def speak(audio):

engine.say(audio) 

engine.runAndWait() #Without this command, speech will not be audible to us.

main() Function

We will create a main() function, and inside this main() Function, we will call our speak function.

if __name__=="__main__" :

speak("Unity Buddy Will Help You!")

Whatever you will write inside this speak() function will be converted into speech

wishMe() Function

We will create wishMe function to make Jarvis more polite. It means to wish us before talking.

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

So this is a simple function. hour means current time in your area. If it is greater than or equal to 00:00 and lesser than 12:00, Jarvis says "Good Morning!"

  • If the time is between 12:00 and 18:00, it's "Good Afternoon!".

  • Else, it means between 18:00 and 00:00, it is "Good Evening!"

takeCommand() Function

The next most important thing for our Jarvis is that it should take command with the help of the microphone of the user's system. So, now we will make a takeCommand() function. With the help of the takeCommand() function, our Jarvis will return a string output by taking microphone input from the user. Cool right? ๐Ÿ˜Ž๐Ÿ˜Ž

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') ##Using google for voice recognition.
        print(f"User said: {query}\n") #User query will be printed.

    except Exception as e:
        # print(e)
        print("Say that again please...") # #Say that again will be printed in case of improper voice
        return "None"   #None string will be returned(rarely)
    return query

Yay! You've successfully created takeCommand(). Well done buddy!

Logic Of Jarvis

To open YouTube site in a web-browser To open any website, we need to import a module called webbrowser. It is an in-built module, and we do not need to install it with a pip statement; we can directly import it into our program by writing an import statement.

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower() #Converting user query into lower case

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

To open Google in a web-browser

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

To Play Music

  elif 'play music' in query:
            music_dir = 'D:\MyPlayList' # Your path
            songs = os.listdir(music_dir)
            print(songs)
            os.startfile(os.path.join(music_dir, songs[0]))

And many as you want! Here are the full code of commands that I added.

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()

        if '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:\MyPlayList'
            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\chenuli\AppData\Local\Programs\Microsoft VS Code\levelmenu.exe"
            os.startfile(codePath)

sendEmail()

We will create a sendEmail() function, which will help us send emails to one or more than one recipient. ๐Ÿ“ง

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

What is smtplib?

  • Simple Mail Transfer Protocol (SMTP) is a protocol that allows us to send emails and to route emails between mail servers. An instance method called sendmail is present in the SMTP module. This instance method allows us to send an email. It takes 3 parameters:
  1. The sender: Email address of the sender.

  2. The receiver: Email of the receiver.

  3. The message: A string message which needs to be sent to one or more than one recipient.

Call sendEmail() function inside the main() function:

 elif 'email to Victoria' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "chenuliilz@gmail.com.com"
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry my friend Unity buddy. I am not able to send this email") # If you email and password is incorrect.

You're Done! ๐ŸŽŠ๐ŸŽŠ

You're a good buddy! This is the full code that we wrote.

import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
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('boobagames123@gmail.com', 'hacker123')
    server.sendmail('boobagames123@gmail.com', to, content)
    server.close()

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()

        if '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:\MyPlayList'
            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\\chenuli\\AppData\\Local\\Programs\\Microsoft VS Code\\levelmenu.exe"
            os.startfile(codePath)

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

Is Our Jarvis And AI?

Many people will argue that the virtual assistant that we have created is not an AI, but it is the output of a bunch of the statement. But, if we look at the fundamental level, the sole purpose of A.I develop machines that can perform human tasks with the same effectiveness or even more effectively than humans.

It is a fact that our virtual assistant is not a very good example of AI, but it is an AI !

Happy Coding!

ย