top of page
  • Writer's pictureThe Arithmancer

Giving Your Mirror a Brain

Updated: Oct 21, 2019

Giving your magic mirror the ability to answer general knowledge questions is easy thanks to the folks at Wolfram.


They have created an API that is super easy to use and is free for hobbyists as long as you use less than 2000 queries per month. While Wolfram have a number of APIs, it is the "Spoken Results API" that you should set up an account for.


Start by creating an account here and make a note of your ID as we will be using it later.



Sample Query


Now that you have an AppID, you can make your first query. The base URL for queries is:


http://api.wolframalpha.com/v1/spoken

Every query requires two pieces of information—an AppID and an input value—in order to be processed correctly. The appid parameter tells your query which AppID to use:


http://api.wolframalpha.com/v1/spoken?appid=DEMO

Next, use the i parameter to specify the URL-encoded input for your query. For instance, here is a query for "How far is Los Angeles from New York?":


http://api.wolframalpha.com/v1/spoken?appid=DEMO&i=How+far+is+Los+Angeles+from+New+York%3f

When executed with a valid AppID, this URL will return a single line of conversational text with a computed response to your query:


The answer is about 2464 miles 

Now in Python

First is to import the URLLib library so that we can query a URL:


import urllib.request
# Next we write the function. We assume this function is being called after the speech recognition has run and then passes the output to CallWolfram in the text variable "OutputFromSpeechRecognition"
# The steps we need to take here is to form the query as described above but also to replace all spaces with "+" and all question marks with "%3f"
def CallWolfram(OutputFromSpeechRecognition)
    base="http://api.wolframalpha.com/v1/spoken?appid=" 
    ID="DEMO"   # This should be replaced with your appid
    start="&i="   
    newquestion=OutputFromSpeechRecognition.replace(" ","+")
    newquestion=newquestion.replace("?","%3f")
    query=base+ID+start+newquestion
 
    try:
        contents = bytes.decode(urllib.request.urlopen(query).read()
    except urllib.error.HTTPError:
        contents="x"
    return(contents)
 



Full code up to this tutorial can be downloaded from my github account here.

24 views0 comments

Recent Posts

See All

Comments


bottom of page