tkadkghdlf commited on
Commit
7c75fed
·
verified ·
1 Parent(s): 5b78af8

Sync DemoService eed6420050899aba766f84bb40caff7c016d1dee

Browse files
api/ai-service/app/api/v1/endpoints/route_generation.py CHANGED
@@ -601,6 +601,48 @@ def _run_fast_road_pipeline(
601
  }
602
 
603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604
  def _run_experimental_next_edge(
605
  module: ModuleType, *, workspace_dir: Path, latitude: float, longitude: float,
606
  selected_label: str, route_count: int, generation_id: str | None,
@@ -1035,7 +1077,12 @@ def generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
1035
  generation_id=payload.generationId,
1036
  )
1037
  if real_roads:
1038
- return real_roads
 
 
 
 
 
1039
  return _coordinate_fallback_routes(
1040
  center_lat=fallback_lat,
1041
  center_lon=fallback_lon,
 
601
  }
602
 
603
 
604
+ def _rank_and_orient_walking_fallback(
605
+ result: dict[str, Any], *, selected_label: str | None,
606
+ templates: list[list[tuple[float, float]]],
607
+ use_hgb_ranker: bool, workspace_dir: Path,
608
+ ) -> dict[str, Any]:
609
+ """Apply the same preview orientation and supported HGB ranking to backup roads."""
610
+ routes = result.get("routes")
611
+ if not isinstance(routes, list) or not routes or not templates:
612
+ return result
613
+ # The independent walking provider caches its result; never mutate that
614
+ # shared object when one request enables the learned ranker.
615
+ ranked = [{**route, "route_quality": dict(route.get("route_quality") or {})}
616
+ for route in routes]
617
+ if selected_label == "dog":
618
+ for route in ranked:
619
+ index = route["route_quality"].get("gpx_example_index")
620
+ coords = route.get("route_coords")
621
+ if isinstance(index, int) and 0 <= index < len(templates) and coords:
622
+ angle = dog_upright_preview_rotation(coords, templates[index])
623
+ if angle is not None:
624
+ route["route_quality"]["preview_rotation_degrees"] = angle
625
+ ranking_mode = "gpx_similarity"
626
+ if use_hgb_ranker and selected_label in {"dog", "symbol_star", "t_shirt"}:
627
+ try:
628
+ script_dir = workspace_dir / "scripts"
629
+ if str(script_dir) not in sys.path:
630
+ sys.path.insert(0, str(script_dir))
631
+ import gpx_candidate_ranker_runtime as ranker_runtime
632
+ model = ranker_runtime.load_ranker(str(workspace_dir / "data/models/gpx_candidate_ranker_experiment.pkl"))
633
+ scores = ranker_runtime.score_candidates(model, [route["route_coords"] for route in ranked], selected_label)
634
+ order = ranker_runtime.guarded_order(
635
+ [route["route_quality"].get("gpx_similarity", 0.0) for route in ranked], scores,
636
+ )
637
+ ranked = [ranked[index] for index in order]
638
+ for route, index in zip(ranked, order):
639
+ route["route_quality"]["ranker_probability"] = float(scores[index])
640
+ ranking_mode = "gpx_ranker_experiment"
641
+ except Exception:
642
+ logger.exception("GPX ranker unavailable for walking fallback; keeping geometric order")
643
+ return {**result, "routes": ranked, "best_route": ranked[0], "ranking_mode": ranking_mode}
644
+
645
+
646
  def _run_experimental_next_edge(
647
  module: ModuleType, *, workspace_dir: Path, latitude: float, longitude: float,
648
  selected_label: str, route_count: int, generation_id: str | None,
 
1077
  generation_id=payload.generationId,
1078
  )
1079
  if real_roads:
1080
+ return _rank_and_orient_walking_fallback(
1081
+ real_roads, selected_label=selected_label,
1082
+ templates=getattr(module, "GPX_SHAPE_TEMPLATES", {}).get(selected_label, []),
1083
+ use_hgb_ranker=payload.experimentalCandidateRanker,
1084
+ workspace_dir=workspace_dir,
1085
+ )
1086
  return _coordinate_fallback_routes(
1087
  center_lat=fallback_lat,
1088
  center_lon=fallback_lon,
api/ai-service/tests/test_route_generation_recovery.py CHANGED
@@ -2,6 +2,7 @@
2
  from __future__ import annotations
3
 
4
  import ast
 
5
  import importlib.util
6
  import math
7
  import sys
@@ -36,6 +37,29 @@ CENTERS = [
36
  LABELS = ["cloud", "cup", "face", "ice_cream", "t_shirt", "fish", "apple", "candle"]
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  @pytest.fixture(autouse=True)
40
  def offline_independent_provider(monkeypatch):
41
  monkeypatch.setattr(routes, "generate_walking_fallback", lambda **_: None)
 
2
  from __future__ import annotations
3
 
4
  import ast
5
+ import json
6
  import importlib.util
7
  import math
8
  import sys
 
37
  LABELS = ["cloud", "cup", "face", "ice_cream", "t_shirt", "fish", "apple", "candle"]
38
 
39
 
40
+ def test_walking_fallback_keeps_first_route_best_and_rotates_dog_preview(monkeypatch):
41
+ template_path = ROOT / "router/ai/data/dog_shape_templates_all.json"
42
+ template = json.loads(template_path.read_text(encoding="utf-8"))["dog"][0]
43
+ coords = [[37.5 - y / 111320, 127 + x / 88400] for x, y in template]
44
+ source = {"routes": [
45
+ {"route_coords": coords, "route_quality": {"gpx_similarity": .91, "gpx_example_index": 0}},
46
+ {"route_coords": coords, "route_quality": {"gpx_similarity": .909, "gpx_example_index": 0}},
47
+ ]}
48
+ fake = SimpleNamespace(load_ranker=lambda _: object(),
49
+ score_candidates=lambda *_: [.2, .9],
50
+ guarded_order=lambda *_: [1, 0])
51
+ monkeypatch.setitem(sys.modules, "gpx_candidate_ranker_runtime", fake)
52
+ result = routes._rank_and_orient_walking_fallback(
53
+ source, selected_label="dog", templates=[template],
54
+ use_hgb_ranker=True, workspace_dir=ROOT / "router/ai",
55
+ )
56
+ assert result["ranking_mode"] == "gpx_ranker_experiment"
57
+ assert result["best_route"] is result["routes"][0]
58
+ assert result["routes"][0]["route_quality"]["ranker_probability"] == .9
59
+ assert result["routes"][0]["route_quality"]["preview_rotation_degrees"] is not None
60
+ assert "preview_rotation_degrees" not in source["routes"][0]["route_quality"]
61
+
62
+
63
  @pytest.fixture(autouse=True)
64
  def offline_independent_provider(monkeypatch):
65
  monkeypatch.setattr(routes, "generate_walking_fallback", lambda **_: None)