def textDetailsAboutFormula( self, query): #get the formual text details from file fileName = fh.FileHandler().createFilePathForTheQuery(query) try: f = open(fileName, 'r') resArray = f.readlines() res = ''.join(resArray) f.close() textList = [] waeqr = wap.WolframAlphaQueryResult(res) #get from titles for pod in waeqr.Pods(): podObject = wap.Pod(pod) for subPod in podObject.Subpods(): subPodObject = wap.Subpod(subPod) if (subPodObject.Plaintext() != [[]]): title = subPodObject.Title() if (title[0] != ''): textList.append(title[0]) else: textList.append(podObject.Title()[0]) return textList except Exception: textList = ["No Text Found"] print("exeption thrown") return textList
def _result_callback(self, msg, result, fail_silent): """ Deferred callback to handle result data. Called when page has sucessfully been downloaded. Negotiate (necessarily) nasty query result data and reply with nice string. """ try: if result[:7] == u"<error>": self.handle_error(msg, "Error in PerformQuery()") return waeqr = wap.WolframAlphaQueryResult(result) pods = [wap.Pod(p) for p in waeqr.Pods()] if len(pods) < 2: if not fail_silent: msg.reply(MESSAGES['no-result-error']) return pod = pods[1] # Usually the second pod has useful stuff in it. title = pod.Title()[0] results = [] # Probably only one, but may be more for subpod in [wap.Subpod(s) for s in pod.Subpods()]: results.append(subpod.Plaintext()[0]) # Unicode resultstring = u'\n'.join(results) # Pretty print, omitting "Result" if possible if title == u'Result': msg.reply(u"{0}".format(resultstring)) else: msg.reply(u"{0}: {1}".format(title, resultstring)) except Exception as e: self.handle_error(msg, "Exception occurred: " + str(e))
def call_api(self, val): '''call API from Wolfram Alpha and return output''' server = 'http://api.wolframalpha.com/v2/query.jsp' appid = '6LA36U-7V45PGUA6E' input = val waeo = wap.WolframAlphaEngine(appid, server) queryStr = waeo.CreateQuery(val) wap.WolframAlphaQuery(queryStr, appid) result = waeo.PerformQuery(queryStr) result = wap.WolframAlphaQueryResult(result) for pod in result.Pods(): waPod = wap.Pod(pod) title = "Pod.title: " + waPod.Title()[0] self.ls_pod.append(waPod.Title()[0]) for subpod in waPod.Subpods(): waSubpod = wap.Subpod(subpod) plaintext = waSubpod.Plaintext()[0] img = waSubpod.Img() src = wap.scanbranches(img[0], 'src')[0] alt = wap.scanbranches(img[0], 'alt')[0] self.ls_src.append(src) self.ls_alt.append(alt) self.ls_src = map(str, self.ls_src) break return self.ls_pod
def get_results(equation): queryStr = waeo.CreateQuery(equation) wap.WolframAlphaQuery(queryStr, WA_APP_ID) result = waeo.PerformQuery(queryStr) result = wap.WolframAlphaQueryResult(result) data = [] answer = [] for pod in result.Pods(): waPod = wap.Pod(pod) title = "Pod.title: " + waPod.Title()[0] print title for subpod in waPod.Subpods(): waSubpod = wap.Subpod(subpod) plaintext = waSubpod.Plaintext()[0] img = waSubpod.Img() src = wap.scanbranches(img[0], 'src')[0] alt = wap.scanbranches(img[0], 'alt')[0] print "-------------" print "img.src: " + src image = "img.src: " + src data.append(src) answer.append(plaintext) print "img.alt: " + alt print "\n" return data, answer
def getSuccess(self): # if the content in the file is valid success result = self.readFile() try: waQueryResult = wap.WolframAlphaQueryResult(result) return waQueryResult.IsSuccess()[0] except Exception: # if any error occured while parsing return false return 'false'
def WolframPyToJson(): #waeqr = wap.WolframAlphaQueryResult(getFromWolfram()) waeqr = wap.WolframAlphaQueryResult(readFile()) jsonResult = waeqr.JsonResult() a = jsonResult.decode() print(a) print(a[0]) #print(jsonResult.) print(jsonResult[2]) print(jsonResult[3])
def running(): """ Method for actually running the display """ global img, queries for e in pygame.event.get(): if e.type is QUIT or (e.type is KEYDOWN and e.key == K_ESCAPE): return False elif e.type is KEYDOWN and e.key == K_SPACE: server = 'http://api.wolframalpha.com/v2/query.jsp' appid = 'RV3P54-H477JEA2XE' pos_queries = [ 'When is the next full moon?', 'What time is it in India?', 'How long is the flight from New York to Atlanta?', 'How far is DC to Anchorage?', 'Where is Emory University?', 'What is the current local time in Portland, Oregon?', ] rand_query = random.choice(pos_queries) queries.add(text='Query: ' + rand_query) waeo = wap.WolframAlphaEngine(appid, server) queryStr = waeo.CreateQuery(rand_query) result = waeo.PerformQuery(queryStr) result = wap.WolframAlphaQueryResult(result) p = result.Pods() try: waPod = wap.Pod(p[1]) waSubpod = wap.Subpod(waPod.Subpods()[0]) plaintext = waSubpod.Plaintext()[0] imgg = waSubpod.Img() alt = wap.scanbranches(imgg[0], 'alt')[0] queries.add(text=str(alt)) except IndexError: queries.add(text='No results found') rand_block(rr(10, 100)) screen = pygame.display.get_surface() screen.fill((0, 0, 0)) for screen_object in SCREEN_OBJECTS: screen_object.update() # draw the image screen.blit(img, (WIDTH - BUFFER - 200, HEIGHT - BUFFER - 200)) pygame.display.flip() return True
def perform_query(self): if self.medical_test_wolram_query_flag is False: query_str = self.prepare_query_with_formula_variables() else: query_str = self.prepare_query_for_medical_tests() if type(query_str) is str: result = self.create_and_perform_wolfram_query.PerformQuery(query_str) results = wap.WolframAlphaQueryResult(result) json_result= json.loads(results.JsonResult()) return json_result else: return False
def checkConfiguration(self): #if configuration is proper set configured waeo = wap.WolframAlphaEngine(self.appid, self.host) waeq = wap.WolframAlphaQuery("pi", self.appid) waeq.ToURL() try: waeqr = wap.WolframAlphaQueryResult(waeo.PerformQuery(waeq.Query)) if (waeqr.IsSuccess()): self.waeo = waeo self.configured = True else: self.configured = False except Exception: print("connection failure")
def WolframPy(): #from urllib import request #url = "http://api.wolframalpha.com/v2/query?input=pi&appid=4WKYHL-AWUQL4GWA3" #urllib.getproxies() #fp = request.urlopen(url) #fp = urllib.urlopen(url) #data = fp.read() #f = open('workfile', 'w') #f.write(data) #n = int(data) #giveTheInt = [n] #print(giveTheInt) #print(data) result = getFromWolfram() #result = readFile() print(result) waeqr = wap.WolframAlphaQueryResult(result) #desktop = XSCRIPTCONTEXT.getDesktop() #model = desktop.getCurrentComponent() #if not hasattr(model, "Text"): # model = desktop.loadComponentFromURL("private:factory/swriter","_blank", 0, () ) #text = model.Text #cursor = text.createTextCursor() for pod in waeqr.Pods(): waep = wap.Pod(pod) xtit = waep.Title() for u in xtit: #text.insertString( cursor, u, 0 ) print(u) if (u == 'Plots of sample individual solutions'): plotSub = waep.Subpods() for pltpod in plotSub: spod = wap.Subpod(pltpod) imgData = spod.Img() a = dict(imgData.pop()) print(a['src']) imgurl = a['src'] f = open('00000001.gif', 'wb') f.write(urllib.urlopen(imgurl).read()) f.close() print("done") #text.insertString( cursor, "Hello World", 0 ) print(waep.Title())
def __init__(self, query, assumption=None, state=None, width=WIDTH, maxwidth=MAX_WIDTH, plotwidth=PLOT_WIDTH, magnification=MAGNIFICATION): engine = wap.WolframAlphaEngine(APP_ID, SERVER) engine.Width = width engine.MaxWidth = maxwidth engine.PlotWidth = plotwidth engine.Mag = magnification queryObj = engine.CreateQuery(query) if assumption: queryObj.AddAssumption(assumption.input) if state: queryObj.AddPodState(state) queryResult = engine.PerformQuery(queryObj) self.__result = wap.WolframAlphaQueryResult(queryResult)
def calcResult(self): query = self.waeo.CreateQuery(self.inpt) raw_result = self.waeo.PerformQuery(query) content = wap.WolframAlphaQueryResult(raw_result) result = None resultImg = None if content.IsSuccess(): dataType = content.DataTypes()[0] if dataType == 'Math': for pod in content.Pods(): waPod = wap.Pod(pod) print waPod.Title()[0] pTitle = str(waPod.Title()[0]) if pTitle == 'Result' or 'result' in pTitle: waSubpod = wap.Subpod(waPod.Subpods()[0]) result = waSubpod.Plaintext()[0] elif 'MathematicalFunctionIdentity' in dataType: for pod in content.Pods(): waPod = wap.Pod(pod) if str(waPod.Title()[0]) == 'Decimal approximation': waSubpod = wap.Subpod(waPod.Subpods()[0]) result = waSubpod.Plaintext()[0] else: for pod in content.Pods(): waPod = wap.Pod(pod) solvedResults = ['Differential equation solution', 'Limit'] waPodTitle = str(waPod.Title()[0]) if 'integral' in waPodTitle or waPodTitle in solvedResults: waSubpod = wap.Subpod(waPod.Subpods()[0]) result = waSubpod.Plaintext()[0] rightIndex = result.rindex('=') + 2 result = result[rightIndex:] img = waSubpod.Img() resultImg = wap.scanbranches(img[0], 'src')[0] break elif 'Result' in waPodTitle: waSubpod = wap.Subpod(waPod.Subpods()[0]) result = waSubpod.Plaintext()[0] img = waSubpod.Img() resultImg = wap.scanbranches(img[0], 'src')[0] else: continue return result, resultImg
def imageDetailsAboutFormula( self, query): #get the formula image details from file fileName = fh.FileHandler().createFilePathForTheQuery(query) try: f = open(fileName, 'r') resArray = f.readlines() res = ''.join(resArray) f.close() imageList = [] waeqr = wap.WolframAlphaQueryResult(res) #get from images count = 0 for pod in waeqr.Pods(): podObject = wap.Pod(pod) for subPod in podObject.Subpods(): subPodObject = wap.Subpod(subPod) if (subPodObject.Img() != [[]]): imageList.append("image" + ` count `) count += 1 return imageList except Exception: imageList = ["No Text Found"] print("exeption thrown") return imageList
def imageDetailsAboutFormula(self,query): fileName = os.sys.path[0]+"/equationFiles/"+query.lower()+".txt" try: f = open(fileName, 'r') resArray =f.readlines() res = ''.join(resArray) f.close() imageList=[] waeqr = wap.WolframAlphaQueryResult(res) count = 0 for pod in waeqr.Pods(): podObject = wap.Pod(pod) for subPod in podObject.Subpods(): subPodObject = wap.Subpod(subPod) if(subPodObject.Img()!=[[]]): image = subPodObject.Img() imageList.append("image"+`count`) count +=1 return imageList except Exception: imageList=["No Text Found"] print("exeption thrown") return imageList
async def wolfram_alpha_query(bot, query, user_ip, indices='', format_param='plaintext,image', units='metric'): """Returns a query result from Wolfram|Alpha.""" client = data.get(bot, __name__, 'client', volatile=True) client_query = client.GetQuery(query=query) client_query.ToURL() if indices: client_query.AddPodIndex(podindex=indices) # client_query.AddFormat(format_param=format_param) # need both client_query.AddIp(ip=user_ip) client_query.AddUnits(units=units) #query_result = await async_query(client, client_query.Query) try: query_result = await utilities.future(client.PerformQuery, client_query.Query) except Exception as e: raise CBException("The query could not be processed.", e=e) result = wap.WolframAlphaQueryResult(query_result) element = ElementTree.fromstring(result.XmlResult) return ElementTree.ElementTree(element=element).getroot()
def getResult(self, query): #method to get result if (self.isConfigured()): try: waeq = wap.WolframAlphaQuery(query, self.appid) waeq.Async = False waeq.ToURL() result = self.waeo.PerformQuery(waeq.Query) waeqr = wap.WolframAlphaQueryResult(result) for pod in waeqr.Pods(): waep = wap.Pod(pod) if (waep.PodStates()[0][1][2][1] == 'Step-by-step solution' ): self.stepinput = waep.PodStates()[0][1][1][1] break waeq = wap.WolframAlphaQuery(query, self.appid) waeq.AddPodState(self.stepinput) waeq.Async = False waeq.ToURL() result = self.waeo.PerformQuery(waeq.Query) f = open(query + '.txt', 'w') f.write(result) f.close() except Exception: print("connection problem")
def textDetailsAboutFormula(self,query): fileName = os.sys.path[0]+"/equationFiles/"+query.lower()+".txt" try: f = open(fileName, 'r') resArray =f.readlines() res = ''.join(resArray) f.close() textList=[] waeqr = wap.WolframAlphaQueryResult(res) for pod in waeqr.Pods(): podObject = wap.Pod(pod) for subPod in podObject.Subpods(): subPodObject = wap.Subpod(subPod) if(subPodObject.Plaintext()!=[[]]): title = subPodObject.Title() if(title[0]!=''): textList.append(title[0]) else: textList.append(podObject.Title()[0]) return textList except Exception: textList=["No Text Found"] print("exeption thrown") return textList
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''An example that provides a python interface to the wap library''' __author__ = '*****@*****.**' __version__ = '1.1-devel' import wap import urllib #url = 'http://preview.wolframalpha.com/api/v1/query.jsp' #url = 'http://preview.wolframalpha.com/api/v1/validatequery.jsp' #url = 'http://api.wolframalpha.com/v1/query.jsp' #url = 'http://api.wolframalpha.com/v1/validatequery.jsp' server = 'http://api.wolframalpha.com/v1/query.jsp' appid = 'XXXX' input = 'who are you?' waeo = wap.WolframAlphaEngine(appid, server) query = waeo.CreateQuery(input) result = waeo.PerformQuery(query) waeqr = wap.WolframAlphaQueryResult(result) jsonresult = waeqr.JsonResult() print jsonresult
def setVariables(self, result): #setting the variables read print(result) self.WolframAlphaQueryResult = wap.WolframAlphaQueryResult(result)
waeo.Async = async queryStr = waeo.CreateQuery(input_str) waq = wap.WolframAlphaQuery(queryStr, appid) waq.ScanTimeout = scantimeout waq.PodTimeout = podtimeout waq.FormatTimeout = formattimeout waq.Async = async waq.AddPodIndex('WordsMadeWithOnlyLetters') waq.AddPodState('WordsMadeWithOnlyLetters__Disallow repetition ') waq.AddPodState('WordsMadeWithOnlyLetters__Sorted by length') waq.AddPodState('WordsMadeWithOnlyLetters__More') e_r = waeo.PerformQuery(waq.Query) result = wap.WolframAlphaQueryResult(e_r) for pod in result.Pods(): waPod = wap.Pod(pod) for subpod in waPod.Subpods(): waSubpod = wap.Subpod(subpod) t = waSubpod.Plaintext()[0] s = t.split(' | ') results = [] for w in s[:-1]: if (needed != ''): for c in needed: if (c in w) and (w not in results): results.append(w) else: results.append(w)
sys.path.insert(0, 'lib/wolfram/Python_Binding_1_1') import wap wolfram_key = appid = os.environ['WOLFRAM_KEY'] query_url = 'http://api.wolframalpha.com/v2/query.jsp' job_name = raw_input("What type of job are you looking for (singular)? ") job_location_name = raw_input("Where would you like to work? ") engine = wap.WolframAlphaEngine(wolfram_key, query_url) query = engine.CreateQuery('Average salary for ' + job_name + ' in ' + job_location_name) wap.WolframAlphaQuery(query, query_url) engine_query = engine.PerformQuery(query) result = wap.WolframAlphaQueryResult(engine_query) if result.IsSuccess(): print('Success!') else: print('Failure!') exit(1) for pod in result.Pods(): waPod = wap.Pod(pod) title = waPod.Title()[0] print title if title == 'Result': for subpod in waPod.Subpods(): waSubpod = wap.Subpod(subpod) plaintext = waSubpod.Plaintext()[0]
qBotLib.resetBotParts(); question=raw_input('\n> '); if qBotLib.isQuestionProfane(question)==1: print qBotLib.proFaneMsg_array[random.randint(0,1)]; elif qBotLib.isQuestionOverriden(question)!=-1: print qBotLib.overridenQAns[qBotLib.isQuestionOverriden(question)]; else: waeo = wap.WolframAlphaEngine(qBotLib.appid, qBotLib.server); queryStr = waeo.CreateQuery(question); wap.WolframAlphaQuery(queryStr, qBotLib.appid); result = waeo.PerformQuery(queryStr); result = wap.WolframAlphaQueryResult(result); for pod in result.Pods(): waPod = wap.Pod(pod); title = waPod.Title()[0]; if title == "Result": qBotLib.findAnswer(waPod); qBotLib.updateNoAnsFlag(1); break; #Check if we have any reply from Knowledge engine if qBotLib.noAns!=1: print qBotLib.preDefinedMsg_array[random.randint(0,1)];