def currentTime(self, speech, language): #first tell that we look it up view = AddViews(self.refId, dialogPhase="Reflection") view.views = [ AssistantUtteranceView( text=timePlugin.localizations['currentTime']['search'] [language], speakableText=timePlugin.localizations['currentTime']['search'] [language], dialogIdentifier="Clock#getTime") ] self.sendRequestWithoutAnswer(view) # tell him to show the current time view = AddViews(self.refId, dialogPhase="Summary") view1 = AssistantUtteranceView( text=timePlugin.localizations['currentTime']['currentTime'] [language], speakableText=timePlugin.localizations['currentTime'] ['currentTime'][language], dialogIdentifier="Clock#showTimeInCurrentLocation") clock = ClockObject() clock.timezoneId = self.connection.assistant.timeZoneId view2 = ClockSnippet(clocks=[clock]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) self.complete_request()
def call(self, phone, person, language): if phone == None: print "abandon" self.complete_request() return root = ResultCallback(commands=[]) rootView = AddViews("", temporary=False, dialogPhase="Completion", views=[]) root.commands.append(rootView) rootView.views.append( AssistantUtteranceView( text=responses['callPerson'][language].format( person.fullName, numberTypesLocalized[phone.label][language], phone.number), speakableText=responses['callPersonSpeak'][language].format( person.fullName, numberTypesLocalized[phone.label][language]), dialogIdentifier="PhoneCall#initiatePhoneCall", listenAfterSpeaking=False)) rootView.callbacks = [] # create some infos of the target personAttribute = PersonAttribute(data=phone.number, displayText=person.fullName, obj=Person()) personAttribute.object.identifer = person.identifier call = PhoneCall("", recipient=phone.number, faceTime=False, callRecipient=personAttribute) rootView.callbacks.append(ResultCallback(commands=[call])) call.callbacks = [] # now fill in error messages (airplanemode, no service, invalidNumber, fatal) for i in range(4): errorRoot = AddViews(None, temporary=False, dialogPhase="Completion", scrollToTop=False, views=[]) errorRoot.views.append( AssistantUtteranceView( text=errorOnCallResponse[language][i]['text'], speakableText=errorOnCallResponse[language][i]['text'], dialogIdentifier=errorOnCallResponse[language][i] ['dialogIdentifier'], listenAfterSpeaking=False)) call.callbacks.append( ResultCallback(commands=[errorRoot], code=errorOnCallResponse[language][i]['code'])) self.complete_request([root])
def whereAmI(self, speech, language): location = self.getCurrentLocation(force_reload=True,accuracy=GetRequestOrigin.desiredAccuracyBest) url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&language={2}".format(str(location.latitude),str(location.longitude), language) try: jsonString = urllib2.urlopen(url, timeout=10).read() except: pass if jsonString != None: response = json.loads(jsonString) if response['status'] == 'OK': components = response['results'][0]['address_components'] street = filter(lambda x: True if "route" in x['types'] else False, components)[0]['long_name'] stateLong= filter(lambda x: True if "administrative_area_level_1" in x['types'] or "country" in x['types'] else False, components)[0]['long_name'] try: postalCode= filter(lambda x: True if "postal_code" in x['types'] else False, components)[0]['long_name'] except: postalCode="" try: city = filter(lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name'] except: city="" countryCode = filter(lambda x: True if "country" in x['types'] else False, components)[0]['short_name'] view = AddViews(self.refId, dialogPhase="Completion") if language == "de-DE": the_header="Dein Standort" elif language == 'fr-FR': the_header="Votre position" elif language == 'zh-CN': self.say(u"这是您的位置 {0}:".format(self.user_name())) the_header=u"您的位置" else: self.say("This is your location {0}".format(self.user_name())) the_header="Your location" view = AddViews(self.refId, dialogPhase="Completion") mapsnippet = MapItemSnippet(items=[MapItem(label=postalCode+" "+city, street=street, city=city, postalCode=postalCode, latitude=location.latitude, longitude=location.longitude, detailType="CURRENT_LOCATION")]) view.views = [AssistantUtteranceView(text=the_header, dialogIdentifier="Map#whereAmI"), mapsnippet] self.sendRequestWithoutAnswer(view) else: if language=="de-DE": self.say('Die Googlemaps informationen waren ungenügend!','Fehler') elif language == 'fr-FR': self.say(u"La réponse de Googlemaps ne contient pas l'information nécessaire",'Erreur') elif language == 'zh-CN': self.say(u"我找不到您的位置。") else: self.say('The Googlemaps response did not hold the information i need!','Error') else: if language=="de-DE": self.say('Ich konnte keine Verbindung zu Googlemaps aufbauen','Fehler') if language=="fr-FR": self.say(u"Je ne peux pas établir de connexion à Googlemaps",'Erreur') if language=="zh-CN": self.say(u"我无法访问谷歌地图。") else: self.say('Could not establish a conenction to Googlemaps','Error'); self.complete_request()
def writeNote(self, speech, language): content_raw = re.match(".*note ([a-zA-Z0-9, ]+)$", speech, re.IGNORECASE) if content_raw == None: view_initial = AddViews(self.refId, dialogPhase="Reflection") view_initial.views = [AssistantUtteranceView(text=note.localizations['noteDefaults']['nothing'][language], speakableText=note.localizations['noteDefaults']['nothing'][language], dialogIdentifier="Note#failed")] self.sendRequestWithoutAnswer(view_initial) else: view_initial = AddViews(self.refId, dialogPhase="Reflection") view_initial.views = [AssistantUtteranceView(text=note.localizations['noteDefaults']['searching'][language], speakableText=note.localizations['noteDefaults']['searching'][language], dialogIdentifier="Note#creating")] self.sendRequestWithoutAnswer(view_initial) content_raw = content_raw.group(1).strip() if "saying" in content_raw: split = content_raw.split(' ') if split[0] == "saying": split.pop(0) content_raw = ' '.join(map(str, split)) if "that" in content_raw: split = content_raw.split(' ') if split[0] == "that": split.pop(0) content_raw = ' '.join(map(str, split)) if "que" in content_raw: split = content_raw.split(' ') if split[0] == "que": split.pop(0) content_raw = ' '.join(map(str, split)) if "for" in content_raw: split = content_raw.split(' ') if split[0] == "for": split.pop(0) content_raw = ' '.join(map(str, split)) note_create = Create() note_create.contents = content_raw note_return = self.getResponseForRequest(note_create) view = AddViews(self.refId, dialogPhase="Summary") view1 = AssistantUtteranceView(text=note.localizations['noteDefaults']['result'][language], speakableText=note.localizations['noteDefaults']['result'][language], dialogIdentifier="Note#created") note_ = NoteObject() note_.contents = content_raw note_.identifier = note_return["properties"]["identifier"] view2 = NoteSnippet(notes=[note_]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) self.complete_request()
def imdb_info(self, speech, language, regex): ShowTitle = regex.group(regex.lastindex) Query = urllib.quote_plus(ShowTitle.encode("utf-8")) IMDBURL = 'http://www.imdbapi.com/?i=&t=%s' % (str(Query)) try: # Query IMDB jsonResponse = urllib2.urlopen(IMDBURL).read() jsonDecoded = json.JSONDecoder().decode(jsonResponse) self.say("Here is the info about the movie:") view = AddViews(self.refId, dialogPhase="Completion") AnswerString = jsonDecoded['Title'] + ' (' + jsonDecoded[ 'Released'] + ')' + '\n Genre: ' + jsonDecoded[ 'Genre'] + '\n Directors: ' + jsonDecoded[ 'Director'] + '\n Actors: ' + jsonDecoded[ 'Actors'] + '\n Plot: ' + jsonDecoded[ 'Plot'] + '\n Runtime: ' + jsonDecoded[ 'Runtime'] + '\n Rating: ' + jsonDecoded[ 'Rating'] + ' / Voted: ' + jsonDecoded[ 'Votes'] + 'x' IMDBAnswerMissed = AnswerObject( title='IMDB:', lines=[AnswerObjectLine(text=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[IMDBAnswerMissed]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() except (urllib2.URLError): self.say( "Sorry, a connection to IMDBapi could not be established.") self.complete_request()
def imdb_poster(self, speech, language, regex): ShowTitle = regex.group(regex.lastindex) Query = urllib.quote_plus(ShowTitle.encode("utf-8")) IMDBURL = 'http://www.imdbapi.com/?i=&t=%s' % (str(Query)) try: # Query IMDB jsonResponse = urllib2.urlopen(IMDBURL).read() jsonDecoded = json.JSONDecoder().decode(jsonResponse) self.say("Here is the movie poster:") view = AddViews(self.refId, dialogPhase="Completion") AnswerString = jsonDecoded['Poster'] IMDBAnswerMissed = AnswerObject( title='Movie Poster:', lines=[AnswerObjectLine(image=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[IMDBAnswerMissed]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() except (urllib2.URLError): self.say( "Sorry, a connection to IMDBapi could not be established.") self.complete_request()
def displaypicture(self, speech, language, regex): if language == "zh-CN": Title = regex.group(3).strip() else: Title = regex.group(regex.lastindex).strip() Query = urllib.quote_plus(Title.encode("utf-8")) SearchURL = u'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&imgsz=small|medium|large|xlarge&q=' + str(Query) try: if language == "zh-CN": self.say(u"这是有关{0}的图片:".format(Title)) else: self.say("Here is the image for "+Title+"...") jsonResponse = urllib2.urlopen(SearchURL).read() jsonDecoded = json.JSONDecoder().decode(jsonResponse) ImageURL = jsonDecoded['responseData']['results'][0]['unescapedUrl'] view = AddViews(self.refId, dialogPhase="Completion") ImageAnswer = AnswerObject(title=Title,lines=[AnswerObjectLine(image=ImageURL)]) view1 = AnswerSnippet(answers=[ImageAnswer]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() except (urllib2.URLError): if language == "zh-CN": self.say(u"抱歉,我无法连接谷歌图片服务。") else: self.say("Sorry, a connection to Google Images could not be established.") self.complete_request()
def presentPossibleUsers(self, persons, language): root = AddViews(self.refId, False, False, "Clarification", [], []) root.views.append(AssistantUtteranceView(responses['select'][language], responses['select'][language], "ContactDataResolutionDucs#disambiguateContact", True)) lst = DisambiguationList([], "OK!", True, "OK!", speakableDemitter[language], ", ", "OK!") root.views.append(lst) for person in persons: item = ListItem(person.fullName, person.fullName, [], person.fullName, person) item.commands.append(SendCommands([StartRequest(False, "^phoneCallContactId^=^urn:ace:{0}".format(person.identifier))])) lst.items.append(item) return root
def webSearchConfirmation(self, speech, language): # lets use a little hack to get that regex matcher = self.webSearchConfirmation.__dict__[__criteria_key__]['de-DE'] regMatched = matcher.match(speech) webSearchQuery = regMatched.group(1) webSearchConfirmation = regMatched.group(2) lang = language.split("-")[0] resultCallback1View = AddViews(refId="", views=[AssistantUtteranceView(dialogIdentifier="WebSearch#initiateWebSearch", text=webSearchAnswerText[lang].format(u"„{0}“".format(webSearchQuery)), speakableText=webSearchAnswerText[lang].format(webSearchQuery))]) search = WebSearch(refId="", aceId="", query=webSearchQuery) resultCallback3View = AddViews(refId="", views=[AssistantUtteranceView(dialogIdentifier="WebSearch#fatalResponse", text=webSearchAnswerFailureText[lang], speakableText=webSearchAnswerFailureText[lang])]) resultCallback3 = ResultCallback(commands=[resultCallback3View]) search.callbacks = [resultCallback3] resultCallback2 = ResultCallback(commands=[search]) resultCallback1View.callbacks = [resultCallback2] self.complete_request(callbacks=[ResultCallback(commands=[resultCallback1View])])
def get_actorbycharacter(self, speech, language, regex): if language == "en-US": # get the name of the character to look up character = regex.group(2) character = character.title().strip() # get the name of the movie to look up movie = regex.group(3) movie = movie.title() ia = IMDb() search_result = ia.search_movie(movie) if not search_result: self.say("No matches found for that title") self.complete_request() else: movietitle = search_result[0]['title'] moviedetails = search_result[0] ia.update(moviedetails) cast = moviedetails['cast'] try: for actor in cast: if character in actor.currentRole['name']: self.say(actor['name']) #Get Image Query = urllib.quote_plus(actor['name'].encode("utf-8")) SearchURL = u'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&imgsz=small|medium|large|xlarge&q=' + str(Query) try: jsonResponse = urllib2.urlopen(SearchURL).read() jsonDecoded = json.JSONDecoder().decode(jsonResponse) ImageURL = jsonDecoded['responseData']['results'][0]['unescapedUrl'] view = AddViews(self.refId, dialogPhase="Completion") ImageAnswer = AnswerObject(title=str(actor['name']),lines=[AnswerObjectLine(image=ImageURL)]) view1 = AnswerSnippet(answers=[ImageAnswer]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() except (urllib2.URLError): self.say("Sorry, a connection to Google Images could not be established.") self.complete_request() self.complete_request() self.complete_request() except: self.say("Sorry, I couldnt find any characters by that name in " + movietitle) self.complete_request()
def testbild(self, speech, language): html = urllib.urlopen( "http://sullenlook.eu/Pix/cydia/info/testbild.png/") soup = BeautifulSoup(html) ImageURL = "http://sullenlook.eu/Pix/cydia/info/testbild.png/" view = AddViews(self.refId, dialogPhase="Completion") ImageAnswer = AnswerObject( title=str("Testbild"), lines=[ AnswerObjectLine( image="http://sullenlook.eu/Pix/cydia/info/testbild.png") ]) view1 = AnswerSnippet(answers=[ImageAnswer]) view.views = [view1] self.sendRequestWithoutAnswer(view)
def defineword(self, speech, language, regex): Title = regex.group(regex.lastindex) Query = urllib.quote_plus(Title.encode("utf-8")) SearchURL = u'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&imgsz=small|medium|large|xlarge&q=' + str(Query) try: jsonResponse = urllib2.urlopen(SearchURL).read() jsonDecoded = json.JSONDecoder().decode(jsonResponse) ImageURL = jsonDecoded['responseData']['results'][0]['unescapedUrl'] view = AddViews(self.refId, dialogPhase="Completion") ImageAnswer = AnswerObject(title=str(Title),lines=[AnswerObjectLine(image=ImageURL)]) view1 = AnswerSnippet(answers=[ImageAnswer]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() except (urllib2.URLError): self.say("Sorry, a connection to Google Images could not be established.") self.complete_request()
def findPhoneForNumberType(self, person, numberType, language): # first check if a specific number was already requested phoneToCall = None if numberType != None: # try to find the phone that fits the numberType phoneToCall = filter(lambda x: x.label == numberType, person.phones) else: favPhones = filter(lambda y: y.favoriteVoice if hasattr(y, "favoriteVoice") else False, person.phones) if len(favPhones) == 1: phoneToCall = favPhones[0] if phoneToCall == None: # lets check if there is more than one number if len(person.phones) == 1: if numberType != None: self.say(errorNumberNotPresent.format(numberTypesLocalized[numberType][language], person.fullName)) phoneToCall = person.phones[0] else: # damn we need to ask the user which one he wants... while(phoneToCall == None): rootView = AddViews(self.refId, temporary=False, dialogPhase="Clarification", scrollToTop=False, views=[]) sayit = responses['selectNumber'][language].format(person.fullName) rootView.views.append(AssistantUtteranceView(text=sayit, speakableText=sayit, listenAfterSpeaking=True,dialogIdentifier="ContactDataResolutionDucs#foundAmbiguousPhoneNumberForContact")) lst = DisambiguationList(items=[], speakableSelectionResponse="OK...", listenAfterSpeaking=True, speakableText="", speakableFinalDemitter=speakableDemitter[language], speakableDemitter=", ",selectionResponse="OK...") rootView.views.append(lst) for phone in person.phones: numberType = phone.label item = ListItem() item.title = "" item.text = u"{0}: {1}".format(numberTypesLocalized[numberType][language], phone.number) item.selectionText = item.text item.speakableText = u"{0} ".format(numberTypesLocalized[numberType][language]) item.object = phone item.commands.append(SendCommands(commands=[StartRequest(handsFree=False, utterance=numberTypesLocalized[numberType][language])])) lst.items.append(item) answer = self.getResponseForRequest(rootView) numberType = self.getNumberTypeForName(answer, language) if numberType != None: matches = filter(lambda x: x.label == numberType, person.phones) if len(matches) == 1: phoneToCall = matches[0] else: self.say(errorNumberTypes[language]) else: self.say(errorNumberTypes[language]) return phoneToCall
def googleplaces_search(self, speech, language, regex): self.say('Searching...',' ') mapGetLocation = self.getCurrentLocation() latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude Title = regex.group(regex.lastindex).strip() Query = urllib.quote_plus(str(Title.encode("utf-8"))) random_results = random.randint(2,15) googleurl = "https://maps.googleapis.com/maps/api/place/search/json?location={0},{1}&radius=5000&name={2}&sensor=true&key={3}".format(latitude,longitude,str(Query),str(googleplaces_api_key)) try: jsonString = urllib2.urlopen(googleurl, timeout=20).read() except: jsonString = None if jsonString != None: response = json.loads(jsonString) if (response['status'] == 'OK') and (len(response['results'])): googleplaces_results = [] for result in response['results']: if "rating" in result: avg_rating = result["rating"] else: avg_rating = 0.0 rating = Rating(value=avg_rating, providerId='Google Places', count=0) details = Business(totalNumberOfReviews=0,name=result['name'],rating=rating) if (len(googleplaces_results) < random_results): mapitem = MapItem(label=result['name'], street=result['vicinity'], latitude=result['geometry']['location']['lat'], longitude=result['geometry']['location']['lng']) mapitem.detail = details googleplaces_results.append(mapitem) else: break mapsnippet = MapItemSnippet(items=googleplaces_results) count_min = min(len(response['results']),random_results) count_max = max(len(response['results']),random_results) view = AddViews(self.refId, dialogPhase="Completion") view.views = [AssistantUtteranceView(speakableText='I found '+str(count_max)+' '+str(Title)+' results... '+str(count_min)+' of them are fairly close to you:', dialogIdentifier="googlePlacesMap"), mapsnippet] self.sendRequestWithoutAnswer(view) else: self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") else: self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") self.complete_request()
def currentTimeIn(self, speech, language): view = AddViews(self.refId, dialogPhase="Reflection") view.views = [ AssistantUtteranceView( text=timePlugin.localizations['currentTimeIn']['search'] [language], speakableText=timePlugin.localizations['currentTimeIn'] ['search'][language], dialogIdentifier="Clock#getTime") ] self.sendRequestWithoutAnswer(view) error = False countryOrCity = re.match("(?u).* in ([\w ]+)$", speech, re.IGNORECASE) if countryOrCity != None: countryOrCity = countryOrCity.group(1).strip() # lets see what we got, a country or a city... # lets use google geocoding API for that url = u"http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false&language={1}".format( urllib.quote_plus(countryOrCity), language) # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) # lets see what we have... if response['status'] == 'OK': components = response['results'][0]['address_components'] types = components[0][ 'types'] # <- this should be the city or country if "country" in types: # OK we have a country as input, that sucks, we need the capital, lets try again and ask for capital also components = filter( lambda x: True if "country" in x['types'] else False, components) url = u"http://maps.googleapis.com/maps/api/geocode/json?address=capital%20{0}&sensor=false&language={1}".format( urllib.quote_plus(components[0]['long_name']), language) # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) if response['status'] == 'OK': components = response['results'][0][ 'address_components'] # response could have changed, lets check again, but it should be a city by now if response['status'] == 'OK': # get latitude and longitude location = response['results'][0]['geometry']['location'] url = u"http://api.geonames.org/timezoneJSON?lat={0}&lng={1}&username={2}".format( location['lat'], location['lng'], geonames_user) jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: timeZoneResponse = json.loads(jsonString) if "timezoneId" in timeZoneResponse: timeZone = timeZoneResponse['timezoneId'] city = filter( lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name'] country = filter( lambda x: True if "country" in x['types'] else False, components)[0]['long_name'] countryCode = filter( lambda x: True if "country" in x['types'] else False, components)[0]['short_name'] view = AddViews(self.refId, dialogPhase="Summary") view1 = AssistantUtteranceView( text=timePlugin.localizations['currentTimeIn'] ['currentTimeIn']['text'][language].format( city, country, timeZone), speakableText=timePlugin. localizations['currentTimeIn']['currentTimeIn'] ['tts'][language].format( city, country, timeZone), dialogIdentifier="Clock#showTimeInOtherLocation" ) clock = ClockObject() clock.timezoneId = timeZone clock.countryCode = countryCode clock.countryName = country clock.cityName = city clock.unlocalizedCityName = city clock.unlocalizedCountryName = country view2 = ClockSnippet(clocks=[clock]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) else: error = True else: error = True else: error = True else: error = True else: error = True if error: view = AddViews(self.refId, dialogPhase="Completion") view.views = [ AssistantUtteranceView( text=timePlugin.localizations['failure'][language], speakableText=timePlugin.localizations['failure'] [language], dialogIdentifier="Clock#cannotShowClocks") ] self.sendRequestWithoutAnswer(view) self.complete_request()
def move_lookup(self, speech, language, regex): MovieTitle = regex.group(regex.lastindex).strip() ia = IMDb() search_result = ia.search_movie(MovieTitle) if not search_result: if language == "zh-CN": self.say(u"抱歉,我没找到“" + str(MovieTitle.encode("utf-8")) + u"”的信息。") else: self.say("Sorry, I could not find any information for " + MovieTitle) self.complete_request() else: if language == "zh-CN": self.say(u"好的,我来为您查找。") else: self.say("Let me look that up for you.") view = AddViews(self.refId, dialogPhase="Completion") # -- Get Movie Info -- movie_info = search_result[0] MovieTitle = movie_info['long imdb canonical title'] ia.update(movie_info) # -- Get the URL for poster -- AnswerStringPosterURL = movie_info['cover url'] # Output to the AnswerObject NurfIMDBAnswerPosterURL = AnswerObject(title=MovieTitle,lines=[AnswerObjectLine(image=AnswerStringPosterURL)]) #-- Get Rating -- AnswerStringRating = str(movie_info['rating']) + "/10 (" + str(movie_info['votes']) + " votes)" # Output to the AnswerObject NurfIMDBAnswerRating = AnswerObject(title='Rating:',lines=[AnswerObjectLine(text=AnswerStringRating)]) #-- Get Plot -- plot = movie_info['plot'][0].split('::') AnswerStringPlot = plot[0] # Output to the AnswerObject NurfIMDBAnswerPlot = AnswerObject(title='Plot:',lines=[AnswerObjectLine(text=AnswerStringPlot)]) #-- Get Directors -- AnswerStringDirectors = '' for director in movie_info['director']: AnswerStringDirectors = AnswerStringDirectors + director['name'] + ", " AnswerStringDirectors = AnswerStringDirectors.rstrip(',') #Remove the last comma from the answerstring # Output to the AnswerObject NurfIMDBAnswerDirectors = AnswerObject(title='Directors:',lines=[AnswerObjectLine(text=AnswerStringDirectors)]) #-- Get Writers -- AnswerStringWriters = '' for writer in movie_info['writer']: AnswerStringWriters = AnswerStringWriters + writer['name'] + ", " AnswerStringWriters = AnswerStringWriters.rstrip(',') #Remove the last comma from the answerstring # Output to the AnswerObject NurfIMDBAnswerWriters = AnswerObject(title='Writers:',lines=[AnswerObjectLine(text=AnswerStringWriters)]) # -- Get Cast -- AnswerStringCast = '' for actor in movie_info['cast']: try: AnswerStringCast = AnswerStringCast + actor['name'] + " (" + str(actor.currentRole['name']) + "), " except: AnswerStringCast = AnswerStringCast + actor['name'] + ", " AnswerStringCast = AnswerStringCast.rstrip(',') #Remove the last comma from the answerstring # Output to the AnswerObject NurfIMDBAnswerCast = AnswerObject(title='Cast:',lines=[AnswerObjectLine(text=AnswerStringCast)]) # -- Results -- #Display the results view1 = AnswerSnippet(answers=[NurfIMDBAnswerPosterURL, NurfIMDBAnswerRating, NurfIMDBAnswerPlot, NurfIMDBAnswerDirectors, NurfIMDBAnswerWriters, NurfIMDBAnswerCast]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request()
def weatherForecastLookUp(self, speech, language): speech = speech.replace(u".", "") viewType = "DAILY" if (speech.count("today") > 0 or speech.count("current") > 0 or speech.count(" for today") > 0) and language == "en-US": viewType = "HOURLY" speech = speech.replace("todays", "") speech = speech.replace("today", "") speech = speech.replace("currently", "") speech = speech.replace("current", "") speech = speech.replace(" for today", " in ") speech = speech.replace(" for ", " in ") if (speech.count("aujourd'hui") > 0 or speech.count("actuel") > 0 or speech.count("maintenant") > 0 or speech.count(" pour aujourd'hui") > 0 or speech.count("fait") > 0 and language == "fr-FR"): viewType = "HOURLY" speech = speech.replace(" pour aujourd'hui", "") speech = speech.replace("aujourd'hui", "") speech = speech.replace("pour maintenant", "") speech = speech.replace("de maintenant", "") speech = speech.replace("maintenant", "") speech = speech.replace("actuellement", "") speech = speech.replace("actuelle", "") speech = speech.replace("actuel", "") if (speech.count("heute") > 0 or speech.count("moment") > 0 or speech.count(u"nächsten Stunden") > 0 or speech.count(u"für heute") > 0) and language == "de-DE": viewType = "HOURLY" speech = speech.replace("heute", "") speech = speech.replace("im moment", "") speech = speech.replace("momentan", "") speech = speech.replace("aktuelle", "") speech = speech.replace("aktuell", "") speech = speech.replace(u"in den nächsten Stunden", "") speech = speech.replace(u"für heute", "") if language == "en-US": speech = speech.replace(" for ", " in ") if language == "de-DE": speech = speech.replace(u"in den nächsten Tagen", "") speech = speech.replace(u"in den nächsten paar Tagen", "") speech = speech.replace(u"in der nächsten Woche", "") speech = speech.replace(u"nächste Woche", "") speech = speech.replace(u" für ", " in ") error = False view = AddViews(refId=self.refId, dialogPhase="Reflection") randomNumber = random.randint(0, 3) view.views = [ AssistantUtteranceView( weatherPlugin.localizations['weatherForecast']['search'] [randomNumber][language], weatherPlugin.localizations['weatherForecast']['search'] [randomNumber][language]) ] self.connection.send_object(view) countryOrCity = re.match(u"(?u).* (a|à|de|pour|dans|en|in) ([\w ]+)", speech, re.IGNORECASE) if countryOrCity != None: countryOrCity = countryOrCity.group( countryOrCity.lastindex).strip() print "found forecast" # lets see what we got, a country or a city... # lets use google geocoding API for that url = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false&language={1}".format( urllib.quote_plus(countryOrCity.encode("utf-8")), language) print url elif countryOrCity == None: currentLocation = self.getCurrentLocation() url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&language={2}".format( str(currentLocation.latitude), str(currentLocation.longitude), language) print url # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) # lets see what we have... if response['status'] == 'OK': components = response['results'][0]['address_components'] types = components[0][ 'types'] # <- this should be the city or country if "country" in types: # OK we have a country as input, that sucks, we need the capital, lets try again and ask for capital also components = filter( lambda x: True if "country" in x['types'] else False, components) url = "http://maps.googleapis.com/maps/api/geocode/json?address=capital%20{0}&sensor=false&language={1}".format( urllib.quote_plus(components[0]['long_name']), language) print url # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) if response['status'] == 'OK': components = response['results'][0][ 'address_components'] # response could have changed, lets check again, but it should be a city by now if response['status'] == 'OK': # get latitude and longitude location = response['results'][0]['geometry']['location'] city = "" country = "" state = "" stateLong = "" countryCode = "" shortName = "" longName = "" try: city = filter( lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name'] country = filter( lambda x: True if "country" in x['types'] else False, components)[0]['long_name'] state = filter( lambda x: True if "administrative_area_level_1" in x[ 'types'] or "country" in x['types'] else False, components)[0]['short_name'] stateLong = filter( lambda x: True if "administrative_area_level_1" in x[ 'types'] or "country" in x['types'] else False, components)[0]['long_name'] countryCode = filter( lambda x: True if "country" in x['types'] else False, components)[0]['short_name'] except: pass url = "http://api.wunderground.com/api/{0}/geolookup/conditions/forecast7day//hourly7day/astronomy/q/{1},{2}.json".format( weatherApiKey, location['lat'], location['lng']) print url # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=5).read() except: pass if jsonString != None: response = json.loads(jsonString) # lets see what we have... if response.has_key("error") == False: weatherTemp = dict() if response.has_key("current_observation"): if response.has_key("moon_phase"): if (int(response["moon_phase"]["current_time"] ["hour"]) > int(response["moon_phase"] ["sunset"]["hour"]) ) or (int(response["moon_phase"] ["current_time"]["hour"]) < int(response["moon_phase"]["sunrise"] ["hour"])): weatherTempNightTime = True else: weatherTempNightTime = False else: weatherTempNightTime = False conditionSwapper = SiriWeatherFunctions() dayOfWeek = [] # for i in range(1, 8): dayOfWeek.append(i % 7 + 1) tempNight = weatherTempNightTime weatherTemp["currentTemperature"] = str( response["current_observation"]["temp_c"]) dailyForecasts = [] for x in range(0, 6): forecastDate = date( int(response["forecast"]["simpleforecast"] ["forecastday"][x]["date"]["year"]), int(response["forecast"]["simpleforecast"] ["forecastday"][x]["date"]["month"]), int(response["forecast"]["simpleforecast"] ["forecastday"][x]["date"]["day"])) weatherTemp[ "tempCondition"] = conditionSwapper.swapCondition( conditionTerm=response["forecast"] ["simpleforecast"]["forecastday"][x] ["icon"], night=tempNight) dailyForecasts.append( SiriForecastAceWeathersDailyForecast( timeIndex=(dayOfWeek[date.weekday( forecastDate)]), highTemperature=response["forecast"] ["simpleforecast"]["forecastday"][x] ["high"]["celsius"], lowTemperature=response["forecast"] ["simpleforecast"]["forecastday"][x] ["low"]["celsius"], condition= SiriForecastAceWeathersConditions( conditionCode=weatherTemp[ "tempCondition"] ["conditionCode"], conditionCodeIndex=weatherTemp[ "tempCondition"] ["conditionCodeIndex"]))) tempNight = False hourlyForecasts = [] for x in range(0, 10): if response["hourly_forecast"][x]: if ( int(response["moon_phase"] ["current_time"]["hour"]) <= int(response["hourly_forecast"][x] ["FCTTIME"]["hour"]) ) or (int(response["forecast"] ["simpleforecast"]["forecastday"] [0]["date"]["day"]) < int(response["hourly_forecast"][x] ["FCTTIME"]["mday"]) ) or (int( response["forecast"] ["simpleforecast"]["forecastday"] [0]["date"]["month"]) < int(response["hourly_forecast"] [x]["FCTTIME"]["mon"])): if response.has_key( "hourly_forecast") == True: weatherTemp = dict() if response.has_key( "current_observation"): if response.has_key( "moon_phase"): if (int( response[ "moon_phase"] ["sunset"]["hour"] ) < int(response[ "hourly_forecast"] [x]["FCTTIME"] ["hour"]) ) or (int( response[ "moon_phase"] ["sunrise"]["hour"] ) > int(response[ "hourly_forecast"] [x]["FCTTIME"] ["hour"])): weatherTempCon = conditionSwapper.swapCondition( conditionTerm= response[ "hourly_forecast"] [x]["icon"], night=True) else: weatherTempCon = conditionSwapper.swapCondition( conditionTerm= response[ "hourly_forecast"] [x]["icon"], night=False) else: weatherTempCon = conditionSwapper.swapCondition( conditionTerm=response[ "hourly_forecast"] [x]["icon"], night=True) hourlyForecasts.append( SiriForecastAceWeathersHourlyForecast( timeIndex=response[ "hourly_forecast"][x] ["FCTTIME"]["hour"], chanceOfPrecipitation=int( response["hourly_forecast"] [x]["pop"]), temperature=response[ "hourly_forecast"][x] ["temp"]["metric"], condition= SiriForecastAceWeathersConditions( conditionCode= weatherTempCon[ "conditionCode"], conditionCodeIndex= weatherTempCon[ "conditionCodeIndex"])) ) weatherTemp[ "currentCondition"] = conditionSwapper.swapCondition( conditionTerm=response[ "current_observation"]["icon"], night=weatherTempNightTime) currentTemperature = str( response["current_observation"]["temp_c"]) currentDate = date( int(response["forecast"]["simpleforecast"] ["forecastday"][0]["date"]["year"]), int(response["forecast"]["simpleforecast"] ["forecastday"][0]["date"]["month"]), int(response["forecast"]["simpleforecast"] ["forecastday"][0]["date"]["day"])) view = AddViews(self.refId, dialogPhase="Summary") currentConditions = SiriForecastAceWeathersCurrentConditions( dayOfWeek=dayOfWeek[int( date.weekday(currentDate))], temperature=currentTemperature, condition=SiriForecastAceWeathersConditions( conditionCode=weatherTemp[ "currentCondition"]["conditionCode"], conditionCodeIndex=weatherTemp[ "currentCondition"] ["conditionCodeIndex"])) aceWethers = [ SiriForecastAceWeathers( extendedForecastUrl=response["location"] ["wuiurl"], currentConditions=currentConditions, hourlyForecasts=hourlyForecasts, dailyForecasts=dailyForecasts, weatherLocation= SiriForecastAceWeathersWeatherLocation(), units=SiriForecastAceWeathersUnits(), view=viewType, ) ] weather = SiriForecastSnippet( aceWeathers=aceWethers) speakCountry = stateLong if country == "United States" else country if language == "de-DE": speakCountry = stateLong + " (" + country + ")" if country == "USA" else country if city == "": city = components[0]['short_name'] if country == "": speakCountry = components[0]['long_name'] rep = None if viewType == "HOURLY": if speech.count(u"chaud") > 0: rep = u"Oui, il fait chaud, {0}°C à {1}, {2}." elif speech.count(u"froid") > 0: rep = u"Non, pas très froid, {0}°C à {1}, {2}." elif speech.count(u"température") > 0: rep = u"La température actuelle est de {0}°C à {1}, {2}." if rep == None: randomNumber = random.randint(0, 2) rep = weatherPlugin.localizations[ 'weatherForecast']['forecast'][viewType][ randomNumber][language].format( city, speakCountry) else: rep = rep.format( response["current_observation"]["temp_c"], city, speakCountry) view.views = [ AssistantUtteranceView( text=rep, speakableText=rep, dialogIdentifier= "Weather#forecastCommentary"), weather ] self.sendRequestWithoutAnswer(view) else: error = True else: error = True else: error = True else: error = True else: error = True if error: self.say(weatherPlugin.localizations['weatherForecast']['failure'] [language]) self.complete_request()
def setAlarm(self, speech, language): alarmString = re.match(alarmPlugin.res['setAlarm'][language], speech, re.IGNORECASE) if language == 'fr-FR': labelGroupId = 8 alarmHour = int(alarmString.group(4)) alarm24Hour = alarmHour alarmMinutes = alarmString.group(6) alarmAMPM = "" alarmLabelExists = alarmString.group(labelGroupId) elif language == 'zh-CN': labelGroupId = 7 alarmHour = toNum(alarmString.group(2)) alarm24Hour = alarmHour if alarmString.group(3) == u'点半': alarmMinutes = str(30) else: alarmMinutes = str(toNum(alarmString.group(5))) alarmAMPM = "" alarmLabelExists = alarmString.group(labelGroupId) else: labelGroupId = 4 alarmHour = int(alarmString.group(1)) alarm24Hour = alarmHour alarmMinutes = alarmString.group(2) alarmAMPM = alarmString.group(3) alarmLabelExists = alarmString.group(labelGroupId) #check if we are naming the alarm if alarmLabelExists == None: alarmLabel = None else: alarmLabel = alarmString.group(labelGroupId) #the siri alarm object requires 24 hour clock if (alarmAMPM == "pm" and alarmHour != 12): alarm24Hour += 12 if alarmMinutes == None: alarmMinutes = "00" else: alarmMinutes = int(alarmMinutes.strip()) view = AddViews(self.refId, dialogPhase="Reflection") view.views = [ AssistantUtteranceView( speakableText=alarmPlugin.localizations['Alarm'] ['settingAlarm'][language], dialogIdentifier="Alarm#settingAlarm") ] self.sendRequestWithoutAnswer(view) #create the alarm alarm = AlarmObject(alarmLabel, int(alarmMinutes), alarm24Hour, None, 1) response = self.getResponseForRequest(AlarmCreate(self.refId, alarm)) #print(alarmPlugin.localizations['Alarm']['alarmWasSet'][language].format(alarmHour, alarmMinutes, alarmAMPM)) view = AddViews(self.refId, dialogPhase="Completion") if alarmLabel == None: view1 = AssistantUtteranceView( speakableText=alarmPlugin.localizations['Alarm']['alarmWasSet'] [language].format(alarmHour, alarmMinutes, alarmAMPM), dialogIdentifier="Alarm#alarmWasSet") else: view1 = AssistantUtteranceView( speakableText=alarmPlugin.localizations['Alarm'] ['alarmSetWithLabel'][language].format(alarmLabelExists, alarmLabel, alarmHour, alarmMinutes, alarmAMPM), dialogIdentifier="Alarm#alarmSetWithLabel") view2 = AlarmSnippet(alarms=[alarm]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) self.complete_request()
def wolfram(self, speech, language, regex): if language == 'fr-FR': wolframQuestion = regex.group(regex.lastindex).strip() wolframQuestion = wolframQuestion.replace("le ", "").replace( "la ", "").replace("les ", "").replace("un ", "").replace( "une ", "").replace("de ", "").replace("du ", "").replace("des ", "") wolframTranslation = 'true' elif language == "en-US": wolframQuestion = speech.replace('who is ', '').replace( 'how many ', '').replace('what was ', '').replace( 'Who is ', '').replace('What is ', '').replace('What was ', '').replace(' ', '%20') wolframTranslation = 'false' elif language == "de-DE": wolframQuestion = speech.replace('wer ist ', '').replace( 'was ist ', '').replace('Wer ist ', '').replace('Was ist ', '').replace( 'Wie viel ', 'How much ').replace('Wie lang ', 'How long ').replace( 'Wie weit ', 'How far ').replace('Wann ist ', 'When is ').replace( 'Zeig mir ', 'Show me ' ).replace('Wie hoch ', 'How high ').replace( 'Wie tief ', 'How deep ').replace('ist', 'is').replace( 'der', 'the').replace('die', 'the').replace( 'das', 'the').replace( 'wie viel ', 'how much ').replace( 'wie lang ', 'how long ').replace( 'wie weit ', 'how far ').replace( 'wann ist ', 'when is ' ).replace( 'zeig mir ', 'show me ' ).replace( 'wie hoch ', 'how high ' ).replace( 'wie tief ', 'how deep ' ).replace('ist', 'is').replace( 'der', 'the' ).replace( 'die', 'the' ).replace( 'das', 'the' ).replace(' ', '%20').replace( u'ä', 'a').replace( u'ö', 'o').replace( u'ü', 'u').replace( u'ß', 's') wolframTranslation = 'true' else: wolframQuestion = speech.replace('who is ', '').replace( 'what is ', '').replace('what was ', '').replace( 'Who is ', '').replace('What is ', '').replace('What was ', '').replace(' ', '%20') wolframTranslation = 'false' wolfram_alpha = u'http://api.wolframalpha.com/v1/query.jsp?input=%s&appid=%s&translation=%s' % ( urllib.quote_plus( wolframQuestion.encode("utf-8")), APPID, wolframTranslation) dom = minidom.parse(urlopen(wolfram_alpha)) count_wolfram = 0 wolfram0 = 12 wolfram_pod0 = 12 wolfram0_img = 12 wolfram1 = 12 wolfram_pod1 = 12 wolfram1_img = 12 wolfram2 = 12 wolfram_pod2 = 12 wolfram2_img = 12 wolfram3 = 12 wolfram_pod3 = 12 wolfram3_img = 12 wolfram4 = 12 wolfram_pod4 = 12 wolfram4_img = 12 wolfram5 = 12 wolfram_pod5 = 12 wolfram5_img = 12 wolfram6 = 12 wolfram_pod6 = 12 wolfram6_img = 12 wolfram7 = 12 wolfram_pod7 = 12 wolfram7_img = 12 wolfram8 = 12 wolfram_pod8 = 12 wolfram8_img = 12 wolframAnswer = 12 wolframAnswer2 = 12 wolframAnswer3 = 12 wolframAnswer4 = 12 wolframAnswer8 = 12 query_list = dom.getElementsByTagName('queryresult')[-1] query_type = query_list.getAttribute('error') for node in dom.getElementsByTagName('queryresult'): for pod in node.getElementsByTagName('pod'): xmlTag = dom.getElementsByTagName( 'plaintext')[count_wolfram].toxml() xmlTag2 = dom.getElementsByTagName('subpod')[count_wolfram] xmlData = xmlTag.replace('<plaintext>', '').replace('</plaintext>', '') if count_wolfram == 0: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram0 = image_type wolfram0_img = 1 else: wolfram0 = xmlData wolfram_pod0 = pod.getAttribute('title') elif count_wolfram == 1: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram1 = image_type wolfram1_img = 1 else: wolfram1 = xmlData wolfram_pod1 = pod.getAttribute('title') elif count_wolfram == 2: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram2 = image_type wolfram2_img = 1 else: wolfram2 = xmlData wolfram_pod2 = pod.getAttribute('title') elif count_wolfram == 3: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram3 = image_type wolfram3_img = 1 else: wolfram3 = xmlData wolfram_pod3 = pod.getAttribute('title') elif count_wolfram == 4: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram4 = image_type wolfram4_img = 1 else: wolfram4 = xmlData wolfram_pod4 = pod.getAttribute('title') elif count_wolfram == 5: wolfram5 = xmlData wolfram_pod5 = pod.getAttribute('title') elif count_wolfram == 6: wolfram6 = xmlData wolfram_pod6 = pod.getAttribute('title') elif count_wolfram == 7: wolfram7 = xmlData wolfram_pod7 = pod.getAttribute('title') elif count_wolfram == 8: wolfram8 = xmlData wolfram_pod8 = pod.getAttribute('title') count_wolfram += 1 # Waiting for a response view = AddViews(self.refId, dialogPhase="Completion") if wolfram_pod0 != 12: if wolfram0_img == 1: wolframAnswer = AnswerObject( title=wolfram_pod0, lines=[AnswerObjectLine(image=wolfram0)]) else: wolframAnswer = AnswerObject( title=wolfram_pod0, lines=[AnswerObjectLine(text=wolfram0)]) else: print wolfram_pod0 if wolfram_pod1 != 12: if wolfram1_img == 1: wolframAnswer1 = AnswerObject( title=wolfram_pod1, lines=[AnswerObjectLine(image=wolfram1)]) else: wolframAnswer1 = AnswerObject( title=wolfram_pod1, lines=[AnswerObjectLine(text=wolfram1)]) else: print wolfram_pod1 if wolfram_pod2 != 12: if wolfram2_img == 1: wolframAnswer2 = AnswerObject( title=wolfram_pod2, lines=[AnswerObjectLine(image=wolfram2)]) else: wolframAnswer2 = AnswerObject( title=wolfram_pod2, lines=[AnswerObjectLine(text=wolfram2)]) else: print wolfram_pod2 if wolfram_pod3 != 12: if wolfram3_img == 1: wolframAnswer3 = AnswerObject( title=wolfram_pod3, lines=[AnswerObjectLine(image=wolfram3)]) else: wolframAnswer3 = AnswerObject( title=wolfram_pod3, lines=[AnswerObjectLine(text=wolfram3)]) else: print wolfram_pod3 if wolfram_pod4 != 12: if wolfram4_img == 1: wolframAnswer4 = AnswerObject( title=wolfram_pod4, lines=[AnswerObjectLine(image=wolfram4)]) else: wolframAnswer4 = AnswerObject( title=wolfram_pod4, lines=[AnswerObjectLine(text=wolfram4)]) else: print wolfram_pod4 if wolfram_pod8 != 12: if wolfram8_img == 1: wolframAnswer8 = AnswerObject( title=wolfram_pod8, lines=[AnswerObjectLine(image=wolfram8)]) else: wolframAnswer8 = AnswerObject( title=wolfram_pod8, lines=[AnswerObjectLine(text=wolfram8)]) if wolfram_pod0 != 12: # I found it if language == 'de-DE': self.say("Dies koennte Ihre Frage beantworten:") elif language == 'fr-FR': rep = [ u"Cela pourrait répondre à votre question : ", u"Voici la réponse à votre question : ", u"Cela répond peut-être à votre question : " ] self.say(random.choice(rep)) else: self.say("This might answer your question:") if wolfram_pod0 == 12: if language == 'de-DE': self.say( "Es tut mir leid. Ich konnte keine Antwort auf Ihre Frage finden." ) elif language == 'fr-FR': rep = [ u"Je n'ai trouvé aucune réponse à votre question !", u"Je ne trouve pas la réponse à votre question !", u"Je ne trouve aucune réponse à votre question !", u"Désolé, je ne connais pas de réponse à votre question !" ] self.say(random.choice(rep)) else: self.say("Nothing was found for your query!") self.complete_request() view1 = 0 elif wolfram_pod1 == 12: view1 = AnswerSnippet(answers=[wolframAnswer]) elif wolfram_pod2 == 12: view1 = AnswerSnippet(answers=[wolframAnswer, wolframAnswer1]) elif wolfram_pod3 == 12: view1 = AnswerSnippet( answers=[wolframAnswer, wolframAnswer1, wolframAnswer2]) elif wolfram_pod4 == 12: view1 = AnswerSnippet(answers=[ wolframAnswer, wolframAnswer1, wolframAnswer2, wolframAnswer3 ]) elif wolfram_pod8 == 12: view1 = AnswerSnippet(answers=[ wolframAnswer, wolframAnswer1, wolframAnswer2, wolframAnswer3, wolframAnswer4 ]) else: view1 = AnswerSnippet(answers=[ wolframAnswer, wolframAnswer1, wolframAnswer2, wolframAnswer3, wolframAnswer4, wolframAnswer8 ]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request()
def whereAmI(self, speech, language): mapGetLocation = self.getCurrentLocation() latitude = mapGetLocation.latitude longitude = mapGetLocation.longitude url = u"http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&language={2}".format( str(latitude), str(longitude), language) try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) if response['status'] == 'OK': components = response['results'][0]['address_components'] street = filter( lambda x: True if "route" in x['types'] else False, components)[0]['long_name'] stateLong = filter( lambda x: True if "administrative_area_level_1" in x['types'] or "country" in x['types'] else False, components)[0]['long_name'] try: postalCode = filter( lambda x: True if "postal_code" in x['types'] else False, components)[0]['long_name'] except: postalCode = "" try: city = filter( lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name'] except: city = "" countryCode = filter( lambda x: True if "country" in x['types'] else False, components)[0]['short_name'] view = AddViews(self.refId, dialogPhase="Completion") if language == "de-DE": the_header = "Dein Standort" else: the_header = "Your location" Location = SiriLocation(the_header, street, city, stateLong, countryCode, postalCode, latitude, longitude) mapsnippet = SiriMapItemSnippet( items=[SiriMapItem(the_header, Location)]) view.views = [ AssistantUtteranceView(text=the_header, dialogIdentifier="Map"), mapsnippet ] self.sendRequestWithoutAnswer(view) else: if language == "de-DE": self.say('Die Googlemaps informationen waren ungenügend!', 'Fehler') else: self.say( 'The Googlemaps response did not hold the information i need!', 'Error') else: if language == "de-DE": self.say('Ich konnte keine Verbindung zu Googlemaps aufbauen', 'Fehler') else: self.say('Could not establish a conenction to Googlemaps', 'Error') self.complete_request()
def wolfram(self, speech, language): if language == "en-US": wolframQuestion = speech.replace('who is ', '').replace( 'what is ', '').replace('what was ', '').replace( 'Who is ', '').replace('What is ', '').replace('What was ', '').replace(' ', '%20') wolframTranslation = 'false' elif language == "de-DE": wolframQuestion = speech.replace('wer ist ', '').replace( 'was ist ', '').replace('Wer ist ', '').replace('Was ist ', '').replace( 'Wie viel ', 'How much ').replace('Wie lang ', 'How long ').replace( 'Wie weit ', 'How far ').replace('Wann ist ', 'When is ').replace( 'Zeig mir ', 'Show me ' ).replace('Wie hoch ', 'How high ').replace( 'Wie tief ', 'How deep ').replace('ist', 'is').replace( 'der', 'the').replace('die', 'the').replace( 'das', 'the').replace( 'wie viel ', 'how much ').replace( 'wie lang ', 'how long ').replace( 'wie weit ', 'how far ').replace( 'wann ist ', 'when is ' ).replace( 'zeig mir ', 'show me ' ).replace( 'wie hoch ', 'how high ' ).replace( 'wie tief ', 'how deep ' ).replace('ist', 'is').replace( 'der', 'the' ).replace( 'die', 'the' ).replace( 'das', 'the' ).replace(' ', '%20').replace( u'ä', 'a').replace( u'ö', 'o').replace( u'ü', 'u').replace( u'ß', 's') wolframTranslation = 'true' else: wolframQuestion = speech.replace('who is ', '').replace( 'what is ', '').replace('what was ', '').replace( 'Who is ', '').replace('What is ', '').replace('What was ', '').replace(' ', '%20') wolframTranslation = 'false' wolfram_alpha = 'http://api.wolframalpha.com/v1/query.jsp?input=%s&appid=%s&translation=%s' % ( wolframQuestion, APPID, wolframTranslation) dom = minidom.parse(urlopen(wolfram_alpha)) count_wolfram = 0 wolfram0 = 12 wolfram_pod0 = 12 wolfram0_img = 12 wolfram1 = 12 wolfram_pod1 = 12 wolfram1_img = 12 wolfram2 = 12 wolfram_pod2 = 12 wolfram2_img = 12 wolfram3 = 12 wolfram_pod3 = 12 wolfram3_img = 12 wolfram4 = 12 wolfram_pod4 = 12 wolfram4_img = 12 wolfram5 = 12 wolfram_pod5 = 12 wolfram5_img = 12 wolfram6 = 12 wolfram_pod6 = 12 wolfram6_img = 12 wolfram7 = 12 wolfram_pod7 = 12 wolfram7_img = 12 wolfram8 = 12 wolfram_pod8 = 12 wolfram8_img = 12 wolframAnswer = 12 wolframAnswer2 = 12 wolframAnswer3 = 12 wolframAnswer4 = 12 wolframAnswer8 = 12 query_list = dom.getElementsByTagName('queryresult')[-1] query_type = query_list.getAttribute('error') for node in dom.getElementsByTagName('queryresult'): for pod in node.getElementsByTagName('pod'): xmlTag = dom.getElementsByTagName( 'plaintext')[count_wolfram].toxml() xmlTag2 = dom.getElementsByTagName('subpod')[count_wolfram] xmlData = xmlTag.replace('<plaintext>', '').replace('</plaintext>', '') if count_wolfram == 0: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram0 = image_type wolfram0_img = 1 else: wolfram0 = xmlData wolfram_pod0 = pod.getAttribute('title') elif count_wolfram == 1: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram1 = image_type wolfram1_img = 1 else: wolfram1 = xmlData wolfram_pod1 = pod.getAttribute('title') elif count_wolfram == 2: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram2 = image_type wolfram2_img = 1 else: wolfram2 = xmlData wolfram_pod2 = pod.getAttribute('title') elif count_wolfram == 3: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram3 = image_type wolfram3_img = 1 else: wolfram3 = xmlData wolfram_pod3 = pod.getAttribute('title') elif count_wolfram == 4: if xmlData == "<plaintext/>": image_list = dom.getElementsByTagName( 'img')[count_wolfram] image_type = image_list.getAttribute('src') wolfram4 = image_type wolfram4_img = 1 else: wolfram4 = xmlData wolfram_pod4 = pod.getAttribute('title') elif count_wolfram == 5: wolfram5 = xmlData wolfram_pod5 = pod.getAttribute('title') elif count_wolfram == 6: wolfram6 = xmlData wolfram_pod6 = pod.getAttribute('title') elif count_wolfram == 7: wolfram7 = xmlData wolfram_pod7 = pod.getAttribute('title') elif count_wolfram == 8: wolfram8 = xmlData wolfram_pod8 = pod.getAttribute('title') count_wolfram += 1 if language == 'de-DE': self.say("Dies könnte Ihre Frage zu beantworten:") else: self.say("This might answer your question:") view = AddViews(self.refId, dialogPhase="Completion") if wolfram_pod0 != 12: if wolfram0_img == 1: wolframAnswer = AnswerObject( title=wolfram_pod0, lines=[AnswerObjectLine(image=wolfram0)]) else: wolframAnswer = AnswerObject( title=wolfram_pod0, lines=[AnswerObjectLine(text=wolfram0)]) else: print wolfram_pod0 if wolfram_pod1 != 12: if wolfram1_img == 1: wolframAnswer1 = AnswerObject( title=wolfram_pod1, lines=[AnswerObjectLine(image=wolfram1)]) else: wolframAnswer1 = AnswerObject( title=wolfram_pod1, lines=[AnswerObjectLine(text=wolfram1)]) else: print wolfram_pod1 if wolfram_pod2 != 12: if wolfram2_img == 1: wolframAnswer2 = AnswerObject( title=wolfram_pod2, lines=[AnswerObjectLine(image=wolfram2)]) else: wolframAnswer2 = AnswerObject( title=wolfram_pod2, lines=[AnswerObjectLine(text=wolfram2)]) else: print wolfram_pod2 if wolfram_pod3 != 12: if wolfram3_img == 1: wolframAnswer3 = AnswerObject( title=wolfram_pod3, lines=[AnswerObjectLine(image=wolfram3)]) else: wolframAnswer3 = AnswerObject( title=wolfram_pod3, lines=[AnswerObjectLine(text=wolfram3)]) else: print wolfram_pod3 if wolfram_pod4 != 12: if wolfram4_img == 1: wolframAnswer4 = AnswerObject( title=wolfram_pod4, lines=[AnswerObjectLine(image=wolfram4)]) else: wolframAnswer4 = AnswerObject( title=wolfram_pod4, lines=[AnswerObjectLine(text=wolfram4)]) else: print wolfram_pod4 if wolfram_pod8 != 12: if wolfram8_img == 1: wolframAnswer8 = AnswerObject( title=wolfram_pod8, lines=[AnswerObjectLine(image=wolfram8)]) else: wolframAnswer8 = AnswerObject( title=wolfram_pod8, lines=[AnswerObjectLine(text=wolfram8)]) if wolfram_pod0 == 12: if APPID == "": self.say( "Sorry I can't process your request. Your APPID is not set! Please register free dev account at http://wolframalpha.com and edit line 21 with you APPID." ) else: if language == 'de-DE': self.say( "Es tut mir leid. Ich konnte keine Antwort auf Ihre Frage finden." ) else: self.say("Nothing has found for your query!") self.complete_request() view1 = 0 elif wolfram_pod1 == 12: view1 = AnswerSnippet(answers=[wolframAnswer]) elif wolfram_pod2 == 12: view1 = AnswerSnippet(answers=[wolframAnswer, wolframAnswer1]) elif wolfram_pod3 == 12: view1 = AnswerSnippet( answers=[wolframAnswer, wolframAnswer1, wolframAnswer2]) elif wolfram_pod4 == 12: view1 = AnswerSnippet(answers=[ wolframAnswer, wolframAnswer1, wolframAnswer2, wolframAnswer3 ]) elif wolfram_pod8 == 12: view1 = AnswerSnippet(answers=[ wolframAnswer, wolframAnswer1, wolframAnswer2, wolframAnswer3, wolframAnswer4 ]) else: view1 = AnswerSnippet(answers=[ wolframAnswer, wolframAnswer1, wolframAnswer2, wolframAnswer3, wolframAnswer4, wolframAnswer8 ]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request()
def whereIs(self, speech, language, regex): the_location = None if language == "de-DE": the_location = re.match("(?u).* liegt ([\w ]+)$", speech, re.IGNORECASE) the_location = the_location.group(1).strip() elif language == 'fr-FR': the_location = regex.group(regex.lastindex).strip() elif language == 'zh-CN': the_location = re.match(u"(?u)([\w ]+)(?:在哪|的位置).*", speech, re.IGNORECASE) the_location = the_location.group(1).strip() else: the_location = re.match("(?u).* is ([\w ]+)$", speech, re.IGNORECASE) the_location = the_location.group(1).strip() if the_location != None: the_location = the_location[0].upper()+the_location[1:] else: if language == "de-DE": self.say('Ich habe keinen Ort gefunden!',None) elif language == 'fr-FR': self.say(u"Désolé, je n'arrive pas à trouver cet endroit !") elif language == 'zh-CN': self.say(u"找不到这个位置。") else: self.say('No location found!',None) self.complete_request() return url = u"http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false&language={1}".format(urllib.quote_plus(the_location.encode("utf-8")), language) jsonString=None try: jsonString = urllib2.urlopen(url, timeout=10).read() except: pass if jsonString != None: response = json.loads(jsonString) if response['status'] == 'OK': location = response['results'][0]['geometry']['location'] city=response['results'][0]['address_components'][0]['long_name'] try: country=response['results'][0]['address_components'][2]['long_name'] countryCode=response['results'][0]['address_components'][2]['short_name'] except: country=the_location countryCode=the_location if language=="de-DE": the_header=u"Hier liegt {0}".format(the_location) elif language =="fr-FR": the_header=u"Voici l'emplacement de {0} :".format(the_location) elif language =="zh-CN": self.say(u"这是{0}".format(the_location)) the_header=u"{0}".format(the_location) else: self.say(u"Here is {0}".format(the_location)) the_header=u"{0}".format(the_location) view = AddViews(self.refId, dialogPhase="Completion") mapsnippet = MapItemSnippet(items=[MapItem(label=city+" "+country, street=city, city=city, postalCode="", latitude=str(location['lat']), longitude=str(location['lng']), detailType="BUSINESS_ITEM")]) view.views = [AssistantUtteranceView(text=the_header, dialogIdentifier="Map#whereIs"), mapsnippet] self.sendRequestWithoutAnswer(view) else: if language=="de-DE": self.say('Die Googlemaps informationen waren ungenügend!','Fehler') elif language == "fr-FR": self.say(u"Les informations demandées ne sont pas sur Google Maps !", u'Erreur') elif language == 'zh-CN': self.say(u"我找不到这个位置。") else: self.say('The Googlemaps response did not hold the information i need!','Error') else: if language=="de-DE": self.say('Ich konnte keine Verbindung zu Googlemaps aufbauen','Fehler') elif language == 'fr-FR': self.say(u"Je n'arrive pas à joindre Google Maps.", 'Erreur') elif language=="zh-CN": self.say(u"我无法访问谷歌地图。") else: self.say('Could not establish a conenction to Google Maps.','Error'); self.complete_request()
def addPictureView(self,title,image_url): view = AddViews(self.refId, dialogPhase="Completion") ImageAnswer = AnswerObject(title=title,lines=[AnswerObjectLine(image=image_url)]) view1 = AnswerSnippet(answers=[ImageAnswer]) view.views = [view1] self.sendRequestWithoutAnswer(view)