RastaAI / app /services /predict_service.py
devmurtaza's picture
Claude Sonnet 4.6
Fix route variety: use 3 OSRM strategies instead of fake bezier curves
d64ead6
Raw History Blame Contribute Delete
7.55 kB
"""Top-level orchestrator for /predict-route."""
from __future__ import annotations
import uuid
from datetime import datetime, timedelta
from typing import List, Dict, Tuple
import asyncio
from app.schemas.route import (
PredictRouteRequest, PredictRouteResponse,
RankedRoute, RouteFeatures, Coordinate, TurnInstruction,
IncidentWarning, LocationInput,
)
from app.services.locations import get_city
from app.services.route_provider import get_candidate_routes
from app.services.feature_extractor import extract_features
from app.services.weather_service import fetch_weather_severity
from app.services.traffic_service import get_route_incidents
from app.services.cache_service import cache
from app.services.explanation import explain, _strengths_and_tradeoffs
from app.models.inference import bundle
from app.models.ranker import rank_routes
from app.utils.logger import logger
PKR_PER_LITER = 280.0
LABEL_ORDER = ["Express", "Smart", "Scenic"]
def _resolve_location(loc: LocationInput) -> Tuple[Tuple[float, float], str]:
if loc.id:
city = get_city(loc.id)
if city:
return (city["lat"], city["lng"]), city["name"]
if loc.coordinate:
return (loc.coordinate.lat, loc.coordinate.lng), (loc.name or "Custom location")
raise ValueError("Location must have either id or coordinate")
def _synthetic_turn_instructions(polyline: List[Tuple[float, float]]) -> List[TurnInstruction]:
if len(polyline) < 4:
return []
out = []
step = max(1, len(polyline) // 6)
for i in range(step, len(polyline) - 1, step):
out.append(TurnInstruction(
distance_km=0.0,
instruction="Continue on route",
coordinate=Coordinate(lat=polyline[i][0], lng=polyline[i][1]),
))
out.append(TurnInstruction(
distance_km=0.0,
instruction="Arrive at destination",
coordinate=Coordinate(lat=polyline[-1][0], lng=polyline[-1][1]),
))
return out
async def predict_route(req: PredictRouteRequest) -> PredictRouteResponse:
origin, origin_name = _resolve_location(req.origin)
destination, dest_name = _resolve_location(req.destination)
departure = req.departure_time or datetime.utcnow()
# ---- cache ----
cache_key = cache.key(
"predict", origin, destination,
departure.strftime("%Y%m%d%H"),
req.vehicle_type, req.preference, req.avoid_tolls,
)
cached = await cache.get_json(cache_key)
if cached and not req.weights:
cached["cached"] = True
return PredictRouteResponse(**cached)
# ---- candidates ----
raw_candidates = await get_candidate_routes(origin, destination)
if not raw_candidates:
raise RuntimeError("No route candidates available")
# ---- weather + incidents fetched concurrently ----
mid = ((origin[0] + destination[0]) / 2, (origin[1] + destination[1]) / 2)
weather_task = asyncio.create_task(fetch_weather_severity(mid))
incident_tasks = [
asyncio.create_task(get_route_incidents(cand["polyline"]))
for cand in raw_candidates
]
weather_severity = await weather_task
incident_results = await asyncio.gather(*incident_tasks)
# ---- feature extraction ----
enriched: List[Dict] = []
for cand in raw_candidates:
features = await extract_features(
cand, origin, destination, departure, req.vehicle_type, weather_severity
)
enriched.append({**cand, "features": features})
# ---- batch ML inference ----
preds = bundle.predict([c["features"] for c in enriched])
for i, c in enumerate(enriched):
c["eta_min"] = float(preds["eta_min"][i])
c["fuel_l"] = float(preds["fuel_l"][i])
# ---- attach incident data + add incident delay to ETA ----
for i, c in enumerate(enriched):
inc_count, inc_delay, inc_list = incident_results[i]
c["incident_count"] = inc_count
c["incident_delay_min"] = inc_delay
c["incidents"] = inc_list
c["eta_min"] += inc_delay # incident delay is added on top of ML-predicted ETA
# ---- ranking ----
ranked = rank_routes(enriched, req.preference, req.weights)
# ---- labels ----
# Sort by ETA ascending: fastest = Express, slowest = Scenic, middle = Smart
by_eta = sorted(enriched, key=lambda c: c["eta_min"])
labels = {}
if len(by_eta) == 1:
labels[id(by_eta[0])] = "Smart"
elif len(by_eta) == 2:
labels[id(by_eta[0])] = "Express"
labels[id(by_eta[1])] = "Smart"
else:
labels[id(by_eta[0])] = "Express"
labels[id(by_eta[-1])] = "Scenic"
for c in by_eta[1:-1]:
labels[id(c)] = "Smart"
def label_for(c: Dict) -> str:
return labels.get(id(c), "Alt")
ranked_routes: List[RankedRoute] = []
for c in ranked:
label = label_for(c)
f = c["features"]
strengths, tradeoffs = _strengths_and_tradeoffs(c, ranked)
route_id = str(uuid.uuid4())
eta_arrival = departure + timedelta(minutes=c["eta_min"])
# Build IncidentWarning objects for response
incident_warnings = [
IncidentWarning(
type=inc["type"],
severity=inc["severity"],
delay_min=inc["delay_min"],
description=inc["description"],
coordinate=Coordinate(lat=inc["lat"], lng=inc["lng"]),
)
for inc in c.get("incidents", [])
]
ranked_routes.append(RankedRoute(
route_id=route_id,
label=label,
polyline=[Coordinate(lat=p[0], lng=p[1]) for p in c["polyline"]],
eta_minutes=round(c["eta_min"], 1),
eta_arrival=eta_arrival,
distance_km=round(f["distance_km"], 2),
fuel_liters=round(c["fuel_l"], 2),
fuel_cost_pkr=round(c["fuel_l"] * PKR_PER_LITER, 0),
traffic_risk=round(c["traffic_risk"], 3),
reliability=round(c["reliability"], 3),
confidence=round(c["confidence"], 3),
score=round(c["score"], 4),
is_best=c["is_best"],
strengths=strengths,
tradeoffs=tradeoffs,
turns=_synthetic_turn_instructions(c["polyline"]),
features=RouteFeatures(
distance_km=f["distance_km"],
turns=f["turns"],
avg_speed_kmh=f["realised_speed_kmh"],
road_type=f["road_type"],
road_quality=f["road_quality"],
traffic_level=f["traffic_level"],
weather_severity=f["weather_severity"],
hour_of_day=f["hour_of_day"],
day_of_week=f["day_of_week"],
),
incident_warnings=incident_warnings,
incident_delay_min=c.get("incident_delay_min", 0.0),
))
best = ranked[0]
response = PredictRouteResponse(
best_route_id=ranked_routes[0].route_id,
ranked_routes=ranked_routes,
explanation=explain(best, ranked, req.preference),
generated_at=datetime.utcnow(),
reroute_suggested=False,
cached=False,
)
await cache.set_json(cache_key, response.model_dump(mode="json"))
total_incidents = sum(c.get("incident_count", 0) for c in ranked)
logger.info(
f"Predicted route {origin_name} -> {dest_name} "
f"(best {ranked_routes[0].label}, {ranked_routes[0].eta_minutes:.0f}min, "
f"incidents={total_incidents})"
)
return response