tkadkghdlf commited on
Commit
b867b42
ยท
verified ยท
1 Parent(s): 980d4d2

Sync DemoService cfd82f578a19486e31051294ae112d064c0c0c42

Browse files
api/ai-service/app/api/v1/endpoints/route_generation.py CHANGED
@@ -18,7 +18,7 @@ from app.services.gpx_shape_similarity import (
18
  best_gpx_shape_alignment, best_gpx_shape_match, prepare_gpx_shape_templates, score_prepared_gpx_shape,
19
  )
20
  from app.services.walking_route_fallback import generate_walking_fallback
21
- from app.services.route_display_orientation import attach_card_display_orientations, attach_display_orientations, validate_card_outline
22
  from app.api.v1.endpoints.route_library import active_outlines
23
 
24
  router = APIRouter(prefix="/ai", tags=["ai"])
@@ -349,7 +349,6 @@ def _run_fast_road_pipeline(
349
  catalog_entry: tuple[str, list] | None = None,
350
  examples_override: list | None = None,
351
  minimum_similarity: float | None = None,
352
- require_card_outline: bool = False,
353
  ) -> dict[str, Any]:
354
  """Create real walkable-road routes without per-route CLIP inference.
355
 
@@ -398,20 +397,6 @@ def _run_fast_road_pipeline(
398
  if examples_override is not None:
399
  examples = examples_override
400
  candidate_pool = min(16 if examples else 8, max(route_count, route_count + (11 if examples else 1)))
401
- verified_candidates: dict[tuple[Any, ...], tuple[list, float, int | None, dict]] = {}
402
-
403
- def verify_candidate(candidate):
404
- signature = tuple(candidate["nodes"])
405
- if signature not in verified_candidates:
406
- coords = _route_nodes_to_coords(graph, candidate["nodes"])
407
- similarity, example_index = best_gpx_shape_match(coords, examples)
408
- card = {"selected_label": selected_label, "route_coords": coords,
409
- "route_quality": {"art_ready": True}}
410
- if example_index is not None and (minimum_similarity is None or similarity >= minimum_similarity):
411
- validate_card_outline(card)
412
- verified_candidates[signature] = (coords, similarity, example_index, card)
413
- return verified_candidates[signature][3].get("card_art_ready") is True
414
-
415
  if (shape_priority or catalog_entry or examples_override is not None) and examples:
416
  # Explore multiple physical sizes on the same road graph. The UI did
417
  # not request a distance; these are search scales, not length targets.
@@ -428,8 +413,6 @@ def _run_fast_road_pipeline(
428
  selected_scales = [(distance, None) for distance in (search_distances_km if shape_priority else (target_distance_km,))]
429
  for search_distance_km, screened_templates in selected_scales:
430
  template_kwargs = {}
431
- if require_card_outline:
432
- template_kwargs["candidate_filter"] = verify_candidate
433
  if examples_override is not None:
434
  template_kwargs["template_examples"] = examples
435
  elif screened_templates is not None:
@@ -493,18 +476,11 @@ def _run_fast_road_pipeline(
493
  seen_nodes.add(node_signature)
494
  # Simplified OSM edges can bend between intersections. Preserve those
495
  # bends rather than drawing straight lines across blocks or water.
496
- card_fields = {}
497
- if require_card_outline:
498
- if not verify_candidate(route):
499
- continue
500
- coords, similarity, example_index, card = verified_candidates[node_signature]
501
- card_fields = {key: value for key, value in card.items() if key.startswith("card_")}
502
- else:
503
- coords = _route_nodes_to_coords(graph, route["nodes"])
504
- similarity, example_index = best_gpx_shape_match(coords, examples) if examples else (0.0, None)
505
  if len(coords) < 2:
506
  continue
507
  shape_quality = float(route.get("shape_quality", 0.0))
 
508
  if minimum_similarity is not None and (example_index is None or similarity < minimum_similarity):
509
  continue
510
  rotation = None
@@ -515,7 +491,6 @@ def _run_fast_road_pipeline(
515
  routes.append(
516
  {
517
  "image_path": "",
518
- **card_fields,
519
  "top1": route_label,
520
  "top1_score": shape_quality,
521
  "top1_rerank_score": shape_quality,
@@ -585,7 +560,7 @@ def _run_fast_road_pipeline(
585
  return {
586
  "place": location_name,
587
  "source": "point" if center_lat is not None and center_lon is not None else "place",
588
- "candidate_count": len(verified_candidates) if require_card_outline else len(candidates),
589
  "requested_count": route_count,
590
  "generated_count": len(routes),
591
  "generation_timings_ms": generation_timings_ms,
@@ -934,7 +909,6 @@ def _generate_automatic_shapes(module, payload, labels, catalog, radius_km, rout
934
  graph_override=(graph, location), search_distances_km=(distance,),
935
  catalog_entry=catalog.get(label), examples_override=examples,
936
  minimum_similarity=AUTO_MIN_SHAPE_SIMILARITY,
937
- require_card_outline=True,
938
  )
939
  elapsed_ms = round((time.perf_counter() - phase_started) * 1000)
940
  candidate_ms += elapsed_ms
 
18
  best_gpx_shape_alignment, best_gpx_shape_match, prepare_gpx_shape_templates, score_prepared_gpx_shape,
19
  )
20
  from app.services.walking_route_fallback import generate_walking_fallback
21
+ from app.services.route_display_orientation import attach_card_display_orientations, attach_display_orientations
22
  from app.api.v1.endpoints.route_library import active_outlines
23
 
24
  router = APIRouter(prefix="/ai", tags=["ai"])
 
349
  catalog_entry: tuple[str, list] | None = None,
350
  examples_override: list | None = None,
351
  minimum_similarity: float | None = None,
 
352
  ) -> dict[str, Any]:
353
  """Create real walkable-road routes without per-route CLIP inference.
354
 
 
397
  if examples_override is not None:
398
  examples = examples_override
399
  candidate_pool = min(16 if examples else 8, max(route_count, route_count + (11 if examples else 1)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  if (shape_priority or catalog_entry or examples_override is not None) and examples:
401
  # Explore multiple physical sizes on the same road graph. The UI did
402
  # not request a distance; these are search scales, not length targets.
 
413
  selected_scales = [(distance, None) for distance in (search_distances_km if shape_priority else (target_distance_km,))]
414
  for search_distance_km, screened_templates in selected_scales:
415
  template_kwargs = {}
 
 
416
  if examples_override is not None:
417
  template_kwargs["template_examples"] = examples
418
  elif screened_templates is not None:
 
476
  seen_nodes.add(node_signature)
477
  # Simplified OSM edges can bend between intersections. Preserve those
478
  # bends rather than drawing straight lines across blocks or water.
479
+ coords = _route_nodes_to_coords(graph, route["nodes"])
 
 
 
 
 
 
 
 
480
  if len(coords) < 2:
481
  continue
482
  shape_quality = float(route.get("shape_quality", 0.0))
483
+ similarity, example_index = best_gpx_shape_match(coords, examples) if examples else (0.0, None)
484
  if minimum_similarity is not None and (example_index is None or similarity < minimum_similarity):
485
  continue
486
  rotation = None
 
491
  routes.append(
492
  {
493
  "image_path": "",
 
494
  "top1": route_label,
495
  "top1_score": shape_quality,
496
  "top1_rerank_score": shape_quality,
 
560
  return {
561
  "place": location_name,
562
  "source": "point" if center_lat is not None and center_lon is not None else "place",
563
+ "candidate_count": len(candidates),
564
  "requested_count": route_count,
565
  "generated_count": len(routes),
566
  "generation_timings_ms": generation_timings_ms,
 
909
  graph_override=(graph, location), search_distances_km=(distance,),
910
  catalog_entry=catalog.get(label), examples_override=examples,
911
  minimum_similarity=AUTO_MIN_SHAPE_SIMILARITY,
 
912
  )
913
  elapsed_ms = round((time.perf_counter() - phase_started) * 1000)
914
  candidate_ms += elapsed_ms
api/ai-service/app/services/route_display_orientation.py CHANGED
@@ -1,9 +1,7 @@
1
- """Validate card outlines and restore their axes without modifying GPS coordinates."""
2
  import math
3
 
4
  from app.services.gpx_shape_similarity import best_gpx_shape_alignment
5
- from app.services.shape_outline_quality import check_outline_features
6
- from app.services.tshirt_outline_quality import T_SHIRT, check_tshirt_features
7
 
8
 
9
  # x east/right, y south/down. These are display references only, not
@@ -22,7 +20,8 @@ _CARD_REFERENCES = {
22
  "symbol_star": [[(math.sin(i * math.pi / 5) * (1 if i % 2 == 0 else .42),
23
  -math.cos(i * math.pi / 5) * (1 if i % 2 == 0 else .42))
24
  for i in range(11)]],
25
- "t_shirt": [T_SHIRT],
 
26
  "dog": [_DOG, _mirrored(_DOG)],
27
  "candle": [[(-.24,.50),(.24,.50),(.24,-.13),(.04,-.13),(.17,-.30),
28
  (.02,-.56),(-.13,-.30),(-.04,-.13),(-.24,-.13)]],
@@ -35,53 +34,26 @@ _CARD_REFERENCES = {
35
  }
36
 
37
 
38
- def validate_card_outline(route):
39
- label = route.get("selected_label") or route.get("top1")
40
- references = _CARD_REFERENCES.get(label)
41
- quality = route.get("route_quality") or {}
42
- route["card_art_ready"] = False
43
- route["card_display_rotation_deg"] = None
44
- route.pop("card_shape_similarity", None)
45
- route.pop("card_shape_features", None)
46
- if not references or not route.get("route_coords") or route.get("estimated_route"):
47
- return False
48
- if quality.get("art_ready") is not True:
49
- return False
50
- score, reference_index, _ = best_gpx_shape_alignment(route["route_coords"], references)
51
- route["card_shape_similarity"] = score
52
- if label == "t_shirt":
53
- features, rotation = check_tshirt_features(route["route_coords"])
54
- else:
55
- features, rotation = check_outline_features(label, route["route_coords"], references, reference_index)
56
- route["card_shape_features"] = features
57
- if not features or not all(features.values()):
58
- return False
59
- if rotation is not None and score >= .85:
60
- if label == "symbol_star":
61
- rotation = (rotation + 36) % 72 - 36
62
- route["card_art_ready"] = True
63
- route["card_display_rotation_deg"] = rotation
64
- return route["card_art_ready"]
65
-
66
-
67
  def attach_card_display_orientations(result):
68
  for route in result.get("routes", []):
69
- if "card_art_ready" not in route:
70
- validate_card_outline(route)
71
- if result.get("generation_mode") == "automatic_art_shapes":
72
- qualified = [route for route in result.get("routes", []) if route.get("card_art_ready") is True]
73
- result["routes"] = qualified
74
- result["generated_count"] = len(qualified)
75
- result["best_route"] = qualified[0] if qualified else None
76
- result["labels"] = list(dict.fromkeys(route["selected_label"] for route in qualified if route.get("selected_label")))
77
- if not qualified:
78
- result["fallback_notice"] = "์ด ์œ„์น˜์—์„œ๋Š” ๊ธฐ์ค€ ๋„์•ˆ๊ณผ ์ถฉ๋ถ„ํžˆ ๋‹ฎ์€ ๊ฒฝ๋กœ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ์ถœ๋ฐœ์ ์ด๋‚˜ ํƒ์ƒ‰ ๋ฒ”์œ„๋ฅผ ๋ฐ”๊ฟ” ๋ณด์„ธ์š”."
 
 
 
79
  best = result.get("best_route")
80
  first = next(iter(result.get("routes", [])), None)
81
  if isinstance(best, dict) and first and best is not first and best.get("route_coords") == first.get("route_coords"):
82
- for key in ("card_art_ready", "card_shape_similarity", "card_display_rotation_deg", "card_shape_features"):
83
- if key in first:
84
- best[key] = first[key]
85
  return result
86
 
87
 
 
1
+ """Presentation-only orientation; never modify coordinates or quality decisions."""
2
  import math
3
 
4
  from app.services.gpx_shape_similarity import best_gpx_shape_alignment
 
 
5
 
6
 
7
  # x east/right, y south/down. These are display references only, not
 
20
  "symbol_star": [[(math.sin(i * math.pi / 5) * (1 if i % 2 == 0 else .42),
21
  -math.cos(i * math.pi / 5) * (1 if i % 2 == 0 else .42))
22
  for i in range(11)]],
23
+ "t_shirt": [[(-.6,-.3),(-.25,-.5),(-.12,-.38),(.12,-.38),(.25,-.5),(.6,-.3),
24
+ (.45,-.05),(.3,-.14),(.3,.5),(-.3,.5),(-.3,-.14),(-.45,-.05)]],
25
  "dog": [_DOG, _mirrored(_DOG)],
26
  "candle": [[(-.24,.50),(.24,.50),(.24,-.13),(.04,-.13),(.17,-.30),
27
  (.02,-.56),(-.13,-.30),(-.04,-.13),(-.24,-.13)]],
 
34
  }
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def attach_card_display_orientations(result):
38
  for route in result.get("routes", []):
39
+ coords = route.get("route_coords")
40
+ label = route.get("selected_label") or route.get("top1")
41
+ references = _CARD_REFERENCES.get(label)
42
+ if not coords or not references or route.get("estimated_route"):
43
+ continue
44
+ if (route.get("route_quality") or {}).get("art_ready") is not True:
45
+ continue
46
+ score, _, rotation = best_gpx_shape_alignment(coords, references)
47
+ # A weak match does not justify an invented upright orientation.
48
+ if rotation is not None and score >= .85:
49
+ if label == "symbol_star":
50
+ rotation = (rotation + 36) % 72 - 36
51
+ route["card_display_rotation_deg"] = rotation
52
  best = result.get("best_route")
53
  first = next(iter(result.get("routes", [])), None)
54
  if isinstance(best, dict) and first and best is not first and best.get("route_coords") == first.get("route_coords"):
55
+ if "card_display_rotation_deg" in first:
56
+ best["card_display_rotation_deg"] = first["card_display_rotation_deg"]
 
57
  return result
58
 
59
 
api/ai-service/app/services/shape_outline_quality.py DELETED
@@ -1,74 +0,0 @@
1
- """Validate local landmarks after a single rotation/scale alignment."""
2
- import math
3
- from functools import lru_cache
4
-
5
- import numpy as np
6
-
7
- from app.services.gpx_shape_similarity import _sample_outline
8
-
9
- _COUNT = 96
10
- _SHIFTS = (np.arange(_COUNT)[:, None] + np.arange(_COUNT)) % _COUNT
11
-
12
- # Each triple is the start, landmark and end of an arc in the canonical outline.
13
- # Repeated triples in a group must all pass (e.g. all five star tips).
14
- LANDMARKS = {
15
- "heart": {"heart_notch": ((69, 0, 11),), "heart_lobes": ((0, 19, 30), (50, 61, 0)),
16
- "heart_tip": ((30, 40, 50),)},
17
- "symbol_star": {
18
- "star_tips": tuple(((i - 1) % 10, i, (i + 1) % 10) for i in range(0, 10, 2)),
19
- "star_valleys": tuple((i - 1, i, (i + 1) % 10) for i in range(1, 10, 2)),
20
- },
21
- "dog": {"dog_head": ((1, 2, 4), (16, 0, 1)), "dog_tail": ((5, 6, 8),),
22
- "dog_legs": ((8, 9, 11), (12, 14, 15))},
23
- "candle": {"candle_flame": ((3, 5, 7),), "candle_body": ((8, 0, 1), (0, 1, 2))},
24
- "christmas_tree_trunk": {"tree_top": ((14, 0, 1),),
25
- "tree_branches": ((2, 3, 4), (4, 5, 6), (9, 10, 11), (11, 12, 13)),
26
- "tree_trunk": ((6, 7, 8), (7, 8, 9))},
27
- "long_pants": {"pants_waist": ((6, 0, 1), (0, 1, 2)),
28
- "pants_legs": ((1, 2, 3), (5, 6, 0)), "pants_crotch": ((3, 4, 5),)},
29
- }
30
- @lru_cache(maxsize=16)
31
- def _prepare(outline):
32
- closed = (*outline, outline[0])
33
- distances = np.concatenate(([0.], np.cumsum([math.dist(a, b) for a, b in zip(closed, closed[1:])])))
34
- vertices = np.rint(distances[:-1] / distances[-1] * _COUNT).astype(int) % _COUNT
35
- ref = np.asarray(_sample_outline(list(outline), _COUNT))
36
- return ref, vertices, max(np.ptp(ref.real), np.ptp(ref.imag))
37
-
38
-
39
- def check_outline_features(label, route_coords, references, reference_index):
40
- profile = LANDMARKS[label]
41
- failed = dict.fromkeys(profile, False)
42
- if reference_index is None or len(route_coords) < 4:
43
- return failed, None
44
- scale = math.cos(math.radians(sum(p[0] for p in route_coords) / len(route_coords)))
45
- sampled = _sample_outline([(lon * scale, -lat) for lat, lon in route_coords], _COUNT)
46
- if not sampled:
47
- return failed, None
48
- ref, vertices, size = _prepare(tuple(references[reference_index]))
49
- road = np.asarray(sampled)
50
- shifts = np.concatenate((road[_SHIFTS], road[::-1][_SHIFTS]))
51
- correlations = np.sum(shifts * ref.conjugate(), axis=1)
52
- index = int(np.argmax(np.abs(correlations)))
53
- if abs(correlations[index]) < 1e-12:
54
- return failed, None
55
- angle = -float(np.angle(correlations[index]))
56
- aligned = shifts[index] * np.exp(1j * angle)
57
- errors = np.abs(aligned - ref) / size
58
-
59
- def matches(triple):
60
- start, tip, end = (int(vertices[i]) for i in triple)
61
- offset, span = (tip - start) % _COUNT, (end - start) % _COUNT
62
- if not 0 < offset < span:
63
- return False
64
- fraction = offset / span
65
- expected = ref[tip] - (1 - fraction) * ref[start] - fraction * ref[end]
66
- actual = aligned[tip] - (1 - fraction) * aligned[start] - fraction * aligned[end]
67
- # Keep the protrusion/indentation on the expected side of the arc.
68
- prominence = (actual * expected.conjugate()).real
69
- arc = (start + np.arange(span + 1)) % _COUNT
70
- return bool(prominence >= .45 * abs(expected)**2 and
71
- np.quantile(errors[arc], .8) <= .13 and errors[tip] <= .15)
72
-
73
- return {key: all(matches(triple) for triple in triples)
74
- for key, triples in profile.items()}, math.degrees(angle)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/ai-service/app/services/tshirt_outline_quality.py DELETED
@@ -1,50 +0,0 @@
1
- """Check the collar and both sleeves after aligning to an upright shirt."""
2
- import math
3
-
4
- import numpy as np
5
-
6
- from app.services.gpx_shape_similarity import _sample_outline
7
-
8
- T_SHIRT = [(-.6, -.3), (-.25, -.5), (-.12, -.38), (.12, -.38),
9
- (.25, -.5), (.6, -.3), (.45, -.05), (.3, -.14), (.3, .5),
10
- (-.3, .5), (-.3, -.14), (-.45, -.05)]
11
- _COUNT = 96
12
- _CLOSED = [*T_SHIRT, T_SHIRT[0]]
13
- _PERIMETERS = np.concatenate(([0.0], np.cumsum([math.dist(a, b) for a, b in zip(_CLOSED, _CLOSED[1:])])))
14
- _REFERENCE = np.asarray(_sample_outline(T_SHIRT, _COUNT))
15
- _WIDTH = np.ptp(_REFERENCE.real)
16
- _VERTEX = np.rint(_PERIMETERS[:-1] / _PERIMETERS[-1] * _COUNT).astype(int) % _COUNT
17
- _SHIFTS = (np.arange(_COUNT)[:, None] + np.arange(_COUNT)) % _COUNT
18
- _FEATURES = ("neckline", "left_sleeve", "right_sleeve")
19
-
20
-
21
- def _arc(first, last):
22
- return np.arange(_VERTEX[first], _VERTEX[last] + 1 + (_COUNT if last < first else 0)) % _COUNT
23
-
24
-
25
- def check_tshirt_features(route_coords):
26
- if len(route_coords) < 4:
27
- return dict.fromkeys(_FEATURES, False), None
28
- scale = math.cos(math.radians(sum(p[0] for p in route_coords) / len(route_coords)))
29
- points = _sample_outline([(lon * scale, -lat) for lat, lon in route_coords], _COUNT)
30
- if not points:
31
- return dict.fromkeys(_FEATURES, False), None
32
- road = np.asarray(points)
33
- alignments = np.concatenate((road[_SHIFTS], road[::-1][_SHIFTS]))
34
- correlations = alignments @ _REFERENCE.conjugate()
35
- index = int(np.argmax(np.abs(correlations)))
36
- if abs(correlations[index]) < 1e-12:
37
- return dict.fromkeys(_FEATURES, False), None
38
- angle = -float(np.angle(correlations[index]))
39
- aligned = alignments[index] * np.exp(1j * angle)
40
- errors = np.abs(aligned - _REFERENCE) / _WIDTH
41
- p = aligned[_VERTEX]
42
- collar_depth = (min(p[2].imag, p[3].imag) - max(p[1].imag, p[4].imag)) / _WIDTH
43
- left_extension = (p[10].real - min(p[0].real, p[11].real)) / _WIDTH
44
- right_extension = (max(p[5].real, p[6].real) - p[7].real) / _WIDTH
45
- features = {
46
- "neckline": bool(collar_depth >= .045 and np.quantile(errors[_arc(1, 4)], .8) <= .085),
47
- "left_sleeve": bool(left_extension >= .13 and np.quantile(errors[_arc(10, 1)], .8) <= .11),
48
- "right_sleeve": bool(right_extension >= .13 and np.quantile(errors[_arc(4, 7)], .8) <= .11),
49
- }
50
- return features, math.degrees(angle)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/ai-service/tests/test_auto_art_catalog.py CHANGED
@@ -1,5 +1,4 @@
1
  import json
2
- import math
3
  from pathlib import Path
4
  import sys
5
  from types import SimpleNamespace
@@ -10,7 +9,6 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
 
11
  from app.api.v1.endpoints import route_generation as api
12
  from app.services.art_route_catalog import coordinate_outline, load_art_route_catalog
13
- from app.services.route_display_orientation import _CARD_REFERENCES
14
 
15
 
16
  TRACE = [[37, 127], [37.003, 127], [37.004, 127.002], [37.002, 127.004],
@@ -54,8 +52,6 @@ def test_automatic_catalog_routes_use_local_roads_and_minimum_score(monkeypatch,
54
  route_points=lambda *_: [], simplify_coords=lambda points: points)
55
  monkeypatch.setattr(api, "_route_nodes_to_coords", lambda *_: road)
56
  monkeypatch.setattr(api, "best_gpx_shape_match", lambda *_: (score, 0))
57
- # This test isolates the catalog matching threshold from the outline gate.
58
- monkeypatch.setattr(api, "validate_card_outline", lambda card: card.update(card_art_ready=True))
59
  request = api.RouteGenerateRequest(source="current", latitude=38, longitude=128, autoShape=True)
60
  result = api._generate_automatic_shapes(module, request, [], {"external": ("Imported", [outline])}, 2.5, 5)
61
  assert calls == [(None, 38, 128, 2.5)]
@@ -86,7 +82,6 @@ def test_auto_explores_other_labels_when_first_choices_fail(monkeypatch):
86
  attempts.append(label)
87
  assert kwargs["graph_override"] == (graph, "target")
88
  assert kwargs["minimum_similarity"] == .82
89
- assert kwargs["require_card_outline"] is True
90
  if label not in {"heart", "star"}:
91
  return {"candidate_count": 1, "routes": []}
92
  offset = labels.index(label)
@@ -102,30 +97,3 @@ def test_auto_explores_other_labels_when_first_choices_fail(monkeypatch):
102
  {"external": ("Imported", [outlines[-1]])}, 2.5, 2)
103
  assert attempts == ["dog", "external", "heart", "star"]
104
  assert [route["selected_label"] for route in result["routes"]] == ["star", "heart"]
105
-
106
-
107
- def test_automatic_outline_gate_runs_before_candidate_limit(monkeypatch):
108
- outline = _CARD_REFERENCES["symbol_star"][0]
109
- damaged = outline[:2] + outline[3:]
110
- to_gps = lambda points: [[37 - y * .001, 127 + x * .001 / math.cos(math.radians(37))]
111
- for x, y in points]
112
- traces = {1: to_gps(damaged), 2: to_gps(outline)}
113
- candidates = [{"nodes": [1, index], "length_m": 6000, "shape_quality": .95, "is_loop": True}
114
- for index in [1] * 6 + [2]]
115
-
116
- def generate(route_count, candidate_filter, **_):
117
- assert route_count == 6
118
- return [row for row in candidates if candidate_filter(row)][:route_count]
119
-
120
- module = SimpleNamespace(
121
- _build_or_get_walk_graph=lambda *_: (object(), "target"),
122
- generate_candidate_routes=generate, route_points=lambda *_: [], simplify_coords=lambda points: points,
123
- GPX_SHAPE_TEMPLATES={"symbol_star": [outline]},
124
- rank_road_template_projections=lambda _g, values, _d, limit: values[:limit],
125
- )
126
- monkeypatch.setattr(api, "_route_nodes_to_coords", lambda _, nodes: traces[nodes[-1]])
127
- request = api.RouteGenerateRequest(source="current", latitude=37, longitude=127, autoShape=True)
128
- result = api._generate_automatic_shapes(module, request, ["symbol_star"], {}, 3, 1)
129
- assert result["generated_count"] == 1
130
- assert result["best_route"]["route_coords"] == traces[2]
131
- assert result["best_route"]["card_art_ready"] is True
 
1
  import json
 
2
  from pathlib import Path
3
  import sys
4
  from types import SimpleNamespace
 
9
 
10
  from app.api.v1.endpoints import route_generation as api
11
  from app.services.art_route_catalog import coordinate_outline, load_art_route_catalog
 
12
 
13
 
14
  TRACE = [[37, 127], [37.003, 127], [37.004, 127.002], [37.002, 127.004],
 
52
  route_points=lambda *_: [], simplify_coords=lambda points: points)
53
  monkeypatch.setattr(api, "_route_nodes_to_coords", lambda *_: road)
54
  monkeypatch.setattr(api, "best_gpx_shape_match", lambda *_: (score, 0))
 
 
55
  request = api.RouteGenerateRequest(source="current", latitude=38, longitude=128, autoShape=True)
56
  result = api._generate_automatic_shapes(module, request, [], {"external": ("Imported", [outline])}, 2.5, 5)
57
  assert calls == [(None, 38, 128, 2.5)]
 
82
  attempts.append(label)
83
  assert kwargs["graph_override"] == (graph, "target")
84
  assert kwargs["minimum_similarity"] == .82
 
85
  if label not in {"heart", "star"}:
86
  return {"candidate_count": 1, "routes": []}
87
  offset = labels.index(label)
 
97
  {"external": ("Imported", [outlines[-1]])}, 2.5, 2)
98
  assert attempts == ["dog", "external", "heart", "star"]
99
  assert [route["selected_label"] for route in result["routes"]] == ["star", "heart"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/ai-service/tests/test_route_display_orientation.py CHANGED
@@ -8,7 +8,6 @@ import pytest
8
 
9
  sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
  from app.services.gpx_shape_similarity import best_gpx_shape_alignment, best_gpx_shape_match
11
- from app.services.tshirt_outline_quality import T_SHIRT
12
  from app.services.route_display_orientation import (
13
  _CARD_REFERENCES, attach_card_display_orientations, attach_display_orientations,
14
  )
@@ -88,9 +87,6 @@ def test_card_uses_upright_reference_without_changing_original_map(label, angle)
88
  result = {"routes": [route], "best_route": copy.deepcopy(route)}
89
  attach_card_display_orientations(result)
90
  rotation = route.pop("card_display_rotation_deg")
91
- assert route.pop("card_art_ready") is True
92
- assert route.pop("card_shape_similarity") > .99
93
- assert all(route.pop("card_shape_features").values())
94
  period = 72 if label == "symbol_star" else 360
95
  assert abs((rotation + angle + period/2) % period - period/2) < .05
96
  assert result["best_route"]["card_display_rotation_deg"] == rotation
@@ -103,86 +99,4 @@ def test_card_does_not_claim_canonical_orientation_for_non_art_or_unknown_shapes
103
  for label, ready, estimated in [("heart", False, False), ("heart", True, True), ("custom", True, False)]]
104
  original = copy.deepcopy(routes)
105
  attach_card_display_orientations({"routes": routes})
106
- for route in routes:
107
- assert route.pop("card_art_ready") is False
108
- assert route.pop("card_display_rotation_deg") is None
109
  assert routes == original
110
-
111
-
112
- @pytest.mark.parametrize("missing", [None, "neckline", "left_sleeve", "right_sleeve"])
113
- def test_tshirt_landmarks_gate_even_high_global_similarity(missing):
114
- outline = [(max(x, -.30) if missing == "left_sleeve" else min(x, .30) if missing == "right_sleeve" else x,
115
- -.50 if missing == "neckline" and i in (2, 3) else y)
116
- for i, (x, y) in enumerate(T_SHIRT)]
117
- coords = [[37.5 - x * .001, 127 - y * .001 / math.cos(math.radians(37.5))]
118
- for x, y in [*outline, outline[0]]]
119
- route = {"selected_label": "t_shirt", "route_coords": coords, "route_quality": {"art_ready": True}}
120
- attach_card_display_orientations({"routes": [route]})
121
- assert route["card_shape_similarity"] > .98
122
- if missing:
123
- assert route["card_shape_features"][missing] is False
124
- assert route["card_art_ready"] is False and route["card_display_rotation_deg"] is None
125
- else:
126
- assert all(route["card_shape_features"].values())
127
- assert route["card_art_ready"] is True
128
- assert route["card_display_rotation_deg"] == pytest.approx(-90, abs=.02)
129
-
130
-
131
- def _card(label, outline, angle=0, start=0, reverse=False):
132
- outline = list(outline)
133
- if math.dist(outline[0], outline[-1]) < 1e-8:
134
- outline.pop()
135
- outline = outline[start:] + outline[:start]
136
- if reverse:
137
- outline.reverse()
138
- c, s = math.cos(math.radians(angle)), math.sin(math.radians(angle))
139
- coords = [[37.5 - (x * s + y * c) / 111320,
140
- 127 + (x * c - y * s) / (111320 * math.cos(math.radians(37.5)))]
141
- for x, y in [*outline, outline[0]]]
142
- return {"selected_label": label, "route_coords": coords, "route_quality": {"art_ready": True}}
143
-
144
-
145
- @pytest.mark.parametrize("label", _CARD_REFERENCES)
146
- @pytest.mark.parametrize("angle,start,reverse", [(0, 0, False), (71, 2, True), (-137, 4, False)])
147
- def test_every_supported_shape_accepts_full_outline(label, angle, start, reverse):
148
- for outline in _CARD_REFERENCES[label]:
149
- route = _card(label, outline, angle, start, reverse)
150
- before = copy.deepcopy(route["route_coords"])
151
- attach_card_display_orientations({"routes": [route]})
152
- assert route["card_shape_features"] and all(route["card_shape_features"].values())
153
- assert route["card_art_ready"] is True
154
- assert route["route_coords"] == before
155
- period = 72 if label == "symbol_star" else 360
156
- assert abs((route["card_display_rotation_deg"] + angle + period / 2) % period - period / 2) < 4
157
-
158
-
159
- @pytest.mark.parametrize("label,feature,left,right", [
160
- ("heart", "heart_notch", 69, 11),
161
- ("symbol_star", "star_tips", 1, 3),
162
- ("dog", "dog_tail", 5, 8),
163
- ("candle", "candle_flame", 3, 7),
164
- ("christmas_tree_trunk", "tree_trunk", 6, 9),
165
- ("long_pants", "pants_crotch", 3, 5),
166
- ])
167
- def test_missing_landmark_rejects_otherwise_similar_shape(label, feature, left, right):
168
- outline = list(_CARD_REFERENCES[label][0])
169
- if math.dist(outline[0], outline[-1]) < 1e-8:
170
- outline.pop()
171
- damaged = outline[:left + 1] + outline[right:] if left < right else outline[right:left + 1]
172
- if label == "long_pants":
173
- # A shallow indentation still resembles pants globally, but has no distinct legs.
174
- damaged = [*outline[:4], (0, .30), *outline[5:]]
175
- route = _card(label, damaged)
176
- attach_card_display_orientations({"routes": [route]})
177
- assert route["card_shape_similarity"] > .85
178
- assert route["card_shape_features"][feature] is False
179
- assert route["card_art_ready"] is False and route["card_display_rotation_deg"] is None
180
-
181
-
182
- def test_external_without_upright_reference_is_not_verified_in_automatic_results():
183
- route = _card("external_shape", _CARD_REFERENCES["dog"][0])
184
- result = {"routes": [route], "generation_mode": "automatic_art_shapes"}
185
- attach_card_display_orientations(result)
186
- assert route["card_art_ready"] is False
187
- assert "card_shape_similarity" not in route
188
- assert result["routes"] == [] and result["best_route"] is None
 
8
 
9
  sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
  from app.services.gpx_shape_similarity import best_gpx_shape_alignment, best_gpx_shape_match
 
11
  from app.services.route_display_orientation import (
12
  _CARD_REFERENCES, attach_card_display_orientations, attach_display_orientations,
13
  )
 
87
  result = {"routes": [route], "best_route": copy.deepcopy(route)}
88
  attach_card_display_orientations(result)
89
  rotation = route.pop("card_display_rotation_deg")
 
 
 
90
  period = 72 if label == "symbol_star" else 360
91
  assert abs((rotation + angle + period/2) % period - period/2) < .05
92
  assert result["best_route"]["card_display_rotation_deg"] == rotation
 
99
  for label, ready, estimated in [("heart", False, False), ("heart", True, True), ("custom", True, False)]]
100
  original = copy.deepcopy(routes)
101
  attach_card_display_orientations({"routes": routes})
 
 
 
102
  assert routes == original
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main/app/_utils/generatedRouteDetails.ts CHANGED
@@ -10,9 +10,6 @@ export type RouteScore = {
10
  export type GeneratedRoute = {
11
  display_rotation_deg?: number | null;
12
  card_display_rotation_deg?: number | null;
13
- card_art_ready?: boolean;
14
- card_shape_similarity?: number;
15
- card_shape_features?: Record<string, boolean>;
16
  display_rotation_source?: string;
17
  image_path: string;
18
  top1: string;
@@ -112,7 +109,6 @@ const routeScoreValue = (row: RouteScore): number =>
112
  typeof row.rerank_score === "number" ? row.rerank_score : row.score;
113
 
114
  export const getPrimaryGeneratedRouteLabel = (route: GeneratedRoute): string => {
115
- // Shape validation controls the quality notice and rotation, not the category.
116
  if (route.selected_label) {
117
  return route.selected_label;
118
  }
@@ -125,11 +121,6 @@ export const getPrimaryGeneratedRouteLabel = (route: GeneratedRoute): string =>
125
  return top.label || route.top1;
126
  };
127
 
128
- export const getGeneratedRoutePreviewRotation = (route: GeneratedRoute): number | undefined =>
129
- route.card_display_rotation_deg === undefined
130
- ? route.display_rotation_deg ?? undefined
131
- : route.card_display_rotation_deg ?? undefined;
132
-
133
  export const getModelTopGeneratedRouteLabel = (route: GeneratedRoute): string => {
134
  if (!Array.isArray(route.results) || route.results.length === 0) {
135
  return route.top1;
 
10
  export type GeneratedRoute = {
11
  display_rotation_deg?: number | null;
12
  card_display_rotation_deg?: number | null;
 
 
 
13
  display_rotation_source?: string;
14
  image_path: string;
15
  top1: string;
 
109
  typeof row.rerank_score === "number" ? row.rerank_score : row.score;
110
 
111
  export const getPrimaryGeneratedRouteLabel = (route: GeneratedRoute): string => {
 
112
  if (route.selected_label) {
113
  return route.selected_label;
114
  }
 
121
  return top.label || route.top1;
122
  };
123
 
 
 
 
 
 
124
  export const getModelTopGeneratedRouteLabel = (route: GeneratedRoute): string => {
125
  if (!Array.isArray(route.results) || route.results.length === 0) {
126
  return route.top1;
main/app/route-results/[id]/page.tsx CHANGED
@@ -12,7 +12,6 @@ import {
12
  findGeneratedRouteDetail,
13
  formatGeneratedRouteLabel,
14
  getGeneratedRouteAiShapeScore,
15
- getGeneratedRoutePreviewRotation,
16
  type GeneratedRouteDetailRecord,
17
  } from "../../_utils/generatedRouteDetails";
18
  import {
@@ -387,7 +386,7 @@ function GeneratedRouteDetailPageContent() {
387
 
388
  <SectionCard className="rts-card-flush">
389
  <div className="h-[330px] w-full bg-[#f5f5f5] sm:h-[460px]">
390
- <LeafletMap center={center} route={routeCoords} displayRotationDeg={getGeneratedRoutePreviewRotation(record.route)} className="h-full w-full" zoom={14} />
391
  </div>
392
  </SectionCard>
393
 
 
12
  findGeneratedRouteDetail,
13
  formatGeneratedRouteLabel,
14
  getGeneratedRouteAiShapeScore,
 
15
  type GeneratedRouteDetailRecord,
16
  } from "../../_utils/generatedRouteDetails";
17
  import {
 
386
 
387
  <SectionCard className="rts-card-flush">
388
  <div className="h-[330px] w-full bg-[#f5f5f5] sm:h-[460px]">
389
+ <LeafletMap center={center} route={routeCoords} displayRotationDeg={record.route.display_rotation_deg} className="h-full w-full" zoom={14} />
390
  </div>
391
  </SectionCard>
392
 
main/app/route-results/page.tsx CHANGED
@@ -24,7 +24,7 @@ import {
24
  import {
25
  createGeneratedRouteDetailId,
26
  formatGeneratedRouteLabel,
27
- getGeneratedRoutePreviewRotation,
28
  getModelTopGeneratedRouteLabel,
29
  getPrimaryGeneratedRouteLabel,
30
  upsertGeneratedRouteDetail,
@@ -52,15 +52,6 @@ type GeneratedRoutesResponse = {
52
 
53
  const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";
54
  const AVAILABLE_LABELS = ["dog", "symbol_star", "t_shirt", "heart", "candle", "christmas_tree_trunk", "long_pants"];
55
- const SHAPE_FEATURE_LABELS: Record<string, string> = {
56
- neckline: "๋ชฉ", left_sleeve: "์™ผ์ชฝ ์†Œ๋งค", right_sleeve: "์˜ค๋ฅธ์ชฝ ์†Œ๋งค",
57
- dog_head: "๋จธ๋ฆฌ", dog_tail: "๊ผฌ๋ฆฌ", dog_legs: "๋‹ค๋ฆฌ",
58
- star_tips: "๋ณ„ ๊ผญ์ง“์ ", star_valleys: "๋ณ„ ์•ˆ์ชฝ ๊ณจ",
59
- heart_notch: "ํ•˜ํŠธ ์ค‘์•™ ํ™ˆ", heart_lobes: "ํ•˜ํŠธ ์–‘์ชฝ ๊ณก์„ ", heart_tip: "ํ•˜ํŠธ ์•„๋ž˜ ๋",
60
- candle_flame: "๋ถˆ๊ฝƒ", candle_body: "์ดˆ ๋ชธํ†ต",
61
- tree_top: "๋‚˜๋ฌด ๊ผญ๋Œ€๊ธฐ", tree_branches: "๊ฐ€์ง€", tree_trunk: "์ค„๊ธฐ",
62
- pants_waist: "ํ—ˆ๋ฆฌ", pants_legs: "์–‘์ชฝ ๋ฐ”์ง“๋‹จ", pants_crotch: "๊ฐ€๋ž‘์ด",
63
- };
64
  const ROUTE_GENERATION_ERROR_MESSAGE =
65
  "์ถ”์ฒœ ๊ฒฝ๋กœ๋ฅผ ๋งŒ๋“ค์ง€ ๋ชปํ–ˆ์–ด์š”. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์ฐพ๊ธฐ๋ฅผ ๋ˆŒ๋Ÿฌ ์ฃผ์„ธ์š”.";
66
  const ROUTE_ART_QUALITY_NOTICE =
@@ -109,6 +100,13 @@ function formatEstimatedTime(distanceKm: number): string {
109
  return rest > 0 ? `์•ฝ ${hours}์‹œ๊ฐ„ ${rest}๋ถ„` : `์•ฝ ${hours}์‹œ๊ฐ„`;
110
  }
111
 
 
 
 
 
 
 
 
112
  function getRouteTitle(routeNumber: number, routeLabel: string): string {
113
  if (routeLabel === "nearby_route") return `์ฃผ๋ณ€ ๋Ÿฌ๋‹ ์ฝ”์Šค ${routeNumber}`;
114
  return `${formatGeneratedRouteLabel(routeLabel)} ์ฝ”์Šค ${routeNumber}`;
@@ -136,7 +134,7 @@ function RouteResultsPageContent() {
136
  const searchParams = useSearchParams();
137
  const router = useRouter();
138
 
139
- const cacheKey = useMemo(() => `route-results:v7:${searchParams.toString()}`, [searchParams]);
140
  const initialPlace = searchParams.get("place") || "Gangnam-gu, Seoul, South Korea";
141
  const initialSource = (searchParams.get("source") as "place" | "current" | null) ?? "place";
142
  const initialLatitude = parseNumberParam(searchParams.get("latitude"));
@@ -346,7 +344,7 @@ function RouteResultsPageContent() {
346
  // and let the runner choose a safe nearby route or search again.
347
  if (typeof parsed.fallback_notice === "string" && parsed.fallback_notice.trim()) {
348
  setRouteQualityNotice(parsed.fallback_notice);
349
- } else if (selectedLabel && !runnableRoutes.some((route) => route.card_art_ready ?? route.route_quality?.art_ready === true)) {
350
  setRouteQualityNotice(ROUTE_ART_QUALITY_NOTICE);
351
  }
352
 
@@ -355,7 +353,7 @@ function RouteResultsPageContent() {
355
  // Store under the request's own key. A separate effect used to write
356
  // the previous result into the newly selected location's cache.
357
  try {
358
- if (runnableRoutes.length > 0 && !placeWasEdited && routeCount === (Number.isFinite(initialCount) ? initialCount : 8)
359
  && targetDistanceKm === (Number.isFinite(initialDistance) ? initialDistance : 5)) {
360
  window.sessionStorage.setItem(cacheKey, JSON.stringify(parsed));
361
  }
@@ -397,7 +395,7 @@ function RouteResultsPageContent() {
397
  const parsed = JSON.parse(cached) as GeneratedRoutesResponse;
398
  setResult(parsed);
399
  setRouteQualityNotice(parsed.fallback_notice ||
400
- (parsed.routes?.some((route) => route.card_art_ready ?? route.route_quality?.art_ready === true) ? null : ROUTE_ART_QUALITY_NOTICE));
401
  } catch {
402
  window.sessionStorage.removeItem(cacheKey);
403
  return scheduleFetch();
@@ -479,7 +477,7 @@ function RouteResultsPageContent() {
479
  label: routeLabel,
480
  center: route.center ?? route.route_coords[0] ?? null,
481
  routeCoords: route.route_coords,
482
- displayRotationDeg: getGeneratedRoutePreviewRotation(route),
483
  createdAt: new Date().toISOString(),
484
  };
485
  const next = upsertSavedRoute(record);
@@ -595,10 +593,7 @@ function RouteResultsPageContent() {
595
  const routeNumber = originalIndex + 1;
596
  const routeLabel = getPrimaryGeneratedRouteLabel(route);
597
  const hasRouteCoords = Boolean(route.route_coords && route.route_coords.length > 1);
598
- const score = typeof route.card_shape_similarity === "number"
599
- ? Math.round(route.card_shape_similarity * 100) : null;
600
- const missingFeatures = Object.entries(route.card_shape_features ?? {})
601
- .filter(([, passed]) => !passed).map(([key]) => SHAPE_FEATURE_LABELS[key] ?? key);
602
  const savedRouteId = createSavedRouteId(route, result.place);
603
  const isBookmarked = savedRouteIds.has(savedRouteId);
604
 
@@ -619,7 +614,7 @@ function RouteResultsPageContent() {
619
  <LeafletMap
620
  center={route.center ?? route.route_coords![0]}
621
  route={route.route_coords}
622
- displayRotationDeg={getGeneratedRoutePreviewRotation(route)}
623
  className="h-full w-full"
624
  zoom={14}
625
  interactive={false}
@@ -637,8 +632,7 @@ function RouteResultsPageContent() {
637
  <h2 className="text-xl font-bold text-black sm:text-2xl">
638
  {getRouteTitle(routeNumber, routeLabel)}
639
  </h2>
640
- <p className="mt-1 text-sm text-[#666]">{route.card_art_ready === false ? "๊ธฐ์ค€ ๋„์•ˆ ๋ฏธ์ถฉ์กฑ" : `${route.art_template_name || formatGeneratedRouteLabel(routeLabel)} ๋ชจ์–‘`}</p>
641
- {missingFeatures.length > 0 && <p className="mt-1 text-xs text-[#666]">๊ธฐ์ค€ ์œค๊ณฝ ๋ฏธ์ถฉ์กฑ: {missingFeatures.join(", ")}</p>}
642
  </div>
643
  <button
644
  type="button"
@@ -661,8 +655,10 @@ function RouteResultsPageContent() {
661
  <p className="rts-data-label">์˜ˆ์ƒ ์‹œ๊ฐ„</p>
662
  </div>
663
  <div className="rts-data-item">
664
- <span className="rts-data-value">{score === null ? "ํ™•์ธ ๋ถˆ๊ฐ€" : `${score}/100`}</span>
665
- <p className="rts-data-label">๊ธฐ์ค€ ์œค๊ณฝ ์œ ์‚ฌ๋„</p>
 
 
666
  </div>
667
  <div className="rts-data-item">
668
  <span className="rts-data-value">{environmentLabel(environment, environmentLoading)}</span>
 
24
  import {
25
  createGeneratedRouteDetailId,
26
  formatGeneratedRouteLabel,
27
+ getGeneratedRouteAiShapeScore,
28
  getModelTopGeneratedRouteLabel,
29
  getPrimaryGeneratedRouteLabel,
30
  upsertGeneratedRouteDetail,
 
52
 
53
  const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";
54
  const AVAILABLE_LABELS = ["dog", "symbol_star", "t_shirt", "heart", "candle", "christmas_tree_trunk", "long_pants"];
 
 
 
 
 
 
 
 
 
55
  const ROUTE_GENERATION_ERROR_MESSAGE =
56
  "์ถ”์ฒœ ๊ฒฝ๋กœ๋ฅผ ๋งŒ๋“ค์ง€ ๋ชปํ–ˆ์–ด์š”. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์ฐพ๊ธฐ๋ฅผ ๋ˆŒ๋Ÿฌ ์ฃผ์„ธ์š”.";
57
  const ROUTE_ART_QUALITY_NOTICE =
 
100
  return rest > 0 ? `์•ฝ ${hours}์‹œ๊ฐ„ ${rest}๋ถ„` : `์•ฝ ${hours}์‹œ๊ฐ„`;
101
  }
102
 
103
+ function getCompletionLabel(score: number | null): string {
104
+ if (score === null) return "ํ˜•ํƒœ ํ™•์ธ ํ•„์š”";
105
+ if (score >= 78) return "ํ˜•ํƒœ ์™„์„ฑ๋„ ๋†’์Œ";
106
+ if (score >= 58) return "๋ชจ์–‘์ด ๋น„๊ต์  ์„ ๋ช…ํ•œ ๊ฒฝ๋กœ";
107
+ return "์ผ๋ถ€ ๊ตฌ๊ฐ„์—์„œ ๋ชจ์–‘์ด ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ์Œ";
108
+ }
109
+
110
  function getRouteTitle(routeNumber: number, routeLabel: string): string {
111
  if (routeLabel === "nearby_route") return `์ฃผ๋ณ€ ๋Ÿฌ๋‹ ์ฝ”์Šค ${routeNumber}`;
112
  return `${formatGeneratedRouteLabel(routeLabel)} ์ฝ”์Šค ${routeNumber}`;
 
134
  const searchParams = useSearchParams();
135
  const router = useRouter();
136
 
137
+ const cacheKey = useMemo(() => `route-results:v8:${searchParams.toString()}`, [searchParams]);
138
  const initialPlace = searchParams.get("place") || "Gangnam-gu, Seoul, South Korea";
139
  const initialSource = (searchParams.get("source") as "place" | "current" | null) ?? "place";
140
  const initialLatitude = parseNumberParam(searchParams.get("latitude"));
 
344
  // and let the runner choose a safe nearby route or search again.
345
  if (typeof parsed.fallback_notice === "string" && parsed.fallback_notice.trim()) {
346
  setRouteQualityNotice(parsed.fallback_notice);
347
+ } else if (selectedLabel && !runnableRoutes.some((route) => route.route_quality?.art_ready === true)) {
348
  setRouteQualityNotice(ROUTE_ART_QUALITY_NOTICE);
349
  }
350
 
 
353
  // Store under the request's own key. A separate effect used to write
354
  // the previous result into the newly selected location's cache.
355
  try {
356
+ if (!placeWasEdited && routeCount === (Number.isFinite(initialCount) ? initialCount : 8)
357
  && targetDistanceKm === (Number.isFinite(initialDistance) ? initialDistance : 5)) {
358
  window.sessionStorage.setItem(cacheKey, JSON.stringify(parsed));
359
  }
 
395
  const parsed = JSON.parse(cached) as GeneratedRoutesResponse;
396
  setResult(parsed);
397
  setRouteQualityNotice(parsed.fallback_notice ||
398
+ (parsed.routes?.some((route) => route.route_quality?.art_ready === true) ? null : ROUTE_ART_QUALITY_NOTICE));
399
  } catch {
400
  window.sessionStorage.removeItem(cacheKey);
401
  return scheduleFetch();
 
477
  label: routeLabel,
478
  center: route.center ?? route.route_coords[0] ?? null,
479
  routeCoords: route.route_coords,
480
+ displayRotationDeg: route.display_rotation_deg ?? undefined,
481
  createdAt: new Date().toISOString(),
482
  };
483
  const next = upsertSavedRoute(record);
 
593
  const routeNumber = originalIndex + 1;
594
  const routeLabel = getPrimaryGeneratedRouteLabel(route);
595
  const hasRouteCoords = Boolean(route.route_coords && route.route_coords.length > 1);
596
+ const score = getGeneratedRouteAiShapeScore(route);
 
 
 
597
  const savedRouteId = createSavedRouteId(route, result.place);
598
  const isBookmarked = savedRouteIds.has(savedRouteId);
599
 
 
614
  <LeafletMap
615
  center={route.center ?? route.route_coords![0]}
616
  route={route.route_coords}
617
+ displayRotationDeg={route.card_display_rotation_deg ?? route.display_rotation_deg}
618
  className="h-full w-full"
619
  zoom={14}
620
  interactive={false}
 
632
  <h2 className="text-xl font-bold text-black sm:text-2xl">
633
  {getRouteTitle(routeNumber, routeLabel)}
634
  </h2>
635
+ <p className="mt-1 text-sm text-[#666]">{route.art_template_name || formatGeneratedRouteLabel(routeLabel)} ๋ชจ์–‘</p>
 
636
  </div>
637
  <button
638
  type="button"
 
655
  <p className="rts-data-label">์˜ˆ์ƒ ์‹œ๊ฐ„</p>
656
  </div>
657
  <div className="rts-data-item">
658
+ <span className="rts-data-value">{autoShape && typeof route.route_quality?.shape_similarity === "number"
659
+ ? `${(route.route_quality.shape_similarity * 100).toFixed(1)}์ `
660
+ : getCompletionLabel(score)}</span>
661
+ <p className="rts-data-label">{autoShape ? "๊ธฐ์ค€ ์œค๊ณฝ ์œ ์‚ฌ๋„" : "ํ˜•ํƒœ ์™„์„ฑ๋„"}</p>
662
  </div>
663
  <div className="rts-data-item">
664
  <span className="rts-data-value">{environmentLabel(environment, environmentLoading)}</span>
main/tests/generatedRouteCategory.cjs CHANGED
@@ -8,12 +8,11 @@ const { outputText } = ts.transpileModule(fs.readFileSync("app/_utils/generatedR
8
  });
9
  const context = { exports: {} };
10
  vm.runInNewContext(outputText, context);
11
- const { formatGeneratedRouteLabel, getPrimaryGeneratedRouteLabel, getGeneratedRoutePreviewRotation } = context.exports;
12
 
13
  const rejected = { selected_label: "dog", top1: "dog", card_art_ready: false,
14
  card_display_rotation_deg: null, display_rotation_deg: 42 };
15
  assert.equal(formatGeneratedRouteLabel(getPrimaryGeneratedRouteLabel(rejected)), "๊ฐ•์•„์ง€");
16
- assert.equal(getGeneratedRoutePreviewRotation(rejected), undefined);
17
  assert.equal(getPrimaryGeneratedRouteLabel({ top1: "heart", card_art_ready: true }), "heart");
18
  assert.equal(getPrimaryGeneratedRouteLabel({ top1: "dog", results: [{ label: "symbol_star", score: .99 }] }), "symbol_star");
19
  assert.equal(getPrimaryGeneratedRouteLabel({ top1: "nearby_route", card_art_ready: false }), "nearby_route");
 
8
  });
9
  const context = { exports: {} };
10
  vm.runInNewContext(outputText, context);
11
+ const { formatGeneratedRouteLabel, getPrimaryGeneratedRouteLabel } = context.exports;
12
 
13
  const rejected = { selected_label: "dog", top1: "dog", card_art_ready: false,
14
  card_display_rotation_deg: null, display_rotation_deg: 42 };
15
  assert.equal(formatGeneratedRouteLabel(getPrimaryGeneratedRouteLabel(rejected)), "๊ฐ•์•„์ง€");
 
16
  assert.equal(getPrimaryGeneratedRouteLabel({ top1: "heart", card_art_ready: true }), "heart");
17
  assert.equal(getPrimaryGeneratedRouteLabel({ top1: "dog", results: [{ label: "symbol_star", score: .99 }] }), "symbol_star");
18
  assert.equal(getPrimaryGeneratedRouteLabel({ top1: "nearby_route", card_art_ready: false }), "nearby_route");
router/ai/scripts/osm_route_runtime.py CHANGED
@@ -1060,7 +1060,6 @@ def generate_candidate_routes(
1060
  selected_label: str | None = None,
1061
  template_examples: list[list[tuple[float, float]]] | None = None,
1062
  template_similarity_fn: Callable[[list[tuple[float, float]], list[tuple[float, float]]], float] | None = None,
1063
- candidate_filter: Callable[[dict[str, Any]], bool] | None = None,
1064
  ) -> list[dict[str, Any]]:
1065
  nodes = list(graph.nodes)
1066
  if len(nodes) < 8:
@@ -1350,8 +1349,6 @@ def generate_candidate_routes(
1350
  -len(x["nodes"]),
1351
  )
1352
  )
1353
- if candidate_filter is not None:
1354
- accepted = [row for row in accepted if candidate_filter(row)]
1355
  if len(accepted) < route_count:
1356
  fallback.sort(
1357
  key=lambda x: (
@@ -1366,7 +1363,7 @@ def generate_candidate_routes(
1366
  for item in fallback:
1367
  if len(accepted) >= route_count:
1368
  break
1369
- if item not in accepted and (candidate_filter is None or candidate_filter(item)):
1370
  accepted.append(item)
1371
 
1372
  return accepted[:route_count]
 
1060
  selected_label: str | None = None,
1061
  template_examples: list[list[tuple[float, float]]] | None = None,
1062
  template_similarity_fn: Callable[[list[tuple[float, float]], list[tuple[float, float]]], float] | None = None,
 
1063
  ) -> list[dict[str, Any]]:
1064
  nodes = list(graph.nodes)
1065
  if len(nodes) < 8:
 
1349
  -len(x["nodes"]),
1350
  )
1351
  )
 
 
1352
  if len(accepted) < route_count:
1353
  fallback.sort(
1354
  key=lambda x: (
 
1363
  for item in fallback:
1364
  if len(accepted) >= route_count:
1365
  break
1366
+ if item not in accepted:
1367
  accepted.append(item)
1368
 
1369
  return accepted[:route_count]