Skip to content

Commit 00a13a9

Browse files
committed
working code that displays the scores
1 parent 474b17a commit 00a13a9

3 files changed

Lines changed: 157 additions & 214 deletions

File tree

backend/main.py

Lines changed: 6 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import os
22
import time
3-
from contextlib import asynccontextmanager
43
from datetime import datetime, timezone
54
from functools import lru_cache
65
from pathlib import Path
@@ -18,18 +17,7 @@
1817
load_dotenv(Path(__file__).resolve().parent / ".env")
1918

2019

21-
@asynccontextmanager
22-
async def lifespan(app):
23-
"""Load risk caches at startup so scores are ready before first request."""
24-
try:
25-
from backend.risk_cache import startup_load
26-
except ModuleNotFoundError:
27-
from risk_cache import startup_load
28-
startup_load()
29-
yield
30-
31-
32-
app = FastAPI(title="SafeWay API", lifespan=lifespan)
20+
app = FastAPI(title="SafeWay API")
3321

3422

3523
# ---------------------------------------------------------------------------
@@ -431,10 +419,7 @@ def compute_route(payload: RouteRequest):
431419

432420
result_routes = []
433421
try:
434-
try:
435-
from backend.risk_cache import score_coordinates
436-
except ModuleNotFoundError:
437-
from risk_cache import score_coordinates
422+
from risk_cache import score_coordinates
438423
for route in raw_routes:
439424
polyline = ((route.get("polyline") or {}).get("encodedPolyline")) or ""
440425
coordinates = decode_polyline(polyline) if polyline else []
@@ -485,54 +470,9 @@ def compute_route(payload: RouteRequest):
485470
"route_source": "google",
486471
})
487472

488-
# ── SafeWay A* safer route ──────────────────────────────────────────
489-
try:
490-
try:
491-
from backend.risk_cache import get_prepared_graph, score_coordinates as sc
492-
from backend.model.route_scoring import find_safer_route, path_to_coordinates, encode_polyline, estimate_route_aadt
493-
except ModuleNotFoundError:
494-
from risk_cache import get_prepared_graph, score_coordinates as sc
495-
from model.route_scoring import find_safer_route, path_to_coordinates, encode_polyline, estimate_route_aadt
496-
import osmnx as ox
497-
498-
G = get_prepared_graph()
499-
orig_node = ox.distance.nearest_nodes(G, X=payload.origin.lng, Y=payload.origin.lat)
500-
dest_node = ox.distance.nearest_nodes(G, X=payload.destination.lng, Y=payload.destination.lat)
501-
502-
if orig_node != dest_node:
503-
astar = find_safer_route(G, orig_node, dest_node, beta=0.5)
504-
safe_coords = path_to_coordinates(G, astar["safe_path"])
505-
506-
if len(safe_coords) >= 2:
507-
safe_polyline = encode_polyline(safe_coords)
508-
safe_safety = sc(safe_coords, sample_every=3, departure_hour=payload.departure_hour)
509-
510-
# Duration as Google-format string (e.g. "600s")
511-
safe_duration = f"{astar['safe_time_secs']}s"
512-
513-
aadt = estimate_route_aadt(G, astar["safe_path"])
514-
result_routes.append({
515-
"distance_meters": astar["safe_distance_m"],
516-
"duration": safe_duration,
517-
"polyline": safe_polyline,
518-
"coordinates": safe_coords,
519-
"safety_score": safe_safety.get("score"),
520-
"safety_label": safe_safety.get("label", "unknown"),
521-
"route_source": "safeway",
522-
"risk_per_km": safe_safety.get("risk_per_km"),
523-
"total_exposure": safe_safety.get("total_exposure"),
524-
"route_km": safe_safety.get("route_km"),
525-
"n_high_risk": safe_safety.get("n_high_risk", 0),
526-
"top_risk_factors": safe_safety.get("top_risk_factors", []),
527-
"time_band": safe_safety.get("time_band"),
528-
"segment_risks": safe_safety.get("segment_risks", []),
529-
"time_penalty_pct": astar["time_penalty_pct"],
530-
"risk_reduction_pct": astar["risk_reduction_pct"],
531-
"aadt_avg": aadt.get("aadt_avg"),
532-
"aadt_max": aadt.get("aadt_max"),
533-
})
534-
except Exception as e:
535-
print(f"[route] SafeWay A* route skipped: {e}", flush=True)
473+
# ── SafeWay A* safer route — temporarily disabled ──────────────────
474+
# TODO: re-enable once Google routes + scoring are confirmed working
475+
pass
536476

537477
# Sort: SafeWay route first, then by safety score ascending (safest first)
538478
result_routes.sort(key=lambda r: (
@@ -910,9 +850,6 @@ def admin_refresh_cache(authorization: str = Header(None)):
910850
expected = f"Bearer {admin_secret}"
911851
if not authorization or authorization != expected:
912852
raise HTTPException(status_code=403, detail="Forbidden")
913-
try:
914-
from backend.risk_cache import refresh_cache
915-
except ModuleNotFoundError:
916-
from risk_cache import refresh_cache
853+
from risk_cache import refresh_cache
917854
result = refresh_cache()
918855
return result

0 commit comments

Comments
 (0)