Project 1: Iron Man Jarvis AI Desktop Voice Assistant | Python Tutorials For Absolute Beginners #120

Code as described/written in the video

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 harry' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "harryyourEmail@gmail.com"    
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry my friend harry bhai. I am not able to send this email")    


Comments(38)

sikendra1234 at 2019-06-23 09:30:09 says
thanks a lot harry bhai for such an awesome vedio. please make some more vedio related to project. please a series of vedio on AI
harry at 2019-06-23 09:30:09 says
Sure brother. I will surely add more videos soon!
kartik100 at 2019-06-23 09:30:09 says
Could not find PyAudio; check installation Sir, I am facing this error, please help.
kartik100 at 2019-06-23 09:30:09 says
how can i change speeking language to hindi
utkarsh at 2019-06-23 09:30:09 says
https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio This should help you :)
nishankt139 at 2019-06-23 09:30:09 says
I m facing attribute error: __enter__. What should I do ????
Mihir787 at 2019-06-23 09:30:09 says
Harry bhai I got error same like I mentioned here https://stackoverflow.com/questions/55984129/attributeerror-could-not-find-pyaudio-check-installation-cant-use-speech-re After that I installed visual studio c++ build tools but then after also error occurred
Kabir12 at 2019-06-23 09:30:09 says
Hi Harry I m not able to give commands to the project it notify me with "unanticipated host error"
Sankalp@1234 at 2019-06-23 09:30:09 says
sir after installing pyaudio it gives error "Please build and install the PortAudio Python bindings first."can anyone tell what is this also sir your work is very appreciable...
Jaisu at 2019-06-23 09:30:09 says
jarvis quite function not working plz help me out from this
ratan at 2019-06-23 09:30:09 says
Harry bhai mere Listen function exit nhi ho raha. Wo kewal listening hi kr raha h
manojkumarmk at 2019-06-23 09:30:09 says
hello when I run this program it shows error $ python jarvismjk.py Traceback (most recent call last): File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyttsx3\__init__.py", line 44, in init eng = _activeEngines[driverName] File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\weakref.py", line 137, in __getitem__ o = self.data[key]() KeyError: 'sapi5' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "jarvismjk.py", line 9, in <module> engine = pyttsx3.init('sapi5') File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyttsx3\__init__.py", line 46, in init eng = engine(driverName, debug) TypeError: 'module' object is not callable
manojkumarmk at 2019-06-23 09:30:09 says
please help me -- I need help my whatsapp no. is 8285064459 Please help I have a problem in coding of python
zarif at 2019-06-23 09:30:09 says
I have add a command called search.It will search any kind of website.
rocoov at 2019-06-23 09:30:09 says
harry sir Getting an error my logs are present at del.dog/rocoov Please Help me out
ElectroIoT at 2019-06-23 09:30:09 says
Many Many Thanks ...........
Omkar at 2019-06-23 09:30:09 says
Hey there i am planning this for final year project . Even i want to learn machine . Since die hard fan of iron man
Karansxa at 2019-06-23 09:30:09 says
Harry Sir error occured what to do? --------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pyttsx3\__init__.py in init(driverName, debug) 19 try: ---> 20 eng = _activeEngines[driverName] 21 except KeyError: ~\Anaconda3\lib\weakref.py in __getitem__(self, key) 136 self._commit_removals() --> 137 o = self.data[key]() 138 if o is None: KeyError: 'sapi5'
capspid4133Y at 2019-06-23 09:30:09 says
pip is not recognized help me
yasho at 2019-06-23 09:30:09 says
thanks a lot bhaiya, now i adding many many more commands to jarvis and speanding at least 3-4 hours on it in a day, i am learning python,javascript,c from you
sushanta at 2019-06-23 09:30:09 says
hello harry bhai main kal rat se try karrahahun kuchha error dikharaha hai..kya karu.(sushantapatra92@gmail.com)error: "C:\Program Files (x86)\Python38-32\python.exe" C:/Users/WETDEV/PycharmProjects/python-learn/jarvis.py Traceback (most recent call last): File "C:\Program Files (x86)\Python38-32\lib\site-packages\speech_recognition\__init__.py", line 108, in get_pyaudio import pyaudio ModuleNotFoundError: No module named 'pyaudio' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/WETDEV/PycharmProjects/python-learn/jarvis.py", line 65, in <module> query = takeCommand().lower() File "C:/Users/WETDEV/PycharmProjects/python-learn/jarvis.py", line 37, in takeCommand with sr.Microphone() as source: File "C:\Program Files (x86)\Python38-32\lib\site-packages\speech_recognition\__init__.py", line 79, in __init__ self.pyaudio_module = self.get_pyaudio() File "C:\Program Files (x86)\Python38-32\lib\site-packages\speech_recognition\__init__.py", line 110, in get_pyaudio raise AttributeError("Could not find PyAudio; check installation") AttributeError: Could not find PyAudio; check installation Process finished with exit code 1
Arpit_007 at 2019-06-23 09:30:09 says
The only thing that i have to say is "love you bro"
DK@123 at 2019-06-23 09:30:09 says
sir, i am facing this problem. please help me. i installed all modules in vscode. Traceback (most recent call last): File "d:/python full course/Jarvis/Jarvis.py", line 69, in <module> query = takeCommand().lower() File "d:/python full course/Jarvis/Jarvis.py", line 39, in takeCommand with sr.Microphone() as source: File "C:\Users\DK\AppData\Local\Programs\Python\Python38\lib\site-packages\speech_recognition\__init__.py", line 138, in __enter__ self.audio.open( File "C:\Users\DK\AppData\Local\Programs\Python\Python38\lib\site-packages\pyaudio.py", line 750, in open stream = Stream(self, *args, **kwargs) File "C:\Users\DK\AppData\Local\Programs\Python\Python38\lib\site-packages\pyaudio.py", line 441, in __init__ self._stream = pa.open(**arguments) OSError: [Errno -9999] Unanticipated host error
blindkrypto at 2019-06-23 09:30:09 says
error aa raha hai Undefined variable 'r'
afjal at 2019-06-23 09:30:09 says
Hi Harry I try to run this same code but it is not working kindly guide me... Traceback (most recent call last): File "C:\python37\lib\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\python37\lib\weakref.py", line 137, in __getitem__ o = self.data[key]() KeyError: 'sapi5' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module> from comtypes.gen import SpeechLib # comtypes ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\python37\lib\site-packages\comtypes\gen\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\python37\lib\ctypes\__init__.py", line 121, in WINFUNCTYPE return _win_functype_cache[(restype, argtypes, flags)] KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'comtypes.automation.LP_tagVARIANT'>, <class 'ctypes.c_long'>), 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/AFJAL/PycharmProjects/quickschoolassistance37/quickschoolAssistance.py", line 9, in <module> engine = pyttsx3.init('sapi5') File "C:\python37\lib\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\python37\lib\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\python37\lib\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module> engine = comtypes.client.CreateObject("SAPI.SpVoice") File "C:\python37\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject return _manage(obj, clsid, interface=interface) File "C:\python37\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage obj = GetBestInterface(obj) File "C:\python37\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface mod = GetModule(tlib) File "C:\python37\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule mod = _CreateWrapper(tlib, pathname) File "C:\python37\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper mod = _my_import(fullname) File "C:\python37\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import return __import__(fullname, globals(), locals(), ['DUMMY']) File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\python37\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 421, in <module> ( ['out', 'retval'], POINTER(POINTER(ISpeechObjectTokens)), 'ObjectTokens' )), File "C:\python37\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__ self._make_methods(value) File "C:\python37\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods prototype = WINFUNCTYPE(restype, *argtypes) File "C:\python37\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE class WinFunctionType(_CFuncPtr): TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported.
afjal at 2019-06-23 09:30:09 says
reply me harry please...
acharyadipak at 2019-06-23 09:30:09 says
Hello Sir, While I was making or learning your code to make Jarvis I got lost of errors so please help me with that. I even tried coping your code from this website but still I got same problem I tried in pycharm as well as In Visual Stdio
Kishan at 2019-06-23 09:30:09 says
when i try to run it shown an error File "jarvis.py", line 45 print(f"User said: {query}\n") ^ SyntaxError: invalid syntax please help
BhosaleYash at 2019-06-23 09:30:09 says
Hi harry bhai I am learning python.. I tried to copy your Jarvis code and tried to run it.. But at the line of engine = pyttsx3.init('sapi5') Error was thrown .. Can u plzz explain reason behind it...
Sean98 at 2019-06-23 09:30:09 says
Hi Harry Bro, I have been following this tutorial but i have some problems that i am facing please help i really need this assistant C:\Users\SEAN JONES\Desktop\pthn> & "C:/Users/SEAN JONES/AppData/Local/Programs/Python/Python38/python.exe" "c:/Users/SEAN JONES/Desktop/pthn/JARVIS/jarvis.py" Traceback (most recent call last): File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\weakref.py", line 131, in __getitem__ o = self.data[key]() KeyError: 'sapi5' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:/Users/SEAN JONES/Desktop/pthn/JARVIS/jarvis.py", line 9, in <module> engine = pyttsx3.init('sapi5') File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\SEAN JONES\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom ModuleNotFoundError: No module named 'pythoncom' PS C:\Users\SEAN JONES\Desktop\pthn>
sabaafrin at 2019-06-23 09:30:09 says
Thank you so much harry bro.
nakulnandhu at 2019-06-23 09:30:09 says
bhai ye "except Exception as e:" mein"Unused variable 'e'pylint(unused-variable)" dikha raha hei. kyakaru?
Mrinal at 2019-06-23 09:30:09 says
Can i use this code for pydriod( in android phone)??
javedkhan at 2019-06-23 09:30:09 says
very good teaching style.....but i am having a problem in the jarvis....when i give command to jarvis with the help of headphones then its all right but when i unplug the headphones and then use it, it just stuck to listening although microphone of laptop is working perfectly
jay@0306 at 2019-06-23 09:30:09 says
KeyError: 'sapi5'. it comes what should i do .plzzzz help quickly.
Amit812 at 2019-06-23 09:30:09 says
Hi Harry please help i am facing following issue : Running setup.py install for pyaudio ... error ERROR: Command errored out with exit status 1: command: 'c:\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Amit\\AppData\\Local\\Temp\\pip-install-g08lbway\\pyaudio\\setup.py'"'"'; __file__='"'"'C:\\Users\\Amit\\AppData\\Local\\Temp\\pip-install-g08lbway\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Amit\AppData\Local\Temp\pip-record-bwshm6jj\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\python\python38-32\Include\pyaudio' cwd: C:\Users\Amit\AppData\Local\Temp\pip-install-g08lbway\pyaudio\ Complete output (13 lines): running install running build running build_py creating build creating build\lib.win32-3.8 copying src\pyaudio.py -> build\lib.win32-3.8 running build_ext building '_portaudio' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\src cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\python\python38-32\include -Ic:\python\python38-32\include /Tcsrc/_portaudiomodule.c /Fobuild\temp.win32-3.8\Release\src/_portaudiomodule.obj error: command 'cl.exe' failed: No such file or directory ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Amit\\AppData\\Local\\Temp\\pip-install-g08lbway\\pyaudio\\setup.py'"'"'; __file__='"'"'C:\\Users\\Amit\\AppData\\Local\\Temp\\pip-install-g08lbway\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Amit\AppData\Local\Temp\pip-record-bwshm6jj\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\python\python38-32\Include\pyaudio' Check the logs for full command output.
Amit812 at 2019-06-23 09:30:09 says
Try this it will work : 1> pip install pipwin after that 2> pipwin install pyaudio it works in my case
Dhruv7 at 2019-06-23 09:30:09 says
harry when I run the code it raises and artributError said pyaudio is not install