Skip to content

Instantly share code, notes, and snippets.

@KhanradCoder
Created April 11, 2020 01:21
Show Gist options
  • Star 61 You must be signed in to star a gist
  • Fork 42 You must be signed in to fork a gist
  • Save KhanradCoder/7886acf1a51d8635ec2ab09f81de6268 to your computer and use it in GitHub Desktop.
Save KhanradCoder/7886acf1a51d8635ec2ab09f81de6268 to your computer and use it in GitHub Desktop.
Code for the video where we build a Jarvis like virtual assistant in python 3
import wolframalpha
client = wolframalpha.Client("lilpumpsaysnopeeking")
import wikipedia
import PySimpleGUI as sg
sg.theme('DarkPurple')
layout =[[sg.Text('Enter a command'), sg.InputText()],[sg.Button('Ok'), sg.Button('Cancel')]]
window = sg.Window('PyDa', layout)
import pyttsx3
engine = pyttsx3.init()
while True:
event, values = window.read()
if event in (None, 'Cancel'):
break
try:
wiki_res = wikipedia.summary(values[0], sentences=2)
wolfram_res = next(client.query(values[0]).results).text
engine.say(wolfram_res)
sg.PopupNonBlocking("Wolfram Result: "+wolfram_res,"Wikipedia Result: "+wiki_res)
except wikipedia.exceptions.DisambiguationError:
wolfram_res = next(client.query(values[0]).results).text
engine.say(wolfram_res)
sg.PopupNonBlocking(wolfram_res)
except wikipedia.exceptions.PageError:
wolfram_res = next(client.query(values[0]).results).text
engine.say(wolfram_res)
sg.PopupNonBlocking(wolfram_res)
except:
wiki_res = wikipedia.summary(values[0], sentences=2)
engine.say(wiki_res)
sg.PopupNonBlocking(wiki_res)
engine.runAndWait()
print (values[0])
window.close()
@BhavyaShah1234
Copy link

Hii. I am getting an error. It goes as follows:

Traceback (most recent call last):
  File "VirtualAssistant.py", line 4, in <module>
    res = client.query('temperature in Washington, DC on October 3, 2012')
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\wolframalpha\__init__.py", line 54, in query
    return Result(resp)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\wolframalpha\__init__.py", line 169, in __init__
    super(Result, self).__init__(doc)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\wolframalpha\__init__.py", line 60, in __init__
    self._handle_error()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\wolframalpha\__init__.py", line 67, in _handle_error
    raise Exception(template.format(**self))
Exception: Error 1: Invalid appid

My code goes as follows:

import wolframalpha as wa

client = wa.Client("H3VKQH-ATJ3J4VYYW")
res = client.query('temperature in Washington, DC on October 3, 2012')
print(res)

@Arduinobo
Copy link

Arduinobo commented Sep 9, 2020 via email

@Arduinobo
Copy link

Well I have answered your question . Check your Gmail inbox

@Arduinobo
Copy link

Any other query you can ask me any time at my Gmail ID (arduinobot.vbps@gmail.com)

@Arduinobo
Copy link

Well the developer of this video had contacted me about his codes (BhavyaShah1234)
bro

@Arduinobo
Copy link

Im using python 3.8. Whenever I create a python file and run the following, I get an ImportError: No module named wolframalpha
I installed wolframalpha using the pip command. Anyone know what the issue may be?

import wolframalpha
client = wolframalpha.Client("3KJ4AR-A9JEVLY5Y9")
res = client.query('temperature in Washington, DC on October 3, 2012')

print(res)

Bro you forgot the output command

@UmairNajmi
Copy link

Im using python 3.8. Whenever I create a python file and run the following, I get an ImportError: No module named wolframalpha
I installed wolframalpha using the pip command. Anyone know what the issue may be?
import wolframalpha
client = wolframalpha.Client("3KJ4AR-A9JEVLY5Y9")
res = client.query('temperature in Washington, DC on October 3, 2012')
print(res)

Bro you forgot the output command

Bro which IDE you are using ?.Write this command (wiki_res) after running the code.well I'm using pycharm IDE.

@LordTomaddo
Copy link

It gives me the following error:

Traceback (most recent call last):
File "D:\Basis\Code\lib\site-packages\pyttsx3_init_.py", line 20, in init
eng = _activeEngines[driverName]
File "D:\Basis\Code\lib\weakref.py", line 134, in getitem
o = self.datakey
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Basis\Code! python programms\wolfram alpha powered digital assistant raw date\7886acf1a51d8635ec2ab09f81de6268-7f16c6f6111e9727b4e9e243842857cb1c199cd1\PyDa.py", line 12, in
engine = pyttsx3.init()
File "D:\Basis\Code\lib\site-packages\pyttsx3_init_.py", line 22, in init
eng = Engine(driverName, debug)
File "D:\Basis\Code\lib\site-packages\pyttsx3\engine.py", line 30, in init
self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
File "D:\Basis\Code\lib\site-packages\pyttsx3\driver.py", line 50, in init
self.module = importlib.import_module(name)
File "D:\Basis\Code\lib\importlib_init
.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1030, in _gcd_import
File "", line 1007, in _find_and_load
File "", line 986, in _find_and_load_unlocked
File "", line 680, in _load_unlocked
File "", line 790, in exec_module
File "", line 228, in _call_with_frames_removed
File "D:\Basis\Code\lib\site-packages\pyttsx3\drivers\sapi5.py", line 10, in
import pythoncom
File "D:\Basis\Code\lib\site-packages\pythoncom.py", line 2, in
import pywintypes
ModuleNotFoundError: No module named 'pywintypes'

So I wanted to install the package pywintypes, but when I tried, the following output came on CMD:

ERROR: Could not find a version that satisfies the requirement pywintypes (from versions: none)
ERROR: No matching distribution found for pywintypes

Anyone knows what to do? Would help me a lot. Thanks! :)

@Arduinobo
Copy link

Arduinobo commented Oct 14, 2020 via email

@LuOwl3
Copy link

LuOwl3 commented Oct 25, 2020

Im using python 3.8. Whenever I create a python file and run the following, I get an ImportError: No module named wolframalpha
I installed wolframalpha using the pip command. Anyone know what the issue may be?
import wolframalpha
client = wolframalpha.Client("3KJ4AR-A9JEVLY5Y9")
res = client.query('temperature in Washington, DC on October 3, 2012')
print(res)

Bro you forgot the output command

Don’t know what you’re meaning

@Arduinobo
Copy link

Arduinobo commented Oct 26, 2020 via email

@Arduinobo
Copy link

Hello, everybody . After working for so long I am successful in building a very powerful AI

Now if you want to become a part of our community please fill this form -

Please support our AI Arduino.

Well you can download the codes from here -


Please support us and the best thing is that for better experience please first head over to the help section by saying arduino help
(please download the dependencies first)

Now you will think it is a simple computer python program... But! please try and read the codes and then come to your decision!
Thanks and regards,
Arduino bot.

@Arduinobo
Copy link

For any queries contact me at arduinobot.vbps@gmail.com

@Arduinobo
Copy link

Hey there please support us!

@Arduinobo
Copy link

Arduinobo commented Nov 3, 2020 via email

@0thm4n3
Copy link

0thm4n3 commented Nov 27, 2020

Clean, straight-forward code.

@josephhaywood
Copy link

I wrote the code the same but for every import statement I get "ModuleNotFoundError: No module named '________'" was there something I forgot to download or has this happen to anyone else

@d33pak123
Copy link

How do I install wolframalpha

First 5 minutes of the video he literally walks you through this. You're not installing anything, you're simply following some links and getting a key from your Wolfram account.

That's false, you have to install wolframalpha using the pip command. Libraries can't be summoned using a simple key.

@adarkz
Copy link

adarkz commented Jan 27, 2021

https://stackoverflow.com/questions/64886214/python-3-urllib-module-basic-function-not-working

This should help the people still getting errors when calling the "res = client.query('temperature in Washington, DC on October 3, 2012')"
command.

open your python3.9 (or whatever version) folder and double click "Install Certificates.command".

@kromil24
Copy link

Sir please give me advance jarvis code🙏

@TonyYTCZ
Copy link

Sorry, but I didn't get that.... how I run it? I haven't that text below code. Can anyone help me? And yes I actually didn't anything with python before.

@azrael0learza
Copy link

Sorry, but I didn't get that.... how I run it? I haven't that text below code. Can anyone help me? And yes I actually didn't anything with python before.

Before you can try run the code you'll need to setup a couple of things.
First you'll need to download python for the operating system you're using, once that is done you'll need to select and IDE [code editor] that you would like to use, after that just copy over the code and run it from there, you should see a window pop up that allows you to enter something to search for.

If I misunderstood you just let me know.

Also check out KhanradCoders YouTube or Udemy, think he still has some content on how to set up everything.

@gibbrann
Copy link

How do I install wolframalpha

@azrael0learza
Copy link

How do I install wolframalpha

Hi there, all you have to do is go to their website and create an account, once your done you'll need to go through to the 'My Apps' option and from there you'll see a window that allows you to get your key that can be added into your code, below is a video by Khanrad that goes through the process, https://youtu.be/NZMTWBpLUa4?t=152

@Deadcrazy-Gamer
Copy link

Exception has occurred: ModuleNotFoundError
No module named 'wolframalpha'
File "/Users/ramprasadmuduli/Desktop/7886acf1a51d8635ec2ab09f81de6268-7f16c6f6111e9727b4e9e243842857cb1c199cd1/PyDa.py", line 1, in
import wolframalpha

@TheSoupMasta
Copy link

Exception has occurred: ModuleNotFoundError
No module named 'wolframalpha'
File "/Users/ramprasadmuduli/Desktop/7886acf1a51d8635ec2ab09f81de6268-7f16c6f6111e9727b4e9e243842857cb1c199cd1/PyDa.py", line 1, in
import wolframalpha

Okay, open your terminal and type in "pip install wolframalpha".
If the editor you are using doesn't have a terminal, open your command prompt and type in 'pip install wolframalpha".

@TheSoupMasta
Copy link

Alright, so since I was quarantined I decided to add speech recognition and turn the code into object oriented programming.

Here is the code:

import pyaudio
import wolframalpha
import PySimpleGUI as sg
import pyttsx3
import speech_recognition as sr
client = wolframalpha.Client(<Enter your code here>)
engine = pyttsx3.init()


class Jarvis():
    def __init__(self, mic_obj, rec_obj):
        self.mic = mic_obj
        self.r = rec_obj
        self.search_engine()


    def search_engine(self):
        sg.theme('DarkPurple')
        layout = [[sg.Text('Enter a command'), sg.InputText()], [sg.Button('Ok'), sg.Button('Cancel'), sg.Button('Use Voice Recognition')]]
        self.window = sg.Window('PyDa', layout)

        while True:
            event, values = self.window.read()
            if event in (None, 'Cancel'):
                break
            if event in (None, 'Use Voice Recognition'):
                self.voicerecognition()
                break
            try:
                wolfram_res = next(client.query(values[0]).results).text
                engine.say(wolfram_res)
                sg.PopupNonBlocking("Wolfram Result: " + wolfram_res)
            except:
                quit('Error')


            engine.runAndWait()

        self.window.close()

    def voicerecognition(self):
        sg.theme('DarkPurple')
        layout = [[sg.Button("Press and Speak"), sg.Button('Cancel')]]
        self.speechrecogwindow = sg.Window("Speech Recognition Assistant", layout)

        while True:
            event, values = self.speechrecogwindow.read()
            if event in (None, "Press and Speak"):
                self.speechrecogwindow.close()
                self.recog(self.r)
                break
            if event in (sg.WIN_CLOSED, 'Cancel'):
                self.speechrecogwindow.close()
                quit()


    def recog(self, rec_obj):
        while True:
            wolfram_res = None
            with self.mic as source:
                print("Speak")
                rec_obj.adjust_for_ambient_noise(source)
                audio = rec_obj.listen(source)
                try:
                    response = rec_obj.recognize_google(audio)
                except(sr.UnknownValueError):
                    quit("Could not recognize")
            try:
                wolfram_res = next(client.query(response).results).text
                engine.say(wolfram_res)
                engine.runAndWait()
                layout = [[sg.Text(wolfram_res)], [sg.Button('Ok')]]
                self.popup = sg.Window('Popup', layout)
                while True:
                    event, values = self.popup.read()
                    if event in (sg.WIN_CLOSED, 'Ok'):
                        self.popup.close()
                        break
                self.voicerecognition()
            except(StopIteration):
                print("Could not find answer")
                self.voicerecognition()

if __name__ == "__main__":
    jarvis = Jarvis(sr.Microphone(), sr.Recognizer())

When you run the code, make sure all libraries have been installed and click "Use Voice Recognition". Then click 'Press to Speak' and talk. I took out the wikipedia entries because it bugged out, and speech recognition works exactly like you think it does. When you talk, it'll respond. After responding, it will open a window with the response in text format. Press "Ok" or the close window button to exit out. I will create a repo with a .exe of the engine when I have time, so if you're reading this then you should probably check if I've done so.

Thanks for reading - TheSoupMasta

@SliverKitsune
Copy link

SliverKitsune commented Jul 22, 2021

OK after messing around I was able to get the right window to appear so you can press the Run Voice Recognition button instead of the other window. Sorry, there wasn't much of a change.

 

import pyaudio
import wolframalpha
import PySimpleGUI as sg
import pyttsx3
import speech_recognition as sr

client = wolframalpha.Client("NoLooking")
engine = pyttsx3.init()



class Jarvis:
    def __init__(self, mic_obj, rec_obj):
        self.mic = mic_obj
        self.r = rec_obj
        self.search_engine()

    def search_engine(self):
        sg.theme('DarkPurple')
        layout = [[sg.Text('Enter a command'), sg.InputText()],
                  [sg.Button('Ok'), sg.Button('Cancel'), sg.Button('Use Voice Recognition')]]
        window = sg.Window('PyDa', layout)

        while True:
            event, values = window.read()
            if event in (None, 'Cancel'):
                break
            if event in (None, 'Use Voice Recognition'):
                self.voicerecognition()
                break
            try:
                wolfram_res = next(client.query(values[0]).results).text
                engine.say(wolfram_res)
                sg.PopupNonBlocking("Wolfram Result: " + wolfram_res)
            except:
                quit('Error')

            engine.runAndWait()

        window.close()

    def voicerecognition(self):
        sg.theme('DarkPurple')
        layout = [[sg.Button("Press and Speak"), sg.Button('Cancel')]]
        self.speechrecogwindow = sg.Window("Speech Recognition Assistant", layout)

        while True:
            event, values = self.speechrecogwindow.read()
            if event in (None, "Press and Speak"):
                self.speechrecogwindow.close()
                self.recog(self.r)
                break
            if event in (sg.WIN_CLOSED, 'Cancel'):
                self.speechrecogwindow.close()
                quit()

    def recog(self, rec_obj):
        while True:
            wolfram_res = None
            with self.mic as source:
                print("Speak")
                rec_obj.adjust_for_ambient_noise(source)
                audio = rec_obj.listen(source)
                try:
                    response = rec_obj.recognize_google(audio)
                except(sr.UnknownValueError):
                    quit("Could not recognize")
            try:
                wolfram_res = next(client.query(response).results).text
                engine.say(wolfram_res)
                engine.runAndWait()
                layout = [[sg.Text(wolfram_res)], [sg.Button('Ok')]]
                self.popup = sg.Window('Popup', layout)
                while True:
                    event, values = self.popup.read()
                    if event in (sg.WIN_CLOSED, 'Ok'):
                        self.popup.close()
                        break
                self.voicerecognition()
            except(StopIteration):
                print("Could not find answer, Try Again")
                self.voicerecognition()


if __name__ == "__main__":
    jarvis = Jarvis(sr.Microphone(), sr.Recognizer())

@TheSoupMasta
Copy link

TheSoupMasta commented Jul 26, 2021

OK after messing around I was able to get the right window to appear so you can press the Run Voice Recognition button instead of the other window. Sorry, there wasn't much of a change.

 

import pyaudio
import wolframalpha
import PySimpleGUI as sg
import pyttsx3
import speech_recognition as sr

client = wolframalpha.Client("NoLooking")
engine = pyttsx3.init()



class Jarvis:
    def __init__(self, mic_obj, rec_obj):
        self.mic = mic_obj
        self.r = rec_obj
        self.search_engine()

    def search_engine(self):
        sg.theme('DarkPurple')
        layout = [[sg.Text('Enter a command'), sg.InputText()],
                  [sg.Button('Ok'), sg.Button('Cancel'), sg.Button('Use Voice Recognition')]]
        window = sg.Window('PyDa', layout)

        while True:
            event, values = window.read()
            if event in (None, 'Cancel'):
                break
            if event in (None, 'Use Voice Recognition'):
                self.voicerecognition()
                break
            try:
                wolfram_res = next(client.query(values[0]).results).text
                engine.say(wolfram_res)
                sg.PopupNonBlocking("Wolfram Result: " + wolfram_res)
            except:
                quit('Error')

            engine.runAndWait()

        window.close()

    def voicerecognition(self):
        sg.theme('DarkPurple')
        layout = [[sg.Button("Press and Speak"), sg.Button('Cancel')]]
        self.speechrecogwindow = sg.Window("Speech Recognition Assistant", layout)

        while True:
            event, values = self.speechrecogwindow.read()
            if event in (None, "Press and Speak"):
                self.speechrecogwindow.close()
                self.recog(self.r)
                break
            if event in (sg.WIN_CLOSED, 'Cancel'):
                self.speechrecogwindow.close()
                quit()

    def recog(self, rec_obj):
        while True:
            wolfram_res = None
            with self.mic as source:
                print("Speak")
                rec_obj.adjust_for_ambient_noise(source)
                audio = rec_obj.listen(source)
                try:
                    response = rec_obj.recognize_google(audio)
                except(sr.UnknownValueError):
                    quit("Could not recognize")
            try:
                wolfram_res = next(client.query(response).results).text
                engine.say(wolfram_res)
                engine.runAndWait()
                layout = [[sg.Text(wolfram_res)], [sg.Button('Ok')]]
                self.popup = sg.Window('Popup', layout)
                while True:
                    event, values = self.popup.read()
                    if event in (sg.WIN_CLOSED, 'Ok'):
                        self.popup.close()
                        break
                self.voicerecognition()
            except(StopIteration):
                print("Could not find answer, Try Again")
                self.voicerecognition()


if __name__ == "__main__":
    jarvis = Jarvis(sr.Microphone(), sr.Recognizer())
import pyaudio
import wolframalpha
import PySimpleGUI as sg
import pyttsx3
import speech_recognition as sr
import webbrowser as wb
client = wolframalpha.Client("U5RKU7-26R988VUA5")
engine = pyttsx3.init()


class Jarvis():
    def __init__(self, mic_obj, rec_obj):
        self.mic = mic_obj
        self.r = rec_obj
        self.r.energy_threshold = 300
        self.search_engine()


    def search_engine(self):
        sg.theme('DarkPurple')
        layout = [[sg.Text('Enter a command'), sg.InputText()], [sg.Button('WolfRamAlpha'), sg.Button('Google'), sg.Button('Use Voice Recognition'), sg.Button('Cancel')]]
        self.window = sg.Window('PyDa', layout)

        while True:
            event, values = self.window.read()
            if event in (None, 'Cancel'):
                break
            if event in (None, 'Use Voice Recognition'):
                self.voicerecognition()
                break
            if event in (None, 'Google'):
                try:
                    wb.get().open_new_tab('https://www.google.com/search?q=' + values[0][0::])
                except:
                    print('Error')
                    self.search_engine()
            if event in (None, 'Ok'):
                try:
                    wolfram_res = next(client.query(values[0]).results).text
                    engine.say(wolfram_res)
                    sg.PopupNonBlocking("Wolfram Result: " + wolfram_res)
                except:
                    quit('Error')




            engine.runAndWait()

        self.window.close()

    def voicerecognition(self):
        sg.theme('DarkPurple')
        layout = [[sg.Button("Press and Speak"), sg.Button('Cancel')]]
        self.speechrecogwindow = sg.Window("Speech Recognition Assistant", layout)

        while True:
            event, values = self.speechrecogwindow.read()
            if event in (None, "Press and Speak"):
                self.speechrecogwindow.close()
                self.recog(self.r)
                break
            if event in (sg.WIN_CLOSED, 'Cancel'):
                self.speechrecogwindow.close()
                quit()


    def recog(self, rec_obj):
        while True:
            wolfram_res = None
            with self.mic as source:
                print("Speak")
                rec_obj.adjust_for_ambient_noise(source)
                audio = rec_obj.listen(source)
                try:
                    response = rec_obj.recognize_google(audio)
                except(sr.UnknownValueError):
                    quit("Could not recognize")
            if response.split()[0] != 'Google':
                try:
                    wolfram_res = next(client.query(response).results).text
                    engine.say(wolfram_res)
                    engine.runAndWait()
                    layout = [[sg.Text(wolfram_res)], [sg.Button('Ok')]]
                    self.popup = sg.Window('Popup', layout)
                    while True:
                        event, values = self.popup.read()
                        if event in (sg.WIN_CLOSED, 'Ok'):
                            self.popup.close()
                            break
                    self.voicerecognition()
                except(StopIteration):
                    print("Could not find answer")
                    self.voicerecognition()
            elif response.split()[0] == 'Google':
                wb.get().open_new_tab('https://www.google.com/search?q=' + response[7::])
                self.voicerecognition()

if __name__ == "__main__":
    jarvis = Jarvis(sr.Microphone(), sr.Recognizer())

Thanks for the help. I also added a choice to google using the google button or saying "google" before your question/comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment