devmurtaza Claude Sonnet 4.6 commited on
Commit
d64ead6
·
1 Parent(s): cf6373a

Fix route variety: use 3 OSRM strategies instead of fake bezier curves

Browse files

When OSRM returns < 3 routes, now makes additional calls with
exclude=motorway and exclude=motorway,trunk to force genuinely
different real road paths. Duplicate detection prevents near-identical
routes from appearing. Also fixes label collision (Express/Smart/Scenic
now assigned by ETA rank, always distinct).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

app/services/predict_service.py CHANGED
@@ -111,20 +111,22 @@ async def predict_route(req: PredictRouteRequest) -> PredictRouteResponse:
111
  ranked = rank_routes(enriched, req.preference, req.weights)
112
 
113
  # ---- labels ----
 
114
  by_eta = sorted(enriched, key=lambda c: c["eta_min"])
115
- express_id = id(by_eta[0])
116
- by_scenic = sorted(enriched, key=lambda c: c["features"]["detour_ratio"], reverse=True)
117
- scenic_id = id(by_scenic[0])
118
- best_id = id(ranked[0])
 
 
 
 
 
 
 
119
 
120
  def label_for(c: Dict) -> str:
121
- if id(c) == best_id:
122
- return "Smart"
123
- if id(c) == express_id:
124
- return "Express"
125
- if id(c) == scenic_id:
126
- return "Scenic"
127
- return "Alt"
128
 
129
  ranked_routes: List[RankedRoute] = []
130
  for c in ranked:
 
111
  ranked = rank_routes(enriched, req.preference, req.weights)
112
 
113
  # ---- labels ----
114
+ # Sort by ETA ascending: fastest = Express, slowest = Scenic, middle = Smart
115
  by_eta = sorted(enriched, key=lambda c: c["eta_min"])
116
+ labels = {}
117
+ if len(by_eta) == 1:
118
+ labels[id(by_eta[0])] = "Smart"
119
+ elif len(by_eta) == 2:
120
+ labels[id(by_eta[0])] = "Express"
121
+ labels[id(by_eta[1])] = "Smart"
122
+ else:
123
+ labels[id(by_eta[0])] = "Express"
124
+ labels[id(by_eta[-1])] = "Scenic"
125
+ for c in by_eta[1:-1]:
126
+ labels[id(c)] = "Smart"
127
 
128
  def label_for(c: Dict) -> str:
129
+ return labels.get(id(c), "Alt")
 
 
 
 
 
 
130
 
131
  ranked_routes: List[RankedRoute] = []
132
  for c in ranked:
app/services/route_provider.py CHANGED
@@ -1,12 +1,14 @@
1
  """Route candidate generation.
2
 
3
- Primary: OSRM HTTP API (public demo server is free; self-host for production).
4
- Fallback: synthetic Bezier-curve routes if OSRM is unreachable, so the system
5
- still works end-to-end offline / during dev.
 
 
6
  """
7
  from __future__ import annotations
8
  import math
9
- from typing import List, Tuple, Dict, Any
10
  import httpx
11
  from app.config import settings
12
  from app.utils.logger import logger
@@ -15,35 +17,25 @@ from app.utils.geometry import haversine_km, polyline_length_km, turn_count
15
  Coord = Tuple[float, float]
16
 
17
 
18
- class RouteCandidate(Dict[str, Any]):
19
- """Loose dict for a routing candidate. Keys: polyline, distance_km, duration_min, turns, source."""
20
-
21
-
22
- async def fetch_osrm_routes(
23
- origin: Coord, destination: Coord, alternatives: int = 3
24
- ) -> List[Dict[str, Any]]:
25
- """Hit OSRM /route/v1/driving and return alternatives.
26
-
27
- OSRM expects lng,lat ordering. Returns up to `alternatives` candidates.
28
- """
29
  lng1, lat1 = origin[1], origin[0]
30
  lng2, lat2 = destination[1], destination[0]
31
  url = (
32
  f"{settings.osrm_url}/route/v1/driving/"
33
  f"{lng1},{lat1};{lng2},{lat2}"
34
- f"?alternatives={'true' if alternatives > 1 else 'false'}"
35
  f"&overview=full&geometries=geojson&steps=true"
36
  )
37
- async with httpx.AsyncClient(timeout=10.0) as client:
38
- resp = await client.get(url)
39
- resp.raise_for_status()
40
- data = resp.json()
41
 
 
 
42
  if data.get("code") != "Ok":
43
  raise RuntimeError(f"OSRM error: {data.get('message', data.get('code'))}")
44
-
45
- out: List[Dict[str, Any]] = []
46
- for r in data["routes"][:alternatives]:
47
  coords_lnglat = r["geometry"]["coordinates"]
48
  polyline: List[Coord] = [(c[1], c[0]) for c in coords_lnglat]
49
  out.append({
@@ -52,18 +44,79 @@ async def fetch_osrm_routes(
52
  "duration_min": r["duration"] / 60.0,
53
  "turns": turn_count(polyline),
54
  "source": "osrm",
 
55
  "steps": r.get("legs", [{}])[0].get("steps", []),
56
  })
57
  return out
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def _bezier_curve(
61
  origin: Coord, destination: Coord, curvature: float, samples: int = 60
62
  ) -> List[Coord]:
63
  """Quadratic Bezier between two points with perpendicular offset for variety."""
64
  mid_lat = (origin[0] + destination[0]) / 2
65
  mid_lng = (origin[1] + destination[1]) / 2
66
- # perpendicular offset
67
  dlat = destination[0] - origin[0]
68
  dlng = destination[1] - origin[1]
69
  nrm = math.hypot(dlat, dlng) or 1e-9
@@ -83,7 +136,7 @@ def _bezier_curve(
83
  def synthetic_routes(origin: Coord, destination: Coord) -> List[Dict[str, Any]]:
84
  """Three Bezier candidates: Express (straight), Smart (mild curve), Scenic (curvier)."""
85
  straight_km = haversine_km(origin, destination)
86
- scale = max(0.4, straight_km / 400.0) # curvature scales with distance
87
 
88
  profiles = [
89
  ("Express", 0.05 * scale, 95.0),
@@ -100,20 +153,24 @@ def synthetic_routes(origin: Coord, destination: Coord) -> List[Dict[str, Any]]:
100
  "duration_min": dist / avg_speed * 60.0,
101
  "turns": turn_count(poly),
102
  "source": "synthetic",
103
- "label_hint": label,
104
  })
105
  return out
106
 
107
 
108
  async def get_candidate_routes(origin: Coord, destination: Coord) -> List[Dict[str, Any]]:
109
- """Try OSRM first; fall back to synthetic if it fails."""
110
  try:
111
  routes = await fetch_osrm_routes(origin, destination, alternatives=3)
112
  if routes:
113
- logger.info(f"OSRM returned {len(routes)} candidate(s)")
114
- # If OSRM only returned 1, pad with synthetic alternatives
115
  if len(routes) < 3:
116
- routes.extend(synthetic_routes(origin, destination)[len(routes):])
 
 
 
 
 
117
  return routes[:3]
118
  except Exception as e:
119
  logger.warning(f"OSRM unavailable, falling back to synthetic: {e}")
 
1
  """Route candidate generation.
2
 
3
+ Primary: OSRM HTTP API — tries three strategies to get distinct real road routes:
4
+ 1. Default fastest route with alternatives=true
5
+ 2. Exclude motorway (avoids highways → balanced city/national road mix)
6
+ 3. Exclude motorway+trunk (forces local roads → slower but different path)
7
+ Fallback: synthetic Bezier-curve routes if all OSRM calls fail.
8
  """
9
  from __future__ import annotations
10
  import math
11
+ from typing import List, Tuple, Dict, Any, Optional
12
  import httpx
13
  from app.config import settings
14
  from app.utils.logger import logger
 
17
  Coord = Tuple[float, float]
18
 
19
 
20
+ def _osrm_url(origin: Coord, destination: Coord, exclude: Optional[str] = None, alternatives: bool = False) -> str:
 
 
 
 
 
 
 
 
 
 
21
  lng1, lat1 = origin[1], origin[0]
22
  lng2, lat2 = destination[1], destination[0]
23
  url = (
24
  f"{settings.osrm_url}/route/v1/driving/"
25
  f"{lng1},{lat1};{lng2},{lat2}"
26
+ f"?alternatives={'true' if alternatives else 'false'}"
27
  f"&overview=full&geometries=geojson&steps=true"
28
  )
29
+ if exclude:
30
+ url += f"&exclude={exclude}"
31
+ return url
 
32
 
33
+
34
+ def _parse_osrm_response(data: dict, source_label: str) -> List[Dict[str, Any]]:
35
  if data.get("code") != "Ok":
36
  raise RuntimeError(f"OSRM error: {data.get('message', data.get('code'))}")
37
+ out = []
38
+ for r in data.get("routes", []):
 
39
  coords_lnglat = r["geometry"]["coordinates"]
40
  polyline: List[Coord] = [(c[1], c[0]) for c in coords_lnglat]
41
  out.append({
 
44
  "duration_min": r["duration"] / 60.0,
45
  "turns": turn_count(polyline),
46
  "source": "osrm",
47
+ "source_label": source_label,
48
  "steps": r.get("legs", [{}])[0].get("steps", []),
49
  })
50
  return out
51
 
52
 
53
+ def _is_duplicate(candidate: Dict, existing: List[Dict], threshold: float = 0.04) -> bool:
54
+ """True if candidate distance_km is within threshold % of any existing route."""
55
+ d = candidate["distance_km"]
56
+ for e in existing:
57
+ if abs(d - e["distance_km"]) / max(d, e["distance_km"], 1e-6) < threshold:
58
+ return True
59
+ return False
60
+
61
+
62
+ async def _osrm_fetch(url: str) -> List[Dict[str, Any]]:
63
+ async with httpx.AsyncClient(timeout=10.0) as client:
64
+ resp = await client.get(url)
65
+ resp.raise_for_status()
66
+ return resp.json()
67
+
68
+
69
+ async def fetch_osrm_routes(
70
+ origin: Coord, destination: Coord, alternatives: int = 3
71
+ ) -> List[Dict[str, Any]]:
72
+ """Try multiple OSRM strategies to get up to 3 distinct real-road routes."""
73
+ routes: List[Dict[str, Any]] = []
74
+
75
+ # Strategy 1: fastest with alternatives=true
76
+ try:
77
+ data = await _osrm_fetch(_osrm_url(origin, destination, alternatives=True))
78
+ candidates = _parse_osrm_response(data, "fastest")
79
+ for c in candidates[:alternatives]:
80
+ if not _is_duplicate(c, routes):
81
+ routes.append(c)
82
+ logger.info(f"OSRM strategy 1 (fastest+alternatives): {len(routes)} route(s)")
83
+ except Exception as e:
84
+ logger.warning(f"OSRM strategy 1 failed: {e}")
85
+
86
+ # Strategy 2: avoid motorway (balanced road mix)
87
+ if len(routes) < alternatives:
88
+ try:
89
+ data = await _osrm_fetch(_osrm_url(origin, destination, exclude="motorway"))
90
+ candidates = _parse_osrm_response(data, "avoid_motorway")
91
+ for c in candidates[:1]:
92
+ if not _is_duplicate(c, routes):
93
+ routes.append(c)
94
+ logger.info("OSRM strategy 2 (avoid motorway): added 1 distinct route")
95
+ except Exception as e:
96
+ logger.debug(f"OSRM strategy 2 (avoid motorway) failed: {e}")
97
+
98
+ # Strategy 3: avoid motorway + trunk (local roads)
99
+ if len(routes) < alternatives:
100
+ try:
101
+ data = await _osrm_fetch(_osrm_url(origin, destination, exclude="motorway,trunk"))
102
+ candidates = _parse_osrm_response(data, "avoid_trunk")
103
+ for c in candidates[:1]:
104
+ if not _is_duplicate(c, routes):
105
+ routes.append(c)
106
+ logger.info("OSRM strategy 3 (avoid trunk): added 1 distinct route")
107
+ except Exception as e:
108
+ logger.debug(f"OSRM strategy 3 (avoid trunk) failed: {e}")
109
+
110
+ logger.info(f"OSRM returned {len(routes)} candidate(s)")
111
+ return routes[:alternatives]
112
+
113
+
114
  def _bezier_curve(
115
  origin: Coord, destination: Coord, curvature: float, samples: int = 60
116
  ) -> List[Coord]:
117
  """Quadratic Bezier between two points with perpendicular offset for variety."""
118
  mid_lat = (origin[0] + destination[0]) / 2
119
  mid_lng = (origin[1] + destination[1]) / 2
 
120
  dlat = destination[0] - origin[0]
121
  dlng = destination[1] - origin[1]
122
  nrm = math.hypot(dlat, dlng) or 1e-9
 
136
  def synthetic_routes(origin: Coord, destination: Coord) -> List[Dict[str, Any]]:
137
  """Three Bezier candidates: Express (straight), Smart (mild curve), Scenic (curvier)."""
138
  straight_km = haversine_km(origin, destination)
139
+ scale = max(0.4, straight_km / 400.0)
140
 
141
  profiles = [
142
  ("Express", 0.05 * scale, 95.0),
 
153
  "duration_min": dist / avg_speed * 60.0,
154
  "turns": turn_count(poly),
155
  "source": "synthetic",
156
+ "source_label": label,
157
  })
158
  return out
159
 
160
 
161
  async def get_candidate_routes(origin: Coord, destination: Coord) -> List[Dict[str, Any]]:
162
+ """Try OSRM first (multiple strategies); fall back to synthetic only if all fail."""
163
  try:
164
  routes = await fetch_osrm_routes(origin, destination, alternatives=3)
165
  if routes:
166
+ # Only pad with synthetic if OSRM strategies gave fewer than 3
 
167
  if len(routes) < 3:
168
+ synthetic = synthetic_routes(origin, destination)
169
+ for s in synthetic:
170
+ if len(routes) >= 3:
171
+ break
172
+ if not _is_duplicate(s, routes, threshold=0.10):
173
+ routes.append(s)
174
  return routes[:3]
175
  except Exception as e:
176
  logger.warning(f"OSRM unavailable, falling back to synthetic: {e}")