Spaces:
Runtime error
Runtime error
Chidam Gopal commited on
NER model updates for infer location
Browse files21 unmodified lines22232425262716 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310421 unmodified lines# Load the ONNX modelself.ort_session = ort.InferenceSession(model_path)def find_location(self, sequence, verbose=False):inputs = self.tokenizer(sequence,return_tensors="np", # ONNX requires inputs in NumPy format16 unmodified lines# Define the threshold for NER probabilitythreshold = 0.6label_map = {0: "O", # Outside any named entity1: "B-PER", # Beginning of a person entity2: "I-PER", # Inside a person entity3: "B-ORG", # Beginning of an organization entity4: "I-ORG", # Inside an organization entity5: "B-LOC", # Beginning of a location entity6: "I-LOC", # Inside a location entity7: "B-MISC", # Beginning of a miscellaneous entity8: "I-MISC" # Inside a miscellaneous entity}tokens = self.tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])# List to hold the detected location termslocation_entities = []current_location = []# Loop through each token and its predicted label and probabilityfor i, (token, predicted_id, prob) in enumerate(zip(tokens, predicted_ids[0], predicted_probs[0])):label = label_map[predicted_id]# Ignore special tokens like [CLS], [SEP]if token in ["[CLS]", "[SEP]", "[PAD]"]:continue# Only consider tokens with probability above the thresholdif prob > threshold:# If the token is a part of a location entity (B-LOC or I-LOC)if label in ["B-LOC", "I-LOC"]:if label == "B-LOC":# If we encounter a B-LOC, we may need to store the previous locationif current_location:location_entities.append(" ".join(current_location).replace("##", ""))# Start a new location entitycurrent_location = [token]elif label == "I-LOC" and current_location:# Continue appending to the current location entitycurrent_location.append(token)else:# If we encounter a non-location entity, store the current location and resetif current_location:location_entities.append(" ".join(current_location).replace("##", ""))current_location = []# Append the last location entity if it existsif current_location:location_entities.append(" ".join(current_location).replace("##", ""))# Return the detected location termsreturn location_entities[0] if location_entities != [] else Noneif __name__ == '__main__':query = "weather in seattle"loc_finder = LocationFinder()location = loc_finder.find_location(query)print(f"query = {query} => {location}")21 unmodified lines222324252627282930313233343536373839404116 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412521 unmodified lines# Load the ONNX modelself.ort_session = ort.InferenceSession(model_path)# State abbreviations list for post-processingself.state_abbr = {"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY","LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND","OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"}# # Helper function to correct misclassified state abbreviations# def correct_state_abbreviation(self, token, predicted_label):# if token.upper() in self.state_abbr and predicted_label == "I-CITY":# return "I-STATE"# return predicted_labeldef find_location(self, sequence, verbose=False):inputs = self.tokenizer(sequence,return_tensors="np", # ONNX requires inputs in NumPy format16 unmodified lines# Define the threshold for NER probabilitythreshold = 0.6# Define the label map for city, state, organization, citystatelabel_map = {0: "O", # Outside any named entity1: "B-PER", # Beginning of a person entity2: "I-PER", # Inside a person entity3: "B-ORG", # Beginning of an organization entity4: "I-ORG", # Inside an organization entity5: "B-CITY", # Beginning of a city entity6: "I-CITY", # Inside a city entity7: "B-STATE", # Beginning of a state entity8: "I-STATE", # Inside a state entity9: "B-CITYSTATE", # Beginning of a city_state entity10: "I-CITYSTATE", # Inside a city_state entity}tokens = self.tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])# List to hold the detected entities (city, state, organization, citystate)city_entities = []state_entities = []org_entities = []city_state_entities = []for i, (token, predicted_id, prob) in enumerate(zip(tokens, predicted_ids[0], predicted_probs[0])):if prob > threshold:if token in ["[CLS]", "[SEP]", "[PAD]"]:continueelse:if label_map[predicted_id] in ["B-CITY", "I-CITY"]:city_entities.append(token.replace("##", ""))elif label_map[predicted_id] in ["B-STATE", "I-STATE"]:state_entities.append(token.replace("##", ""))elif label_map[predicted_id] in ["B-CITYSTATE", "I-CITYSTATE"]:city_state_entities.append(token.replace("##", ""))elif label_map[predicted_id] in ["B-ORG", "I-ORG"]:org_entities.append(token.replace("##", ""))city_state_res = "".join(cs_entity.replace(",", ", ") for cs_entity in city_state_entities) if city_state_entities else Noneif city_entities:city_res = " ".join(city_entities)elif city_state_res:city_res = city_state_res.split(", ")[0]else:city_res = Noneif state_entities:state_res = " ".join(state_entities)elif city_state_res and len(city_state_res) > 0:state_res = city_state_res.split(", ")[-1]else:state_res = Noneorg_res = " ".join(org_entities) if org_entities else None# Return the detected entitiesreturn {'city': city_res,'state': state_res,'organization': org_res,}if __name__ == '__main__':query = "weather in san francisco, ca"loc_finder = LocationFinder()entities = loc_finder.find_location(query)print(f"query = {query} => {entities}")
infer_location.py+60-39