class StoryTeller: """docstring""" def __init__(self): self.wikipedia = MediaWiki(lang=u'fr') self._latitude = None self._longitude = None self._response = None self._url = None self._summary = None def set_position(self, latitude, longitude): """docstring""" self._latitude = latitude self._longitude = longitude if self._latitude == None and self._longitude == None: self._response = [] else: self._response = self.wikipedia.geosearch( latitude=self._latitude, longitude=self._longitude) def choice_title(self): """docstring""" return random.choice(self._response) def get_informations(self): """docstring""" if self._response == []: return [self._summary, self._url] else: page = self.wikipedia.page(self.choice_title()) self._summary = page.summary self._url = page.url return [self._summary, self._url]
def get_prediction(): wikipedia = MediaWiki() word = request.args.get('word') # Set stop words language stop_words = get_stop_words('en') stop_words = get_stop_words('english') # split query filtered_sentence = "" filtered_sentence = word.split() reponse = [] for each in filtered_sentence: if each not in stop_words: reponse.append(each) string_query = ' '.join(reponse) serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?' address = string_query if len(address) < 1: return try: url = serviceurl + "key=" + app.config['KEY_API'] +\ "&" + urllib.parse.urlencode({'address': address}) uh = urllib.request.urlopen(url) data = uh.read().decode() js = json.loads(data) except: print('==== Failure URL ====') js = None if not js: if 'status' not in js: if js['status'] != 'OK': print('==== Failure To Retrieve ====') print(js) else: lat = js["results"][0]["geometry"]["location"]["lat"] lng = js["results"][0]["geometry"]["location"]["lng"] # sent coordinates to Media wiki query = wikipedia.geosearch(str(lat), str(lng)) # Save first answer history = query[0] # sent answer to Media wiki summary = wikipedia.summary(history) # return summary to view html return jsonify({'html': summary})
def make_geosearch(self, lat, lon): wikipedia = MediaWiki() wikipedia_result = wikipedia.geosearch(lat, lon) try: opensearch_result = self.make_opensearch(wikipedia_result[0]) return opensearch_result[0][1], wikipedia_result[0] except IndexError: return "this is a very nice place but i do not have any story about this place." return opensearch_result
def return_answer(self): """this function returns a dictionnary containing {'result' : 2, 'commentary' : "sentence from bot", 'latitude' : number,'longitude' : number, "adress" : "info", "summary" : "text", "link_wiki" : "url"} 2 = result found, wiki found, 1 = result found no wiki, 0 = not found. If 0 appears, there won't be latt, lng, neither summary""" # if result from parse is null if self.sentence == "Error": self.result['result'] = 0 self.result['commentary'] = random.choice(GENERIC_NO_ANSWER) # if there is a result else: # creating googlemaps client gmaps = googlemaps.Client(key=os.environ.get("BACKEND_KEY", "")) returned_list = gmaps.geocode(self.sentence) # if result is empty, we're returning a message # and a number that will let ajax know if not returned_list: self.result['result'] = 0 self.result['commentary'] = random.choice(GENERIC_NO_ANSWER) # answers = 0 else: #creating local var that will display first googlemaps answer best_result = returned_list[0] compile_dic(best_result, self.result) wikipedia = MediaWiki(lang='fr') t = wikipedia.geosearch(latitude=self.result["latitude"], \ longitude=self.result["longitude"]) # if wiki does not have stories regarding that place if not t: self.result['result'] = 1 self.result['commentary'] = random.choice( GENERIC_LOC_FOUND) # if wiki has full info else: self.result['result'] = 2 self.result['commentary'] = random.choice( GENERIC_LOC_FOUND) p = wikipedia.page(t[0]) self.result["summary"] = p.summary[:250] + "..." self.result["link_wiki"] = p.url return self.result
class WikimediaApi: """ Class that interact with wikimedia api """ def __init__(self, coord, route): """ Function that instanciate a WikimediaApi object """ self.lat = str(coord['lat']) if coord else "" self.lng = str(coord['lng']) if coord else "" self.route = route self.wikipedia = MediaWiki(lang=u'fr') def geosearch(self): """ Function that return a list of pages from wikipedia and coordinate """ try: geores = self.wikipedia.geosearch(self.lat, self.lng, results=5) except: geores = [] return geores def get_pagetitle(self): """ Function that return the title of a page that match the route """ geores = self.geosearch() pagetitle = "" try: regex_route = r"" + self.route i = 0 for i in range(len(geores)): if re.match(regex_route, geores[i]): pagetitle = geores[i] except: pass if not pagetitle: pagetitle = geores[0] if geores else "" return pagetitle def get_about(self): """ Function that return a summary and the url of a wikipedia page """ pagetitle = self.get_pagetitle() page = self.wikipedia.page(pagetitle) if pagetitle else "" about_url = page.url if page else "" try: regex = r'== Situation et accès ==\n.*' section = re.search(regex, page.content).group(0) regex_sub = r'== Situation et accès ==' about_text = (re.sub(regex_sub, "", section)).strip() except: about_text = page.summary if page else "" return {"about_text": about_text, 'about_url': about_url}
def message(coordinates): data = json.loads(coordinates) # get data from json latitude = data[0] longitude = data[1] address = data[2] # instanciation wikipedia object wikipedia = MediaWiki() # sent coordinates to Media wiki query = wikipedia.geosearch(str(latitude), str(longitude)) # Save first answer history = query[0] # sent answer to Media wiki summary = wikipedia.summary(history) # format answer to display answer = "Of course! There she is : " + address +\ ". But have I already told you his history: " + summary return (answer)
class WikiClient: """ The module sentence_manipulator.py returns a string of key words. The module grandpy_map uses those key words to find an address with the Google Maps API. This class uses the previous address to find some background on wikipedia to be told by the good old gramps'. """ def __init__(self, lang='fr'): self.geodata = None self.wikipedia = MediaWiki(lang=lang) def get_article_from_geodata(self, geodata): """ This function gets the result of the module grandpy_map.py and send it to the Wikipedia's API. """ formatted_address, latitude, longitude = geodata if latitude is None and longitude is None: return "", "" """ geosearch(latitude='x.x', longitude='x.x') returns a list of different places/monuments within the radius (in meters). """ titles = self.wikipedia.geosearch(latitude=latitude, longitude=longitude, radius=5000) # Select just one of the different results of the geosearch function : if titles != []: title = random.sample(titles, 1) title = title.pop() construction_to_describe = self.wikipedia.page(title) # In order to return the address of the wikipedia's article. url_address = construction_to_describe.url # The summarize function returns x first sentences of the summary. summary = construction_to_describe.summarize(sentences=4) return summary, url_address
class Research: def __init__(self, user_input): try: # Get input from user : change it to get by the parser self.query = PlaceExtractor.extract(user_input) print("self.query : ", self.query) # googlemaps initialisation self.gmaps = googlemaps.Client(key) self.search_json = self.get_geocode() # Wikipedia initialisation self.wikipedia = MediaWiki(lang='fr') lat = self.get_latitude() lng = self.get_longitude() self.article = self.wikipedia.geosearch(latitude=lat, longitude=lng)[0] self.page = self.wikipedia.page(self.article) self.summary = self.page.summarize(chars=140) self.title = self.page.title self.url = self.page.url except Exception as e: print("désolé, je ne te comprends pas ", e) def get_wiki(self): # Wiki answer try: result = {"title": self.title, "summary": self.summary, "url": self.url, "error": None} return result except Exception as e: return {"error": True, "error message": str(e)} def get_latitude(self): # latitude try: lat = self.search_json[0]["geometry"]["location"]["lat"] return lat except: return 'Nothing Found for Latitude' def get_longitude(self): # longitude try: lng = self.search_json[0]["geometry"]["location"]["lng"] return lng except: return 'Nothing found for Longitude' def get_formatted_name(self): # Name only try: name = self.search_json[0]["formatted_address"] return name except: return "Name not found" def get_geocode(self): geocode_result = self.gmaps.geocode(self.query) print(geocode_result) return geocode_result
results = json.load(read_file) wikipedia = MediaWiki() wiki_results = [] for res in results["elements"]: # Отлов ошибок, если не нашлось никаких страниц try: # Если в данных уже есть нужный тег if "wikipedia" in res["tags"]: search_page = wikipedia.page(res["tags"]["wikipedia"][3:]) else: # Отлов ошибок, если в запросе нет имени try: # Поиск по координатам page_names = wikipedia.geosearch(latitude=res["lat"], longitude=res["lon"]) page_name = [ name for name in page_names if check_levenshtein(name, res["tags"].get("name")) ] if not page_name and res["tags"].get("name"): page_names = wikipedia.search(res["tags"].get("name")) page_name = [ name for name in page_names if check_levenshtein(name, res["tags"].get("name")) ] if page_name: search_page = wikipedia.page(page_name[0])
result_data = [] i = 0 with open("query_result.json", "r") as read_file: data = json.load(read_file) for value in data['elements']: data_found = False p = '' # Проверим, возможно ссылка на википедию уже есть if "wikipedia" in value['tags']: p = wikipedia.page(value['tags']['wikipedia']) data_found = True else: # Проверим по геоположению и полю name geo = wikipedia.geosearch(latitude=value['lat'], longitude=value['lon']) if "name" in value['tags']: for geo_res in geo: if Levenshtein.distance(geo_res, value['tags']['name']) <= 3: p = wikipedia.page(geo_res) data_found = True break # Проверим по геоположению и полю alt_name if not data_found and "alt_name" in value['tags']: for geo_res in geo: if Levenshtein.distance(geo_res, value['tags']['alt_name']) <= 3: p = wikipedia.page(geo_res) data_found = True break