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 resumeTimer(self, speech, language): response = self.getResponseForRequest(TimerGet(self.refId)) timer_properties = response['properties']['timer']['properties'] timer = TimerObject(timerValue=timer_properties['timerValue'], state=timer_properties['state']) if timer.state == "Paused": response = self.getResponseForRequest(TimerResume(self.refId)) if response['class'] == "ResumeCompleted": view = AddViews(self.refId, dialogPhase="Completion") view1 = AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['timerWasResumed'][language], dialogIdentifier="Timer#timerWasResumed") view2 = TimerSnippet(timers=[timer]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) self.complete_request() else: view = AddViews(self.refId, dialogPhase="Completion") view1 = AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['timerIsAlreadyStopped'][language], dialogIdentifier="Timer#timerIsAlreadyStopped") view2 = TimerSnippet(timers=[timer]) 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 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 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 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 showTimer(self, speech, language): response = self.getResponseForRequest(TimerGet(self.refId)) timer_properties = response['properties']['timer']['properties'] timer = TimerObject(timerValue=timer_properties['timerValue'], state=timer_properties['state']) view = AddViews(self.refId, dialogPhase="Summary") view1 = AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer']['showTheTimer'] [language], dialogIdentifier="Timer#showTheTimer") view2 = TimerSnippet(timers=[timer]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) 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 setTimer(self, speech, language): m = re.match(timerPlugin.res['setTimer'][language], speech, re.IGNORECASE) timer_length = u"" if language == 'zh-CN': ch_hour = toNum(m.group('h')) ch_min = toNum(m.group('m')) ch_sec = toNum(m.group('s')) if ch_hour != 0: timer_length += str(ch_hour) + u"小时" if ch_min != 0: timer_length += str(ch_min) + u"分钟" if ch_sec != 0: timer_length += str(ch_sec) + u"秒" duration = ch_hour * 3600 + ch_min * 60 + ch_sec else: timer_length = m.group('length') duration = parse_timer_length(timer_length, language) view = AddViews(self.refId, dialogPhase="Reflection") view.views = [ AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['settingTimer'][language], dialogIdentifier="Timer#settingTimer") ] self.sendRequestWithoutAnswer(view) # check the current state of the timer response = self.getResponseForRequest(TimerGet(self.refId)) if response['class'] == 'CancelRequest': self.complete_request() return timer_properties = response['properties']['timer']['properties'] timer = TimerObject(timerValue=timer_properties['timerValue'], state=timer_properties['state']) if timer.state == "Running": # timer is already running! view = AddViews(self.refId, dialogPhase="Completion") view1 = AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['timerIsAlreadyRunning'][language], dialogIdentifier="Timer#timerIsAlreadyRunning") view2 = TimerSnippet(timers=[timer], confirm=True) view.views = [view1, view2] utterance = self.getResponseForRequest(view) #if response['class'] == 'StartRequest': view = AddViews(self.refId, dialogPhase="Reflection") view.views = [ AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['settingTimer'][language], dialogIdentifier="Timer#settingTimer") ] self.sendRequestWithoutAnswer(view) if re.match('\^timerConfirmation\^=\^no\^', utterance): # user canceled view = AddViews(self.refId, dialogPhase="Completion") view.views = [ AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['wontSetTimer'][language], dialogIdentifier="Timer#wontSetTimer") ] self.sendRequestWithoutAnswer(view) self.complete_request() return else: # user wants to set the timer still - continue on pass if duration > 24 * 60 * 60: view = AddViews(self.refId, dialogPhase='Clarification') view.views = [ AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer'] ['durationTooBig'][language], dialogIdentifier='Timer#durationTooBig') ] self.sendRequestWithoutAnswer(view) self.complete_request() return # start a new timer timer = TimerObject(timerValue=duration, state="Running") response = self.getResponseForRequest(TimerSet(self.refId, timer=timer)) print(timerPlugin.localizations['Timer']['timerWasSet'] [language].format(timer_length)) view = AddViews(self.refId, dialogPhase="Completion") view1 = AssistantUtteranceView( speakableText=timerPlugin.localizations['Timer']['timerWasSet'] [language].format(timer_length), dialogIdentifier="Timer#timerWasSet") view2 = TimerSnippet(timers=[timer]) view.views = [view1, view2] self.sendRequestWithoutAnswer(view) 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 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 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 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 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()