File size: 7,547 Bytes
0ddcb86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d64ead6
0ddcb86
d64ead6
 
 
 
 
 
 
 
 
 
 
0ddcb86
 
d64ead6
0ddcb86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""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