Spaces:
Build error
Build error
Commit ·
13d7c9d
1
Parent(s): 99568fb
Update helper.py
Browse files10 unmodified lines111213141516171 unmodified line192021222324252627 unmodified lines5455565758596016 unmodified lines777879808182833 unmodified lines8788899091929394959697989910010110210310410510613 unmodified lines12012112212312412512612712812957 unmodified lines18718818919019119219352 unmodified lines24624724824925025125225318 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429510 unmodified linesfrom transformers import BertTokenizer, BertModelimport torch# initial loads# load the spacy model1 unmodified linenlp = spacy.load("en_core_web_lg")# load the pre-trained BERT tokenizer and modeltokenizer = BertTokenizer.from_pretrained('bert-base-uncased')model = BertModel.from_pretrained('bert-base-uncased')# Load valid city names from geonamescachegc = geonamescache.GeonamesCache()27 unmodified linesdef is_city(reference):"""Check if the given reference is a valid city name"""# Check if the reference is a valid city name16 unmodified linesreturn Truereturn Falsedef validate_locations(locations):"""3 unmodified linesvalidated_loc = []for location in locations:if is_city(location):validated_loc.append((location, 'city'))elif is_country(location):validated_loc.append((location, 'country'))else:# Check if the location is a multi-word namewords = location.split()if len(words) > 1:# Try to find the country or city name among the wordsfor i in range(len(words)):name = ' '.join(words[i:])if is_country(name):validated_loc.append((name, 'country'))breakelif is_city(name):validated_loc.append((name, 'city'))break13 unmodified lines# GPE and LOC are the labels for location entities in spaCyfor ent in doc.ents:if ent.label_ in ['GPE', 'LOC']:if len(ent.text.split()) > 1:ner_locations.append(ent.text)else:for token in ent:if token.ent_type_ == 'GPE':ner_locations.append(ent.text)break57 unmodified linesregex_locations = []# Country references can be preceded by 'in', 'from' or 'of'pattern = r"\b(in|from|of)\b\s([\w\s]+)"additional_refs = re.findall(pattern, sentence)52 unmodified lineslocations = []# add all the identified country/cities results in a listtry:# ner18 unmodified lines# flatten the embeddings listlocations_flat_3 = list(flatten(locations))# acquire the unique country/city names (because it is possible that many different approaches will capture the same countries/cities)flat_loc_list = set(locations_flat_3)# validate that indeed each one of the countries/cities are indeed countries/citiesvalidated_locations = validate_locations(flat_loc_list)# create a proper dictionary with country/city tags and the relevant entries as a resultlocations_dict = {}for location, loc_type in validated_locations:if loc_type not in locations_dict:locations_dict[loc_type] = []locations_dict[loc_type].append(location)return locations_dictexcept:# handle the exception if any errors occur while identifying a country/cityprint(f"An error occurred while checking if a city or country exists")return ""10 unmodified lines1112131415161 unmodified line181920212223242527 unmodified lines5354555657585916 unmodified lines767778798081823 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211313 unmodified lines12712812913013113213313413513613757 unmodified lines19519619719819920020152 unmodified lines25425525625725825918 unmodified lines27827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738810 unmodified linesfrom transformers import BertTokenizer, BertModelimport torch# initial loads# load the spacy model1 unmodified linenlp = spacy.load("en_core_web_lg")# load the pre-trained BERT tokenizer and modeltokenizer = BertTokenizer.from_pretrained('bert-base-cased')model = BertModel.from_pretrained('bert-base-cased')# Load valid city names from geonamescachegc = geonamescache.GeonamesCache()27 unmodified linesdef is_city(reference):"""Check if a given reference is a valid city name"""# Check if the reference is a valid city name16 unmodified linesreturn Truereturn Falsedef validate_locations(locations):"""3 unmodified linesvalidated_loc = []for location in locations:# validate whether it is a cityif is_city(location):validated_loc.append((location, 'city'))# validate whether it is a countryelif is_country(location):validated_loc.append((location, 'country'))else:# Check if the location is a multi-word namewords = location.split()if len(words) > 1:# Try to find the country or city name among the wordsfor i in range(len(words)):name = ' '.join(words[i:])if is_country(name):validated_loc.append((name, 'country'))breakelif is_city(name):validated_loc.append((name, 'city'))break13 unmodified lines# GPE and LOC are the labels for location entities in spaCyfor ent in doc.ents:if ent.label_ in ['GPE', 'LOC']:if len(ent.text.split()) > 1:ner_locations.append(ent.text)else:for token in ent:if token.ent_type_ == 'GPE':ner_locations.append(ent.text)break57 unmodified linesregex_locations = []# Country and cities references can be preceded by 'in', 'from' or 'of'pattern = r"\b(in|from|of)\b\s([\w\s]+)"additional_refs = re.findall(pattern, sentence)52 unmodified lineslocations = []try:# ner18 unmodified lines# flatten the embeddings listlocations_flat_3 = list(flatten(locations))# remove duplicates while also taking under consideration capitalization (e.g. a reference of italy should be valid, while also a reference of Italy and italy)# Lowercase the words and get their unique references using set()loc_unique = set([loc.lower() for loc in locations_flat_3])# Create a new list of locations with initial capitalization, removing duplicatesloc_capitalization = list(set([loc.capitalize() if loc.lower() in loc_unique else loc.lower() for loc in locations_flat_3]))# validate that indeed each one of the countries/cities are indeed countries/citiesvalidated_locations = validate_locations(loc_capitalization)# create a proper dictionary with country/city tags and the relevant entries as a resultlocations_dict = {}for location, loc_type in validated_locations:if loc_type not in locations_dict:locations_dict[loc_type] = []locations_dict[loc_type].append(location)# conditions for multiple references# it is mandatory that a country will existif locations_dict['country']:# if a city existsif 'city' in locations_dict:# we accept one country and one cityif len(locations_dict['country']) == 1 and len(locations_dict['city']) == 1:# capitalize because there may be cases that it will return 'italy'locations_dict['country'][0] = locations_dict['country'][0].capitalize()return locations_dict# we can accept an absence of city but a country is always mandatoryelif len(locations_dict['country']) == 1 and len(locations_dict['city']) == 0:locations_dict['country'][0] = locations_dict['country'][0].capitalize()return locations_dict# error if more than one country or cityelse:return (0, "LOCATION", "more_city_or_country")# if a city does not existelse:# we only accept for one countryif len(locations_dict['country']) == 1:locations_dict['country'][0] = locations_dict['country'][0].capitalize()return locations_dict# error if more than one countryelse:return (0, "LOCATION", "more_country")# error if no country is referredelse:return (0, "LOCATION", "no_country")except:# handle the exception if any errors occur while identifying a country/cityreturn (0, "LOCATION", "unknown_error")def identify_locations2(sentence):"""Identify all the possible Country and City references in the given sentence, using different approaches in a hybrid manner"""locations = []# nerlocations.append(identify_loc_ner(sentence))# geoparse libsgeoparse_list, countries, cities = identify_loc_geoparselibs(sentence)locations.append(geoparse_list)# flatten the geoparse listlocations_flat_1 = list(flatten(locations))# regexlocations_flat_1.append(identify_loc_regex(sentence))# flatten the regex listlocations_flat_2 = list(flatten(locations))# embeddingslocations_flat_2.append(identify_loc_embeddings(sentence, countries, cities))# flatten the embeddings listlocations_flat_3 = list(flatten(locations))# remove duplicates while also taking under consideration capitalization (e.g. a reference of italy should be valid, while also a reference of Italy and italy)# Lowercase the words and get their unique references using set()loc_unique = set([loc.lower() for loc in locations_flat_3])# Create a new list of locations with initial capitalization, removing duplicatesloc_capitalization = list(set([loc.capitalize() if loc.lower() in loc_unique else loc.lower() for loc in locations_flat_3]))# validate that indeed each one of the countries/cities are indeed countries/citiesvalidated_locations = validate_locations(loc_capitalization)# create a proper dictionary with country/city tags and the relevant entries as a resultlocations_dict = {}for location, loc_type in validated_locations:if loc_type not in locations_dict:locations_dict[loc_type] = []locations_dict[loc_type].append(location)return locations_dict
helper.py+112-19