geo_location_api / services /location_service.py
Omkar008's picture
Update services/location_service.py
2112f7c verified
raw
history blame
3.03 kB
# import locationtagger
from fastapi import FastAPI
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut, GeocoderUnavailable
from models.location_models import LocationData, Coordinates, ErrorResponse
class LocationService:
app = FastAPI()
@staticmethod
def extract_location_entities(ner_results):
city, state, country = None, None, None
for entity in ner_results:
word = entity['word'].replace("##", "").strip()
if entity['entity_group'] == 'CITY' and word.isalpha():
city = word
elif entity['entity_group'] == 'STATE' and word.isalpha():
state = word
elif entity['entity_group'] == 'COUNTRY' and word.isalpha():
country = word
if city or state or country:
return {k: v for k, v in {"city": city, "state": state, "country": country}.items() if v is not None}
else:
return None
@staticmethod
def get_coordinates(data:dict) -> Coordinates | ErrorResponse:
print("Inside get coordinates")
print(data)
try:
location = data.get('location')
except:
return Coordinates(latitude=None, longitude=None)
city = None
state = None
country = None
if location:
# Assuming `app.nlp` is already initialized elsewhere and accessible
ner_results = app.state.nlp(location)
# Extract city, state, and country using the logic from extract_location_entities
location_entities = LocationService.extract_location_entities(ner_results)
if location_entities:
city = location_entities.get('city')
state = location_entities.get('state')
country = location_entities.get('country')
# Create the location string
location_string = ' '.join(filter(None, [city, state, country]))
if not location_string:
location_string = location
else:
return ErrorResponse(error="No location information provided")
geolocator = Nominatim(user_agent="Geolocation")
print("Printing location string")
print(location_string)
if city or state or country :
location_string = city
elif country is None:
location_string = city
elif city is None:
location_string = state
elif state is None:
location_string = city
try:
getLoc = geolocator.geocode(location_string)
print(getLoc.latitude)
print(getLoc.longitude)
return Coordinates(
latitude=getLoc.latitude,
longitude=getLoc.longitude
)
except Exception as e:
print(f"Error {e}")
return Coordinates(latitude=None , longitude=None)