erp-gpt-eu / geo_utils.py
Kuangdai
Initial release of ERP-GPT-EU
b8bc5ba
import re
import time
import warnings
from typing import Dict, Any, Optional
import pycountry
from geopy.exc import GeocoderTimedOut, GeocoderServiceError
from geopy.geocoders import Nominatim
from gadm_utils import GADMHandler
def resolve_place(
place_name: str,
fall_back_country: Optional[str] = None,
session_name: Optional[str] = None,
gadm_handler: Optional[GADMHandler] = None,
) -> Dict[str, Any]:
"""
Resolve a place name to coordinates using Nominatim,
with fallback to country via pycountry + GADMHandler.
"""
def fail(status: str) -> Dict[str, Any]:
return {
"status": status,
"used_name": None,
"latitude": None,
"longitude": None,
"bbox_area": None,
"gid": None
}
def compute_bbox_area_from_nominatim(bbox) -> Optional[float]:
try:
lat_min, lat_max = float(bbox[0]), float(bbox[1])
lon_min, lon_max = float(bbox[2]), float(bbox[3])
if lon_min > lon_max:
lon_max += 360.0
return abs((lat_max - lat_min) * (lon_max - lon_min))
except Exception:
return None
def geocode(query: str, max_retries: int = 3, backoff: float = 1.0):
for attempt in range(1, max_retries + 1):
try:
return geocoder.geocode(query, timeout=5, geometry="geojson")
except (GeocoderTimedOut, GeocoderServiceError) as e:
if attempt == max_retries:
warnings.warn(
f"Geocoding failed: {query}\n{type(e).__name__}: {e}",
RuntimeWarning,
)
return None
time.sleep(backoff * attempt)
except Exception as e:
if attempt == max_retries:
warnings.warn(
f"Unexpected error: {query}\n{type(e).__name__}: {e}",
RuntimeWarning,
)
return None
time.sleep(backoff * attempt)
# --- Step 0: validate input ---
if not isinstance(place_name, str) or not place_name.strip():
return fail("Invalid input: place_name must be a non-empty string.")
# --- setup geocoder ---
identifier = "ERP_SOIL_GPT"
if session_name:
identifier += "_" + re.sub(r"[^a-zA-Z0-9_]", "_", session_name)
geocoder = Nominatim(user_agent=identifier)
# --- Step 0: try direct GADM match (aliases only) ---
if gadm_handler:
def norm(s: str) -> str:
return s.strip().lower()
place_norm = norm(place_name)
for gid, node in gadm_handler.tree.items():
raw_aliases = node.get("aliases", [])
aliases = {norm(a) for a in raw_aliases}
aliases.add(norm(node["name"]))
aliases.add(norm(gid))
if not aliases:
continue
if place_norm in aliases:
geom_info = gadm_handler.get_geometry_info(gid)
if geom_info is None:
return fail(
f"Matched GADM node '{gid}' but geometry is missing."
)
return {
"status": "Resolved by direct GADM alias match.",
"used_name": place_name,
"latitude": geom_info["latitude"],
"longitude": geom_info["longitude"],
"bbox_area": geom_info["bbox_area"],
"gid": gid,
}
# --- Step 1: try full place name ---
query = place_name
if fall_back_country and fall_back_country not in query:
query += f", {fall_back_country}"
result = geocode(query)
if result:
try:
lat = float(result.latitude)
lon = float(result.longitude)
except (TypeError, ValueError):
return fail("Geocoding succeeded but returned invalid coordinates.")
bbox_area = compute_bbox_area_from_nominatim(
result.raw.get("boundingbox")
)
return {
"status": "Success. Resolved by Nominatim.",
"used_name": query,
"latitude": lat,
"longitude": lon,
"bbox_area": bbox_area,
"gid": gadm_handler.find_gid(lat, lon, bbox_area)
if gadm_handler
else None,
}
# --- Step 2: try country via Nominatim ---
if fall_back_country:
result = geocode(fall_back_country)
if result:
try:
lat = float(result.latitude)
lon = float(result.longitude)
except (TypeError, ValueError):
return fail("Fallback succeeded but returned invalid coordinates.")
bbox_area = compute_bbox_area_from_nominatim(
result.raw.get("boundingbox")
)
return {
"status": (
f"Fallback. Failed with '{place_name}', "
f"succeeded with '{fall_back_country}' by Nominatim."
),
"used_name": fall_back_country,
"latitude": lat,
"longitude": lon,
"bbox_area": bbox_area,
"gid": gadm_handler.find_gid(lat, lon, bbox_area)
if gadm_handler
else None,
}
# --- Step 3: offline country fallback via pycountry + GADMHandler ---
if fall_back_country and gadm_handler:
try:
country = pycountry.countries.lookup(fall_back_country)
except LookupError:
country = None
if country:
alpha3 = country.alpha_3
geom_info = gadm_handler.get_geometry_info(alpha3)
if geom_info:
return {
"status": (
f"Fallback. Failed with '{place_name}', "
f"succeeded with '{fall_back_country}' by PyCountry."
),
"used_name": country.name,
"latitude": geom_info["latitude"],
"longitude": geom_info["longitude"],
"bbox_area": geom_info["bbox_area"],
"gid": alpha3,
}
# --- Step 4: complete failure ---
return fail("Failed.")
def main():
handler = GADMHandler("data_api/gadm_tree_europe.pkl")
place = "Balkan"
fallback = None
t0 = time.time()
result = resolve_place(
place_name=place,
fall_back_country=fallback,
gadm_handler=handler,
)
print("Seconds:", time.time() - t0)
print("\n--- Resolution Result ---")
for k, v in result.items():
print(f"{k}: {v}")
if __name__ == "__main__":
main()