We're live-coding on Twitch! Join us!
Build a virtual assistant in Python 3.x using wolframalpha, Wikipedia, pyttsx and speech recognition API’s [Part 2]

Build a virtual assistant in Python 3.x using wolframalpha, Wikipedia, pyttsx and speech recognition API’s [Part 2]

Code Project

Wikipedia, pyttsx and speech recognition API’s [part 2] This is a continuation of our series on building a virtual assistant in python 3.x. From the previous article we highlighted all the core features of the application, like how to use both the wolframalpha and wikipedia API. In this article, we will be looking to implement the wolframalpha and the Wikipedia API into one main application and put into a GUI (Graphical User Interface).

Putting everything together

Start by creating a new python file and import the necessary library to proceed.

import wikipedia
import wolframalpha

Then we create a forever loop so the user can input questions multiple times.

import wikipedia
import wolframalpha
while True:
    my_input = input("Question: ")

Next we build a try and except loop. Basically the loop tells python to try the code you put in the try block and if the code causes an error then try the code that you put in the except block. So, in the try block we will be including the code for the wolframalpha code and the except block is going to have the Wikipedia code. When a question is asked the program tries to anwer through the wolframalpha API first, if it discovers it can’t answer the question it moves to query the Wikipedia API with same question for results. That is how the code below works.

import wikipedia
import wolframalpha

while True:
    my_input = input("Question: ")
        #wolframalpha code here
        app_id = "Q2HXJ5-GYYYX6PYYP"
        client = wolframalpha.Client(app_id)
        res = client.query(my_input)
        answer = next(res.results).text 

        #wikipedia code here

N|B: Make sure to indent your code properly, because python is sensitive to poorly indented codes.

Ok, now all we have to do is run our application on the terminal and test it out. Remember to run this app, open terminal (cmd) and navigate to the path you stored this file and input the command “python ”

python pyda.py

To test the app, you can try with simple math questions like 100 + 25, 2x + 5x, 81/9 or even 9 * 8. This questions will be answered by the wolframalpha API. You can also try with questions like fela kuti, owerri, Nigeria, this questions will be answered by the Wikipedia API. Ok, hope you app is running smoothly to this point, next we will need to create a GUI to make it more friendly instead of running it from the terminal.

Creating the Graphical User Interface (GUI)

We will be creating our GUI with the aid of a python library called wxPython. You can get more info about this library on the python site. We first of all install the wxPython library on our local machine using the pip tool.

pip install wxpython

After that, we proceed to create our GUI by importing the library into our code. For clarity sake you can create a new python file first.

import wx

Let’s set a main class for the app frame

import wx
#set a main class for the app frame
class MyFrame(wx.Frame):

We need to define an init function for the app and set it to self. To define a function in python we use the def syntax

import wx
class MyFrame(wx.Frame):
    def __init__(self):

The next step is to set some basic GUI info about the app. These basic info defines the app size (width and height) and also label. The size will be set to 450 X 100, you can change it to anything you want.

import wx
#set a main class for the app frame
class MyFrame(wx.Frame):
    def __init__(self):        
        #set some basic gui info about the app
        wx.Frame.__init__(self, None,
            pos=wx.DefaultPosition, size=wx.Size(450, 100),
            style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |
            wx.CLOSE_BOX | wx.CLIP_CHILDREN,
        panel = wx.Panel(self)
        my_sizer = wx.BoxSizer(wx.VERTICAL)
        lbl = wx.StaticText(panel, 
        label="Hello I am PyDa the Python  Digital Assistant. How can I help you?")
        my_sizer.Add(lbl, 0, wx.ALL, 5)

We will need to set up a simple text box with basic properties and trigger function. These properties defines the shape of the text box as well as a function to accept input from a user. Add the following code below to complete the one above still on the same indentation.

#set up a simple text box with the following properties
self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER,size=(400,30))
self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
my_sizer.Add(self.txt, 0, wx.ALL, 5)

We need to define the OnEnter function, which allows the user to submit an input through the text box. To do this let’s move out from the init function indentation and create a new function.

def OnEnter(self, event):
        input = self.txt.GetValue()
        input = input.lower()
        print("It worked!")

This is how the above code works, the user inputs a question into the text box, the textbox gets and temporarily stores the value using self.txt.GetValue() and converts it to lower case using input.lower(). If the function works we then output print(it worked”). Ok, next is outside the OnEnter function indentation we need to run the app by declaring the code below.

#run the app with the below code
if __name__ == "__main__":
    app = wx.App(True)
    frame = MyFrame()

The above code is simply the basic way to run an app built with wx library. We instantiate a wx app using app = wx.App(True) and to instantiate the class for the app frame we use MyFrame(). To keep the frame running without termination (external) we use app.MainLoop() . Now we can check our progress by running the app. Open your terminal and run the command python

python pyda.py

When we run the command a window like the one shown below pops up and when we press enter you should see a message “it worked!”

Ok, great now we have created the GUI for our app and also in the previous article shown how to make our app dynamic and useful by using the wolframalpha and Wikipedia API. In the next article we will combine these two files to make our digital assistant dynamic, robust and come to life. Save this file and let’s continue this awesome journey in the next article here. In case you miss your way, you can access the codes for this series on my github page .

Like this article? Follow @LK_wapiti on Twitter