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 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 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 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()