tkadkghdlf commited on
Commit
ff0b3ad
·
verified ·
1 Parent(s): 59dcb8f

Sync DemoService 13be91a6d88fd7adceb6dbc903eb2aef3d545309

Browse files
api/ai-service/app/api/v1/endpoints/route_generation.py CHANGED
@@ -449,7 +449,7 @@ def _run_fast_road_pipeline(
449
  rank_projections = getattr(module, "rank_road_template_projections", None)
450
  for search_distance_km in (6.0, 11.0, 18.0):
451
  template_kwargs = {}
452
- if selected_label in {"symbol_star", "dog", "heart"} and callable(rank_projections):
453
  # Screen every supplied animal/shape outline against this road graph;
454
  # only the best fits enter the expensive shortest-path stage.
455
  template_kwargs["template_examples"] = rank_projections(
@@ -525,7 +525,7 @@ def _run_fast_road_pipeline(
525
  "route_quality": {
526
  "art_ready": generation_mode == "fast_walk_roads" and bool(selected_label),
527
  **({"shape_similarity": similarity, "shape_example_index": example_index} if examples else {}),
528
- **({"gpx_similarity": similarity, "gpx_example_index": example_index} if examples and selected_label in {"dog", "symbol_star", "heart"} else {}),
529
  "target_shape": {
530
  "score": shape_quality,
531
  "route_coverage": shape_quality,
@@ -596,7 +596,8 @@ def _run_experimental_next_edge(
596
  """Return routes chosen by the experimental PT, with explicit provenance."""
597
  script_dir = workspace_dir / "scripts"
598
  script_path = script_dir / "experimental_next_edge_service.py"
599
- checkpoint_path = workspace_dir / "data" / "models" / "gatv2_next_edge_experiment.pt"
 
600
  if not script_path.is_file() or not checkpoint_path.is_file():
601
  raise RuntimeError("GATv2 experiment files are missing")
602
  if str(script_dir) not in sys.path:
@@ -650,7 +651,7 @@ def _run_experimental_next_edge(
650
 
651
  @router.post("/routes/discover-shapes")
652
  def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
653
- """Find runnable dog, star, T-shirt and heart outlines near a picked map point."""
654
  workspace_dir = Path(settings.ai_workspace_dir)
655
  script_dir = workspace_dir / "scripts"
656
  script_path = script_dir / "experimental_next_edge_service.py"
@@ -675,6 +676,7 @@ def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
675
  legacy_model = load_prefilter(str(legacy_prefilter_path))
676
  prefilter_model = {label: legacy_model for label in ("dog", "symbol_star", "t_shirt")}
677
  prefilter_model["heart"] = heart_model
 
678
  outline_selection_mode = "learned_top_100_plus_geometric_12"
679
  except (OSError, ValueError, ImportError):
680
  logger.exception("GPX outline prefilter unavailable; using full search")
@@ -684,7 +686,7 @@ def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
684
  graph = experiment.fetch_small_walk_graph(payload.latitude, payload.longitude, radius_km=2.0)
685
  stage = "route_outlines"
686
  road, paths_by_label, snap_distance = experiment.discover_shape_paths(
687
- graph, {label: outlines.get(label, []) for label in ("dog", "symbol_star", "t_shirt", "heart")},
688
  payload.latitude, payload.longitude, candidate_limit=None,
689
  snap_limit=None, return_sources=True,
690
  prefilter_model=prefilter_model, prefilter_limit=100,
@@ -696,7 +698,7 @@ def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
696
  import gpx_candidate_ranker_runtime as ranker_runtime
697
  ranker = ranker_runtime.load_ranker(str(workspace_dir / "data" / "models" / "gpx_candidate_ranker_experiment.pkl"))
698
  candidates = []
699
- for label in ("dog", "symbol_star", "t_shirt", "heart"):
700
  examples = outlines[label]
701
  prepared_examples = [prepare_gpx_shape_templates([outline]) for outline in examples]
702
  ranked = []
@@ -709,7 +711,7 @@ def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
709
  ranked.append((score, similarity, retrace, path, coords))
710
  if ranked:
711
  probability = None
712
- if ranker is not None and ranker_runtime is not None:
713
  probabilities = ranker_runtime.score_candidates(ranker, [row[4] for row in ranked], label)
714
  order = ranker_runtime.guarded_order([row[0] for row in ranked], probabilities)
715
  chosen = order[0]
@@ -737,9 +739,9 @@ def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
737
  "snap_distance_m": round(snap_distance, 1),
738
  "search_radius_km": 2.0, "ranking_mode": "gpx_ranker_experiment" if ranker is not None else "gpx_similarity",
739
  "outline_selection_mode": outline_selection_mode,
740
- "outlines_considered": {label: len(outlines[label]) for label in ("dog", "symbol_star", "t_shirt", "heart")},
741
  "outlines_routed": {label: len({source for _, source in paths_by_label[label]})
742
- for label in ("dog", "symbol_star", "t_shirt", "heart")},
743
  "candidates": candidates}
744
  except ValueError as exc:
745
  raise HTTPException(status_code=422, detail=str(exc)) from exc
@@ -909,8 +911,8 @@ def generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
909
  radius_km = min(10.0, max(5.0 if shape_priority else 1.5, min(10.0, payload.radiusKm), required_radius_km))
910
 
911
  if payload.experimentalNextEdge:
912
- if selected_label not in {"dog", "symbol_star", "t_shirt", "heart"}:
913
- raise HTTPException(status_code=400, detail="GATv2 experiment supports dog, star, T-shirt, and heart only")
914
  center_lat = payload.latitude if use_current else payload.fallbackLatitude
915
  center_lon = payload.longitude if use_current else payload.fallbackLongitude
916
  if center_lat is None or center_lon is None:
 
449
  rank_projections = getattr(module, "rank_road_template_projections", None)
450
  for search_distance_km in (6.0, 11.0, 18.0):
451
  template_kwargs = {}
452
+ if selected_label in {"symbol_star", "dog", "heart", "candle"} and callable(rank_projections):
453
  # Screen every supplied animal/shape outline against this road graph;
454
  # only the best fits enter the expensive shortest-path stage.
455
  template_kwargs["template_examples"] = rank_projections(
 
525
  "route_quality": {
526
  "art_ready": generation_mode == "fast_walk_roads" and bool(selected_label),
527
  **({"shape_similarity": similarity, "shape_example_index": example_index} if examples else {}),
528
+ **({"gpx_similarity": similarity, "gpx_example_index": example_index} if examples and selected_label in {"dog", "symbol_star", "heart", "candle"} else {}),
529
  "target_shape": {
530
  "score": shape_quality,
531
  "route_coverage": shape_quality,
 
596
  """Return routes chosen by the experimental PT, with explicit provenance."""
597
  script_dir = workspace_dir / "scripts"
598
  script_path = script_dir / "experimental_next_edge_service.py"
599
+ checkpoint_name = "gatv2_next_edge_candle.pt" if selected_label == "candle" else "gatv2_next_edge_experiment.pt"
600
+ checkpoint_path = workspace_dir / "data" / "models" / checkpoint_name
601
  if not script_path.is_file() or not checkpoint_path.is_file():
602
  raise RuntimeError("GATv2 experiment files are missing")
603
  if str(script_dir) not in sys.path:
 
651
 
652
  @router.post("/routes/discover-shapes")
653
  def discover_shapes(payload: ShapeDiscoveryRequest) -> dict[str, Any]:
654
+ """Find runnable dog, star, T-shirt, heart and candle outlines near a picked map point."""
655
  workspace_dir = Path(settings.ai_workspace_dir)
656
  script_dir = workspace_dir / "scripts"
657
  script_path = script_dir / "experimental_next_edge_service.py"
 
676
  legacy_model = load_prefilter(str(legacy_prefilter_path))
677
  prefilter_model = {label: legacy_model for label in ("dog", "symbol_star", "t_shirt")}
678
  prefilter_model["heart"] = heart_model
679
+ prefilter_model["candle"] = load_prefilter(str(workspace_dir / "data" / "models" / "gpx_outline_prefilter_candle.pkl"))
680
  outline_selection_mode = "learned_top_100_plus_geometric_12"
681
  except (OSError, ValueError, ImportError):
682
  logger.exception("GPX outline prefilter unavailable; using full search")
 
686
  graph = experiment.fetch_small_walk_graph(payload.latitude, payload.longitude, radius_km=2.0)
687
  stage = "route_outlines"
688
  road, paths_by_label, snap_distance = experiment.discover_shape_paths(
689
+ graph, {label: outlines.get(label, []) for label in ("dog", "symbol_star", "t_shirt", "heart", "candle")},
690
  payload.latitude, payload.longitude, candidate_limit=None,
691
  snap_limit=None, return_sources=True,
692
  prefilter_model=prefilter_model, prefilter_limit=100,
 
698
  import gpx_candidate_ranker_runtime as ranker_runtime
699
  ranker = ranker_runtime.load_ranker(str(workspace_dir / "data" / "models" / "gpx_candidate_ranker_experiment.pkl"))
700
  candidates = []
701
+ for label in ("dog", "symbol_star", "t_shirt", "heart", "candle"):
702
  examples = outlines[label]
703
  prepared_examples = [prepare_gpx_shape_templates([outline]) for outline in examples]
704
  ranked = []
 
711
  ranked.append((score, similarity, retrace, path, coords))
712
  if ranked:
713
  probability = None
714
+ if ranker is not None and ranker_runtime is not None and label in ranker_runtime.LABELS:
715
  probabilities = ranker_runtime.score_candidates(ranker, [row[4] for row in ranked], label)
716
  order = ranker_runtime.guarded_order([row[0] for row in ranked], probabilities)
717
  chosen = order[0]
 
739
  "snap_distance_m": round(snap_distance, 1),
740
  "search_radius_km": 2.0, "ranking_mode": "gpx_ranker_experiment" if ranker is not None else "gpx_similarity",
741
  "outline_selection_mode": outline_selection_mode,
742
+ "outlines_considered": {label: len(outlines[label]) for label in ("dog", "symbol_star", "t_shirt", "heart", "candle")},
743
  "outlines_routed": {label: len({source for _, source in paths_by_label[label]})
744
+ for label in ("dog", "symbol_star", "t_shirt", "heart", "candle")},
745
  "candidates": candidates}
746
  except ValueError as exc:
747
  raise HTTPException(status_code=422, detail=str(exc)) from exc
 
911
  radius_km = min(10.0, max(5.0 if shape_priority else 1.5, min(10.0, payload.radiusKm), required_radius_km))
912
 
913
  if payload.experimentalNextEdge:
914
+ if selected_label not in {"dog", "symbol_star", "t_shirt", "heart", "candle"}:
915
+ raise HTTPException(status_code=400, detail="GATv2 experiment supports dog, star, T-shirt, heart, and candle only")
916
  center_lat = payload.latitude if use_current else payload.fallbackLatitude
917
  center_lon = payload.longitude if use_current else payload.fallbackLongitude
918
  if center_lat is None or center_lon is None:
api/ai-service/tests/test_candle_replacement.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """New candle data must replace old templates and work with the shipped model."""
2
+ import ast
3
+ import json
4
+ import random
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import networkx as nx
9
+ import numpy as np
10
+ import pytest
11
+
12
+ ROOT = Path(__file__).resolve().parents[3]
13
+ SCRIPTS = ROOT / 'router' / 'ai' / 'scripts'
14
+ sys.path.insert(0, str(SCRIPTS))
15
+
16
+
17
+ def candle_scope():
18
+ script = SCRIPTS / 'clip_osm_region_test.py'
19
+ tree = ast.parse(script.read_text(encoding='utf-8-sig'))
20
+ names = {'_load_gpx_shape_templates', 'guided_waypoints_for_label'}
21
+ functions = ast.Module(body=[n for n in tree.body if isinstance(n, ast.FunctionDef)
22
+ and n.name in names], type_ignores=[])
23
+ scope = {'__file__': str(script), 'Path': Path, 'json': json, 'random': random,
24
+ 'LABEL_GUIDED_WAYPOINTS': {'candle': ['old drawing']}}
25
+ exec(compile(functions, str(script), 'exec'), scope)
26
+ return scope
27
+
28
+
29
+ def test_candle_uses_only_replacement_and_fails_instead_of_old_fallback():
30
+ scope = candle_scope()
31
+ data = scope['_load_gpx_shape_templates']()
32
+ expected = json.loads((SCRIPTS.parent / 'data/candle_shape_templates_all.json').read_text())
33
+ assert data['candle'] == [[tuple(p) for p in outline] for outline in expected['candle']]
34
+ assert len(data['candle']) == 189
35
+ assert all(5 <= len(o) <= 25 and o[0] == o[-1] for o in data['candle'])
36
+ scope['GPX_SHAPE_TEMPLATES'] = data
37
+ assert scope['guided_waypoints_for_label']('candle') in data['candle']
38
+ data['candle'] = []
39
+ with pytest.raises(ValueError, match='Replacement candle'):
40
+ scope['guided_waypoints_for_label']('candle')
41
+
42
+
43
+ def test_trained_candle_selector_routes_on_connected_roads():
44
+ from experimental_next_edge_service import discover_shape_paths
45
+ from gpx_outline_prefilter import load_prefilter
46
+ graph = nx.MultiDiGraph()
47
+ for y in range(8):
48
+ for x in range(8):
49
+ node = y * 8 + x
50
+ graph.add_node(node, y=37.5 + y * .001, x=127 + x * .001)
51
+ for neighbor in (node - 1 if x else None, node - 8 if y else None):
52
+ if neighbor is not None:
53
+ graph.add_edge(node, neighbor, length=100)
54
+ graph.add_edge(neighbor, node, length=100)
55
+ outlines = candle_scope()['_load_gpx_shape_templates']()['candle'][:5]
56
+ model = load_prefilter(str(SCRIPTS.parent / 'data/models/gpx_outline_prefilter_candle.pkl'))
57
+ assert np.isfinite(model.predict(np.zeros((1, 23)))).all()
58
+ road, routes, _ = discover_shape_paths(graph, {'candle': outlines}, 37.502, 127.002,
59
+ prefilter_model={'candle': model}, prefilter_limit=2)
60
+ assert routes['candle']
61
+ assert all(path[0] == path[-1] and all((a, b) in road.length for a, b in zip(path, path[1:]))
62
+ for path in routes['candle'])
63
+
64
+
65
+ def test_builder_excludes_review_candidates(tmp_path):
66
+ from build_candle_shape_templates import build
67
+ points = ''.join(f'<trkpt lat="{37.5 + .002*np.sin(t)}" lon="{127 + .002*np.cos(t)}"/>'
68
+ for t in np.linspace(0, 2*np.pi, 20))
69
+ def track(passed):
70
+ return f'<trk><type>candle</type><extensions><geometry_passed>{passed}</geometry_passed></extensions><trkseg>{points}</trkseg></trk>'
71
+ source = tmp_path / 'candle.gpx'
72
+ source.write_text('<gpx>' + track('true') + track('true') + track('false') + '</gpx>')
73
+ active, pending, report = build(source)
74
+ assert len(active['candle']) == 1 and len(pending['candle']) == 1
75
+ assert report['duplicates'] == 1 and report['review_candidates'] == 1
docs/CANDLE_GPX_REPLACEMENT.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 양초 GPX 교체 — 2026-11-01
2
+
3
+ `candle_all_1000.gpx`로 기존 수작업 양초 도안을 교체했다. 다른 도형의 데이터와
4
+ 모델은 유지한다. 양초 선택 화면, 지도 지점 모양 탐색, 일반 경로 생성에 새 윤곽을
5
+ 연결했다. 양초 데이터 파일을 읽지 못하면 이전 양초 그림으로 되돌아가지 않는다.
6
+
7
+ ## 데이터
8
+
9
+ - 원본 1,000개 트랙, 11개 지역, 18개 도안.
10
+ - 원본의 `geometry_passed=true` 191개에서 정규화 중복 2개를 제외한 189개를 사용한다.
11
+ - 나머지 809개는 `D:/tranimal/gatv2-data/candle_review_candidates.json`에 별도 보관한다.
12
+ - 원본 GPX는 Downloads에 유지한다. 배포에는 위치를 제거한 윤곽만 포함한다.
13
+ - 원본 SHA-256과 출처는 `candle_shape_templates_all.manifest.json`에 기록했다.
14
+ - 원본의 기하 통과 표시는 현장 안전성 검증을 의미하지 않는다.
15
+ - 지도 원자료: OpenStreetMap contributors, ODbL-1.0.
16
+
17
+ ## 학습과 적용
18
+
19
+ 도안 선택기 `gpx_outline_prefilter_candle.pkl`은 서울 8개 지점에서 생성한
20
+ 3,024개 투영 후보로 학습했다. 서울 3개·부산 2개 추가 지점에서 평가했다.
21
+ 기존 도형 모델의 입력 구조를 유지하기 위해 양초 전용 모델의 라벨 특성은
22
+ 모두 0이다. 기하 특성으로 양초 후보를 평가하며 기존 모델에는 양초를 보내지 않는다.
23
+ 평가 지점은 추가 지점이지 모든 도로가 서로 겹치지 않는 지리적 홀드아웃은 아니다.
24
+
25
+ `gatv2_next_edge_candle.pt`는 새 양초 도안을 도로에 투영한 3,771개 분기 선택
26
+ 예시로 4 epoch 학습했다. 기존 모델을 덮어쓰지 않고 양초의 실험 옵션에서만 사용한다.
27
+ 학습·평가 도로의 공통 노드는 0개다. 평가 윤곽은 학습에도 사용했으므로 새로운
28
+ 양초 디자인에 대한 일반화 실험은 아니다.
29
+
30
+ 평가 21개 경로 모두 도로 연결이 유효했다. 평균 윤곽 유사도는 기본 최단경로 방식
31
+ 0.905, GATv2 0.811로, 모델의 모양 개선을 입증하지 못했다. 따라서 일반 생성기를
32
+ GATv2로 대체하지 않는다.
33
+
34
+ ## 재현
35
+
36
+ ```powershell
37
+ python router/ai/scripts/build_candle_shape_templates.py C:/Users/SAMSUNG/Downloads/candle_all_1000.gpx router/ai/data/candle_shape_templates_all.json --review-output D:/tranimal/gatv2-data/candle_review_candidates.json
38
+ python router/ai/scripts/train_gpx_outline_prefilter.py --seoul D:/tranimal/gatv2-data/seoul_full.graphml --busan D:/tranimal/gatv2-data/busan_holdout.graphml --labels candle --output router/ai/data/models/gpx_outline_prefilter_candle.pkl
39
+ python router/ai/scripts/train_candle_next_edge.py --templates router/ai/data/candle_shape_templates_all.json --graph D:/tranimal/gatv2-data/seoul_train.graphml --holdout-graph D:/tranimal/gatv2-data/holdout.graphml --output router/ai/data/models/gatv2_next_edge_candle.pt
40
+ ```
41
+
42
+ 워치의 세로 고정 코드와 기기 회전 설정은 변경하지 않았다. APK 빌드·설치는 수행하지 않았다.
main/app/route-search/page.tsx CHANGED
@@ -16,7 +16,7 @@ import { prepareCoursePreview } from "../_utils/coursePreview";
16
  type Point = [number, number];
17
 
18
  type ShapeDiscoveryCandidate = {
19
- label: "dog" | "symbol_star" | "t_shirt" | "heart";
20
  score: number;
21
  shape_similarity: number;
22
  available: boolean;
@@ -342,6 +342,32 @@ const SHAPE_OPTIONS: ShapeOption[] = [
342
  [0.0026, 0.0008], [0, 0.0032],
343
  ],
344
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  ];
346
 
347
  const normalizeLocationText = (value: string): string =>
@@ -961,7 +987,7 @@ function RouteSearchPageContent() {
961
  {discoveryError && <p role="alert" className="mt-3 text-sm text-red-600">{discoveryError}</p>}
962
  {discoveryCandidates.length > 0 && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4">
963
  {discoveryCandidates.map((candidate) => {
964
- const label = candidate.label === "dog" ? "강아지" : candidate.label === "symbol_star" ? "별" : candidate.label === "heart" ? "하트" : "티셔츠";
965
  return <button key={candidate.label} type="button"
966
  disabled={!candidate.available}
967
  onClick={() => setPreviewDiscoveryLabel(candidate.label)}
@@ -975,7 +1001,7 @@ function RouteSearchPageContent() {
975
  className="mt-3 w-full rounded-full bg-[#1E40AF] px-4 py-3 text-sm font-bold text-white"
976
  onClick={() => router.push(prepareCoursePreview({
977
  id: `discovered-${previewDiscovery.label}-${Date.now()}`,
978
- title: `${previewDiscovery.label === "dog" ? "강아지" : previewDiscovery.label === "symbol_star" ? "별" : previewDiscovery.label === "heart" ? "하트" : "티셔츠"} 모양 코스`,
979
  place, distanceKm: previewDiscovery.distance_km,
980
  center: discoveryPoint, route: previewDiscovery.route_coords,
981
  label: previewDiscovery.label, source: "지도 지점 모양 탐색",
 
16
  type Point = [number, number];
17
 
18
  type ShapeDiscoveryCandidate = {
19
+ label: "dog" | "symbol_star" | "t_shirt" | "heart" | "candle";
20
  score: number;
21
  shape_similarity: number;
22
  available: boolean;
 
342
  [0.0026, 0.0008], [0, 0.0032],
343
  ],
344
  },
345
+ {
346
+ key: "candle",
347
+ label: "양초",
348
+ // Preview uses the replacement GPX outline.
349
+ offsets: [
350
+ [-0.0010086, 0.003],
351
+ [-0.0001982, 0.0027331],
352
+ [0.0005372, 0.0029495],
353
+ [0.0011009, 0.0025778],
354
+ [0.0012471, -0.0005602],
355
+ [0.0011069, -0.0010902],
356
+ [0.0005352, -0.0009694],
357
+ [0.0010037, -0.002089],
358
+ [0.0007631, -0.0028595],
359
+ [0.0003961, -0.003],
360
+ [-0.0006345, -0.0024712],
361
+ [-0.0004505, -0.0011899],
362
+ [-0.0011377, -0.0008173],
363
+ [-0.000947, -0.0005598],
364
+ [-0.0012904, 0.0007261],
365
+ [-0.0010058, 0.0018218],
366
+ [-0.0013705, 0.0019315],
367
+ [-0.0010604, 0.002844],
368
+ [-0.0010086, 0.003],
369
+ ],
370
+ },
371
  ];
372
 
373
  const normalizeLocationText = (value: string): string =>
 
987
  {discoveryError && <p role="alert" className="mt-3 text-sm text-red-600">{discoveryError}</p>}
988
  {discoveryCandidates.length > 0 && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4">
989
  {discoveryCandidates.map((candidate) => {
990
+ const label = candidate.label === "dog" ? "강아지" : candidate.label === "symbol_star" ? "별" : candidate.label === "heart" ? "하트" : candidate.label === "candle" ? "양초" : "티셔츠";
991
  return <button key={candidate.label} type="button"
992
  disabled={!candidate.available}
993
  onClick={() => setPreviewDiscoveryLabel(candidate.label)}
 
1001
  className="mt-3 w-full rounded-full bg-[#1E40AF] px-4 py-3 text-sm font-bold text-white"
1002
  onClick={() => router.push(prepareCoursePreview({
1003
  id: `discovered-${previewDiscovery.label}-${Date.now()}`,
1004
+ title: `${previewDiscovery.label === "dog" ? "강아지" : previewDiscovery.label === "symbol_star" ? "별" : previewDiscovery.label === "heart" ? "하트" : previewDiscovery.label === "candle" ? "양초" : "티셔츠"} 모양 코스`,
1005
  place, distanceKm: previewDiscovery.distance_km,
1006
  center: discoveryPoint, route: previewDiscovery.route_coords,
1007
  label: previewDiscovery.label, source: "지도 지점 모양 탐색",
router/ai/data/candle_shape_templates_all.json ADDED
The diff for this file is too large to render. See raw diff
 
router/ai/data/candle_shape_templates_all.manifest.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_filename": "candle_all_1000.gpx",
3
+ "source_sha256": "0aa8aeff6cd49b52e37fa18b56772502c57cd66a668c8a7b0b4d9e1a69ddc0ef",
4
+ "tracks": 1000,
5
+ "geometry_passed": 191,
6
+ "duplicates": 2,
7
+ "review_candidates": 809,
8
+ "active_outlines": 189,
9
+ "cities": {
10
+ "jeonju": 38,
11
+ "busan": 14,
12
+ "gwangju": 13,
13
+ "daejeon": 13,
14
+ "cheongju": 5,
15
+ "jeju": 17,
16
+ "incheon": 42,
17
+ "seoul": 46,
18
+ "suwon": 1
19
+ },
20
+ "qualification": "Source geometry_passed=true; not a field safety review",
21
+ "attribution": "OpenStreetMap contributors",
22
+ "license": "ODbL-1.0"
23
+ }
router/ai/data/models/gatv2_next_edge_candle.metrics.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "label": "candle",
3
+ "source": "candle_shape_templates_all.json",
4
+ "outlines": 189,
5
+ "transferred_outlines": 189,
6
+ "decisions": 3771,
7
+ "epochs": 4,
8
+ "train_graph_nodes": 1409,
9
+ "holdout_graph_nodes": 2615,
10
+ "comparison": {
11
+ "shortest_path": {
12
+ "routes": 21,
13
+ "successes": 21,
14
+ "road_valid": 21,
15
+ "mean_similarity": 0.9045604503066432,
16
+ "mean_retrace": 0.035020299122217324,
17
+ "mean_seconds": 0.18980952380956123
18
+ },
19
+ "gatv2": {
20
+ "routes": 21,
21
+ "successes": 21,
22
+ "road_valid": 21,
23
+ "mean_similarity": 0.8108879731785557,
24
+ "mean_retrace": 0.07750448914266762,
25
+ "mean_seconds": 0.23723809523809386
26
+ }
27
+ },
28
+ "evaluation_scope": "Held-out roads; outlines also used in training",
29
+ "training_kind": "Projected pseudo-expert paths, not original road matches"
30
+ }
router/ai/data/models/gatv2_next_edge_candle.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7f08502906e3dd1528a3ca867496573c485b71523ba7423c9d25f19e3572ca3
3
+ size 37181
router/ai/data/models/gpx_outline_prefilter_candle.metrics.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architecture": "GPXOutlinePrefilterHGB",
3
+ "feature_version": 3,
4
+ "outline_counts": {
5
+ "candle": 189
6
+ },
7
+ "training_points": 8,
8
+ "validation_points": 5,
9
+ "training_variants": 3024,
10
+ "comparison": [
11
+ {
12
+ "city": "seoul",
13
+ "point": [
14
+ 37.5,
15
+ 127.061
16
+ ],
17
+ "label": "candle",
18
+ "road_nodes": 1618,
19
+ "geometric12": {
20
+ "oracle": 0.99097,
21
+ "best": 0.99067,
22
+ "selected_outlines": 12
23
+ },
24
+ "geometric50": {
25
+ "oracle": 0.99097,
26
+ "best": 0.99067,
27
+ "selected_outlines": 50
28
+ },
29
+ "learned50_plus12": {
30
+ "oracle": 0.99097,
31
+ "best": 0.99088,
32
+ "selected_outlines": 62
33
+ }
34
+ },
35
+ {
36
+ "city": "seoul",
37
+ "point": [
38
+ 37.516,
39
+ 127.049
40
+ ],
41
+ "label": "candle",
42
+ "road_nodes": 3220,
43
+ "geometric12": {
44
+ "oracle": 0.99353,
45
+ "best": 0.99164,
46
+ "selected_outlines": 12
47
+ },
48
+ "geometric50": {
49
+ "oracle": 0.99353,
50
+ "best": 0.99353,
51
+ "selected_outlines": 50
52
+ },
53
+ "learned50_plus12": {
54
+ "oracle": 0.99353,
55
+ "best": 0.99246,
56
+ "selected_outlines": 62
57
+ }
58
+ },
59
+ {
60
+ "city": "seoul",
61
+ "point": [
62
+ 37.528,
63
+ 127.038
64
+ ],
65
+ "label": "candle",
66
+ "road_nodes": 2496,
67
+ "geometric12": {
68
+ "oracle": 0.99251,
69
+ "best": 0.98678,
70
+ "selected_outlines": 12
71
+ },
72
+ "geometric50": {
73
+ "oracle": 0.99251,
74
+ "best": 0.99239,
75
+ "selected_outlines": 50
76
+ },
77
+ "learned50_plus12": {
78
+ "oracle": 0.99251,
79
+ "best": 0.99251,
80
+ "selected_outlines": 62
81
+ }
82
+ },
83
+ {
84
+ "city": "busan",
85
+ "point": [
86
+ 35.17,
87
+ 129.066
88
+ ],
89
+ "label": "candle",
90
+ "road_nodes": 583,
91
+ "geometric12": {
92
+ "oracle": 0.97866,
93
+ "best": 0.94742,
94
+ "selected_outlines": 12
95
+ },
96
+ "geometric50": {
97
+ "oracle": 0.97866,
98
+ "best": 0.95999,
99
+ "selected_outlines": 50
100
+ },
101
+ "learned50_plus12": {
102
+ "oracle": 0.97866,
103
+ "best": 0.96819,
104
+ "selected_outlines": 62
105
+ }
106
+ },
107
+ {
108
+ "city": "busan",
109
+ "point": [
110
+ 35.178,
111
+ 129.078
112
+ ],
113
+ "label": "candle",
114
+ "road_nodes": 520,
115
+ "geometric12": {
116
+ "oracle": 0.98584,
117
+ "best": 0.98584,
118
+ "selected_outlines": 12
119
+ },
120
+ "geometric50": {
121
+ "oracle": 0.98584,
122
+ "best": 0.98584,
123
+ "selected_outlines": 50
124
+ },
125
+ "learned50_plus12": {
126
+ "oracle": 0.98584,
127
+ "best": 0.98584,
128
+ "selected_outlines": 62
129
+ }
130
+ }
131
+ ],
132
+ "elapsed_seconds": 21.7
133
+ }
router/ai/data/models/gpx_outline_prefilter_candle.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91283ab92bb0eac28fe883a4f594daa83c48fc8516f71c739915fa9f1e263684
3
+ size 597661
router/ai/scripts/build_candle_shape_templates.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replace candle outlines with qualified tracks from the supplied GPX bundle."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import xml.etree.ElementTree as ET
9
+ from collections import Counter
10
+ from pathlib import Path
11
+
12
+ from build_gpx_shape_templates import normalized_outline_from_track
13
+
14
+
15
+ def build(source: Path):
16
+ outlines, pending, seen = [], [], set()
17
+ counts, cities = Counter(), Counter()
18
+ for track in ET.parse(source).getroot().findall('{*}trk'):
19
+ counts['tracks'] += 1
20
+ fields = {node.tag.rsplit('}', 1)[-1]: node.text for node in track.iter()}
21
+ segments = track.findall('{*}trkseg')
22
+ if len(segments) != 1 or fields.get('type') != 'candle':
23
+ raise ValueError('Expected candle tracks with one continuous segment')
24
+ points = [(float(node.attrib['lat']), float(node.attrib['lon']))
25
+ for node in segments[0].findall('{*}trkpt')]
26
+ if any(not (math.isfinite(lat) and math.isfinite(lon) and
27
+ -90 <= lat <= 90 and -180 <= lon <= 180) for lat, lon in points):
28
+ raise ValueError('Invalid GPX coordinates')
29
+ outline = normalized_outline_from_track(points, fields.get('name', 'candle'))
30
+ if fields.get('geometry_passed') != 'true':
31
+ counts['review_candidates'] += 1
32
+ pending.append(outline)
33
+ continue
34
+ counts['geometry_passed'] += 1
35
+ signature = tuple(map(tuple, outline))
36
+ if signature in seen:
37
+ counts['duplicates'] += 1
38
+ continue
39
+ seen.add(signature)
40
+ outlines.append(outline)
41
+ cities[fields.get('city', 'unknown')] += 1
42
+ if not outlines:
43
+ raise ValueError('No qualified candle outlines')
44
+ report = {'source_filename': source.name,
45
+ 'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
46
+ **dict(counts), 'active_outlines': len(outlines), 'cities': dict(cities),
47
+ 'qualification': 'Source geometry_passed=true; not a field safety review',
48
+ 'attribution': 'OpenStreetMap contributors', 'license': 'ODbL-1.0'}
49
+ return {'candle': outlines}, {'candle': pending}, report
50
+
51
+
52
+ if __name__ == '__main__':
53
+ parser = argparse.ArgumentParser(description=__doc__)
54
+ parser.add_argument('source', type=Path)
55
+ parser.add_argument('output', type=Path)
56
+ parser.add_argument('--review-output', type=Path, required=True)
57
+ args = parser.parse_args()
58
+ active, pending, report = build(args.source)
59
+ for path, payload in ((args.output, active), (args.review_output, pending),
60
+ (args.output.with_suffix('.manifest.json'), report)):
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
63
+ print(json.dumps(report, ensure_ascii=False))
router/ai/scripts/clip_osm_region_test.py CHANGED
@@ -1,4 +1,4 @@
1
- from __future__ import annotations
2
 
3
  import argparse
4
  import json
@@ -109,11 +109,6 @@ LABEL_GUIDED_WAYPOINTS: dict[str, list[tuple[float, float]]] = {
109
  (-0.28, 0.22), (-0.36, 0.02), (-0.28, -0.04), (-0.02, -0.30),
110
  (0.02, -0.46), (0.18, -0.40),
111
  ],
112
- "candle": [
113
- (-0.18, 0.42), (0.18, 0.42), (0.18, -0.10), (0.04, -0.10),
114
- (0.02, -0.25), (0.12, -0.38), (0.00, -0.50), (-0.12, -0.38),
115
- (-0.02, -0.25), (-0.04, -0.10), (-0.18, -0.10), (-0.18, 0.42),
116
- ],
117
  "face": [
118
  (0.00, -0.42), (0.28, -0.30), (0.42, 0.00), (0.30, 0.30),
119
  (0.00, 0.42), (-0.30, 0.30), (-0.42, 0.00), (-0.28, -0.30),
@@ -146,14 +141,16 @@ LABEL_GUIDED_WAYPOINTS: dict[str, list[tuple[float, float]]] = {
146
  def _load_gpx_shape_templates() -> dict[str, list[list[tuple[float, float]]]]:
147
  """Load location-free GPX and independently road-checked outline examples."""
148
  data_dir = Path(__file__).resolve().parents[1] / "data"
149
- templates: dict[str, list[list[tuple[float, float]]]] = {"dog": [], "symbol_star": [], "t_shirt": [], "heart": []}
150
  seen: dict[str, set[tuple[tuple[float, float], ...]]] = {label: set() for label in templates}
151
- for filename in ("gpx_shape_templates.json", "approved_road_shape_templates.json", "tshirt_shape_templates.json", "tshirt_shape_templates_all.json", "star_shape_templates.json", "star_shape_templates_all.json", "dog_shape_templates_all.json", "multiregion_shape_templates_all.json", "heart_shape_templates_all.json"):
152
  try:
153
  payload = json.loads((data_dir / filename).read_text(encoding="utf-8"))
154
  except (OSError, ValueError, TypeError):
155
  continue
156
  for label in templates:
 
 
157
  for outline in payload.get(label, []):
158
  try:
159
  points = [(float(x), float(y)) for x, y in outline]
@@ -745,6 +742,8 @@ def guided_waypoints_for_label(label: str | None) -> list[tuple[float, float]]:
745
  return []
746
  if label in GPX_SHAPE_TEMPLATES and GPX_SHAPE_TEMPLATES[label]:
747
  return random.choice(GPX_SHAPE_TEMPLATES[label]).copy()
 
 
748
  return LABEL_GUIDED_WAYPOINTS.get(label, [])
749
 
750
 
@@ -860,7 +859,7 @@ def guided_geo_waypoints(
860
  scale_jitter = random.uniform(0.72, 1.18)
861
  scale_x_m = base_scale_m * scale_jitter * random.uniform(0.86, 1.18)
862
  scale_y_m = base_scale_m * scale_jitter * random.uniform(0.86, 1.18)
863
- if label == "candle":
864
  scale_x_m *= 0.72
865
  scale_y_m *= 1.18
866
  elif label in {"fish", "t_shirt"}:
@@ -1167,9 +1166,12 @@ def draw_template_mask(label: str, size: int = CANVAS_SIZE) -> np.ndarray:
1167
  cv2.line(m, (int(0.50 * s), int(0.43 * s)), (int(0.50 * s), int(0.32 * s)), 255, max(3, thick // 2))
1168
  cv2.ellipse(m, (int(0.57 * s), int(0.33 * s)), (int(0.06 * s), int(0.03 * s)), -22, 0, 360, 255, max(3, thick // 2))
1169
  elif label == "candle":
1170
- cv2.rectangle(m, (int(0.41 * s), int(0.42 * s)), (int(0.59 * s), int(0.80 * s)), 255, thick)
1171
- cv2.line(m, (int(0.50 * s), int(0.42 * s)), (int(0.50 * s), int(0.37 * s)), 255, max(3, thick // 2))
1172
- cv2.ellipse(m, (int(0.50 * s), int(0.32 * s)), (int(0.05 * s), int(0.08 * s)), 0, 0, 360, 255, max(3, thick // 2))
 
 
 
1173
  elif label == "dog":
1174
  body = np.array(
1175
  [
 
1
+ from __future__ import annotations
2
 
3
  import argparse
4
  import json
 
109
  (-0.28, 0.22), (-0.36, 0.02), (-0.28, -0.04), (-0.02, -0.30),
110
  (0.02, -0.46), (0.18, -0.40),
111
  ],
 
 
 
 
 
112
  "face": [
113
  (0.00, -0.42), (0.28, -0.30), (0.42, 0.00), (0.30, 0.30),
114
  (0.00, 0.42), (-0.30, 0.30), (-0.42, 0.00), (-0.28, -0.30),
 
141
  def _load_gpx_shape_templates() -> dict[str, list[list[tuple[float, float]]]]:
142
  """Load location-free GPX and independently road-checked outline examples."""
143
  data_dir = Path(__file__).resolve().parents[1] / "data"
144
+ templates: dict[str, list[list[tuple[float, float]]]] = {"dog": [], "symbol_star": [], "t_shirt": [], "heart": [], "candle": []}
145
  seen: dict[str, set[tuple[tuple[float, float], ...]]] = {label: set() for label in templates}
146
+ for filename in ("gpx_shape_templates.json", "approved_road_shape_templates.json", "tshirt_shape_templates.json", "tshirt_shape_templates_all.json", "star_shape_templates.json", "star_shape_templates_all.json", "dog_shape_templates_all.json", "multiregion_shape_templates_all.json", "heart_shape_templates_all.json", "candle_shape_templates_all.json"):
147
  try:
148
  payload = json.loads((data_dir / filename).read_text(encoding="utf-8"))
149
  except (OSError, ValueError, TypeError):
150
  continue
151
  for label in templates:
152
+ if label == "candle" and filename != "candle_shape_templates_all.json":
153
+ continue
154
  for outline in payload.get(label, []):
155
  try:
156
  points = [(float(x), float(y)) for x, y in outline]
 
742
  return []
743
  if label in GPX_SHAPE_TEMPLATES and GPX_SHAPE_TEMPLATES[label]:
744
  return random.choice(GPX_SHAPE_TEMPLATES[label]).copy()
745
+ if label == "candle":
746
+ raise ValueError("Replacement candle GPX templates are unavailable")
747
  return LABEL_GUIDED_WAYPOINTS.get(label, [])
748
 
749
 
 
859
  scale_jitter = random.uniform(0.72, 1.18)
860
  scale_x_m = base_scale_m * scale_jitter * random.uniform(0.86, 1.18)
861
  scale_y_m = base_scale_m * scale_jitter * random.uniform(0.86, 1.18)
862
+ if label == "candle" and not GPX_SHAPE_TEMPLATES.get("candle"):
863
  scale_x_m *= 0.72
864
  scale_y_m *= 1.18
865
  elif label in {"fish", "t_shirt"}:
 
1166
  cv2.line(m, (int(0.50 * s), int(0.43 * s)), (int(0.50 * s), int(0.32 * s)), 255, max(3, thick // 2))
1167
  cv2.ellipse(m, (int(0.57 * s), int(0.33 * s)), (int(0.06 * s), int(0.03 * s)), -22, 0, 360, 255, max(3, thick // 2))
1168
  elif label == "candle":
1169
+ outlines = GPX_SHAPE_TEMPLATES.get("candle")
1170
+ if not outlines:
1171
+ raise ValueError("Replacement candle GPX templates are unavailable")
1172
+ pts = np.array([[(x * .74 + .5) * s, (y * .74 + .5) * s]
1173
+ for x, y in outlines[0]], dtype=np.int32)
1174
+ cv2.polylines(m, [pts.reshape(-1, 1, 2)], isClosed=True, color=255, thickness=thick)
1175
  elif label == "dog":
1176
  body = np.array(
1177
  [
router/ai/scripts/train_candle_next_edge.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train a candle-only checkpoint without changing other shapes' policy."""
2
+ from __future__ import annotations
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ import torch
7
+ import osmnx as ox
8
+ from train_gpx_next_edge import evaluate, examples_from_path
9
+ from train_gpx_next_edge_full import strongest_walk_component, fast_transfer, train_batched
10
+
11
+
12
+ def main():
13
+ parser = argparse.ArgumentParser(description=__doc__)
14
+ parser.add_argument('--templates', type=Path, required=True)
15
+ parser.add_argument('--graph', type=Path, required=True)
16
+ parser.add_argument('--holdout-graph', type=Path, required=True)
17
+ parser.add_argument('--output', type=Path, required=True)
18
+ args = parser.parse_args()
19
+ outlines = json.loads(args.templates.read_text(encoding='utf-8'))['candle']
20
+ road = strongest_walk_component(ox.load_graphml(args.graph))
21
+ holdout = strongest_walk_component(ox.load_graphml(args.holdout_graph))
22
+ examples, used = [], 0
23
+ for index, outline in enumerate(outlines):
24
+ path = fast_transfer(road, outline, salt=42000 + index)
25
+ if path:
26
+ steps = examples_from_path(road, path, max_steps=20)
27
+ examples.extend(steps)
28
+ used += bool(steps)
29
+ if not examples:
30
+ raise ValueError('No road-choice training examples')
31
+ model = train_batched(examples, epochs=4, seed=42, batch_size=128)
32
+ comparison = evaluate(holdout, outlines[::max(1, len(outlines)//20)], model)
33
+ report = {'label': 'candle', 'source': args.templates.name,
34
+ 'outlines': len(outlines), 'transferred_outlines': used,
35
+ 'decisions': len(examples), 'epochs': 4,
36
+ 'train_graph_nodes': len(road.ids), 'holdout_graph_nodes': len(holdout.ids),
37
+ 'comparison': comparison,
38
+ 'evaluation_scope': 'Held-out roads; outlines also used in training',
39
+ 'training_kind': 'Projected pseudo-expert paths, not original road matches'}
40
+ args.output.parent.mkdir(parents=True, exist_ok=True)
41
+ torch.save({'architecture': 'NextEdgeGATv2', 'model': model.state_dict(), 'report': report}, args.output)
42
+ args.output.with_suffix('.metrics.json').write_text(json.dumps(report, indent=2)+'\n', encoding='utf-8')
43
+ print(json.dumps(report, indent=2))
44
+
45
+
46
+ if __name__ == '__main__':
47
+ main()
router/ai/scripts/train_gpx_outline_prefilter.py CHANGED
@@ -30,17 +30,19 @@ SEOUL_EVAL = ((37.500, 127.061), (37.516, 127.049), (37.528, 127.038))
30
  BUSAN_EVAL = ((35.170, 129.066), (35.178, 129.078))
31
 
32
 
33
- def load_templates(directory):
34
- result = {label: [] for label in LABELS}
35
- seen = {label: set() for label in LABELS}
36
  filenames = ("gpx_shape_templates.json", "approved_road_shape_templates.json",
37
  "tshirt_shape_templates.json", "tshirt_shape_templates_all.json",
38
  "star_shape_templates.json", "star_shape_templates_all.json",
39
  "dog_shape_templates_all.json", "multiregion_shape_templates_all.json",
40
- "heart_shape_templates_all.json")
41
  for name in filenames:
42
  payload = json.loads((directory / name).read_text(encoding="utf-8"))
43
- for label in LABELS:
 
 
44
  for outline in payload.get(label, []):
45
  signature = tuple(tuple(point) for point in outline)
46
  if 5 <= len(outline) <= 25 and signature not in seen[label]:
@@ -66,7 +68,7 @@ def gather(graph, latitude, longitude, templates, prepared):
66
  road = RoadGraph(crop(graph, latitude, longitude))
67
  start = int(road.nearest(road.project([(latitude, longitude)]))[0][0])
68
  rows = {}
69
- for label in LABELS:
70
  screened = screen_variants(road, start, templates[label], label)
71
  features, targets, sources, geometric = [], [], [], []
72
  for cheap_score, source, anchors, feature in screened:
@@ -120,12 +122,14 @@ def main():
120
  parser.add_argument("--seoul", type=Path, required=True)
121
  parser.add_argument("--busan", type=Path, required=True)
122
  parser.add_argument("--output", type=Path, required=True)
 
123
  args = parser.parse_args()
124
  sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "api" / "ai-service" / "app" / "services"))
125
  from gpx_shape_similarity import prepare_gpx_shape_templates
126
- templates = load_templates(Path(__file__).resolve().parents[1] / "data")
 
127
  prepared = {label: [prepare_gpx_shape_templates([outline]) for outline in templates[label]]
128
- for label in LABELS}
129
  graphs = {"seoul": ox.load_graphml(args.seoul), "busan": ox.load_graphml(args.busan)}
130
  samples = []
131
  started = time.monotonic()
@@ -156,7 +160,7 @@ def main():
156
  "road_nodes": nodes, "geometric12": baseline,
157
  "geometric50": geometric50, "learned50_plus12": learned})
158
  report = {"architecture": "GPXOutlinePrefilterHGB", "feature_version": FEATURE_VERSION,
159
- "outline_counts": {label: len(templates[label]) for label in LABELS},
160
  "training_points": len(SEOUL_TRAIN), "validation_points": len(SEOUL_EVAL) + len(BUSAN_EVAL),
161
  "training_variants": len(y), "comparison": comparisons,
162
  "elapsed_seconds": round(time.monotonic() - started, 1)}
 
30
  BUSAN_EVAL = ((35.170, 129.066), (35.178, 129.078))
31
 
32
 
33
+ def load_templates(directory, labels=LABELS):
34
+ result = {label: [] for label in labels}
35
+ seen = {label: set() for label in labels}
36
  filenames = ("gpx_shape_templates.json", "approved_road_shape_templates.json",
37
  "tshirt_shape_templates.json", "tshirt_shape_templates_all.json",
38
  "star_shape_templates.json", "star_shape_templates_all.json",
39
  "dog_shape_templates_all.json", "multiregion_shape_templates_all.json",
40
+ "heart_shape_templates_all.json", "candle_shape_templates_all.json")
41
  for name in filenames:
42
  payload = json.loads((directory / name).read_text(encoding="utf-8"))
43
+ for label in result:
44
+ if label == "candle" and name != "candle_shape_templates_all.json":
45
+ continue
46
  for outline in payload.get(label, []):
47
  signature = tuple(tuple(point) for point in outline)
48
  if 5 <= len(outline) <= 25 and signature not in seen[label]:
 
68
  road = RoadGraph(crop(graph, latitude, longitude))
69
  start = int(road.nearest(road.project([(latitude, longitude)]))[0][0])
70
  rows = {}
71
+ for label in templates:
72
  screened = screen_variants(road, start, templates[label], label)
73
  features, targets, sources, geometric = [], [], [], []
74
  for cheap_score, source, anchors, feature in screened:
 
122
  parser.add_argument("--seoul", type=Path, required=True)
123
  parser.add_argument("--busan", type=Path, required=True)
124
  parser.add_argument("--output", type=Path, required=True)
125
+ parser.add_argument("--labels", default=",".join(LABELS))
126
  args = parser.parse_args()
127
  sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "api" / "ai-service" / "app" / "services"))
128
  from gpx_shape_similarity import prepare_gpx_shape_templates
129
+ labels = tuple(args.labels.split(","))
130
+ templates = load_templates(Path(__file__).resolve().parents[1] / "data", labels)
131
  prepared = {label: [prepare_gpx_shape_templates([outline]) for outline in templates[label]]
132
+ for label in labels}
133
  graphs = {"seoul": ox.load_graphml(args.seoul), "busan": ox.load_graphml(args.busan)}
134
  samples = []
135
  started = time.monotonic()
 
160
  "road_nodes": nodes, "geometric12": baseline,
161
  "geometric50": geometric50, "learned50_plus12": learned})
162
  report = {"architecture": "GPXOutlinePrefilterHGB", "feature_version": FEATURE_VERSION,
163
+ "outline_counts": {label: len(templates[label]) for label in labels},
164
  "training_points": len(SEOUL_TRAIN), "validation_points": len(SEOUL_EVAL) + len(BUSAN_EVAL),
165
  "training_variants": len(y), "comparison": comparisons,
166
  "elapsed_seconds": round(time.monotonic() - started, 1)}