import json import os import requests import geopandas as gpd from shapely.geometry import LineString import polyline # ============================================================ # HELPER: Safe Geocoding Function # ============================================================ def geocode(address): """ Return (lon, lat) tuple or None if geocoding fails. """ try: url = "https://nominatim.openstreetmap.org/search" params = {"q": address, "format": "json", "limit": 1} response = requests.get( url, params=params, headers={"User-Agent": "RouteFatalityExplorer/1.0"}, timeout=10, ) if response.status_code != 200: return None data = response.json() if not data: return None return float(data[0]["lon"]), float(data[0]["lat"]) except Exception: return None # ============================================================ # MAIN BACKEND FUNCTION # ============================================================ def get_route_fatalities(origin, destination, buffer_m=50): """ Backend function: - Geocode origin/destination - Request ORS route - Build buffer around route - Filter fatalities from GeoFatalities.gpkg - ALWAYS return a dictionary (never None) """ try: # -------------------------- # 1. Geocode origin + destination # -------------------------- origin_coord = geocode(origin) dest_coord = geocode(destination) if origin_coord is None: return {"error": "Could not geocode origin address."} if dest_coord is None: return {"error": "Could not geocode destination address."} # -------------------------- # 2. Request ORS route # -------------------------- ORS_API_KEY = os.environ.get("ORS_API_KEY") if not ORS_API_KEY: return {"error": "ORS API key not configured."} ORS_URL = "https://api.openrouteservice.org/v2/directions/driving-car" headers = { "Authorization": ORS_API_KEY, "Content-Type": "application/json", } body = {"coordinates": [list(origin_coord), list(dest_coord)]} response = requests.post( ORS_URL, headers=headers, data=json.dumps(body), timeout=20, ) if response.status_code != 200: return { "error": "ORS request failed.", "details": response.text, } route_json = response.json() routes = route_json.get("routes") if not routes: return {"error": "ORS returned no routes."} encoded_geom = routes[0].get("geometry") if not encoded_geom: return {"error": "ORS route geometry missing."} # -------------------------- # 3. Decode ORS polyline # -------------------------- decoded_latlon = polyline.decode(encoded_geom) # (lat, lon) if not decoded_latlon: return {"error": "Decoded route geometry is empty."} route_coords = [(lon, lat) for lat, lon in decoded_latlon] # -------------------------- # 4. Create LineString + buffer # -------------------------- route_line = LineString(route_coords) route_gdf = gpd.GeoDataFrame( {"id": [1]}, geometry=[route_line], crs="EPSG:4326", ) route_buffer = ( route_gdf.to_crs(3857) .geometry.iloc[0] .buffer(buffer_m) ) # -------------------------- # 5. Load GeoFatalities dataset # -------------------------- fatalities_gdf = gpd.read_file( "GeoFatalities.gpkg", layer="fatalities", ) if fatalities_gdf.empty: return { "route_coords": route_coords, "num_fatalities": 0, "fatalities": [], } fatalities_merc = fatalities_gdf.to_crs(3857) # -------------------------- # 6. Spatial filter — fatalities inside buffer # -------------------------- fatalities_in_buffer_merc = fatalities_merc[ fatalities_merc.geometry.within(route_buffer) ] fatalities_in_buffer = fatalities_in_buffer_merc.to_crs(4326) # -------------------------- # 7. Select fields to return # -------------------------- cols = [ "CRASH_ID", "YEAR", "LATITUDE", "LONGITUDE", "top_contributor", "top_contributor_color", ] result_df = fatalities_in_buffer[cols].copy() return { "route_coords": route_coords, "num_fatalities": len(result_df), "fatalities": result_df.to_dict(orient="records"), } except Exception as e: # Absolute last-resort safety net return { "error": "Backend processing failed.", "details": str(e), }