tkadkghdlf commited on
Commit
7c3b4e1
·
verified ·
1 Parent(s): 0cb29be

Sync DemoService 76f893441672db15ff5bae90c66b523164f62e2b

Browse files
api/ai-service/app/api/v1/endpoints/route_generation.py CHANGED
@@ -27,6 +27,9 @@ SHAPE_DISCOVERY_LABELS = ("dog", "symbol_star", "t_shirt", "heart", "candle", "c
27
  logger = logging.getLogger("uvicorn.error")
28
 
29
  _PIPELINE_MODULE_CACHE: dict[str, tuple[int, ModuleType]] = {}
 
 
 
30
 
31
 
32
  class RouteGenerateRequest(BaseModel):
@@ -333,6 +336,14 @@ def _run_fast_road_pipeline(
333
  # larger pool on the CPU-only Space makes a five-route request look like a
334
  # failed request before it can return any usable road loop.
335
  examples = getattr(module, "GPX_SHAPE_TEMPLATES", {}).get(selected_label, [])
 
 
 
 
 
 
 
 
336
  if shape_priority and not examples:
337
  outline = getattr(module, "LABEL_GUIDED_WAYPOINTS", {}).get(selected_label, [])
338
  examples = [outline] if outline else []
@@ -366,6 +377,7 @@ def _run_fast_road_pipeline(
366
  selected_label=selected_label,
367
  template_similarity_fn=lambda coords, template: best_gpx_shape_match(coords, [template])[0],
368
  **template_kwargs,
 
369
  ))
370
  generation_timings_ms["candidate_routes"] = round((time.perf_counter() - started_at) * 1000) - generation_timings_ms["road_graph"] - generation_timings_ms["scale_screening"]
371
  else:
@@ -374,6 +386,7 @@ def _run_fast_road_pipeline(
374
  route_count=candidate_pool,
375
  target_distance_m=target_distance_km * 1000.0,
376
  selected_label=selected_label,
 
377
  )
378
  # A selected shape is a preference, not a reason to leave the runner with
379
  # no route. Sparse neighbourhoods and long distances do not always have
@@ -389,6 +402,7 @@ def _run_fast_road_pipeline(
389
  target_distance_m=target_distance_km * 1000.0,
390
  selected_label=None,
391
  tolerance_ratio=0.60,
 
392
  )
393
  generation_mode = "fast_walk_roads_nearby_fallback"
394
  if not candidates:
@@ -437,7 +451,7 @@ def _run_fast_road_pipeline(
437
  "art_ready": generation_mode == "fast_walk_roads" and bool(selected_label),
438
  "road_connection": route.get("road_connection", "shortest"),
439
  **({"shape_similarity": similarity, "shape_example_index": example_index} if examples else {}),
440
- **({"gpx_similarity": similarity, "gpx_example_index": example_index} if examples and selected_label in {"dog", "symbol_star", "heart", "candle", "christmas_tree_trunk", "long_pants"} else {}),
441
  "target_shape": {
442
  "score": shape_quality,
443
  "route_coverage": shape_quality,
@@ -459,7 +473,7 @@ def _run_fast_road_pipeline(
459
  -route["route_quality"]["shape_similarity"],
460
  abs(route["length_km"] - target_distance_km) if not shape_priority else 0,
461
  ))
462
- if experimental_candidate_ranker and selected_label in SHAPE_DISCOVERY_LABELS:
463
  try:
464
  script_dir = Path(settings.ai_workspace_dir) / "scripts"
465
  if str(script_dir) not in sys.path:
 
27
  logger = logging.getLogger("uvicorn.error")
28
 
29
  _PIPELINE_MODULE_CACHE: dict[str, tuple[int, ModuleType]] = {}
30
+ # Temporary live comparison policy. Set False to restore geometry gates and
31
+ # opt-in HGB reranking without changing the client or model.
32
+ GPX_SIMILARITY_FIRST = True
33
 
34
 
35
  class RouteGenerateRequest(BaseModel):
 
336
  # larger pool on the CPU-only Space makes a five-route request look like a
337
  # failed request before it can return any usable road loop.
338
  examples = getattr(module, "GPX_SHAPE_TEMPLATES", {}).get(selected_label, [])
339
+ gpx_examples = bool(examples)
340
+ similarity_first = GPX_SIMILARITY_FIRST and gpx_examples
341
+ similarity_kwargs = {}
342
+ if similarity_first:
343
+ prepared = prepare_gpx_shape_templates(examples)
344
+ similarity_kwargs["gpx_similarity_score"] = lambda nodes: score_prepared_gpx_shape(
345
+ _route_nodes_to_coords(graph, nodes), prepared,
346
+ )
347
  if shape_priority and not examples:
348
  outline = getattr(module, "LABEL_GUIDED_WAYPOINTS", {}).get(selected_label, [])
349
  examples = [outline] if outline else []
 
377
  selected_label=selected_label,
378
  template_similarity_fn=lambda coords, template: best_gpx_shape_match(coords, [template])[0],
379
  **template_kwargs,
380
+ **similarity_kwargs,
381
  ))
382
  generation_timings_ms["candidate_routes"] = round((time.perf_counter() - started_at) * 1000) - generation_timings_ms["road_graph"] - generation_timings_ms["scale_screening"]
383
  else:
 
386
  route_count=candidate_pool,
387
  target_distance_m=target_distance_km * 1000.0,
388
  selected_label=selected_label,
389
+ **similarity_kwargs,
390
  )
391
  # A selected shape is a preference, not a reason to leave the runner with
392
  # no route. Sparse neighbourhoods and long distances do not always have
 
402
  target_distance_m=target_distance_km * 1000.0,
403
  selected_label=None,
404
  tolerance_ratio=0.60,
405
+ **similarity_kwargs,
406
  )
407
  generation_mode = "fast_walk_roads_nearby_fallback"
408
  if not candidates:
 
451
  "art_ready": generation_mode == "fast_walk_roads" and bool(selected_label),
452
  "road_connection": route.get("road_connection", "shortest"),
453
  **({"shape_similarity": similarity, "shape_example_index": example_index} if examples else {}),
454
+ **({"gpx_similarity": similarity, "gpx_example_index": example_index} if gpx_examples else {}),
455
  "target_shape": {
456
  "score": shape_quality,
457
  "route_coverage": shape_quality,
 
473
  -route["route_quality"]["shape_similarity"],
474
  abs(route["length_km"] - target_distance_km) if not shape_priority else 0,
475
  ))
476
+ if not similarity_first and experimental_candidate_ranker and selected_label in SHAPE_DISCOVERY_LABELS:
477
  try:
478
  script_dir = Path(settings.ai_workspace_dir) / "scripts"
479
  if str(script_dir) not in sys.path:
api/ai-service/tests/test_route_generation_recovery.py CHANGED
@@ -205,6 +205,7 @@ def test_shape_priority_uses_road_selected_scales_when_available(monkeypatch):
205
 
206
  @pytest.mark.parametrize("label", ["dog", "heart", "candle", "christmas_tree_trunk", "long_pants"])
207
  def test_opt_in_ranker_only_reorders_near_equal_road_routes(monkeypatch, label):
 
208
  sys.path.insert(0, str(ROOT / "router" / "ai" / "scripts"))
209
  import gpx_candidate_ranker_runtime as ranker_runtime
210
 
@@ -229,6 +230,58 @@ def test_opt_in_ranker_only_reorders_near_equal_road_routes(monkeypatch, label):
229
  assert [route["route_quality"]["shape_similarity"] for route in result["routes"]] == [.948, .95, .8]
230
 
231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  @pytest.mark.parametrize("label", ["symbol_star", "dog", "heart", "long_pants"])
233
  def test_gpx_search_screens_all_outlines_before_road_routing(monkeypatch, label):
234
  examples = [[(index, 0), (index, 1), (index + 1, 1), (index, 0)] for index in range(1000)]
 
205
 
206
  @pytest.mark.parametrize("label", ["dog", "heart", "candle", "christmas_tree_trunk", "long_pants"])
207
  def test_opt_in_ranker_only_reorders_near_equal_road_routes(monkeypatch, label):
208
+ monkeypatch.setattr(routes, "GPX_SIMILARITY_FIRST", False)
209
  sys.path.insert(0, str(ROOT / "router" / "ai" / "scripts"))
210
  import gpx_candidate_ranker_runtime as ranker_runtime
211
 
 
230
  assert [route["route_quality"]["shape_similarity"] for route in result["routes"]] == [.948, .95, .8]
231
 
232
 
233
+ def test_gpx_first_does_not_rerank_even_when_client_requests_hgb(monkeypatch):
234
+ candidates = [
235
+ {"nodes": [1, 2], "length_m": 6000, "shape_quality": .15, "is_loop": True},
236
+ {"nodes": [3, 4], "length_m": 6000, "shape_quality": .85, "is_loop": True},
237
+ ]
238
+ build = Mock(return_value=candidates)
239
+ module = SimpleNamespace(
240
+ GPX_SHAPE_TEMPLATES={"dog": [[(0, 0), (1, 0), (1, 1), (0, 0)]]},
241
+ _build_or_get_walk_graph=lambda *_: (object(), "test"),
242
+ generate_candidate_routes=build, route_points=lambda *_: [],
243
+ simplify_coords=lambda points: points,
244
+ )
245
+ monkeypatch.setattr(routes, "_route_nodes_to_coords", lambda _graph, nodes: [[nodes[0], 0], [nodes[1], 1]])
246
+ monkeypatch.setattr(routes, "best_gpx_shape_match", lambda coords, _: (.989 if coords[0][0] == 1 else .986, 0))
247
+ result = routes._run_fast_road_pipeline(
248
+ module, place=None, center_lat=37, center_lon=127, radius_km=2,
249
+ route_count=2, target_distance_km=6, selected_label="dog",
250
+ experimental_candidate_ranker=True,
251
+ )
252
+ assert callable(build.call_args.kwargs["gpx_similarity_score"])
253
+ assert result["ranking_mode"] == "gpx_similarity"
254
+ assert [route["route_quality"]["gpx_similarity"] for route in result["routes"]] == [.989, .986]
255
+ assert result["best_route"]["top1_score"] == .15
256
+ assert all("ranker_probability" not in route["route_quality"] for route in result["routes"])
257
+
258
+
259
+ def test_gpx_first_retains_low_geometry_candidate_before_pool_truncation(monkeypatch):
260
+ runtime = routes._load_pipeline_module(ROOT / "router" / "ai" / "scripts" / "osm_route_runtime.py")
261
+ graph = nx.MultiDiGraph()
262
+ high_gpx = list(range(18)) + [0]
263
+ low_gpx = list(range(18, 36)) + [18]
264
+ for path in (high_gpx, low_gpx):
265
+ for a, b in zip(path, path[1:]):
266
+ graph.add_edge(a, b, length=6000 / 18)
267
+ monkeypatch.setattr(runtime, "guided_geo_waypoints", lambda **_: [])
268
+ monkeypatch.setattr(runtime, "nearest_nodes_for_geo_points", lambda *_: [])
269
+ attempts = iter([high_gpx, low_gpx] * 100)
270
+ monkeypatch.setattr(runtime, "build_guided_route_nodes", lambda *_: next(attempts))
271
+ monkeypatch.setattr(runtime, "connect_contour", lambda *_args, **_kwargs: [])
272
+ monkeypatch.setattr(runtime, "route_points", lambda _graph, nodes: [(nodes[0], 0)])
273
+ monkeypatch.setattr(runtime, "route_shape_quality_with_metrics", lambda points, **_: (
274
+ .15 if points[0][0] == 0 else .85,
275
+ {"straight_ratio": .2, "turn_count_score": .5, "closure_score": 1},
276
+ ))
277
+ kwargs = dict(graph=graph, route_count=1, target_distance_m=6000, selected_label="dog",
278
+ template_examples=[[(0, 0), (1, 1)]], template_similarity_fn=lambda *_: .98)
279
+ assert runtime.generate_candidate_routes(**kwargs)[0]["nodes"] == low_gpx
280
+ assert runtime.generate_candidate_routes(
281
+ **kwargs, gpx_similarity_score=lambda nodes: .989 if nodes == high_gpx else .986,
282
+ )[0]["nodes"] == high_gpx
283
+
284
+
285
  @pytest.mark.parametrize("label", ["symbol_star", "dog", "heart", "long_pants"])
286
  def test_gpx_search_screens_all_outlines_before_road_routing(monkeypatch, label):
287
  examples = [[(index, 0), (index, 1), (index + 1, 1), (index, 0)] for index in range(1000)]
main/app/_utils/generatedRouteDetails.ts CHANGED
@@ -22,6 +22,7 @@ export type GeneratedRoute = {
22
  is_loop?: boolean;
23
  route_quality?: {
24
  art_ready?: boolean | null;
 
25
  retrace_ratio?: number;
26
  intentional_retrace_ratio?: number;
27
  unplanned_retrace_ratio?: number;
 
22
  is_loop?: boolean;
23
  route_quality?: {
24
  art_ready?: boolean | null;
25
+ gpx_similarity?: number;
26
  retrace_ratio?: number;
27
  intentional_retrace_ratio?: number;
28
  unplanned_retrace_ratio?: number;
main/app/route-results/page.tsx CHANGED
@@ -131,7 +131,7 @@ function RouteResultsPageContent() {
131
  const searchParams = useSearchParams();
132
  const router = useRouter();
133
 
134
- const cacheKey = useMemo(() => `route-results:v3:${searchParams.toString()}`, [searchParams]);
135
  const initialPlace = searchParams.get("place") || "Gangnam-gu, Seoul, South Korea";
136
  const initialSource = (searchParams.get("source") as "place" | "current" | null) ?? "place";
137
  const initialLatitude = parseNumberParam(searchParams.get("latitude"));
@@ -533,9 +533,6 @@ function RouteResultsPageContent() {
533
  {result?.ranking_mode === "gpx_ranker_experiment" ? (
534
  <p className="mt-4 rounded-xl bg-[#fafafa] px-3 py-2 text-sm font-bold text-[#111111]">GPX 학습 모델로 모양이 비슷한 경로의 순서를 비교했습니다.</p>
535
  ) : null}
536
- {result && experimentalCandidateRanker && result.ranking_mode !== "gpx_ranker_experiment" ? (
537
- <p className="mt-4 rounded-xl bg-[#fff4df] px-3 py-2 text-sm font-semibold text-[#754d08]">이번 결과는 도로망 대체 경로로, GPX 학습 순위가 적용되지 않았습니다.</p>
538
- ) : null}
539
  {result ? (
540
  <div className="rts-result-summary-grid mt-4">
541
  <div>
@@ -582,6 +579,8 @@ function RouteResultsPageContent() {
582
  const routeLabel = getPrimaryGeneratedRouteLabel(route);
583
  const hasRouteCoords = Boolean(route.route_coords && route.route_coords.length > 1);
584
  const score = getGeneratedRouteAiShapeScore(route);
 
 
585
  const savedRouteId = createSavedRouteId(route, result.place);
586
  const isBookmarked = savedRouteIds.has(savedRouteId);
587
 
@@ -643,8 +642,8 @@ function RouteResultsPageContent() {
643
  <p className="rts-data-label">예상 시간</p>
644
  </div>
645
  <div className="rts-data-item">
646
- <span className="rts-data-value">{getCompletionLabel(score)}</span>
647
- <p className="rts-data-label">형태 완성도</p>
648
  </div>
649
  </div>
650
 
 
131
  const searchParams = useSearchParams();
132
  const router = useRouter();
133
 
134
+ const cacheKey = useMemo(() => `route-results:v4:${searchParams.toString()}`, [searchParams]);
135
  const initialPlace = searchParams.get("place") || "Gangnam-gu, Seoul, South Korea";
136
  const initialSource = (searchParams.get("source") as "place" | "current" | null) ?? "place";
137
  const initialLatitude = parseNumberParam(searchParams.get("latitude"));
 
533
  {result?.ranking_mode === "gpx_ranker_experiment" ? (
534
  <p className="mt-4 rounded-xl bg-[#fafafa] px-3 py-2 text-sm font-bold text-[#111111]">GPX 학습 모델로 모양이 비슷한 경로의 순서를 비교했습니다.</p>
535
  ) : null}
 
 
 
536
  {result ? (
537
  <div className="rts-result-summary-grid mt-4">
538
  <div>
 
579
  const routeLabel = getPrimaryGeneratedRouteLabel(route);
580
  const hasRouteCoords = Boolean(route.route_coords && route.route_coords.length > 1);
581
  const score = getGeneratedRouteAiShapeScore(route);
582
+ const gpxSimilarity = route.route_quality?.gpx_similarity;
583
+ const hasGpxSimilarity = typeof gpxSimilarity === "number" && Number.isFinite(gpxSimilarity);
584
  const savedRouteId = createSavedRouteId(route, result.place);
585
  const isBookmarked = savedRouteIds.has(savedRouteId);
586
 
 
642
  <p className="rts-data-label">예상 시간</p>
643
  </div>
644
  <div className="rts-data-item">
645
+ <span className="rts-data-value">{hasGpxSimilarity ? `${(gpxSimilarity * 100).toFixed(1)}%` : getCompletionLabel(score)}</span>
646
+ <p className="rts-data-label">{hasGpxSimilarity ? "GPX 유사도" : "형태 완성도"}</p>
647
  </div>
648
  </div>
649
 
main/tests/routeGeneration.browser.cjs CHANGED
@@ -28,7 +28,8 @@ if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(base)) throw Error('Local on
28
  const center = body.place.includes('울릉') ? [37.4845,130.9057]
29
  : body.place.includes('해운대') ? [35.1631,129.1635] : [33.4996,126.5312];
30
  const routes = Array.from({length: 5}, (_, i) => ({image_path:'',top1:'cloud',top1_score:0,
31
- selected_label:'cloud',length_km:6,estimated_route:true,route_quality:{art_ready:false},results:[],
 
32
  center,route_coords:[center,[center[0]+0.001+i*0.0001,center[1]+0.001],center]}));
33
  return route.fulfill({json:{place:body.place,requested_count:5,generated_count:5,
34
  target_distance_km:6,labels:['cloud'],routes,best_route:routes[0],
@@ -68,35 +69,35 @@ if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(base)) throw Error('Local on
68
  await navigate({source:'place',place:'울릉군, 경상북도, 대한민국',fallbackLatitude:'37.4845',fallbackLongitude:'130.9057',routeCount:'5',targetDistanceKm:'6'});
69
  assert.ok(requests.at(-1).place.includes('울릉'));
70
  assert.equal(requests.at(-1).fallbackLatitude,37.4845);
 
 
71
  await navigate({source:'current',place:'현재 위치',latitude:'33.4996',longitude:'126.5312',routeCount:'5',targetDistanceKm:'6'});
72
- const beforeEdit = await page.evaluate(() => Object.fromEntries(Object.entries(sessionStorage).filter(([key])=>key.startsWith('route-results:v3:'))));
73
- await page.getByRole('textbox', {name:'지역',exact:true}).fill('해운대구, 부산광역시, 대한민국');
74
  const editedResponse = page.waitForResponse(response =>
75
  new URL(response.url()).pathname.endsWith('/routes/generate') &&
76
- response.request().postDataJSON()?.place?.includes('해운대'));
77
  await page.getByRole('button',{name:'다시 찾기',exact:true}).click();
78
  await editedResponse;
79
  await page.locator('.rts-route-rank').first().waitFor();
80
  const edited = requests.at(-1);
81
- assert.equal(edited.source,'place','editing location must override previous GPS origin');
82
- assert.equal(edited.latitude,null);
83
- assert.equal(edited.longitude,null);
84
- assert.equal(edited.fallbackLatitude,null,'old coordinates must never become the new place fallback');
85
- assert.equal(edited.fallbackLongitude,null);
86
- const afterEdit = await page.evaluate(() => Object.fromEntries(Object.entries(sessionStorage).filter(([key])=>key.startsWith('route-results:v3:'))));
87
  for (const [key,value] of Object.entries(beforeEdit)) {
88
  assert.equal(afterEdit[key],value,'edited result must not poison previous-location cache');
89
  }
90
- assert.ok(new URL(page.url()).searchParams.get('place').includes('해운대'),'edited search owns its result URL');
91
  const requestCount = requests.length;
92
  await page.getByRole('button',{name:'이 경로 선택',exact:true}).first().click();
93
  await page.waitForURL('**/route-results/generated_*?*');
94
  await page.goBack();
95
  await page.getByRole('button',{name:'이 경로 선택',exact:true}).first().waitFor();
96
  await page.waitForFunction(()=>document.querySelectorAll('input.rts-input').length===3);
97
- assert.ok((await page.getByRole('textbox',{name:'지역',exact:true}).inputValue()).includes('해운대'));
98
  assert.equal(requests.length,requestCount,'detail back restores the edited generation instead of the old GPS result');
99
  assert.deepEqual(errors,[]);
100
- console.log('PASS: delayed location lookup, region switching, 5 mapped routes, cached notice, same-page navigation, GPS-to-place editing, cache isolation');
101
  } finally { await browser.close(); }
102
  })().catch(error => {console.error(error);process.exit(1);});
 
28
  const center = body.place.includes('울릉') ? [37.4845,130.9057]
29
  : body.place.includes('해운대') ? [35.1631,129.1635] : [33.4996,126.5312];
30
  const routes = Array.from({length: 5}, (_, i) => ({image_path:'',top1:'cloud',top1_score:0,
31
+ selected_label:'cloud',length_km:6,estimated_route:true,
32
+ route_quality:{art_ready:false,...(body.place.includes('울릉') ? {gpx_similarity:0.989-i*0.001} : {})},results:[],
33
  center,route_coords:[center,[center[0]+0.001+i*0.0001,center[1]+0.001],center]}));
34
  return route.fulfill({json:{place:body.place,requested_count:5,generated_count:5,
35
  target_distance_km:6,labels:['cloud'],routes,best_route:routes[0],
 
69
  await navigate({source:'place',place:'울릉군, 경상북도, 대한민국',fallbackLatitude:'37.4845',fallbackLongitude:'130.9057',routeCount:'5',targetDistanceKm:'6'});
70
  assert.ok(requests.at(-1).place.includes('울릉'));
71
  assert.equal(requests.at(-1).fallbackLatitude,37.4845);
72
+ await page.getByText('98.9%',{exact:true}).waitFor();
73
+ assert.equal(await page.getByText('GPX 유사도',{exact:true}).count(),5);
74
  await navigate({source:'current',place:'현재 위치',latitude:'33.4996',longitude:'126.5312',routeCount:'5',targetDistanceKm:'6'});
75
+ const beforeEdit = await page.evaluate(() => Object.fromEntries(Object.entries(sessionStorage).filter(([key])=>key.startsWith('route-results:v4:'))));
76
+ await page.getByRole('spinbutton', {name:'목표 거리',exact:true}).fill('7');
77
  const editedResponse = page.waitForResponse(response =>
78
  new URL(response.url()).pathname.endsWith('/routes/generate') &&
79
+ response.request().postDataJSON()?.targetDistanceKm === 7);
80
  await page.getByRole('button',{name:'다시 찾기',exact:true}).click();
81
  await editedResponse;
82
  await page.locator('.rts-route-rank').first().waitFor();
83
  const edited = requests.at(-1);
84
+ assert.equal(edited.source,'current','distance retry must retain the selected GPS origin');
85
+ assert.equal(edited.latitude,33.4996);
86
+ assert.equal(edited.longitude,126.5312);
87
+ const afterEdit = await page.evaluate(() => Object.fromEntries(Object.entries(sessionStorage).filter(([key])=>key.startsWith('route-results:v4:'))));
 
 
88
  for (const [key,value] of Object.entries(beforeEdit)) {
89
  assert.equal(afterEdit[key],value,'edited result must not poison previous-location cache');
90
  }
91
+ assert.equal(new URL(page.url()).searchParams.get('targetDistanceKm'),'7','retry owns its result URL');
92
  const requestCount = requests.length;
93
  await page.getByRole('button',{name:'이 경로 선택',exact:true}).first().click();
94
  await page.waitForURL('**/route-results/generated_*?*');
95
  await page.goBack();
96
  await page.getByRole('button',{name:'이 경로 선택',exact:true}).first().waitFor();
97
  await page.waitForFunction(()=>document.querySelectorAll('input.rts-input').length===3);
98
+ assert.equal(await page.getByRole('spinbutton',{name:'목표 거리',exact:true}).inputValue(),'7');
99
  assert.equal(requests.length,requestCount,'detail back restores the edited generation instead of the old GPS result');
100
  assert.deepEqual(errors,[]);
101
+ console.log('PASS: region switching, mapped routes, GPX display, cached notice, same-page navigation, distance retry, cache isolation');
102
  } finally { await browser.close(); }
103
  })().catch(error => {console.error(error);process.exit(1);});
router/ai/scripts/osm_route_runtime.py CHANGED
@@ -1041,6 +1041,7 @@ def generate_candidate_routes(
1041
  selected_label: str | None = None,
1042
  template_examples: list[list[tuple[float, float]]] | None = None,
1043
  template_similarity_fn: Callable[[list[tuple[float, float]], list[tuple[float, float]]], float] | None = None,
 
1044
  ) -> list[dict[str, Any]]:
1045
  nodes = list(graph.nodes)
1046
  if len(nodes) < 8:
@@ -1092,6 +1093,8 @@ def generate_candidate_routes(
1092
  edges = list(zip(path, path[1:]))
1093
  retrace = 1.0 - len(set(edges)) / max(1, len(edges))
1094
  detour = max(0.0, route_length_m(graph, path) / baseline_length - 1.0)
 
 
1095
  return (template_similarity_fn(route_points(graph, path), template)
1096
  - 0.08 * retrace - 0.01 * detour)
1097
  route_nodes, connection_mode = max(options, key=option_score)
@@ -1117,19 +1120,20 @@ def generate_candidate_routes(
1117
  min_guided_quality += 0.01
1118
  elif soft_closed:
1119
  min_guided_quality += 0.005
1120
- if shape_quality < min_guided_quality:
1121
- continue
1122
- if float(shape_metrics.get("chord_penalty", 0.0)) > 0.24:
1123
- continue
1124
- if float(shape_metrics.get("straight_ratio", 1.0)) > 0.68:
1125
- continue
1126
- if float(shape_metrics.get("turn_count_score", 0.0)) < 0.06:
1127
- continue
1128
- if float(shape_metrics.get("closure_score", 0.0)) < max(
1129
- 0.04,
1130
- closure_threshold_for_label(selected_label, is_loop=True) * 0.75,
1131
- ):
1132
- continue
 
1133
 
1134
  sig = route_signature(route_nodes)
1135
  key = (sig, int(length_m // 120), "guided", selected_label)
@@ -1203,27 +1207,28 @@ def generate_candidate_routes(
1203
  min_loop_quality += 0.06
1204
  elif soft_closed:
1205
  min_loop_quality += 0.03
1206
- if shape_quality < min_loop_quality:
1207
- continue
1208
- max_chord_penalty = 0.22 if strict_closed else 0.32
1209
- if float(shape_metrics.get("chord_penalty", 0.0)) > max_chord_penalty:
1210
- continue
1211
- max_loop_straight_ratio = 0.46
1212
- if strict_closed:
1213
- max_loop_straight_ratio = 0.38
1214
- elif soft_closed:
1215
- max_loop_straight_ratio = 0.42
1216
- if float(shape_metrics.get("straight_ratio", 1.0)) > max_loop_straight_ratio:
1217
- continue
1218
- min_loop_turn_score = 0.16
1219
- if strict_closed:
1220
- min_loop_turn_score = 0.20
1221
- elif soft_closed:
1222
- min_loop_turn_score = 0.18
1223
- if float(shape_metrics.get("turn_count_score", 0.0)) < min_loop_turn_score:
1224
- continue
1225
- if float(shape_metrics.get("closure_score", 0.0)) < closure_threshold_for_label(selected_label, is_loop=True):
1226
- continue
 
1227
 
1228
  sig = route_signature(route_nodes)
1229
  key = (sig, int(length_m // 120), "loop")
@@ -1277,24 +1282,25 @@ def generate_candidate_routes(
1277
  min_open_quality += 0.04
1278
  elif soft_closed:
1279
  min_open_quality += 0.02
1280
- if shape_quality < min_open_quality:
1281
- continue
1282
- max_open_straight_ratio = 0.56
1283
- if strict_closed:
1284
- max_open_straight_ratio = 0.45
1285
- elif soft_closed:
1286
- max_open_straight_ratio = 0.50
1287
- if float(shape_metrics.get("straight_ratio", 1.0)) > max_open_straight_ratio:
1288
- continue
1289
- min_open_turn_score = 0.12
1290
- if strict_closed:
1291
- min_open_turn_score = 0.15
1292
- elif soft_closed:
1293
- min_open_turn_score = 0.13
1294
- if float(shape_metrics.get("turn_count_score", 0.0)) < min_open_turn_score:
1295
- continue
1296
- if float(shape_metrics.get("closure_score", 0.0)) < closure_threshold_for_label(selected_label, is_loop=False):
1297
- continue
 
1298
  sig = route_signature(route_nodes)
1299
  key = (sig, int(length_m // 120), "open")
1300
  if key in seen:
@@ -1320,6 +1326,18 @@ def generate_candidate_routes(
1320
  accepted.append(row)
1321
  fallback.append(row)
1322
 
 
 
 
 
 
 
 
 
 
 
 
 
1323
  accepted.sort(
1324
  key=lambda x: (
1325
  -generation_mode_priority(x),
 
1041
  selected_label: str | None = None,
1042
  template_examples: list[list[tuple[float, float]]] | None = None,
1043
  template_similarity_fn: Callable[[list[tuple[float, float]], list[tuple[float, float]]], float] | None = None,
1044
+ gpx_similarity_score: Callable[[list[int]], float] | None = None,
1045
  ) -> list[dict[str, Any]]:
1046
  nodes = list(graph.nodes)
1047
  if len(nodes) < 8:
 
1093
  edges = list(zip(path, path[1:]))
1094
  retrace = 1.0 - len(set(edges)) / max(1, len(edges))
1095
  detour = max(0.0, route_length_m(graph, path) / baseline_length - 1.0)
1096
+ if gpx_similarity_score is not None:
1097
+ return (gpx_similarity_score(path), -retrace, -detour)
1098
  return (template_similarity_fn(route_points(graph, path), template)
1099
  - 0.08 * retrace - 0.01 * detour)
1100
  route_nodes, connection_mode = max(options, key=option_score)
 
1120
  min_guided_quality += 0.01
1121
  elif soft_closed:
1122
  min_guided_quality += 0.005
1123
+ if gpx_similarity_score is None:
1124
+ if shape_quality < min_guided_quality:
1125
+ continue
1126
+ if float(shape_metrics.get("chord_penalty", 0.0)) > 0.24:
1127
+ continue
1128
+ if float(shape_metrics.get("straight_ratio", 1.0)) > 0.68:
1129
+ continue
1130
+ if float(shape_metrics.get("turn_count_score", 0.0)) < 0.06:
1131
+ continue
1132
+ if float(shape_metrics.get("closure_score", 0.0)) < max(
1133
+ 0.04,
1134
+ closure_threshold_for_label(selected_label, is_loop=True) * 0.75,
1135
+ ):
1136
+ continue
1137
 
1138
  sig = route_signature(route_nodes)
1139
  key = (sig, int(length_m // 120), "guided", selected_label)
 
1207
  min_loop_quality += 0.06
1208
  elif soft_closed:
1209
  min_loop_quality += 0.03
1210
+ if gpx_similarity_score is None:
1211
+ if shape_quality < min_loop_quality:
1212
+ continue
1213
+ max_chord_penalty = 0.22 if strict_closed else 0.32
1214
+ if float(shape_metrics.get("chord_penalty", 0.0)) > max_chord_penalty:
1215
+ continue
1216
+ max_loop_straight_ratio = 0.46
1217
+ if strict_closed:
1218
+ max_loop_straight_ratio = 0.38
1219
+ elif soft_closed:
1220
+ max_loop_straight_ratio = 0.42
1221
+ if float(shape_metrics.get("straight_ratio", 1.0)) > max_loop_straight_ratio:
1222
+ continue
1223
+ min_loop_turn_score = 0.16
1224
+ if strict_closed:
1225
+ min_loop_turn_score = 0.20
1226
+ elif soft_closed:
1227
+ min_loop_turn_score = 0.18
1228
+ if float(shape_metrics.get("turn_count_score", 0.0)) < min_loop_turn_score:
1229
+ continue
1230
+ if float(shape_metrics.get("closure_score", 0.0)) < closure_threshold_for_label(selected_label, is_loop=True):
1231
+ continue
1232
 
1233
  sig = route_signature(route_nodes)
1234
  key = (sig, int(length_m // 120), "loop")
 
1282
  min_open_quality += 0.04
1283
  elif soft_closed:
1284
  min_open_quality += 0.02
1285
+ if gpx_similarity_score is None:
1286
+ if shape_quality < min_open_quality:
1287
+ continue
1288
+ max_open_straight_ratio = 0.56
1289
+ if strict_closed:
1290
+ max_open_straight_ratio = 0.45
1291
+ elif soft_closed:
1292
+ max_open_straight_ratio = 0.50
1293
+ if float(shape_metrics.get("straight_ratio", 1.0)) > max_open_straight_ratio:
1294
+ continue
1295
+ min_open_turn_score = 0.12
1296
+ if strict_closed:
1297
+ min_open_turn_score = 0.15
1298
+ elif soft_closed:
1299
+ min_open_turn_score = 0.13
1300
+ if float(shape_metrics.get("turn_count_score", 0.0)) < min_open_turn_score:
1301
+ continue
1302
+ if float(shape_metrics.get("closure_score", 0.0)) < closure_threshold_for_label(selected_label, is_loop=False):
1303
+ continue
1304
  sig = route_signature(route_nodes)
1305
  key = (sig, int(length_m // 120), "open")
1306
  if key in seen:
 
1326
  accepted.append(row)
1327
  fallback.append(row)
1328
 
1329
+ if gpx_similarity_score is not None:
1330
+ # Distance-qualified routes stay ahead of the existing distance fallback.
1331
+ # Within either pool, do not truncate by geometry or generation mode.
1332
+ pool = accepted if len(accepted) >= route_count else fallback
1333
+ scores = {tuple(row["nodes"]): gpx_similarity_score(row["nodes"]) for row in pool}
1334
+ key = lambda row: (-scores[tuple(row["nodes"])], row["delta"])
1335
+ accepted.sort(key=key)
1336
+ if len(accepted) < route_count:
1337
+ accepted_nodes = {tuple(row["nodes"]) for row in accepted}
1338
+ accepted.extend(row for row in sorted(fallback, key=key) if tuple(row["nodes"]) not in accepted_nodes)
1339
+ return accepted[:route_count]
1340
+
1341
  accepted.sort(
1342
  key=lambda x: (
1343
  -generation_mode_priority(x),