saef-api / backend /locations.py
m4az19's picture
Deploy SAHAB-1 backend and pretrained AI
124816b verified
Raw History Blame Contribute Delete
4.55 kB
"""UAE study-area registry and country-filtered place lookup."""
import hashlib
import json
from functools import lru_cache
from pathlib import Path
import httpx
from pydantic import BaseModel, ConfigDict, Field, model_validator
from shapely.geometry import Point, shape
from shapely.ops import unary_union
from . import store
PRESETS=[
{'id':'dubai','name':'Dubai','lat':25.2048,'lon':55.2708,'kind':'city'},
{'id':'abu-dhabi','name':'Abu Dhabi','lat':24.4539,'lon':54.3773,'kind':'city'},
{'id':'sharjah','name':'Sharjah','lat':25.3463,'lon':55.4033,'kind':'city'},
{'id':'ajman','name':'Ajman','lat':25.4052,'lon':55.5136,'kind':'city'},
{'id':'ras-al-khaimah','name':'Ras Al Khaimah','lat':25.7895,'lon':55.9432,'kind':'city'},
{'id':'fujairah','name':'Fujairah','lat':25.1288,'lon':56.3261,'kind':'city'},
{'id':'umm-al-quwain','name':'Umm Al Quwain','lat':25.5647,'lon':55.5552,'kind':'city'},
{'id':'al-ain','name':'Al Ain','lat':24.2075,'lon':55.7447,'kind':'city'},
{'id':'shawka','name':'Wadi Shawka','lon':56.029,'lat':25.103,'kind':'example'},
{'id':'ham','name':'Wadi Ham','lon':56.242,'lat':25.184,'kind':'example'},
{'id':'buraq','name':'Wadi Buraq','lon':56.094,'lat':24.934,'kind':'example'},
]
@lru_cache(maxsize=1)
def coverage():
document=json.loads((Path(__file__).resolve().parents[1]/'data/boundaries/uae.geojson').read_text())
return unary_union([shape(f['geometry']) for f in document['features']])
def within_uae(lon,lat):
return coverage().covers(Point(lon,lat))
def require_uae(lon,lat):
if not within_uae(lon,lat):raise ValueError('Choose a location within the UAE coverage boundary')
class AreaRequest(BaseModel):
model_config=ConfigDict(extra='forbid',allow_inf_nan=False)
name:str=Field(min_length=1,max_length=120)
lon:float=Field(ge=-180,le=180)
lat:float=Field(ge=-80,le=80)
@model_validator(mode='after')
def validate_area(self):
self.name=self.name.strip()
if not self.name:raise ValueError('A study area needs a name')
require_uae(self.lon,self.lat)
return self
def all_areas():
return [*PRESETS,*store.all_records('study_areas')]
def get_area(id):
result=next((a for a in all_areas() if a['id']==id),None)
if not result:raise ValueError('Unknown study area; select or save a UAE location first')
return result
def save(req:AreaRequest):
id='uae-'+hashlib.sha256(f'{req.lon:.5f},{req.lat:.5f}'.encode()).hexdigest()[:16]
return store.put('study_areas',{**req.model_dump(),'kind':'custom','country_code':'AE','created_at':store.now()},id)
def search(query):
query=query.strip()
if len(query)>120:raise ValueError('Location search is limited to 120 characters')
if ',' in query:
try:
lat,lon=map(float,query.split(','))
except ValueError:pass
else:
req=AreaRequest(name=f'{lat:.4f}, {lon:.4f}',lon=lon,lat=lat)
return {'results':[{**req.model_dump(),'kind':'coordinates','country_code':'AE'}],'source':'coordinates'}
local=[a for a in all_areas() if not query or query.casefold() in a['name'].casefold()]
if len(query)<2:return {'results':local,'source':'saved UAE locations'}
cache_id=hashlib.sha256(query.casefold().encode()).hexdigest()
try:
cached=store.get('place_cache',cache_id)
except KeyError:cached=None
if cached:return {'results':local+cached['results'],'source':'cached GeoNames / Open-Meteo'}
try:
r=httpx.get('https://geocoding-api.open-meteo.com/v1/search',params={'name':query,'count':20,'language':'en','countryCode':'AE'},timeout=12)
r.raise_for_status();remote=[]
for p in r.json().get('results',[]):
if p.get('country_code')!='AE' or not within_uae(p['longitude'],p['latitude']):continue
if any(abs(a['lon']-p['longitude'])<.002 and abs(a['lat']-p['latitude'])<.002 for a in local):continue
remote.append({'name':p['name'],'lon':p['longitude'],'lat':p['latitude'],'kind':'place','country_code':'AE','admin1':p.get('admin1'),'provider_id':p['id']})
store.put('place_cache',{'results':remote,'retrieved_at':store.now(),'source':'GeoNames / Open-Meteo'},cache_id)
return {'results':local+remote,'source':'GeoNames / Open-Meteo'}
except (httpx.HTTPError,KeyError,ValueError):
return {'results':local,'source':'saved UAE locations','warning':'Place search is temporarily unavailable. Saved locations and UAE latitude, longitude entry remain available.'}