def googleplaces_search(self, speech, language, regex): #added global Title #end addition if language == "fr-FR": self.say('Je recherche...',' ') else: self.say('Searching...',' ') mapGetLocation = self.getCurrentLocation() latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude #modified if Title == None: Title = regex.group(regex.lastindex).strip() Query = urllib.quote_plus(str(Title.encode("utf-8"))) else: Query = urllib.quote_plus(Title) #end modify 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: if language == "fr-FR": self.say("Je suis désolé, je n'ai pas trouvé de résultats pour "+str(Title)+" près de vous!") else: self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") else: if language == "fr-FR": self.say("Je suis désolé, je n'ai pas trouvé de résultats pour "+str(Title)+" près de vous!") else: self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") self.complete_request()
def googleplaces_search(self, speech, language, regex): self.say(u"搜尋中",' ') mapGetLocation = self.getCurrentLocation() latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude Title = re.findall(u"(找附近|搜尋附近).*(.*)",speech)[0][1] ##regex.group(regex.lastindex).strip() if Title.count(u'的') > 0: Title = Title.replace(u"的","") if Title.count(u"seven") > 0 or Title.count(u"統一") > 0: Title = u"7-11" 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)) print googleurl 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") if Title == u"7-11": Title = u"Seven Eleven" view.views = [AssistantUtteranceView(speakableText=u'我找到 '+str(count_max)+u' 個 '+ Title +u' 其中 '+str(count_min)+u' 個非常靠近你:', dialogIdentifier="googlePlacesMap"), mapsnippet] self.sendRequestWithoutAnswer(view) else: self.say(u"很抱歉,在你附近找不到"+Title) else: self.say(u"很抱歉,在你附近找不到"+Title) self.complete_request()
def GooglePlaceSearch(self, speech, language, Title): self.say('Buscando...',' ') global notAvailable mapGetLocation = self.getCurrentLocation() latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude Query = urllib.quote_plus(Title) random_results = random.randint(2,15) googleurl = "https://maps.googleapis.com/maps/api/place/search/json?location={0},{1}&radius=10000&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='He encontrado '+str(count_max)+' resultados de '+str(Title)+'. Los más cercanos hacia ti:', dialogIdentifier="googlePlacesMap"), mapsnippet] self.sendRequestWithoutAnswer(view) else: if notAvailable != None: self.say(notAvailable) else: self.say("Lo siento, pero no he encontrado ningún resultado para "+str(Title)+".") else: if notAvailable != None: self.say(notAvailable) else: self.say("Lo siento, pero no he encontrado ningún resultado para "+str(Title)+".") notAvailable = None self.complete_request()
def yelp_search(self, speech, language, regex): #this has been added global Title #end additions self.say(yelpSearch.res['searching'][language],' ') mapGetLocation = self.getCurrentLocation() latitude = mapGetLocation.latitude longitude = mapGetLocation.longitude #this has been modified if Title == None: Title = regex.group(regex.lastindex).strip() Query = urllib.quote_plus(str(Title.encode("utf-8"))) else: Query = urllib.quote_plus(Title) #end modification random_results = random.randint(2,15) yelpurl = "http://api.yelp.com/business_review_search?term={0}&lat={1}&long={2}&radius=5&limit=20&ywsid={3}".format(str(Query),latitude,longitude,str(yelp_api_key)) try: jsonString = urllib2.urlopen(yelpurl, timeout=20).read() except: jsonString = None if jsonString != None: response = json.loads(jsonString) if (response['message']['text'] == 'OK') and (len(response['businesses'])): response['businesses'] = sorted(response['businesses'], key=lambda business: float(business['distance'])) yelp_results = [] for result in response['businesses']: rating = Rating(value=result['avg_rating'], providerId='YELP', count=result['review_count']) details = Business(totalNumberOfReviews=result['review_count'],name=result['name'],rating=rating) if (len(yelp_results) < random_results): mapitem = MapItem(label=result['name'], street=result['address1'], stateCode=result['state_code'], postalCode=result['zip'],latitude=result['latitude'], longitude=result['longitude']) mapitem.detail = details yelp_results.append(mapitem) else: break mapsnippet = MapItemSnippet(items=yelp_results) count_min = min(len(response['businesses']),random_results) count_max = max(len(response['businesses']),random_results) view = AddViews(self.refId, dialogPhase="Completion") responseText = yelpSearch.res['results'][language].format(str(count_max), str(Title), str(count_min)) view.views = [AssistantUtteranceView(speakableText=responseText, dialogIdentifier="yelpSearchMap"), mapsnippet] self.sendRequestWithoutAnswer(view) else: self.say(yelpSearch.res['no-results'][language].format(str(Title))) else: self.say(yelpSearch.res['no-results'][language].format(str(Title))) self.complete_request()
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&keyword={2}&sensor=true&key={3}".format(str(latitude),str(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 = [] response['results'] = sorted(response['results'], key=lambda result: self.haversine_distance(result['geometry']['location']['lat'],result['geometry']['location']['lng'],latitude,longitude)) 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)+' query results... '+str(count_min)+' of them are fairly close to you:', dialogIdentifier="googlePlacesMap"), mapsnippet] self.sendRequestWithoutAnswer(view) else: self.say("Sorry, I cannot found it. Your location is: ("+str(latitude)+","+str(longitude)+")") #self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") else: self.say('Could not establish a conenction to Googlemaps','Error') #self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") 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 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 yahoo_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) yahoourl = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid={0}&query={1}&latitude={2}&longitude={3}&results=20&sort=distance&output=json".format(str(yahoo_api_key),str(Query),latitude,longitude) try: jsonString = urllib2.urlopen(yahoourl, timeout=20).read() except: jsonString = None if jsonString != None: response = json.loads(jsonString) if response['ResultSet']['totalResultsReturned'] >= 1: #response['ResultSet'] = sorted(response['ResultSet']['Result'], key=lambda result: float(result['Distance'])) yahoo_results = [] for result in response['ResultSet']['Result']: rating = Rating(value=result['Rating']['AverageRating'], providerId='Yahoo', count=result['Rating']['TotalRatings']) details = Business(totalNumberOfReviews=result['Rating']['TotalRatings'],name=result['Title'],rating=rating) if (len(yahoo_results) < random_results): mapitem = MapItem(label=result['Title'], street=result['Address'], stateCode=result['State'], latitude=result['Latitude'], longitude=result['Longitude']) mapitem.detail = details yahoo_results.append(mapitem) else: break mapsnippet = MapItemSnippet(items=yahoo_results) count_min = min(len(response['ResultSet']['Result']),random_results) count_max = max(len(response['ResultSet']['Result']),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="yahooLocalSearchMap"), 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 directions(self, speech, language, regex): searchlocation = regex.group('location') Title = searchlocation Query = urllib.quote_plus(str(Title.encode("utf-8"))) googleurl = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true&language=en".format(Query) jsonString = urllib2.urlopen(googleurl, timeout=20).read() response = json.loads(jsonString) if (response['status'] == 'OK') and (len(response['results'])): for result in response['results']: label = "{0}".format(Title.title()) latitude=result['geometry']['location']['lat'] longitude=result['geometry']['location']['lng'] city=result['address_components'][0]['long_name'] state=result['address_components'][2]['short_name'] country=result['address_components'][3]['short_name'] else: self.say("Leider koennen Richtungen nur Straßennamen gegeben werden bis jetzt.") self.conplete_request() code = 0 Loc = Location(self.refId) Loc.street = "" Loc.countryCode = country Loc.city = city Loc.latitude = latitude Loc.stateCode = state Loc.longitude = longitude Map = MapItem(self.refId) Map.detailType = "ADDRESS_ITEM" Map.label = label Map.location = Loc Source = MapItem(self.refId) Source.detailType = "CURRENT_LOCATION" ShowPoints = ShowMapPoints(self.refId) ShowPoints.showTraffic = False ShowPoints.showDirections = True ShowPoints.regionOfInterestRadiusInMiles = "10.0" ShowPoints.itemDestination = Map ShowPoints.itemSource = Source AddViews = UIAddViews(self.refId) AddViews.dialogPhase = "Summary" AssistantUtteranceView = UIAssistantUtteranceView() AssistantUtteranceView.dialogIdentifier = "LocationSearch#foundLocationForDirections" AssistantUtteranceView.speakableText = "Hier ist der Weg nach {0}:".format(label) AssistantUtteranceView.text = "Hier ist der Weg nach {0}:".format(label) AddViews.views = [(AssistantUtteranceView)] AddViews.scrollToTop = False AddViews.callbacks = [ResultCallback([ShowPoints], code)] callback = [ResultCallback([AddViews])] self.complete_request(callbacks=[ResultCallback([AddViews], code)])
def trafficSelf(self, speech, language, regex): mapGetLocation = self.getCurrentLocation(force_reload=True,accuracy=GetRequestOrigin.desiredAccuracyBest) latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude label = "You Are Here" code = 0 Loc = Location(self.refId) Loc.street = "" Loc.countryCode = "US" Loc.city = "" Loc.latitude = latitude Loc.stateCode = "" Loc.longitude = longitude Map = MapItem(self.refId) Map.detailType = "ADDRESS_ITEM" Map.label = label Map.location = Loc Source = MapItem(self.refId) Source.detailType = "CURRENT_LOCATION" MapSnippet = MapItemSnippet(items=[Map]) ShowPoints = ShowMapPoints(self.refId) ShowPoints.showTraffic = True ShowPoints.showDirections = False ShowPoints.regionOfInterestRadiusInMiles = "10.0" #ShowPoints.itemDestination = Map ShowPoints.itemDestination = MapSnippet ShowPoints.itemSource = Source AddViews = UIAddViews(self.refId) AddViews.dialogPhase = "Summary" AssistantUtteranceView = UIAssistantUtteranceView() AssistantUtteranceView.dialogIdentifier = "LocationSearch#foundLocationForTraffic" AssistantUtteranceView.speakableText = "Here\'s the traffic:" AssistantUtteranceView.text = "Here\'s the traffic:" #AddViews.views = [(AssistantUtteranceView)] AddViews.views = [(AssistantUtteranceView), MapSnippet] AddViews.scrollToTop = False AddViews.callbacks = [ResultCallback([ShowPoints], code)] callback = [ResultCallback([AddViews])] self.complete_request(callbacks=[ResultCallback([AddViews], code)])
def traffic(self, speech, language, regex): if regex.group('userlocation'): locationType = regex.group('userlocation').capitalize() label = locationType.title() if locationType == "Work" or locationType == "Home": locationType = "_$!<{0}>!$_".format(locationType) meSearch = ABPersonSearch(self.refId) meSearch.me = True meSearch.scope = "Local" answer = self.getResponseForRequest(meSearch) if ObjectIsCommand(answer, ABPersonSearchCompleted): results = ABPersonSearchCompleted(answer) persons = results.results identfind = results.results[0] contactIdentifier = identfind.identifier me = persons[0] Addresses = filter(lambda x: x.label == locationType, me.addresses) if len(Addresses) > 0: Result = Addresses[0] street = Result.street PostalCode = Result.postalCode city = Result.city Title = "{0}, {1}, {2}".format(street, city, PostalCode) Query = urllib.quote_plus(str(Title.encode("utf-8"))) googleurl = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true".format(Query) jsonString = urllib2.urlopen(googleurl, timeout=20).read() response = json.loads(jsonString) if (response['status'] == 'OK') and (len(response['results'])): for result in response['results']: latitude=result['geometry']['location']['lat'] longitude=result['geometry']['location']['lng'] state=result['address_components'][4]['long_name'] else: self.say("Sorry, I couldn't find {0} in your address book".format(label)) self.complete_request() else: searchlocation = regex.group('location') Title = searchlocation Query = urllib.quote_plus(str(Title.encode("utf-8"))) googleurl = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true&language=en".format(Query) jsonString = urllib2.urlopen(googleurl, timeout=20).read() response = json.loads(jsonString) label = Title.title() if (response['status'] == 'OK') and (len(response['results'])): response = response['results'][0] label = "{0}".format(Title.title()) latitude=response['geometry']['location']['lat'] longitude=response['geometry']['location']['lng'] city=response['address_components'][0]['long_name'] state=response['address_components'][2]['short_name'] country="US" street="" else: random_results = random.randint(2,15) mapGetLocation = self.getCurrentLocation(force_reload=True,accuracy=GetRequestOrigin.desiredAccuracyBest) latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude yelpurl = "http://api.yelp.com/business_review_search?term={0}&lat={1}&long={2}&radius=10&limit=10&ywsid={3}".format(Query, latitude, longitude, yelp_api_key) try: jsonString = urllib2.urlopen(yelpurl, timeout=20).read() except: jsonString = None if jsonString != None: response = json.loads(jsonString) if (response['message']['text'] == 'OK') and (len(response['businesses'])): sortedResults = sorted(response['businesses'], key=lambda business: float(business['distance'])) response = response['businesses'] sortedResults = sortedResults[0] label = sortedResults['name'] latitude = sortedResults['latitude'] longitude = sortedResults['longitude'] state = sortedResults['state'] street = sortedResults['address1'] city = sortedResults['city'] else: self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!") self.complete_request() code = 0 Loc = Location(self.refId) Loc.street = street Loc.countryCode = "US" Loc.city = city Loc.latitude = latitude Loc.stateCode = state Loc.longitude = longitude Map = MapItem(self.refId) Map.detailType = "ADDRESS_ITEM" Map.label = label Map.location = Loc Source = MapItem(self.refId) Source.detailType = "CURRENT_LOCATION" ShowPoints = ShowMapPoints(self.refId) ShowPoints.showTraffic = False ShowPoints.showDirections = True ShowPoints.regionOfInterestRadiusInMiles = "10.0" ShowPoints.itemDestination = Map ShowPoints.itemSource = Source AddViews = UIAddViews(self.refId) AddViews.dialogPhase = "Summary" AssistantUtteranceView = UIAssistantUtteranceView() AssistantUtteranceView.dialogIdentifier = "LocationSearch#foundLocationForDirections" AssistantUtteranceView.speakableText = "Here are directions to {0}:".format(label) AssistantUtteranceView.text = "Here are directions to {0}:".format(label) AddViews.views = [(AssistantUtteranceView)] AddViews.scrollToTop = False AddViews.callbacks = [ResultCallback([ShowPoints], code)] callback = [ResultCallback([AddViews])] self.complete_request(callbacks=[ResultCallback([AddViews], code)])
def whereisPlaces(self, speech, language, regex): res = self.res keyword = regex.group('keyword') if keyword == None: keyword = regex.group('keyword2') keyword = keyword.strip(); if language == 'fr-FR': keyword = keyword.replace(u"près ","").replace(u"plus proches","").replace(u"plus proche","").replace(u"à proximité","").replace(u"dans le coin","").replace(u"coin ","").replace("par ","").replace('la ','').replace('les ','').replace('le ','').replace('des ','').replace('de ','').replace('du ','').replace('une ','').replace('un ','').replace("dans ","") elif language == 'en-US': keyword = keyword.replace(u"near by ","").replace(u"nearby ","").replace(u"the ","").replace(u"an ","").replace(u"a ","") location = self.getCurrentLocation(force_reload=True,accuracy=GetRequestOrigin.desiredAccuracyBest) latlong = str(location.latitude)+","+str(location.longitude) if language == "fr-FR" and speech.count("pied") > 0: radius = "2500" keyword = keyword.replace(u"à pied","").replace(u"a pied","").replace("pied","") elif language == "en-US" and speech.count("walk") > 0: radius = "2500" keyword = keyword.replace(u"in walking distance","").replace(u"walking distance","").replace(u"walking","").replace("walk","") else: radius = "15000" print "Keyword : " + keyword response = None url = "https://maps.googleapis.com/maps/api/place/search/json?location={0}&radius={1}&keyword={2}&sensor=true&key={3}".format(latlong,radius,urllib.quote_plus(keyword.encode("utf-8")),APIKEY) print url try: jsonString = urllib2.urlopen(url, timeout=3) response = json.load(jsonString); except: pass if response["status"] == "OK": results = [] for result in response["results"]: ident = result["id"] name = result["name"] lat = result["geometry"]["location"]["lat"] lng = result["geometry"]["location"]["lng"] vicinity = result["vicinity"] if "rating" in result: rate = result["rating"] nb_review = 1 else: rate = 0.0 nb_review = 0 #distance = self.haversine_distance(location.latitude, location.longitude, lat, lng) rating = Rating(value=rate, providerId='Google', count=nb_review) details = Business(totalNumberOfReviews=nb_review,name=name,rating=rating) mapitem = MapItem(label=name, street="", stateCode="", postalCode="",latitude=lat, longitude=lng) mapitem.detail = details results.append(mapitem) mapsnippet = MapItemSnippet(items=results) view = AddViews(self.refId, dialogPhase="Completion") view.views = [AssistantUtteranceView(speakableText=res["results_found"][language].format(len(response["results"])), dialogIdentifier="googlePlacesMap"), mapsnippet] self.sendRequestWithoutAnswer(view) elif response["status"] == "ZERO_RESULTS": self.say(res["no_result"][language]) else: self.say(res["connection_error"][language]) self.complete_request()
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 = [] response["results"] = sorted( response["results"], key=lambda result: self.haversine_distance( result["geometry"]["location"]["lat"], result["geometry"]["location"]["lng"], latitude, longitude, ), ) 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 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 googleplaces_search(self, speech, language, regex): view = AddViews(refId=self.refId, dialogPhase="Reflection") view.views = [AssistantUtteranceView("Searching...", '')] self.connection.send_object(view) mapGetLocation = self.getCurrentLocation() latitude= mapGetLocation.latitude longitude= mapGetLocation.longitude Title = regex.group(regex.lastindex).strip() if Title[-3:] == ' is': Title = Title[:-3] if Title[-4:] == ' are': Title = Title[:-4] if Title[-1:] == 's': Title = Title[:-1] userHasUsedPlural = True; if (Title.count(' ')+1) == 1: typeOfSearch = 'keyword' else: typeOfSearch = 'name' 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&{4}={2}&sensor=true&key={3}".format(latitude,longitude,str(Query),str(googleplaces_api_key),str(typeOfSearch)) 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 = [] response['results'] = sorted(response['results'], key=lambda result: self.haversine_distance(result['geometry']['location']['lat'],result['geometry']['location']['lng'],latitude,longitude)) 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") if str(count_min) == '1': isOrAre = 'is' else: isOrAre = 'are' if str(count_max) > 1: plural = 's' else: plural = '' view.views = [AssistantUtteranceView(speakableText='I found '+str(count_max)+' '+str(Title)+plural+', '+str(count_min)+' of them '+isOrAre+' fairly close to you:', dialogIdentifier="googlePlacesMap"), mapsnippet] self.sendRequestWithoutAnswer(view) else: self.say("I'm sorry but I did not find a "+str(Title)+" near you!") else: self.say("I'm sorry but I did not find any results for "+str(Title)+"s near you!") self.complete_request()