Spaces:
Running
Running
Sync DemoService f6702fda819cde1392e8834b63b13e99f09d811a
Browse files- api/ai-service/app/api/v1/endpoints/route_generation.py +130 -12
- api/ai-service/app/services/art_route_catalog.py +85 -0
- api/ai-service/tests/test_auto_art_catalog.py +98 -0
- api/auth-service/app/api/v1/endpoints/active_run.py +33 -1
- api/auth-service/tests/test_active_run.py +19 -2
- deploy/huggingface/start-hf.sh +6 -0
- docs/LOCAL_ART_ROUTE_CATALOG.md +36 -0
- docs/running-environment.md +91 -0
- main/app/_components/NearbySampleRoutesCard.tsx +18 -11
- main/app/_utils/generatedRouteDetails.ts +2 -0
- main/app/_utils/regionalCrowd.ts +26 -0
- main/app/_utils/runningEnvironment.ts +63 -0
- main/app/_utils/useRunningEnvironment.ts +48 -0
- main/app/api/running-environment/route.ts +258 -0
- main/app/route-results/[id]/page.tsx +41 -0
- main/app/route-results/page.tsx +35 -18
- main/app/route-search/page.tsx +15 -5
- main/next.config.js +2 -0
- main/tests/runningEnvironment.cjs +14 -0
- main/tests/runningEnvironmentApi.cjs +68 -0
- tools/import_regional_crowd.py +179 -0
- tools/import_running_environment.py +195 -0
api/ai-service/app/api/v1/endpoints/route_generation.py
CHANGED
|
@@ -13,6 +13,7 @@ from fastapi import APIRouter, HTTPException, status
|
|
| 13 |
from pydantic import BaseModel, Field, field_validator
|
| 14 |
|
| 15 |
from app.core.config import settings
|
|
|
|
| 16 |
from app.services.gpx_shape_similarity import (
|
| 17 |
best_gpx_shape_alignment, best_gpx_shape_match, prepare_gpx_shape_templates, score_prepared_gpx_shape,
|
| 18 |
)
|
|
@@ -40,6 +41,7 @@ class RouteGenerateRequest(BaseModel):
|
|
| 40 |
shapePriority: bool = False
|
| 41 |
labels: list[str] | None = None
|
| 42 |
selectedLabel: str | None = None
|
|
|
|
| 43 |
experimentalCandidateRanker: bool = False
|
| 44 |
generationId: str | None = Field(default=None, max_length=200)
|
| 45 |
# The route-search page knows the centre of every selectable region. Keep
|
|
@@ -305,6 +307,9 @@ def _run_fast_road_pipeline(
|
|
| 305 |
experimental_candidate_ranker: bool = False,
|
| 306 |
graph_override: tuple[Any, str] | None = None,
|
| 307 |
search_distances_km: tuple[float, ...] = (6.0, 11.0, 18.0),
|
|
|
|
|
|
|
|
|
|
| 308 |
) -> dict[str, Any]:
|
| 309 |
"""Create real walkable-road routes without per-route CLIP inference.
|
| 310 |
|
|
@@ -336,24 +341,31 @@ def _run_fast_road_pipeline(
|
|
| 336 |
if shape_priority and not examples:
|
| 337 |
outline = getattr(module, "LABEL_GUIDED_WAYPOINTS", {}).get(selected_label, [])
|
| 338 |
examples = [outline] if outline else []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
candidate_pool = min(16 if examples else 8, max(route_count, route_count + (11 if examples else 1)))
|
| 340 |
-
if shape_priority and examples:
|
| 341 |
# Explore multiple physical sizes on the same road graph. The UI did
|
| 342 |
# not request a distance; these are search scales, not length targets.
|
| 343 |
candidates = []
|
| 344 |
rank_projections = getattr(module, "rank_road_template_projections", None)
|
| 345 |
adaptive_scales = getattr(module, "rank_road_search_scales", None)
|
| 346 |
selected_scales = None
|
| 347 |
-
if selected_label and callable(adaptive_scales):
|
| 348 |
selected_scales = adaptive_scales(graph, examples)
|
| 349 |
generation_timings_ms["scale_screening"] = round((time.perf_counter() - started_at) * 1000) - generation_timings_ms["road_graph"]
|
| 350 |
if not selected_scales:
|
| 351 |
-
selected_scales = [(distance, None) for distance in search_distances_km]
|
| 352 |
for search_distance_km, screened_templates in selected_scales:
|
| 353 |
template_kwargs = {}
|
| 354 |
-
if
|
|
|
|
|
|
|
| 355 |
template_kwargs["template_examples"] = screened_templates
|
| 356 |
-
elif selected_label in {"symbol_star", "dog", "heart", "candle", "christmas_tree_trunk", "long_pants"} and callable(rank_projections):
|
| 357 |
# Screen every supplied animal/shape outline against this road graph;
|
| 358 |
# only the best fits enter the expensive shortest-path stage.
|
| 359 |
template_kwargs["template_examples"] = rank_projections(
|
|
@@ -382,7 +394,7 @@ def _run_fast_road_pipeline(
|
|
| 382 |
# the response marks them as non-art-ready so the UI can state this
|
| 383 |
# honestly instead of showing a red generation failure.
|
| 384 |
generation_mode = "fast_walk_roads"
|
| 385 |
-
if not candidates and selected_label:
|
| 386 |
candidates = build_candidates(
|
| 387 |
graph=graph,
|
| 388 |
route_count=candidate_pool,
|
|
@@ -391,14 +403,14 @@ def _run_fast_road_pipeline(
|
|
| 391 |
tolerance_ratio=0.60,
|
| 392 |
)
|
| 393 |
generation_mode = "fast_walk_roads_nearby_fallback"
|
| 394 |
-
if not candidates:
|
| 395 |
# Rural/island road graphs may have no acceptable drawing or loop.
|
| 396 |
# A return trip along existing walking edges is still a real route.
|
| 397 |
candidates = _nearby_road_return_routes(
|
| 398 |
graph, route_count, target_distance_km * 1000.0, center_lat, center_lon
|
| 399 |
)
|
| 400 |
generation_mode = "fast_walk_roads_return_trip"
|
| 401 |
-
if not candidates:
|
| 402 |
raise RuntimeError("No walkable road routes were generated near this location.")
|
| 403 |
|
| 404 |
routes: list[dict[str, Any]] = []
|
|
@@ -415,6 +427,8 @@ def _run_fast_road_pipeline(
|
|
| 415 |
continue
|
| 416 |
shape_quality = float(route.get("shape_quality", 0.0))
|
| 417 |
similarity, example_index = best_gpx_shape_match(coords, examples) if examples else (0.0, None)
|
|
|
|
|
|
|
| 418 |
rotation = None
|
| 419 |
if generation_mode == "fast_walk_roads" and example_index is not None:
|
| 420 |
_, _, rotation = best_gpx_shape_alignment(coords, [examples[example_index]])
|
|
@@ -428,6 +442,9 @@ def _run_fast_road_pipeline(
|
|
| 428 |
"top1_rerank_score": shape_quality,
|
| 429 |
"top1_shape": shape_quality,
|
| 430 |
"selected_label": selected_label,
|
|
|
|
|
|
|
|
|
|
| 431 |
"selected_label_score": shape_quality if selected_label else None,
|
| 432 |
"selected_label_rerank_score": shape_quality if selected_label else None,
|
| 433 |
**({"display_rotation_deg": rotation, "display_rotation_source": "template_match"}
|
|
@@ -459,7 +476,7 @@ def _run_fast_road_pipeline(
|
|
| 459 |
-route["route_quality"]["shape_similarity"],
|
| 460 |
abs(route["length_km"] - target_distance_km) if not shape_priority else 0,
|
| 461 |
))
|
| 462 |
-
if experimental_candidate_ranker and selected_label in SHAPE_DISCOVERY_LABELS:
|
| 463 |
try:
|
| 464 |
script_dir = Path(settings.ai_workspace_dir) / "scripts"
|
| 465 |
if str(script_dir) not in sys.path:
|
|
@@ -478,7 +495,7 @@ def _run_fast_road_pipeline(
|
|
| 478 |
except Exception:
|
| 479 |
logger.exception("GPX candidate ranker unavailable; keeping geometric order")
|
| 480 |
routes = routes[:route_count]
|
| 481 |
-
if not routes:
|
| 482 |
raise RuntimeError("Walkable road routes did not contain usable map coordinates.")
|
| 483 |
|
| 484 |
generation_timings_ms["final_ranking"] = round((time.perf_counter() - started_at) * 1000) - sum(generation_timings_ms.values())
|
|
@@ -495,7 +512,7 @@ def _run_fast_road_pipeline(
|
|
| 495 |
"labels": [selected_label] if selected_label else [],
|
| 496 |
"selected_label": selected_label,
|
| 497 |
"selected_top_k": 0,
|
| 498 |
-
"best_route": routes[0],
|
| 499 |
"routes": routes,
|
| 500 |
"generation_mode": generation_mode,
|
| 501 |
"ranking_mode": ranking_mode,
|
|
@@ -748,6 +765,97 @@ def generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
|
|
| 748 |
return result
|
| 749 |
|
| 750 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 751 |
def _generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
|
| 752 |
workspace_dir = Path(settings.ai_workspace_dir)
|
| 753 |
script_path = workspace_dir / "scripts" / "osm_route_runtime.py"
|
|
@@ -774,12 +882,21 @@ def _generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
|
|
| 774 |
route_count_cap = 20 if use_current else 100
|
| 775 |
route_count = min(route_count_cap, max(1, payload.routeCount))
|
| 776 |
target_distance_km = max(0.5, payload.targetDistanceKm)
|
| 777 |
-
shape_priority = payload.shapePriority and selected_label is not None
|
| 778 |
# A 1.5 km graph is enough for ordinary short courses, but it cannot make
|
| 779 |
# a truthful 16~30 km route. Grow the road graph only as much as the
|
| 780 |
# requested distance needs, up to the request model's safe 10 km limit.
|
| 781 |
required_radius_km = target_distance_km / 5.5
|
| 782 |
radius_km = min(10.0, max(5.0 if shape_priority else 1.5, min(10.0, payload.radiusKm), required_radius_km))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 783 |
|
| 784 |
module = None
|
| 785 |
try:
|
|
@@ -795,6 +912,7 @@ def _generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
|
|
| 795 |
selected_label=selected_label,
|
| 796 |
shape_priority=shape_priority,
|
| 797 |
experimental_candidate_ranker=payload.experimentalCandidateRanker,
|
|
|
|
| 798 |
)
|
| 799 |
except Exception as primary_exc:
|
| 800 |
logger.exception("fast walk-road route generation failed")
|
|
|
|
| 13 |
from pydantic import BaseModel, Field, field_validator
|
| 14 |
|
| 15 |
from app.core.config import settings
|
| 16 |
+
from app.services.art_route_catalog import load_art_route_catalog
|
| 17 |
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 |
)
|
|
|
|
| 41 |
shapePriority: bool = False
|
| 42 |
labels: list[str] | None = None
|
| 43 |
selectedLabel: str | None = None
|
| 44 |
+
autoShape: bool = False
|
| 45 |
experimentalCandidateRanker: bool = False
|
| 46 |
generationId: str | None = Field(default=None, max_length=200)
|
| 47 |
# The route-search page knows the centre of every selectable region. Keep
|
|
|
|
| 307 |
experimental_candidate_ranker: bool = False,
|
| 308 |
graph_override: tuple[Any, str] | None = None,
|
| 309 |
search_distances_km: tuple[float, ...] = (6.0, 11.0, 18.0),
|
| 310 |
+
catalog_entry: tuple[str, list] | None = None,
|
| 311 |
+
examples_override: list | None = None,
|
| 312 |
+
minimum_similarity: float | None = None,
|
| 313 |
) -> dict[str, Any]:
|
| 314 |
"""Create real walkable-road routes without per-route CLIP inference.
|
| 315 |
|
|
|
|
| 341 |
if shape_priority and not examples:
|
| 342 |
outline = getattr(module, "LABEL_GUIDED_WAYPOINTS", {}).get(selected_label, [])
|
| 343 |
examples = [outline] if outline else []
|
| 344 |
+
if catalog_entry:
|
| 345 |
+
examples = [*examples, *catalog_entry[1]]
|
| 346 |
+
catalog_outline_ids = {id(outline) for outline in catalog_entry[1]} if catalog_entry else set()
|
| 347 |
+
if examples_override is not None:
|
| 348 |
+
examples = examples_override
|
| 349 |
candidate_pool = min(16 if examples else 8, max(route_count, route_count + (11 if examples else 1)))
|
| 350 |
+
if (shape_priority or catalog_entry or examples_override is not None) and examples:
|
| 351 |
# Explore multiple physical sizes on the same road graph. The UI did
|
| 352 |
# not request a distance; these are search scales, not length targets.
|
| 353 |
candidates = []
|
| 354 |
rank_projections = getattr(module, "rank_road_template_projections", None)
|
| 355 |
adaptive_scales = getattr(module, "rank_road_search_scales", None)
|
| 356 |
selected_scales = None
|
| 357 |
+
if shape_priority and examples_override is None and selected_label and callable(adaptive_scales):
|
| 358 |
selected_scales = adaptive_scales(graph, examples)
|
| 359 |
generation_timings_ms["scale_screening"] = round((time.perf_counter() - started_at) * 1000) - generation_timings_ms["road_graph"]
|
| 360 |
if not selected_scales:
|
| 361 |
+
selected_scales = [(distance, None) for distance in (search_distances_km if shape_priority else (target_distance_km,))]
|
| 362 |
for search_distance_km, screened_templates in selected_scales:
|
| 363 |
template_kwargs = {}
|
| 364 |
+
if examples_override is not None:
|
| 365 |
+
template_kwargs["template_examples"] = examples
|
| 366 |
+
elif screened_templates is not None:
|
| 367 |
template_kwargs["template_examples"] = screened_templates
|
| 368 |
+
elif (catalog_entry or selected_label in {"symbol_star", "dog", "heart", "candle", "christmas_tree_trunk", "long_pants"}) and callable(rank_projections):
|
| 369 |
# Screen every supplied animal/shape outline against this road graph;
|
| 370 |
# only the best fits enter the expensive shortest-path stage.
|
| 371 |
template_kwargs["template_examples"] = rank_projections(
|
|
|
|
| 394 |
# the response marks them as non-art-ready so the UI can state this
|
| 395 |
# honestly instead of showing a red generation failure.
|
| 396 |
generation_mode = "fast_walk_roads"
|
| 397 |
+
if not candidates and selected_label and minimum_similarity is None:
|
| 398 |
candidates = build_candidates(
|
| 399 |
graph=graph,
|
| 400 |
route_count=candidate_pool,
|
|
|
|
| 403 |
tolerance_ratio=0.60,
|
| 404 |
)
|
| 405 |
generation_mode = "fast_walk_roads_nearby_fallback"
|
| 406 |
+
if not candidates and minimum_similarity is None:
|
| 407 |
# Rural/island road graphs may have no acceptable drawing or loop.
|
| 408 |
# A return trip along existing walking edges is still a real route.
|
| 409 |
candidates = _nearby_road_return_routes(
|
| 410 |
graph, route_count, target_distance_km * 1000.0, center_lat, center_lon
|
| 411 |
)
|
| 412 |
generation_mode = "fast_walk_roads_return_trip"
|
| 413 |
+
if not candidates and minimum_similarity is None:
|
| 414 |
raise RuntimeError("No walkable road routes were generated near this location.")
|
| 415 |
|
| 416 |
routes: list[dict[str, Any]] = []
|
|
|
|
| 427 |
continue
|
| 428 |
shape_quality = float(route.get("shape_quality", 0.0))
|
| 429 |
similarity, example_index = best_gpx_shape_match(coords, examples) if examples else (0.0, None)
|
| 430 |
+
if minimum_similarity is not None and (example_index is None or similarity < minimum_similarity):
|
| 431 |
+
continue
|
| 432 |
rotation = None
|
| 433 |
if generation_mode == "fast_walk_roads" and example_index is not None:
|
| 434 |
_, _, rotation = best_gpx_shape_alignment(coords, [examples[example_index]])
|
|
|
|
| 442 |
"top1_rerank_score": shape_quality,
|
| 443 |
"top1_shape": shape_quality,
|
| 444 |
"selected_label": selected_label,
|
| 445 |
+
**({"art_template_name": catalog_entry[0]}
|
| 446 |
+
if catalog_entry and example_index is not None
|
| 447 |
+
and id(examples[example_index]) in catalog_outline_ids else {}),
|
| 448 |
"selected_label_score": shape_quality if selected_label else None,
|
| 449 |
"selected_label_rerank_score": shape_quality if selected_label else None,
|
| 450 |
**({"display_rotation_deg": rotation, "display_rotation_source": "template_match"}
|
|
|
|
| 476 |
-route["route_quality"]["shape_similarity"],
|
| 477 |
abs(route["length_km"] - target_distance_km) if not shape_priority else 0,
|
| 478 |
))
|
| 479 |
+
if routes and experimental_candidate_ranker and selected_label in SHAPE_DISCOVERY_LABELS:
|
| 480 |
try:
|
| 481 |
script_dir = Path(settings.ai_workspace_dir) / "scripts"
|
| 482 |
if str(script_dir) not in sys.path:
|
|
|
|
| 495 |
except Exception:
|
| 496 |
logger.exception("GPX candidate ranker unavailable; keeping geometric order")
|
| 497 |
routes = routes[:route_count]
|
| 498 |
+
if not routes and minimum_similarity is None:
|
| 499 |
raise RuntimeError("Walkable road routes did not contain usable map coordinates.")
|
| 500 |
|
| 501 |
generation_timings_ms["final_ranking"] = round((time.perf_counter() - started_at) * 1000) - sum(generation_timings_ms.values())
|
|
|
|
| 512 |
"labels": [selected_label] if selected_label else [],
|
| 513 |
"selected_label": selected_label,
|
| 514 |
"selected_top_k": 0,
|
| 515 |
+
"best_route": routes[0] if routes else None,
|
| 516 |
"routes": routes,
|
| 517 |
"generation_mode": generation_mode,
|
| 518 |
"ranking_mode": ranking_mode,
|
|
|
|
| 765 |
return result
|
| 766 |
|
| 767 |
|
| 768 |
+
AUTO_MIN_SHAPE_SIMILARITY = .82
|
| 769 |
+
AUTO_INITIAL_LABELS = 2
|
| 770 |
+
AUTO_MAX_LABELS = 4
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def _generate_automatic_shapes(module, payload, labels, catalog, radius_km, route_count):
|
| 774 |
+
"""Compare nearby road fits across labels; never fill with generic loops."""
|
| 775 |
+
build_graph = module._build_or_get_walk_graph
|
| 776 |
+
place = None if payload.source == "current" else payload.place.strip()
|
| 777 |
+
lat = payload.latitude if place is None else None
|
| 778 |
+
lon = payload.longitude if place is None else None
|
| 779 |
+
try:
|
| 780 |
+
graph, location = build_graph(place, lat, lon, radius_km)
|
| 781 |
+
except Exception:
|
| 782 |
+
if place is None or payload.fallbackLatitude is None or payload.fallbackLongitude is None:
|
| 783 |
+
raise
|
| 784 |
+
graph, location = build_graph(None, payload.fallbackLatitude, payload.fallbackLongitude, radius_km)
|
| 785 |
+
|
| 786 |
+
bundled = getattr(module, "GPX_SHAPE_TEMPLATES", {})
|
| 787 |
+
guided = getattr(module, "LABEL_GUIDED_WAYPOINTS", {})
|
| 788 |
+
outlines = []
|
| 789 |
+
owners = {}
|
| 790 |
+
for label in dict.fromkeys([*labels, *catalog]):
|
| 791 |
+
for outline in [*bundled.get(label, []), *(catalog.get(label, ("", []))[1])] or ([guided[label]] if label in guided else []):
|
| 792 |
+
outlines.append(outline)
|
| 793 |
+
owners[id(outline)] = label
|
| 794 |
+
routes = []
|
| 795 |
+
total_candidates = 0
|
| 796 |
+
rank = module.rank_road_template_projections
|
| 797 |
+
external_ids = {id(outline) for _, examples in catalog.values() for outline in examples}
|
| 798 |
+
for distance in ((6., 11., 18.) if payload.shapePriority else (payload.targetDistanceKm,)):
|
| 799 |
+
if not outlines:
|
| 800 |
+
break
|
| 801 |
+
shortlist = rank(graph, outlines, distance * 1000, limit=40)
|
| 802 |
+
external = [outline for outline in outlines if id(outline) in external_ids]
|
| 803 |
+
# Reserve an imported outline without displacing the best overall fit.
|
| 804 |
+
if external and shortlist and id(shortlist[0]) not in external_ids:
|
| 805 |
+
imported = next((outline for outline in shortlist if id(outline) in external_ids), None)
|
| 806 |
+
if imported is None:
|
| 807 |
+
imported = next(iter(rank(graph, external, distance * 1000, limit=1)), None)
|
| 808 |
+
if imported is not None:
|
| 809 |
+
shortlist = [shortlist[0], imported, *(outline for outline in shortlist[1:] if outline is not imported)]
|
| 810 |
+
by_label = {}
|
| 811 |
+
for outline in shortlist:
|
| 812 |
+
label = owners[id(outline)]
|
| 813 |
+
if label not in by_label and len(by_label) >= AUTO_MAX_LABELS:
|
| 814 |
+
continue
|
| 815 |
+
if len(by_label.setdefault(label, [])) < 4:
|
| 816 |
+
by_label[label].append(outline)
|
| 817 |
+
accepted_signatures = set()
|
| 818 |
+
for attempt, (label, examples) in enumerate(by_label.items()):
|
| 819 |
+
if attempt >= AUTO_INITIAL_LABELS and len(accepted_signatures) >= route_count:
|
| 820 |
+
break
|
| 821 |
+
found = _run_fast_road_pipeline(
|
| 822 |
+
module, place=place, center_lat=lat, center_lon=lon, radius_km=radius_km,
|
| 823 |
+
route_count=min(6, route_count), target_distance_km=distance, selected_label=label,
|
| 824 |
+
shape_priority=payload.shapePriority, experimental_candidate_ranker=payload.experimentalCandidateRanker,
|
| 825 |
+
graph_override=(graph, location), search_distances_km=(distance,),
|
| 826 |
+
catalog_entry=catalog.get(label), examples_override=examples,
|
| 827 |
+
minimum_similarity=AUTO_MIN_SHAPE_SIMILARITY,
|
| 828 |
+
)
|
| 829 |
+
total_candidates += found["candidate_count"]
|
| 830 |
+
routes.extend(found["routes"])
|
| 831 |
+
accepted_signatures.update(_automatic_route_signature(route) for route in found["routes"])
|
| 832 |
+
routes.sort(key=lambda route: -route["route_quality"]["shape_similarity"])
|
| 833 |
+
unique = []
|
| 834 |
+
seen = set()
|
| 835 |
+
for route in routes:
|
| 836 |
+
signature = _automatic_route_signature(route)
|
| 837 |
+
if signature not in seen:
|
| 838 |
+
seen.add(signature)
|
| 839 |
+
unique.append(route)
|
| 840 |
+
if len(unique) == route_count:
|
| 841 |
+
break
|
| 842 |
+
return {
|
| 843 |
+
"place": location, "source": "place" if place else "point",
|
| 844 |
+
"requested_count": route_count, "generated_count": len(unique), "candidate_count": total_candidates,
|
| 845 |
+
"target_distance_km": 0.0 if payload.shapePriority else payload.targetDistanceKm,
|
| 846 |
+
"radius_km": radius_km, "labels": list(dict.fromkeys(r["selected_label"] for r in unique)),
|
| 847 |
+
"routes": unique, "best_route": unique[0] if unique else None,
|
| 848 |
+
"generation_mode": "automatic_art_shapes", "ranking_mode": "gpx_similarity",
|
| 849 |
+
**({"fallback_notice": "이 위치에서는 기준 유사도를 충족하는 아트 경로를 찾지 못했습니다. 출발점이나 탐색 범위를 바꿔 보세요."}
|
| 850 |
+
if not unique else {}),
|
| 851 |
+
}
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
def _automatic_route_signature(route):
|
| 855 |
+
trace = tuple(tuple(point) for point in route["route_coords"])
|
| 856 |
+
return frozenset(tuple(sorted(edge)) for edge in zip(trace, trace[1:]))
|
| 857 |
+
|
| 858 |
+
|
| 859 |
def _generate_routes(payload: RouteGenerateRequest) -> dict[str, Any]:
|
| 860 |
workspace_dir = Path(settings.ai_workspace_dir)
|
| 861 |
script_path = workspace_dir / "scripts" / "osm_route_runtime.py"
|
|
|
|
| 882 |
route_count_cap = 20 if use_current else 100
|
| 883 |
route_count = min(route_count_cap, max(1, payload.routeCount))
|
| 884 |
target_distance_km = max(0.5, payload.targetDistanceKm)
|
| 885 |
+
shape_priority = payload.shapePriority and (selected_label is not None or payload.autoShape)
|
| 886 |
# A 1.5 km graph is enough for ordinary short courses, but it cannot make
|
| 887 |
# a truthful 16~30 km route. Grow the road graph only as much as the
|
| 888 |
# requested distance needs, up to the request model's safe 10 km limit.
|
| 889 |
required_radius_km = target_distance_km / 5.5
|
| 890 |
radius_km = min(10.0, max(5.0 if shape_priority else 1.5, min(10.0, payload.radiusKm), required_radius_km))
|
| 891 |
+
catalog = load_art_route_catalog()
|
| 892 |
+
if payload.autoShape:
|
| 893 |
+
if selected_label is not None:
|
| 894 |
+
raise HTTPException(status_code=400, detail="autoShape cannot be combined with selectedLabel")
|
| 895 |
+
try:
|
| 896 |
+
return _generate_automatic_shapes(_load_pipeline_module(script_path), payload, labels, catalog, radius_km, route_count)
|
| 897 |
+
except Exception:
|
| 898 |
+
logger.exception("Automatic art shape generation unavailable")
|
| 899 |
+
raise HTTPException(status_code=503, detail="보행 도로망을 불러오지 못해 아트 경로를 탐색할 수 없습니다.")
|
| 900 |
|
| 901 |
module = None
|
| 902 |
try:
|
|
|
|
| 912 |
selected_label=selected_label,
|
| 913 |
shape_priority=shape_priority,
|
| 914 |
experimental_candidate_ranker=payload.experimentalCandidateRanker,
|
| 915 |
+
catalog_entry=catalog.get(selected_label),
|
| 916 |
)
|
| 917 |
except Exception as primary_exc:
|
| 918 |
logger.exception("fast walk-road route generation failed")
|
api/ai-service/app/services/art_route_catalog.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read validated GPS exemplars, never serve their original GPS as a new route."""
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
from app.services.gpx_shape_similarity import _sample_outline
|
| 11 |
+
|
| 12 |
+
LOG = logging.getLogger(__name__)
|
| 13 |
+
CATALOG_SQL = """
|
| 14 |
+
SELECT t.template_key, t.name, r.coordinates
|
| 15 |
+
FROM art_route_candidates r JOIN art_templates t ON t.id = r.template_id
|
| 16 |
+
WHERE r.validation_status = 'passed'
|
| 17 |
+
ORDER BY r.validation_score DESC NULLS LAST, r.created_at DESC, r.id
|
| 18 |
+
LIMIT 200
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def coordinate_outline(coordinates, order="latlon"):
|
| 23 |
+
if not isinstance(coordinates, list) or not 4 <= len(coordinates) <= 100000:
|
| 24 |
+
return None
|
| 25 |
+
points = []
|
| 26 |
+
for pair in coordinates:
|
| 27 |
+
if not isinstance(pair, (list, tuple)) or len(pair) != 2:
|
| 28 |
+
return None
|
| 29 |
+
lat, lon = pair if order == "latlon" else pair[::-1]
|
| 30 |
+
if (type(lat) not in (int, float) or type(lon) not in (int, float)
|
| 31 |
+
or not -90 <= lat <= 90 or not -180 <= lon <= 180):
|
| 32 |
+
return None
|
| 33 |
+
if not points or (lat, lon) != points[-1]:
|
| 34 |
+
points.append((lat, lon))
|
| 35 |
+
if len(set(points)) < 4:
|
| 36 |
+
return None
|
| 37 |
+
lat, lon = points[0]
|
| 38 |
+
scale = math.cos(math.radians(lat))
|
| 39 |
+
xy = [((x - lon) * scale, lat - y) for y, x in points]
|
| 40 |
+
perimeter = sum(math.dist(a, b) for a, b in zip(xy, xy[1:]))
|
| 41 |
+
if perimeter <= 0 or math.dist(xy[0], xy[-1]) > perimeter * .15:
|
| 42 |
+
return None # Do not invent a closing side for a substantially open trace.
|
| 43 |
+
samples = _sample_outline(xy, 32)
|
| 44 |
+
outline = [(p.real, p.imag) for p in samples]
|
| 45 |
+
return [*outline, outline[0]] if outline else None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@lru_cache(maxsize=4)
|
| 49 |
+
def _load(dsn, filename, order, _refresh_bucket):
|
| 50 |
+
try:
|
| 51 |
+
if filename:
|
| 52 |
+
records = json.loads(Path(filename).read_text(encoding="utf-8"))
|
| 53 |
+
if not isinstance(records, list):
|
| 54 |
+
raise ValueError("Expected a list of route records")
|
| 55 |
+
rows = [(r.get("template_key"), r.get("name"), r.get("coordinates"))
|
| 56 |
+
for r in records[:200] if isinstance(r, dict) and r.get("validation_status") == "passed"]
|
| 57 |
+
elif dsn:
|
| 58 |
+
import psycopg
|
| 59 |
+
with psycopg.connect(dsn, connect_timeout=3,
|
| 60 |
+
options="-c default_transaction_read_only=on -c statement_timeout=3000") as conn:
|
| 61 |
+
rows = conn.execute(CATALOG_SQL).fetchall()
|
| 62 |
+
else:
|
| 63 |
+
return {}
|
| 64 |
+
catalog = {}
|
| 65 |
+
for key, name, coordinates in rows:
|
| 66 |
+
if not isinstance(key, str) or not key.strip():
|
| 67 |
+
continue
|
| 68 |
+
outline = coordinate_outline(coordinates, order)
|
| 69 |
+
if outline:
|
| 70 |
+
entry = catalog.setdefault(key, (str(name or key), []))
|
| 71 |
+
entry[1].append(outline)
|
| 72 |
+
return catalog
|
| 73 |
+
except Exception as exc:
|
| 74 |
+
# Do not log connection strings or source coordinate records.
|
| 75 |
+
LOG.warning("Art route catalog unavailable (%s); using bundled templates", type(exc).__name__)
|
| 76 |
+
return {}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def load_art_route_catalog():
|
| 80 |
+
order = os.getenv("ART_ROUTE_COORDINATE_ORDER", "latlon")
|
| 81 |
+
if order not in {"latlon", "lonlat"}:
|
| 82 |
+
LOG.warning("Invalid ART_ROUTE_COORDINATE_ORDER; ignoring external catalog")
|
| 83 |
+
return {}
|
| 84 |
+
return _load(os.getenv("ART_ROUTE_CATALOG_DATABASE_URL"), os.getenv("ART_ROUTE_CATALOG_JSON"),
|
| 85 |
+
order, int(time.monotonic() // 60))
|
api/ai-service/tests/test_auto_art_catalog.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
from types import SimpleNamespace
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 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],
|
| 15 |
+
[36.999, 127.002], [37, 127]]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_local_catalog_imports_only_valid_passed_traces(tmp_path, monkeypatch):
|
| 19 |
+
path = tmp_path / "catalog.json"
|
| 20 |
+
path.write_text(json.dumps([
|
| 21 |
+
{"template_key": "external", "name": "Imported", "coordinates": TRACE, "validation_status": "passed"},
|
| 22 |
+
{"template_key": "failed", "coordinates": TRACE, "validation_status": "failed"},
|
| 23 |
+
{"template_key": "open", "coordinates": TRACE[:-1], "validation_status": "passed"},
|
| 24 |
+
]), encoding="utf-8")
|
| 25 |
+
monkeypatch.setenv("ART_ROUTE_CATALOG_JSON", str(path))
|
| 26 |
+
monkeypatch.setenv("ART_ROUTE_COORDINATE_ORDER", "latlon")
|
| 27 |
+
catalog = load_art_route_catalog()
|
| 28 |
+
assert set(catalog) == {"external"}
|
| 29 |
+
name, (outline,) = catalog["external"]
|
| 30 |
+
assert name == "Imported" and len(outline) == 33 and outline[0] == outline[-1]
|
| 31 |
+
assert coordinate_outline([p[::-1] for p in TRACE], "lonlat") == outline
|
| 32 |
+
assert coordinate_outline([p[::-1] for p in TRACE], "latlon") is None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.mark.parametrize("score, expected_count", [(.81, 0), (.82, 1), (.95, 1)])
|
| 36 |
+
def test_automatic_catalog_routes_use_local_roads_and_minimum_score(monkeypatch, score, expected_count):
|
| 37 |
+
outline = coordinate_outline(TRACE)
|
| 38 |
+
road = [[lat + 1, lon + 1] for lat, lon in TRACE]
|
| 39 |
+
graph = object()
|
| 40 |
+
calls = []
|
| 41 |
+
|
| 42 |
+
def build_graph(*args):
|
| 43 |
+
calls.append(args)
|
| 44 |
+
return graph, "target"
|
| 45 |
+
|
| 46 |
+
def generate(**kwargs):
|
| 47 |
+
assert kwargs["graph"] is graph and kwargs["template_examples"] == [outline]
|
| 48 |
+
return [{"nodes": [1, 2], "length_m": 6000, "shape_quality": .95, "is_loop": True}]
|
| 49 |
+
|
| 50 |
+
module = SimpleNamespace(_build_or_get_walk_graph=build_graph, generate_candidate_routes=generate,
|
| 51 |
+
rank_road_template_projections=lambda _g, examples, _d, limit: examples[:limit],
|
| 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)]
|
| 58 |
+
assert result["generation_mode"] == "automatic_art_shapes"
|
| 59 |
+
assert result["generated_count"] == expected_count
|
| 60 |
+
if expected_count:
|
| 61 |
+
assert result["best_route"]["route_coords"] == road
|
| 62 |
+
assert result["best_route"]["art_template_name"] == "Imported"
|
| 63 |
+
assert "display_rotation_deg" in result["best_route"]
|
| 64 |
+
else:
|
| 65 |
+
assert result["best_route"] is None and result["fallback_notice"]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_auto_explores_other_labels_when_first_choices_fail(monkeypatch):
|
| 69 |
+
outlines = [[(0, 0), (i, 1), (1, 0), (0, 0)] for i in range(1, 6)]
|
| 70 |
+
labels = ["dog", "heart", "star", "cup", "external"]
|
| 71 |
+
graph = object()
|
| 72 |
+
module = SimpleNamespace(
|
| 73 |
+
_build_or_get_walk_graph=lambda *_: (graph, "target"),
|
| 74 |
+
GPX_SHAPE_TEMPLATES=dict(zip(labels[:-1], ([o] for o in outlines[:-1]))),
|
| 75 |
+
rank_road_template_projections=lambda _g, values, _d, limit: values[:limit],
|
| 76 |
+
)
|
| 77 |
+
attempts = []
|
| 78 |
+
|
| 79 |
+
def generate(_module, **kwargs):
|
| 80 |
+
label = kwargs["selected_label"]
|
| 81 |
+
attempts.append(label)
|
| 82 |
+
assert kwargs["graph_override"] == (graph, "target")
|
| 83 |
+
assert kwargs["minimum_similarity"] == .82
|
| 84 |
+
if label not in {"heart", "star"}:
|
| 85 |
+
return {"candidate_count": 1, "routes": []}
|
| 86 |
+
offset = labels.index(label)
|
| 87 |
+
return {"candidate_count": 1, "routes": [{
|
| 88 |
+
"selected_label": label,
|
| 89 |
+
"route_coords": [[37 + offset, 127], [37.01 + offset, 127]],
|
| 90 |
+
"route_quality": {"shape_similarity": .91 if label == "heart" else .94},
|
| 91 |
+
}]}
|
| 92 |
+
|
| 93 |
+
monkeypatch.setattr(api, "_run_fast_road_pipeline", generate)
|
| 94 |
+
request = api.RouteGenerateRequest(source="current", latitude=38, longitude=128, autoShape=True)
|
| 95 |
+
result = api._generate_automatic_shapes(module, request, labels[:-1],
|
| 96 |
+
{"external": ("Imported", [outlines[-1]])}, 2.5, 2)
|
| 97 |
+
assert attempts == ["dog", "external", "heart", "star"]
|
| 98 |
+
assert [route["selected_label"] for route in result["routes"]] == ["star", "heart"]
|
api/auth-service/app/api/v1/endpoints/active_run.py
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 1 |
"""Recovery state only: neither real nor simulated checkpoints create workouts."""
|
| 2 |
import json
|
|
|
|
|
|
|
|
|
|
| 3 |
import time
|
| 4 |
from typing import Literal
|
| 5 |
from urllib.parse import urlsplit, parse_qs, unquote
|
| 6 |
-
from fastapi import APIRouter, Depends, HTTPException
|
| 7 |
from pydantic import BaseModel, Field, model_validator
|
| 8 |
from sqlalchemy import select
|
| 9 |
from sqlalchemy.orm import Session
|
|
@@ -63,6 +66,35 @@ def read_active(db: Session = Depends(get_db), user: User = Depends(get_current_
|
|
| 63 |
row = db.scalar(select(ActiveRun).where(ActiveRun.user_id == user.id, ActiveRun.ended == 0))
|
| 64 |
return {"active": envelope(row)}
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
@router.post("/start")
|
| 67 |
def start(payload: WriteRequest, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
| 68 |
lock_user(db, user)
|
|
|
|
| 1 |
"""Recovery state only: neither real nor simulated checkpoints create workouts."""
|
| 2 |
import json
|
| 3 |
+
import hmac
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
import time
|
| 7 |
from typing import Literal
|
| 8 |
from urllib.parse import urlsplit, parse_qs, unquote
|
| 9 |
+
from fastapi import APIRouter, Depends, Header, HTTPException, Response
|
| 10 |
from pydantic import BaseModel, Field, model_validator
|
| 11 |
from sqlalchemy import select
|
| 12 |
from sqlalchemy.orm import Session
|
|
|
|
| 66 |
row = db.scalar(select(ActiveRun).where(ActiveRun.user_id == user.id, ActiveRun.ended == 0))
|
| 67 |
return {"active": envelope(row)}
|
| 68 |
|
| 69 |
+
@router.get("/environment-density")
|
| 70 |
+
def environment_density(response: Response, db: Session = Depends(get_db),
|
| 71 |
+
key: str = Header(default="", alias="X-Run-Environment-Key")):
|
| 72 |
+
expected = os.getenv("RUN_ENV_INTERNAL_KEY")
|
| 73 |
+
if not expected or not hmac.compare_digest(key.encode(), expected.encode()):
|
| 74 |
+
raise HTTPException(404)
|
| 75 |
+
response.headers["Cache-Control"] = "no-store"
|
| 76 |
+
now = int(time.time() * 1000)
|
| 77 |
+
snapshots = db.scalars(select(ActiveRun.snapshot).where(
|
| 78 |
+
ActiveRun.ended == 0, ActiveRun.lease_at >= now - 120_000)).yield_per(100)
|
| 79 |
+
cells: dict[str, int] = {}
|
| 80 |
+
for raw in snapshots:
|
| 81 |
+
try:
|
| 82 |
+
cp = json.loads(raw)
|
| 83 |
+
if cp.get("mode") != "real" or cp.get("isPaused") is not False:
|
| 84 |
+
continue
|
| 85 |
+
# A start/recovery coordinate alone is not evidence of a measured run.
|
| 86 |
+
if not cp.get("actualRoute") or not 0 <= now - cp["savedAt"] <= 120_000:
|
| 87 |
+
continue
|
| 88 |
+
lat, lon = cp["currentPosition"]
|
| 89 |
+
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
| 90 |
+
continue
|
| 91 |
+
cell = f"{math.floor(lat * 200)}:{math.floor(lon * 200)}"
|
| 92 |
+
cells[cell] = cells.get(cell, 0) + 1
|
| 93 |
+
except (ValueError, TypeError, KeyError, AttributeError):
|
| 94 |
+
continue
|
| 95 |
+
return {"cells": {cell: count for cell, count in cells.items() if count >= 3},
|
| 96 |
+
"occupiedCells": list(cells)}
|
| 97 |
+
|
| 98 |
@router.post("/start")
|
| 99 |
def start(payload: WriteRequest, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
| 100 |
lock_user(db, user)
|
api/auth-service/tests/test_active_run.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
"""Isolated checkpoint contract tests; never connect to the deployed database."""
|
| 2 |
import unittest
|
|
|
|
|
|
|
| 3 |
from sqlalchemy import create_engine, select, func
|
| 4 |
from sqlalchemy.orm import Session
|
| 5 |
-
from fastapi import HTTPException
|
| 6 |
from pydantic import ValidationError
|
| 7 |
from app.db.base import Base
|
| 8 |
from app.models.user import User
|
| 9 |
from app.models.active_run import ActiveRun
|
| 10 |
-
from app.api.v1.endpoints.active_run import Checkpoint, WriteRequest, abandon, start, checkpoint, complete, read_active
|
| 11 |
|
| 12 |
|
| 13 |
class ActiveRunTests(unittest.TestCase):
|
|
@@ -66,6 +68,21 @@ class ActiveRunTests(unittest.TestCase):
|
|
| 66 |
self.assert_error(409, "another_active_session", start, self.payload(session="run-2"), self.db, self.user)
|
| 67 |
self.assertEqual(self.db.scalar(select(func.count()).select_from(ActiveRun)), 1)
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
def test_same_session_reentry_takes_writer_immediately_and_old_writer_is_rejected(self):
|
| 70 |
start(self.payload(), self.db, self.user)
|
| 71 |
resumed = start(self.payload(writer="tab-2"), self.db, self.user)
|
|
|
|
| 1 |
"""Isolated checkpoint contract tests; never connect to the deployed database."""
|
| 2 |
import unittest
|
| 3 |
+
import time
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
from sqlalchemy import create_engine, select, func
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
+
from fastapi import HTTPException, Response
|
| 8 |
from pydantic import ValidationError
|
| 9 |
from app.db.base import Base
|
| 10 |
from app.models.user import User
|
| 11 |
from app.models.active_run import ActiveRun
|
| 12 |
+
from app.api.v1.endpoints.active_run import Checkpoint, WriteRequest, abandon, start, checkpoint, complete, read_active, environment_density
|
| 13 |
|
| 14 |
|
| 15 |
class ActiveRunTests(unittest.TestCase):
|
|
|
|
| 68 |
self.assert_error(409, "another_active_session", start, self.payload(session="run-2"), self.db, self.user)
|
| 69 |
self.assertEqual(self.db.scalar(select(func.count()).select_from(ActiveRun)), 1)
|
| 70 |
|
| 71 |
+
def test_density_uses_recent_real_sessions_and_hides_small_counts(self):
|
| 72 |
+
now = int(time.time() * 1000)
|
| 73 |
+
for i, changes in enumerate([{}, {}, {}, {"isPaused": True},
|
| 74 |
+
{"mode": "simulation"}, {"savedAt": now - 121000},
|
| 75 |
+
{"currentPosition": [38, 128]}]):
|
| 76 |
+
user = User(email=f"density{i}@example.invalid", hashed_password="test")
|
| 77 |
+
self.db.add(user)
|
| 78 |
+
self.db.commit()
|
| 79 |
+
start(self.payload(**{"savedAt": now, **changes}), self.db, user)
|
| 80 |
+
with patch.dict("os.environ", {"RUN_ENV_INTERNAL_KEY": "test-key"}):
|
| 81 |
+
self.assert_error(404, "Not Found", environment_density, Response(), self.db, "wrong")
|
| 82 |
+
density = environment_density(Response(), self.db, "test-key")
|
| 83 |
+
self.assertEqual(density["cells"], {"7400:25400": 3})
|
| 84 |
+
self.assertIn("7400:25400", density["occupiedCells"])
|
| 85 |
+
|
| 86 |
def test_same_session_reentry_takes_writer_immediately_and_old_writer_is_rejected(self):
|
| 87 |
start(self.payload(), self.db, self.user)
|
| 88 |
resumed = start(self.payload(writer="tab-2"), self.db, self.user)
|
deploy/huggingface/start-hf.sh
CHANGED
|
@@ -79,6 +79,12 @@ fi
|
|
| 79 |
|
| 80 |
export PORT="${PORT:-7860}"
|
| 81 |
export AUTH_SERVICE_URL="${AUTH_SERVICE_URL:-http://127.0.0.1:8001}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
export AI_SERVICE_URL="${AI_SERVICE_URL:-http://127.0.0.1:8002}"
|
| 83 |
export AI_WORKSPACE_DIR="${AI_WORKSPACE_DIR:-/app/router/ai}"
|
| 84 |
export PYTHON_COMMAND="${PYTHON_COMMAND:-${PYTHON_BIN}}"
|
|
|
|
| 79 |
|
| 80 |
export PORT="${PORT:-7860}"
|
| 81 |
export AUTH_SERVICE_URL="${AUTH_SERVICE_URL:-http://127.0.0.1:8001}"
|
| 82 |
+
export RUN_ENV_AUTH_URL="${RUN_ENV_AUTH_URL:-${AUTH_SERVICE_URL}}"
|
| 83 |
+
export RUN_ENV_DATA_DIR="${RUN_ENV_DATA_DIR:-/data/running-environment}"
|
| 84 |
+
export RUN_ENV_INTERNAL_KEY="${RUN_ENV_INTERNAL_KEY:-$("${PYTHON_BIN}" -c 'import secrets; print(secrets.token_hex(32))')}"
|
| 85 |
+
if [[ ! -d "${RUN_ENV_DATA_DIR}/roads" ]]; then
|
| 86 |
+
echo "Running environment: road index not mounted; road scores will be unavailable."
|
| 87 |
+
fi
|
| 88 |
export AI_SERVICE_URL="${AI_SERVICE_URL:-http://127.0.0.1:8002}"
|
| 89 |
export AI_WORKSPACE_DIR="${AI_WORKSPACE_DIR:-/app/router/ai}"
|
| 90 |
export PYTHON_COMMAND="${PYTHON_COMMAND:-${PYTHON_BIN}}"
|
docs/LOCAL_ART_ROUTE_CATALOG.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 로컬 검증 경로 카탈로그와 모양 자동 추천
|
| 2 |
+
|
| 3 |
+
경로 생성 화면의 기본값인 **모양 상관없음 · 자동 추천**은 내장 예시와 검증 경로
|
| 4 |
+
카탈로그를 같은 주변 보행망에서 비교한다. 도로 투영으로 먼저 후보 도안을 추리고,
|
| 5 |
+
거리별 우선 두 모양을 실제 도로망에 연결하고, 통과한 경로가 부족하면 최대 네 모양까지
|
| 6 |
+
탐색한다. 최종 기준 윤곽 유사도 0.82 이상만
|
| 7 |
+
표시한다. 이 값은 초기 운영 후보 기준이며 사람 평가로 보정되지 않았다.
|
| 8 |
+
통과 경로가 모자라도 일반 러닝 경로를 아트 추천에 넣어 개수를 채우지 않는다.
|
| 9 |
+
|
| 10 |
+
DB 원본 GPS는 절대 새 경로로 반환하지 않는다. 경로를 평면 윤곽으로 변환해 위치와
|
| 11 |
+
스케일을 제거하고, 사용자가 선택한 지역의 보행 도로에 다시 맞춘다. 원본의 방향은
|
| 12 |
+
저장된 GPS를 북쪽이 위로 보았을 때의 방향이며, 별도 정방향 기준점이 있는 것은 아니다.
|
| 13 |
+
크게 열린 경로와 유효하지 않은 좌표는 현재 폐곡선 생성에서 제외한다.
|
| 14 |
+
기존 HGB는 지원하는 내장 모양에서만 사용하고, 새 모양의 생성·표시에 새 모델 학습은 필요하지 않다.
|
| 15 |
+
|
| 16 |
+
## DB 읽기 연결
|
| 17 |
+
|
| 18 |
+
AI 서비스 실행 환경에 `ART_ROUTE_CATALOG_DATABASE_URL`을 설정한다. 기존 두 테이블
|
| 19 |
+
(`art_templates`, `art_route_candidates`)의 SELECT만 허용한 DB 계정을 권장한다.
|
| 20 |
+
쿼리도 읽기 전용 트랜잭션으로 실행하며 `validation_status='passed'`만 읽는다.
|
| 21 |
+
운영 데이터 복제가 준비돼 있다면 운영 계정 대신 로컬 복제본을 지정한다.
|
| 22 |
+
기존 마이그레이션이나 테이블은 바꾸지 않는다.
|
| 23 |
+
|
| 24 |
+
좌표 배열이 `[경도, 위도]`이면 `ART_ROUTE_COORDINATE_ORDER=lonlat`를 설정한다.
|
| 25 |
+
기본값은 프로젝트 좌표 배열과 같은 `[위도, 경도]`다. 접속에 실패하거나 설정하지
|
| 26 |
+
않으면 내장 도안으로 동작한다. 접속 정보를 프런트엔드 환경변수에 넣지 않는다.
|
| 27 |
+
|
| 28 |
+
직접 실행하는 AI 서비스에서는 읽기 전용 JSON 내보내기 파일을
|
| 29 |
+
`ART_ROUTE_CATALOG_JSON`으로 지정할 수도 있다. JSON은
|
| 30 |
+
`[{ "template_key": "...", "name": "...", "validation_status": "passed", "coordinates": [[37.0, 127.0], ...] }]`
|
| 31 |
+
형태다. 이 변수가 있으면 DB 대신 파일을 사용한다.
|
| 32 |
+
|
| 33 |
+
Docker Compose를 사용하는 경우 기존 `./router` 마운트를 이용할 수 있다.
|
| 34 |
+
내보낸 파일을 로컬 `router` 폴더에 둔 뒤
|
| 35 |
+
`ART_ROUTE_CATALOG_JSON=/workspace/router/<파일명>.json`을 지정한다.
|
| 36 |
+
실데이터 내보내기 파일은 Git에 커밋하지 않는다.
|
docs/running-environment.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 러닝 환경 점수
|
| 2 |
+
|
| 3 |
+
추천 결과와 AI 샘플은 점수가 높은 순으로 정렬한다. 원래 순서는 추천 점수 동률에,
|
| 4 |
+
지도 중심까지의 거리는 샘플 점수 동률에 사용한다. 점수와 추천 순위는 경로 ID를 바꾸지 않는다.
|
| 5 |
+
|
| 6 |
+
- 보행로 구조 25%, 지역 인구 혼잡도 45%, 앱 활동 30%. 경로를 거리 기준으로 샘플링한다.
|
| 7 |
+
- 비어 있는 신호는 중립값이며 한산하다는 증거가 아니다. 전부 비어 있으면 `자료 부족`.
|
| 8 |
+
- 실시간 인구는 공식 POI 영역과 교차하는 부분만 사용한다. 서울시 API가 20분 넘게
|
| 9 |
+
오래됐거나, 대체값이거나, 실패하면 반영하지 않는다. 시간대별 자료가 있는 구간은 별도로 추정한다.
|
| 10 |
+
- 앱 활동은 최근 2분 이내에 저장되고 GPS 경로가 있는 진행 중 실제 러닝만 포함한다.
|
| 11 |
+
시뮬레이션, 일시정지, 종료는 제외한다. 주변 구역에 소수 인원이 있으면 존재 여부만 표시하고,
|
| 12 |
+
인원수는 구역당 3명 이상인 집계만 합산한다. 브라우저에는 위치나 구역 목록을 반환하지 않는다.
|
| 13 |
+
- 이 점수는 추천 순위용이며 통행 가능 여부나 안전을 인증하지 않는다.
|
| 14 |
+
|
| 15 |
+
## Hugging Face 배포
|
| 16 |
+
|
| 17 |
+
GitHub의 `DemoService` 브랜치 푸시는 Space 동기화를 시작한다. 배포 이미지에는
|
| 18 |
+
인덱스 파일이나 인증키가 포함되지 않는다. 배포 환경에 인덱스 디렉터리를 제공하고
|
| 19 |
+
`RUN_ENV_DATA_DIR`로 지정한다(기본값 `/data/running-environment`). 내부 활동 집계 키는
|
| 20 |
+
컨테이너 시작 시 생성하며 인증 서버와 Next가 공유한다. 운영 실시간 인구 API를 활성화하려면
|
| 21 |
+
전송 보안 및 이용조건을 확인한 뒤 Space의 서버 Secret `RUN_ENV_SEOUL_API_KEY`를 설정한다.
|
| 22 |
+
인덱스나 키가 없으면 해당 신호를 자료 부족으로 처리한다.
|
| 23 |
+
|
| 24 |
+
## 가져오기
|
| 25 |
+
|
| 26 |
+
1. [대한민국 OSM PBF](https://tiles.osm.kr/download/)를 다운로드한다.
|
| 27 |
+
2. [국토정보플랫폼](https://map.ngii.go.kr/)에서 수치지형도 도엽을 받아 필요한 레이어를
|
| 28 |
+
SHP 또는 WGS84 GeoJSON으로 준비한다. `sidewalk-1000`, `sidewalk-5000`,
|
| 29 |
+
`road-width`, `carriageway`에 각각 대응한다. 아래 필드명은 예시다.
|
| 30 |
+
도엽의 조사연도와 이용조건을 확인한 후 넣고, 같은 지역의 구버전과 신버전은 중복 투입하지 않는다.
|
| 31 |
+
3. [서울 실시간 도시데이터](https://data.seoul.go.kr/dataList/OA-21285/A/1/datasetView.do)의
|
| 32 |
+
주요 121장소 영역 ZIP을 풀고 SHP의 `AREA_CD` 필드를 사용한다.
|
| 33 |
+
|
| 34 |
+
```powershell
|
| 35 |
+
python -m pip install osmium geopandas
|
| 36 |
+
python tools/import_running_environment.py --out D:/data/run-env-v1 --osm D:/data/south-korea.osm.pbf --roads sidewalk-1000 D:/data/sidewalk.shp WIDTH SURFACE --seoul-areas D:/data/seoul-areas.shp AREA_CD
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
`--roads`는 여러 번 지정할 수 있고 `--seoul-areas`도 선택 사항이다.
|
| 40 |
+
OSM만 먼저 가져올 수 있다. 차도나 도로 전체의 폭을 보도 폭으로 읽지 않는다.
|
| 41 |
+
새 버전을 빈 폴더에 생성한 뒤 경로를 바꿔 Next 서버를 재시작한다.
|
| 42 |
+
|
| 43 |
+
## 로컬 실행
|
| 44 |
+
|
| 45 |
+
Next 프로세스에 다음 변수를 설정한 후 `main`에서 `npm run dev`를 실행한다.
|
| 46 |
+
|
| 47 |
+
- `RUN_ENV_DATA_DIR`: 생성된 인덱스의 절대 경로.
|
| 48 |
+
- `RUN_ENV_SEOUL_API_KEY`: 발급받은 서버용 서울시 API 키. `sample`은 광화문·덕수궁 한 곳만 검증 가능.
|
| 49 |
+
- `RUN_ENV_INTERNAL_KEY`: Next와 로컬 auth-service에 같은 임의의 긴 비밀값을 설정한다.
|
| 50 |
+
Docker Compose로 auth-service를 띄우는 경우 Compose 실행 환경에도 같은 값을 제공한다.
|
| 51 |
+
- `NEXT_INTERNAL_API_PROXY_TARGET`: 로컬 API Gateway 주소 (기본 `http://localhost:8000`).
|
| 52 |
+
|
| 53 |
+
비밀값과 인덱스는 저장소에 커밋하지 않는다. 서울시 API는 공식 예제와 같은
|
| 54 |
+
HTTP 포트 8088을 사용하므로 개발 검증용으로만 사용하고, 운영 연결 전 전송 보안과 이용조건을 확인한다.
|
| 55 |
+
전국 OSM을 쓴다는 것은 전국에 동일한 폭/보도 데이터가 있다는 뜻이 아니다.
|
| 56 |
+
OpenStreetMap © OpenStreetMap contributors (ODbL).
|
| 57 |
+
|
| 58 |
+
## 지역별 과거 혼잡도
|
| 59 |
+
|
| 60 |
+
실시간 값이 없는 경로 지점은 한국 시간 기준 평일/주말 시간대 패턴을 사용한다.
|
| 61 |
+
각 장소의 자체 일평균 대비 비율이며, 다른 도시와 인구수를 직접 비교하지 않는다.
|
| 62 |
+
실시간과 과거 값을 같은 지점에 중복 반영하지 않고, 과거 자료의 반영 강도는 실시간의 65%다.
|
| 63 |
+
|
| 64 |
+
- [서울 250m 격자 생활인구](https://data.seoul.go.kr/dataList/OA-22784/S/1/datasetView.do): 내국인 추정치, 시간별. [공식 격자 SHP](https://data.seoul.go.kr/dataVisual/seoul/seoulLivingPopulation.do)와 결합한다.
|
| 65 |
+
- [인천 부평구 주요지역 유동인구](https://www.data.go.kr/data/15167608/fileData.do): 4시간 단위.
|
| 66 |
+
[인천관광협의회 시장·문화의거리 좌표](https://www.incheontour.or.kr/place-bupyeong_market) 주변 150m만 근사 적용���다.
|
| 67 |
+
이는 조사 경계가 아니다. 공간 범위를 확인하지 못한 축제지역과 부평4동은 제외한다.
|
| 68 |
+
|
| 69 |
+
```powershell
|
| 70 |
+
python tools/import_regional_crowd.py --seoul 서울생활인구.zip 격자.shp --bupyeong 부평구.csv --out D:/data/run-env-v1/regional-crowd.json
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
인덱스 생성 후 Next 서버를 다시 시작한다. 부산 API는 키와 원본 응답 확인, 경기 데이터는
|
| 74 |
+
원본 및 경계·이용 조건 확인, 제주 실시간은 공식 연동 경로 확인 후 추가한다.
|
| 75 |
+
|
| 76 |
+
### 보행자 센서 및 경기 격자
|
| 77 |
+
|
| 78 |
+
- [서울 열린데이터광장 S-DoT](https://data.seoul.go.kr/dataList/OA-22832/S/1/datasetView.do)의
|
| 79 |
+
카메라 식별 범위 4001~4050만 사용한다. [분류 근거](https://kpaj.or.kr/_PR/view/?aidx=34568&bidx=3103).
|
| 80 |
+
45m는 추천 적용 반경이며 관측 시야가 아니다. 실시간 장소 관측이 없을 때 센서의 과거
|
| 81 |
+
시간대 패턴을 기존 광역 추정보다 우선한다. 최신 관측일이 90일을 넘으면 반영하지 않는다.
|
| 82 |
+
- `--gyeonggi-verified-grid HOURLY_CSV GRID_FILE`로 경기도 50m 격자 자료를 추가할 수 있다.
|
| 83 |
+
CSV는 `grid_id,date,hour,count` (날짜 YYYY-MM-DD), 경계 파일은 같은 `grid_id`를 가진
|
| 84 |
+
좌표계가 명시된 격자여야 한다. 무료 서비스 이용이 확인된 시간별 원본만 사용한다.
|
| 85 |
+
8월 행정동 유입 ZIP과 평일/주말 주간 평균만 있는 데이터는 이 입력으로 쓰지 않는다.
|
| 86 |
+
|
| 87 |
+
```powershell
|
| 88 |
+
python -m pip install openpyxl
|
| 89 |
+
python tools/import_regional_crowd.py --sdot 위치.xlsx 첫주.csv 둘째주.csv --out D:/data/run-env-v1/pedestrian-crowd.json
|
| 90 |
+
python tools/import_regional_crowd.py --gyeonggi-verified-grid 시간별.csv 격자.shp --out D:/data/run-env-v1/gyeonggi-crowd.json
|
| 91 |
+
```
|
main/app/_components/NearbySampleRoutesCard.tsx
CHANGED
|
@@ -10,6 +10,8 @@ import {
|
|
| 10 |
import { fetchCommunityPostsFromApi } from "../_utils/communityApi";
|
| 11 |
import { prepareCoursePreview } from "../_utils/coursePreview";
|
| 12 |
import { withSampleOrientation } from "../_utils/sampleRouteOrientation";
|
|
|
|
|
|
|
| 13 |
|
| 14 |
type Point = [number, number];
|
| 15 |
|
|
@@ -21,7 +23,7 @@ const GANGNAM_SAMPLE_CENTER: Point = [37.510493, 127.035246];
|
|
| 21 |
type DemoSampleRun = {
|
| 22 |
displayRotationDeg?: number;
|
| 23 |
id: string;
|
| 24 |
-
label: "dog" | "symbol_star" | "t_shirt";
|
| 25 |
title: string;
|
| 26 |
distanceKm: number;
|
| 27 |
center: Point;
|
|
@@ -82,18 +84,21 @@ export default function NearbySampleRoutesCard({
|
|
| 82 |
|
| 83 |
const selectedPost = communityPosts.find((post) => post.id === selectedPostId) ?? null;
|
| 84 |
const selectedSample = sampleRuns.find((sample) => sample.id === selectedSampleId) ?? null;
|
|
|
|
|
|
|
| 85 |
const nearbySamples = useMemo(() =>
|
| 86 |
sampleRuns
|
| 87 |
.map((sample) => ({ sample, distanceKm: distanceBetweenKm(mapCenter, sample.center) }))
|
| 88 |
.filter(({ distanceKm }) => distanceKm <= Math.max(radiusKm, 1))
|
| 89 |
-
.sort((a, b) => a.distanceKm - b.distanceKm)
|
| 90 |
.slice(0, 12),
|
| 91 |
-
[mapCenter, radiusKm, sampleRuns]
|
| 92 |
);
|
| 93 |
const gallerySamples = sampleGalleryLabel
|
| 94 |
? sampleRuns
|
| 95 |
.filter((sample) => sample.label === sampleGalleryLabel)
|
| 96 |
-
.sort((a, b) =>
|
|
|
|
| 97 |
: [];
|
| 98 |
const galleryMapSamples = gallerySamples.filter((sample) => distanceBetweenKm(mapCenter, sample.center) <= 30);
|
| 99 |
const nearbyPosts = useMemo(() => {
|
|
@@ -125,7 +130,7 @@ export default function NearbySampleRoutesCard({
|
|
| 125 |
id: sample.id,
|
| 126 |
position: sample.center,
|
| 127 |
title: sample.title,
|
| 128 |
-
kind: sample.label === "dog" ? "sampleDog" : sample.label === "t_shirt" ? "sampleTshirt" : "sampleStar",
|
| 129 |
}));
|
| 130 |
const selectedMapRoutes: MapRouteLayer[] =
|
| 131 |
selectedSample?.route && selectedSample.route.length > 1
|
|
@@ -163,7 +168,7 @@ export default function NearbySampleRoutesCard({
|
|
| 163 |
|
| 164 |
useEffect(() => {
|
| 165 |
let isMounted = true;
|
| 166 |
-
void Promise.allSettled(["/demo-sample-runs.json", "/tshirt-sample-runs.json"].map(async (url) => {
|
| 167 |
const response = await fetch(url);
|
| 168 |
if (!response.ok) throw new Error("Sample GPX data unavailable");
|
| 169 |
return response.json() as Promise<DemoSampleRun[]>;
|
|
@@ -228,7 +233,7 @@ export default function NearbySampleRoutesCard({
|
|
| 228 |
selectedMarkerId={selectedSampleId ?? (selectedPostId ? `post-${selectedPostId}` : null)}
|
| 229 |
onMarkerClick={(marker) => {
|
| 230 |
if (marker.id !== "picked-recommendation-origin") setPickedPoint(null);
|
| 231 |
-
if (marker.kind === "sampleDog" || marker.kind === "sampleStar" || marker.kind === "sampleTshirt") {
|
| 232 |
setSelectedPostId(null);
|
| 233 |
setSelectedSampleId((current) => current === marker.id ? null : marker.id);
|
| 234 |
} else if (marker.kind === "communityPost") {
|
|
@@ -273,7 +278,7 @@ export default function NearbySampleRoutesCard({
|
|
| 273 |
)}
|
| 274 |
<div className="flex items-start justify-between gap-3"><div className="min-w-0">
|
| 275 |
<p className="truncate text-sm font-black text-black">
|
| 276 |
-
{selectedSample ? selectedSample.title : sampleGalleryLabel ? `${sampleGalleryLabel === "dog" ? "강아지" : sampleGalleryLabel === "t_shirt" ? "티셔츠" : "별"} 샘플 ${gallerySamples.length}개` : selectedPost ? selectedPost.title || "게시물 루트" : "주변 러닝 경로"}
|
| 277 |
</p>
|
| 278 |
<p className="mt-1 text-xs leading-5 text-[#666]">
|
| 279 |
{selectedSample
|
|
@@ -288,20 +293,22 @@ export default function NearbySampleRoutesCard({
|
|
| 288 |
</p>
|
| 289 |
</div></div>
|
| 290 |
{sampleRuns.length > 0 && <div className="mt-3 flex flex-wrap gap-2" aria-label="AI 샘플 러닝 미리보기">
|
| 291 |
-
{(["dog", "symbol_star", "t_shirt"] as const).map((label) => <button key={label} type="button" onClick={() => {
|
| 292 |
setSelectedPostId(null); setSelectedSampleId(null); setSampleGalleryLabel((current) => current === label ? null : label);
|
| 293 |
}} className={`rounded-full border px-3 py-2 text-xs font-bold ${sampleGalleryLabel === label ? "border-black bg-black text-white" : "border-black/10 bg-[#f7f7f7] text-black"}`}>
|
| 294 |
-
{label === "dog" ? "🐕 강아지" : label === "t_shirt" ? "👕 티셔츠" : "★ 별"} 샘플 {sampleRuns.filter((sample) => sample.label === label).length}개 보기
|
| 295 |
</button>)}
|
| 296 |
</div>}
|
| 297 |
{sampleGalleryLabel && <div className="mt-3 max-h-52 overflow-y-auto rounded-2xl border border-black/10 p-2" aria-label="AI 샘플 전체 목록"><div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
| 298 |
{gallerySamples.map((sample) => <button key={sample.id} type="button" onClick={() => setSelectedSampleId((current) => current === sample.id ? null : sample.id)} className={`rounded-xl px-3 py-2 text-left text-xs font-bold ${selectedSampleId === sample.id ? "bg-black text-white" : "bg-[#f7f7f7] text-black"}`}>
|
| 299 |
{sample.title} · {sample.distanceKm.toFixed(1)}km<span className="block font-normal opacity-70">지도 중심에서 약 {Math.round(distanceBetweenKm(mapCenter, sample.center))}km</span>
|
|
|
|
| 300 |
</button>)}
|
| 301 |
</div></div>}
|
| 302 |
{!sampleGalleryLabel && nearbySamples.length > 0 && <div className="mt-3 flex gap-2 overflow-x-auto pb-1" aria-label="주변 AI 샘플 러닝">
|
| 303 |
{nearbySamples.map(({ sample }) => <button key={sample.id} type="button" onClick={() => { setSelectedPostId(null); setSelectedSampleId((current) => current === sample.id ? null : sample.id); }} className={`shrink-0 rounded-full border px-3 py-2 text-xs font-bold ${selectedSampleId === sample.id ? "border-black bg-black text-white" : "border-black/10 bg-white text-black"}`}>
|
| 304 |
-
{sample.label === "dog" ? "🐕" : sample.label === "t_shirt" ? "👕" : "★"} {sample.distanceKm.toFixed(1)}km
|
|
|
|
| 305 |
</button>)}
|
| 306 |
</div>}
|
| 307 |
{selectedSample ? <><p className="mt-3 text-xs text-[#666]">이 경로는 AI 샘플입니다. 실제 통행 가능 여부를 확인하고 원본 시작점 근처에서 달려주세요.</p><button type="button" onClick={handleStartSelectedSampleRoute} className="mt-3 h-10 w-full rounded-full bg-black text-sm font-black text-white">이 루트로 달리기</button></> : <button type="button" onClick={handleStartSelectedPostRoute} disabled={!selectedPost} className="mt-3 h-10 w-full rounded-full bg-black text-sm font-black text-white disabled:bg-black/20">이 루트로 달리기</button>}
|
|
|
|
| 10 |
import { fetchCommunityPostsFromApi } from "../_utils/communityApi";
|
| 11 |
import { prepareCoursePreview } from "../_utils/coursePreview";
|
| 12 |
import { withSampleOrientation } from "../_utils/sampleRouteOrientation";
|
| 13 |
+
import { compareEnvironment, environmentLabel } from "../_utils/runningEnvironment";
|
| 14 |
+
import { useRunningEnvironment } from "../_utils/useRunningEnvironment";
|
| 15 |
|
| 16 |
type Point = [number, number];
|
| 17 |
|
|
|
|
| 23 |
type DemoSampleRun = {
|
| 24 |
displayRotationDeg?: number;
|
| 25 |
id: string;
|
| 26 |
+
label: "dog" | "symbol_star" | "t_shirt" | "heart";
|
| 27 |
title: string;
|
| 28 |
distanceKm: number;
|
| 29 |
center: Point;
|
|
|
|
| 84 |
|
| 85 |
const selectedPost = communityPosts.find((post) => post.id === selectedPostId) ?? null;
|
| 86 |
const selectedSample = sampleRuns.find((sample) => sample.id === selectedSampleId) ?? null;
|
| 87 |
+
const { scores, loading: environmentLoading } = useRunningEnvironment(sampleRuns);
|
| 88 |
+
const sampleEnvironment = (id: string) => environmentLabel(scores?.get(id), environmentLoading);
|
| 89 |
const nearbySamples = useMemo(() =>
|
| 90 |
sampleRuns
|
| 91 |
.map((sample) => ({ sample, distanceKm: distanceBetweenKm(mapCenter, sample.center) }))
|
| 92 |
.filter(({ distanceKm }) => distanceKm <= Math.max(radiusKm, 1))
|
| 93 |
+
.sort((a, b) => compareEnvironment(scores?.get(a.sample.id), scores?.get(b.sample.id)) || a.distanceKm - b.distanceKm)
|
| 94 |
.slice(0, 12),
|
| 95 |
+
[mapCenter, radiusKm, sampleRuns, scores]
|
| 96 |
);
|
| 97 |
const gallerySamples = sampleGalleryLabel
|
| 98 |
? sampleRuns
|
| 99 |
.filter((sample) => sample.label === sampleGalleryLabel)
|
| 100 |
+
.sort((a, b) => compareEnvironment(scores?.get(a.id), scores?.get(b.id)) ||
|
| 101 |
+
distanceBetweenKm(mapCenter, a.center) - distanceBetweenKm(mapCenter, b.center))
|
| 102 |
: [];
|
| 103 |
const galleryMapSamples = gallerySamples.filter((sample) => distanceBetweenKm(mapCenter, sample.center) <= 30);
|
| 104 |
const nearbyPosts = useMemo(() => {
|
|
|
|
| 130 |
id: sample.id,
|
| 131 |
position: sample.center,
|
| 132 |
title: sample.title,
|
| 133 |
+
kind: sample.label === "dog" ? "sampleDog" : sample.label === "t_shirt" ? "sampleTshirt" : sample.label === "heart" ? "sampleHeart" : "sampleStar",
|
| 134 |
}));
|
| 135 |
const selectedMapRoutes: MapRouteLayer[] =
|
| 136 |
selectedSample?.route && selectedSample.route.length > 1
|
|
|
|
| 168 |
|
| 169 |
useEffect(() => {
|
| 170 |
let isMounted = true;
|
| 171 |
+
void Promise.allSettled(["/demo-sample-runs.json", "/tshirt-sample-runs.json", "/heart-sample-runs.json"].map(async (url) => {
|
| 172 |
const response = await fetch(url);
|
| 173 |
if (!response.ok) throw new Error("Sample GPX data unavailable");
|
| 174 |
return response.json() as Promise<DemoSampleRun[]>;
|
|
|
|
| 233 |
selectedMarkerId={selectedSampleId ?? (selectedPostId ? `post-${selectedPostId}` : null)}
|
| 234 |
onMarkerClick={(marker) => {
|
| 235 |
if (marker.id !== "picked-recommendation-origin") setPickedPoint(null);
|
| 236 |
+
if (marker.kind === "sampleDog" || marker.kind === "sampleStar" || marker.kind === "sampleTshirt" || marker.kind === "sampleHeart") {
|
| 237 |
setSelectedPostId(null);
|
| 238 |
setSelectedSampleId((current) => current === marker.id ? null : marker.id);
|
| 239 |
} else if (marker.kind === "communityPost") {
|
|
|
|
| 278 |
)}
|
| 279 |
<div className="flex items-start justify-between gap-3"><div className="min-w-0">
|
| 280 |
<p className="truncate text-sm font-black text-black">
|
| 281 |
+
{selectedSample ? selectedSample.title : sampleGalleryLabel ? `${sampleGalleryLabel === "dog" ? "강아지" : sampleGalleryLabel === "t_shirt" ? "티셔츠" : sampleGalleryLabel === "heart" ? "하트" : "별"} 샘플 ${gallerySamples.length}개` : selectedPost ? selectedPost.title || "게시물 루트" : "주변 러닝 경로"}
|
| 282 |
</p>
|
| 283 |
<p className="mt-1 text-xs leading-5 text-[#666]">
|
| 284 |
{selectedSample
|
|
|
|
| 293 |
</p>
|
| 294 |
</div></div>
|
| 295 |
{sampleRuns.length > 0 && <div className="mt-3 flex flex-wrap gap-2" aria-label="AI 샘플 러닝 미리보기">
|
| 296 |
+
{(["dog", "symbol_star", "t_shirt", "heart"] as const).map((label) => <button key={label} type="button" onClick={() => {
|
| 297 |
setSelectedPostId(null); setSelectedSampleId(null); setSampleGalleryLabel((current) => current === label ? null : label);
|
| 298 |
}} className={`rounded-full border px-3 py-2 text-xs font-bold ${sampleGalleryLabel === label ? "border-black bg-black text-white" : "border-black/10 bg-[#f7f7f7] text-black"}`}>
|
| 299 |
+
{label === "dog" ? "🐕 강아지" : label === "t_shirt" ? "👕 티셔츠" : label === "heart" ? "♥ 하트" : "★ 별"} 샘플 {sampleRuns.filter((sample) => sample.label === label).length}개 보기
|
| 300 |
</button>)}
|
| 301 |
</div>}
|
| 302 |
{sampleGalleryLabel && <div className="mt-3 max-h-52 overflow-y-auto rounded-2xl border border-black/10 p-2" aria-label="AI 샘플 전체 목록"><div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
| 303 |
{gallerySamples.map((sample) => <button key={sample.id} type="button" onClick={() => setSelectedSampleId((current) => current === sample.id ? null : sample.id)} className={`rounded-xl px-3 py-2 text-left text-xs font-bold ${selectedSampleId === sample.id ? "bg-black text-white" : "bg-[#f7f7f7] text-black"}`}>
|
| 304 |
{sample.title} · {sample.distanceKm.toFixed(1)}km<span className="block font-normal opacity-70">지도 중심에서 약 {Math.round(distanceBetweenKm(mapCenter, sample.center))}km</span>
|
| 305 |
+
<span className="block font-normal">러닝 환경 점수 {sampleEnvironment(sample.id)}</span>
|
| 306 |
</button>)}
|
| 307 |
</div></div>}
|
| 308 |
{!sampleGalleryLabel && nearbySamples.length > 0 && <div className="mt-3 flex gap-2 overflow-x-auto pb-1" aria-label="주변 AI 샘플 러닝">
|
| 309 |
{nearbySamples.map(({ sample }) => <button key={sample.id} type="button" onClick={() => { setSelectedPostId(null); setSelectedSampleId((current) => current === sample.id ? null : sample.id); }} className={`shrink-0 rounded-full border px-3 py-2 text-xs font-bold ${selectedSampleId === sample.id ? "border-black bg-black text-white" : "border-black/10 bg-white text-black"}`}>
|
| 310 |
+
{sample.label === "dog" ? "🐕" : sample.label === "t_shirt" ? "👕" : sample.label === "heart" ? "♥" : "★"} {sample.distanceKm.toFixed(1)}km
|
| 311 |
+
<span className="block font-normal">러닝 환경 점수 {sampleEnvironment(sample.id)}</span>
|
| 312 |
</button>)}
|
| 313 |
</div>}
|
| 314 |
{selectedSample ? <><p className="mt-3 text-xs text-[#666]">이 경로는 AI 샘플입니다. 실제 통행 가능 여부를 확인하고 원본 시작점 근처에서 달려주세요.</p><button type="button" onClick={handleStartSelectedSampleRoute} className="mt-3 h-10 w-full rounded-full bg-black text-sm font-black text-white">이 루트로 달리기</button></> : <button type="button" onClick={handleStartSelectedPostRoute} disabled={!selectedPost} className="mt-3 h-10 w-full rounded-full bg-black text-sm font-black text-white disabled:bg-black/20">이 루트로 달리기</button>}
|
main/app/_utils/generatedRouteDetails.ts
CHANGED
|
@@ -16,11 +16,13 @@ export type GeneratedRoute = {
|
|
| 16 |
top1_rerank_score?: number;
|
| 17 |
top1_shape?: number;
|
| 18 |
selected_label?: string | null;
|
|
|
|
| 19 |
selected_label_score?: number | null;
|
| 20 |
selected_label_rerank_score?: number | null;
|
| 21 |
selected_label_margin?: number | null;
|
| 22 |
is_loop?: boolean;
|
| 23 |
route_quality?: {
|
|
|
|
| 24 |
art_ready?: boolean | null;
|
| 25 |
retrace_ratio?: number;
|
| 26 |
intentional_retrace_ratio?: number;
|
|
|
|
| 16 |
top1_rerank_score?: number;
|
| 17 |
top1_shape?: number;
|
| 18 |
selected_label?: string | null;
|
| 19 |
+
art_template_name?: string;
|
| 20 |
selected_label_score?: number | null;
|
| 21 |
selected_label_rerank_score?: number | null;
|
| 22 |
selected_label_margin?: number | null;
|
| 23 |
is_loop?: boolean;
|
| 24 |
route_quality?: {
|
| 25 |
+
shape_similarity?: number;
|
| 26 |
art_ready?: boolean | null;
|
| 27 |
retrace_ratio?: number;
|
| 28 |
intentional_retrace_ratio?: number;
|
main/app/_utils/regionalCrowd.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { RunPoint } from "./runningEnvironment";
|
| 2 |
+
|
| 3 |
+
export type CrowdProfile = { weekday: (number | null)[]; weekend: (number | null)[] };
|
| 4 |
+
export type CrowdArea = CrowdProfile & {
|
| 5 |
+
id: string; kind?: "pedestrian-camera" | "hourly-grid"; observedTo?: string;
|
| 6 |
+
polygons?: RunPoint[][][]; center?: RunPoint; radiusM?: number;
|
| 7 |
+
};
|
| 8 |
+
|
| 9 |
+
export function koreanCrowdTime(timestamp: number) {
|
| 10 |
+
const local = new Date(timestamp + 9 * 3600000);
|
| 11 |
+
return { hour: local.getUTCHours(), weekend: [0, 6].includes(local.getUTCDay()), timestamp };
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export function isCurrentCrowdProfile(observedTo: string | undefined, timestamp: number) {
|
| 15 |
+
if (observedTo === undefined) return true; // Existing profiles use their original policy.
|
| 16 |
+
if (!/^\d{8}$/.test(observedTo)) return false;
|
| 17 |
+
const last = Date.parse(`${observedTo.slice(0, 4)}-${observedTo.slice(4, 6)}-${observedTo.slice(6)}T00:00:00+09:00`);
|
| 18 |
+
return Number.isFinite(last) && timestamp >= last && timestamp - last < 91 * 86400000;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
export function crowdRisk(area: CrowdProfile, time: ReturnType<typeof koreanCrowdTime>) {
|
| 22 |
+
const ratio = (time.weekend ? area.weekend : area.weekday)?.[time.hour];
|
| 23 |
+
if (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio < 0) return undefined;
|
| 24 |
+
// Compare a location with its own usual daily level, not with another city's counts.
|
| 25 |
+
return Math.max(0.15, Math.min(0.85, 0.5 + (ratio - 1) * 0.35));
|
| 26 |
+
}
|
main/app/_utils/runningEnvironment.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export type RunPoint = [number, number];
|
| 2 |
+
export type EnvironmentScore = {
|
| 3 |
+
score: number | null;
|
| 4 |
+
coverage: number;
|
| 5 |
+
sources: string[];
|
| 6 |
+
details?: {
|
| 7 |
+
runners?: number;
|
| 8 |
+
runnerStatus?: "reported" | "present" | "none" | "unavailable";
|
| 9 |
+
road?: { cautionPercent: number; coveragePercent: number; unclearSeparationPercent?: number; reasons: string[] };
|
| 10 |
+
crowd?: { level: "높음" | "보통" | "낮음"; basis: "실시간 관측" | "시간대별 추정" | "실시간·시간대별 자료" };
|
| 11 |
+
};
|
| 12 |
+
};
|
| 13 |
+
export type Signal = { risk: number; coverage: number; source: string; weight: number };
|
| 14 |
+
|
| 15 |
+
// Unknown observations stay neutral; missing sources never become evidence of quiet.
|
| 16 |
+
export function environmentScore(signals: Signal[]): EnvironmentScore {
|
| 17 |
+
const available = signals.filter((s) => s.coverage > 0);
|
| 18 |
+
const totalWeight = signals.reduce((sum, s) => sum + s.weight, 0);
|
| 19 |
+
const measured = available.reduce((sum, s) => sum + s.weight * s.coverage, 0);
|
| 20 |
+
return {
|
| 21 |
+
score: measured > 0 ? Math.round(100 * (1 - (
|
| 22 |
+
available.reduce((sum, s) => sum + s.weight * s.coverage * s.risk, 0) +
|
| 23 |
+
(totalWeight - measured) * 0.5
|
| 24 |
+
) / totalWeight)) / 10 : null,
|
| 25 |
+
coverage: totalWeight ? measured / totalWeight : 0,
|
| 26 |
+
sources: available.map((s) => s.source),
|
| 27 |
+
};
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
export function compareEnvironment(a?: EnvironmentScore, b?: EnvironmentScore): number {
|
| 31 |
+
return (b?.score ?? -1) - (a?.score ?? -1);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
export function environmentLabel(value?: EnvironmentScore, loading = false): string {
|
| 35 |
+
if (value?.score == null) return loading ? "확인 중" : "자료 부족";
|
| 36 |
+
return `${value.score.toFixed(1)}/10${value.coverage < 0.6 ? " (부분 자료)" : ""}`;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
export function cellKey([lat, lon]: RunPoint, scale: number): string {
|
| 40 |
+
return `${Math.floor(lat * scale)}:${Math.floor(lon * scale)}`;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export function segmentLength(a: RunPoint, b: RunPoint): number {
|
| 44 |
+
return Math.hypot((b[0] - a[0]) * 111320,
|
| 45 |
+
(b[1] - a[1]) * 111320 * Math.cos((a[0] + b[0]) * Math.PI / 360));
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// Sample by distance, not by source vertex count, so dense GPX sections do not dominate.
|
| 49 |
+
export function sampleEnvironmentRoute(route: RunPoint[], limit = 500): RunPoint[] {
|
| 50 |
+
const lengths = route.slice(1).map((b, i) => segmentLength(route[i], b));
|
| 51 |
+
const total = lengths.reduce((a, b) => a + b, 0);
|
| 52 |
+
if (!(total > 0)) return [];
|
| 53 |
+
const count = Math.min(limit, Math.max(1, Math.ceil(total / 35)));
|
| 54 |
+
let segment = 0;
|
| 55 |
+
let start = 0;
|
| 56 |
+
return Array.from({ length: count }, (_, i) => {
|
| 57 |
+
const distance = (i + 0.5) * total / count;
|
| 58 |
+
while (segment < lengths.length - 1 && start + lengths[segment] <= distance) start += lengths[segment++];
|
| 59 |
+
const t = (distance - start) / lengths[segment];
|
| 60 |
+
const a = route[segment], b = route[segment + 1];
|
| 61 |
+
return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
|
| 62 |
+
});
|
| 63 |
+
}
|
main/app/_utils/useRunningEnvironment.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import { useEffect, useMemo, useState } from "react";
|
| 4 |
+
import { sampleEnvironmentRoute, type EnvironmentScore, type RunPoint } from "./runningEnvironment";
|
| 5 |
+
|
| 6 |
+
export function useRunningEnvironment(routes: { id: string; route: RunPoint[] }[]) {
|
| 7 |
+
const input = useMemo(() => JSON.stringify(routes.map(({ id, route }) =>
|
| 8 |
+
[id, sampleEnvironmentRoute(route)])), [routes]);
|
| 9 |
+
const [snapshot, setSnapshot] = useState<{ input: string; values: Map<string, EnvironmentScore> }>();
|
| 10 |
+
useEffect(() => {
|
| 11 |
+
const items = JSON.parse(input) as [string, RunPoint[]][];
|
| 12 |
+
if (!items.length) return;
|
| 13 |
+
const controller = new AbortController();
|
| 14 |
+
let running = false;
|
| 15 |
+
async function update() {
|
| 16 |
+
if (running || controller.signal.aborted || document.hidden) return;
|
| 17 |
+
running = true;
|
| 18 |
+
const values = new Map<string, EnvironmentScore>();
|
| 19 |
+
try {
|
| 20 |
+
for (let offset = 0; offset < items.length && !controller.signal.aborted; offset += 24) {
|
| 21 |
+
const chunks = [items.slice(offset, offset + 12), items.slice(offset + 12, offset + 24)];
|
| 22 |
+
await Promise.all(chunks.filter((chunk) => chunk.length).map(async (chunk) => {
|
| 23 |
+
try {
|
| 24 |
+
const response = await fetch("/api/running-environment", {
|
| 25 |
+
method: "POST", headers: { "Content-Type": "application/json" },
|
| 26 |
+
body: JSON.stringify(chunk.map((item) => item[1])), signal: controller.signal,
|
| 27 |
+
});
|
| 28 |
+
if (!response.ok) return;
|
| 29 |
+
const result = await response.json() as EnvironmentScore[];
|
| 30 |
+
chunk.forEach(([id], i) => { if (result[i]) values.set(id, result[i]); });
|
| 31 |
+
} catch { /* Unavailable signals remain unknown. */ }
|
| 32 |
+
}));
|
| 33 |
+
}
|
| 34 |
+
if (!controller.signal.aborted) setSnapshot({ input, values });
|
| 35 |
+
} finally { running = false; }
|
| 36 |
+
}
|
| 37 |
+
void update();
|
| 38 |
+
const timer = window.setInterval(update, 60000);
|
| 39 |
+
document.addEventListener("visibilitychange", update);
|
| 40 |
+
return () => {
|
| 41 |
+
controller.abort();
|
| 42 |
+
window.clearInterval(timer);
|
| 43 |
+
document.removeEventListener("visibilitychange", update);
|
| 44 |
+
};
|
| 45 |
+
}, [input]);
|
| 46 |
+
return { scores: snapshot?.input === input ? snapshot.values : undefined,
|
| 47 |
+
loading: routes.length > 0 && snapshot?.input !== input };
|
| 48 |
+
}
|
main/app/api/running-environment/route.ts
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { readFile } from "node:fs/promises";
|
| 2 |
+
import { join } from "node:path";
|
| 3 |
+
import { NextResponse } from "next/server";
|
| 4 |
+
import { cellKey, environmentScore, type EnvironmentScore, type RunPoint } from "../../_utils/runningEnvironment";
|
| 5 |
+
import { crowdRisk, isCurrentCrowdProfile, koreanCrowdTime, type CrowdArea } from "../../_utils/regionalCrowd";
|
| 6 |
+
|
| 7 |
+
export const runtime = "nodejs";
|
| 8 |
+
export const dynamic = "force-dynamic";
|
| 9 |
+
type Road = [RunPoint, RunPoint, number, number, (RunPoint[][] | null)?, string[]?];
|
| 10 |
+
type Area = { code: string; polygons: RunPoint[][][] };
|
| 11 |
+
const directory = process.env.RUN_ENV_DATA_DIR;
|
| 12 |
+
const roadCache = new Map<string, Promise<Record<string, Road[]>>>();
|
| 13 |
+
const liveCache = new Map<string, { until: number; result: Promise<number | undefined> }>();
|
| 14 |
+
let areaIndex: Promise<(Area & { bounds: number[] })[]> | undefined;
|
| 15 |
+
type RunnerDensity = { counts: Record<string, number>; occupied: Set<string> | null };
|
| 16 |
+
let activeCache: { until: number; result: Promise<RunnerDensity | null> } | undefined;
|
| 17 |
+
let historicalIndex: Promise<Map<string, CrowdArea[]>> | undefined;
|
| 18 |
+
|
| 19 |
+
async function file<T>(name: string, fallback: T): Promise<T> {
|
| 20 |
+
if (!directory) return fallback;
|
| 21 |
+
try { return JSON.parse(await readFile(join(directory, name), "utf8")) as T; }
|
| 22 |
+
catch { return fallback; }
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
async function seoulApiKey() {
|
| 26 |
+
const direct = process.env.RUN_ENV_SEOUL_API_KEY?.trim();
|
| 27 |
+
if (direct) return /^[a-zA-Z0-9_-]+$/.test(direct) ? direct : undefined;
|
| 28 |
+
const path = process.env.RUN_ENV_SEOUL_API_KEY_FILE;
|
| 29 |
+
if (!path) return undefined;
|
| 30 |
+
try {
|
| 31 |
+
const key = (await readFile(path, "utf8")).trim();
|
| 32 |
+
return /^[a-zA-Z0-9_-]+$/.test(key) ? key : undefined;
|
| 33 |
+
} catch { return undefined; }
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
function seoulAreas() {
|
| 37 |
+
return areaIndex ??= file<Area[]>("seoul-areas.json", []).then((areas) => areas.map((area) => {
|
| 38 |
+
const bounds = [90, 180, -90, -180];
|
| 39 |
+
for (const [outer] of area.polygons) for (const [lat, lon] of outer) {
|
| 40 |
+
bounds[0] = Math.min(bounds[0], lat); bounds[1] = Math.min(bounds[1], lon);
|
| 41 |
+
bounds[2] = Math.max(bounds[2], lat); bounds[3] = Math.max(bounds[3], lon);
|
| 42 |
+
}
|
| 43 |
+
return { ...area, bounds };
|
| 44 |
+
}));
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
async function roadRisk(point: RunPoint) {
|
| 48 |
+
const tile = cellKey(point, 10);
|
| 49 |
+
let pending = roadCache.get(tile);
|
| 50 |
+
if (!pending) {
|
| 51 |
+
if (roadCache.size >= 128) roadCache.delete(roadCache.keys().next().value!);
|
| 52 |
+
pending = file<Record<string, Road[]>>(`roads/${tile.replace(":", "_")}.json`, {});
|
| 53 |
+
roadCache.set(tile, pending);
|
| 54 |
+
}
|
| 55 |
+
const items = (await pending)[cellKey(point, 1000)] ?? [];
|
| 56 |
+
const cos = Math.cos(point[0] * Math.PI / 180);
|
| 57 |
+
const matches = items.map(([a, b, risk, priority, polygon, reasons]) => {
|
| 58 |
+
// Legacy OSM indexes encode a shared street or absent sidewalk as exactly .76.
|
| 59 |
+
const evidence = reasons ?? (priority === 1 && risk === 0.76 ? ["보도 없음 또는 차량과 공간 공유"] : []);
|
| 60 |
+
if (polygon) {
|
| 61 |
+
const [outer, ...holes] = polygon;
|
| 62 |
+
return { distance: inside(point, outer) && !holes.some((hole) => inside(point, hole)) ? 0 : Infinity, risk, priority, reasons: evidence };
|
| 63 |
+
}
|
| 64 |
+
const x = (a[1] - point[1]) * cos, y = a[0] - point[0];
|
| 65 |
+
const dx = (b[1] - a[1]) * cos, dy = b[0] - a[0];
|
| 66 |
+
const t = Math.max(0, Math.min(1, -(x * dx + y * dy) / (dx * dx + dy * dy || 1)));
|
| 67 |
+
return { distance: Math.hypot(x + dx * t, y + dy * t) * 111320, risk, priority, reasons: evidence };
|
| 68 |
+
}).filter((item) => item.distance <= 14).sort((a, b) => a.distance - b.distance);
|
| 69 |
+
if (!matches.length) return undefined;
|
| 70 |
+
const close = matches.filter((item) => item.distance <= matches[0].distance + 3);
|
| 71 |
+
const priority = Math.max(...close.map((item) => item.priority));
|
| 72 |
+
const candidates = close.filter((item) => item.priority === priority);
|
| 73 |
+
// Ambiguous parallel paths: do not silently choose the more favorable one.
|
| 74 |
+
return candidates.reduce((worst, item) => item.risk > worst.risk ? item : worst);
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
function inside([y, x]: RunPoint, ring: RunPoint[]): boolean {
|
| 78 |
+
let result = false;
|
| 79 |
+
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
| 80 |
+
const [yi, xi] = ring[i], [yj, xj] = ring[j];
|
| 81 |
+
if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) result = !result;
|
| 82 |
+
}
|
| 83 |
+
return result;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
function historicalAreas() {
|
| 87 |
+
return historicalIndex ??= Promise.all(["regional-crowd.json", "pedestrian-crowd.json", "gyeonggi-crowd.json"].map((name) =>
|
| 88 |
+
file<{ areas: CrowdArea[] }>(name, { areas: [] }))).then((inputs) => {
|
| 89 |
+
const bins = new Map<string, CrowdArea[]>();
|
| 90 |
+
for (const area of inputs.flatMap(({ areas }) => areas)) {
|
| 91 |
+
const points = area.polygons?.flatMap(([outer]) => outer) ?? (area.center ? [area.center] : []);
|
| 92 |
+
if (!points.length) continue;
|
| 93 |
+
const padding = area.center ? (area.radiusM ?? 0) / 80000 : 0;
|
| 94 |
+
const bounds = points.reduce(([s, w, n, e], [lat, lon]) =>
|
| 95 |
+
[Math.min(s, lat), Math.min(w, lon), Math.max(n, lat), Math.max(e, lon)], [90, 180, -90, -180]);
|
| 96 |
+
const [s, w, n, e] = bounds.map((value, i) => Math.floor((value + (i < 2 ? -padding : padding)) * 100));
|
| 97 |
+
for (let y = s; y <= n; y++) for (let x = w; x <= e; x++) {
|
| 98 |
+
const key = `${y}:${x}`;
|
| 99 |
+
if (!bins.has(key)) bins.set(key, []);
|
| 100 |
+
bins.get(key)!.push(area);
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
return bins;
|
| 104 |
+
});
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
function typicalRisk(p: RunPoint, index: Map<string, CrowdArea[]>, time: ReturnType<typeof koreanCrowdTime>) {
|
| 108 |
+
const risks = (index.get(cellKey(p, 100)) ?? []).filter((area) => {
|
| 109 |
+
if (!isCurrentCrowdProfile(area.observedTo, time.timestamp)) return false;
|
| 110 |
+
if (area.polygons) return area.polygons.some(([outer, ...holes]) =>
|
| 111 |
+
inside(p, outer) && !holes.some((hole) => inside(p, hole)));
|
| 112 |
+
if (!area.center || !area.radiusM) return false;
|
| 113 |
+
const [lat, lon] = area.center;
|
| 114 |
+
return Math.hypot(p[0] - lat, (p[1] - lon) * Math.cos(lat * Math.PI / 180)) * 111320 <= area.radiusM;
|
| 115 |
+
}).flatMap((area) => {
|
| 116 |
+
const risk = crowdRisk(area, time);
|
| 117 |
+
return risk === undefined ? [] : [{ risk, camera: area.kind === "pedestrian-camera" }];
|
| 118 |
+
});
|
| 119 |
+
const camera = risks.filter((item) => item.camera);
|
| 120 |
+
const chosen = camera.length ? camera : risks;
|
| 121 |
+
return chosen.length ? { risk: Math.max(...chosen.map((item) => item.risk)), camera: camera.length > 0 } : undefined;
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
function liveRisk(code: string, key: string) {
|
| 125 |
+
if (!/^POI\d{3,5}$/.test(code) || (key === "sample" && code !== "POI009")) return Promise.resolve(undefined);
|
| 126 |
+
const previous = liveCache.get(code);
|
| 127 |
+
if (previous && previous.until > Date.now()) return previous.result;
|
| 128 |
+
const result = (async () => {
|
| 129 |
+
try {
|
| 130 |
+
const response = await fetch(`http://openapi.seoul.go.kr:8088/${encodeURIComponent(key)}/json/citydata/1/1/${code}`,
|
| 131 |
+
{ cache: "no-store", signal: AbortSignal.timeout(4000) });
|
| 132 |
+
if (!response.ok) return undefined;
|
| 133 |
+
const area = (await response.json()).CITYDATA?.LIVE_PPLTN_STTS?.[0];
|
| 134 |
+
if (area?.AREA_CD !== code || area?.REPLACE_YN === "Y") return undefined;
|
| 135 |
+
const timestamp = Date.parse(String(area?.PPLTN_TIME ?? "").replace(" ", "T") + "+09:00");
|
| 136 |
+
const age = Date.now() - timestamp;
|
| 137 |
+
if (!Number.isFinite(age) || age > 20 * 60000 || age < -60000) return undefined;
|
| 138 |
+
return ({ "여유": 0.15, "보통": 0.45, "약간 붐빔": 0.7, "붐빔": 0.95 } as Record<string, number>)[area?.AREA_CONGEST_LVL];
|
| 139 |
+
} catch { return undefined; }
|
| 140 |
+
})();
|
| 141 |
+
liveCache.set(code, { until: Date.now() + 60000, result });
|
| 142 |
+
return result;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
async function runnerCells(): Promise<RunnerDensity | null> {
|
| 146 |
+
const key = process.env.RUN_ENV_INTERNAL_KEY;
|
| 147 |
+
if (!key) return null;
|
| 148 |
+
try {
|
| 149 |
+
const base = process.env.RUN_ENV_AUTH_URL ?? process.env.NEXT_INTERNAL_API_PROXY_TARGET ?? "http://localhost:8000";
|
| 150 |
+
const response = await fetch(`${base}/api/v1/auth/active-run/environment-density`, {
|
| 151 |
+
headers: { "X-Run-Environment-Key": key }, cache: "no-store", signal: AbortSignal.timeout(3000),
|
| 152 |
+
});
|
| 153 |
+
if (!response.ok) return null;
|
| 154 |
+
const { cells, occupiedCells } = await response.json();
|
| 155 |
+
if (!cells || typeof cells !== "object" || Array.isArray(cells)) return null;
|
| 156 |
+
return { counts: cells, occupied: Array.isArray(occupiedCells) ? new Set(occupiedCells) : null };
|
| 157 |
+
} catch { return null; }
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
function nearbyRunnerCells([lat, lon]: RunPoint, includes: (key: string) => boolean) {
|
| 161 |
+
const row = Math.floor(lat * 200), col = Math.floor(lon * 200);
|
| 162 |
+
const matches: string[] = [];
|
| 163 |
+
for (let y = row - 1; y <= row + 1; y++) for (let x = col - 1; x <= col + 1; x++) {
|
| 164 |
+
const key = `${y}:${x}`;
|
| 165 |
+
if (!includes(key)) continue;
|
| 166 |
+
const dy = Math.max(y / 200 - lat, lat - (y + 1) / 200, 0);
|
| 167 |
+
const dx = Math.max(x / 200 - lon, lon - (x + 1) / 200, 0) * Math.cos(lat * Math.PI / 180);
|
| 168 |
+
if (Math.hypot(dy, dx) * 111320 <= 200) matches.push(key);
|
| 169 |
+
}
|
| 170 |
+
return matches;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
export async function POST(request: Request) {
|
| 174 |
+
let body: unknown;
|
| 175 |
+
try {
|
| 176 |
+
if (Number(request.headers.get("content-length")) > 350000) return NextResponse.json({}, { status: 413 });
|
| 177 |
+
const raw = await request.text();
|
| 178 |
+
if (raw.length > 350000) return NextResponse.json({}, { status: 413 });
|
| 179 |
+
body = JSON.parse(raw);
|
| 180 |
+
} catch { return NextResponse.json({}, { status: 400 }); }
|
| 181 |
+
if (!Array.isArray(body) || body.length > 12 || body.some((route) =>
|
| 182 |
+
!Array.isArray(route) || route.length > 500 || route.some((p) => !Array.isArray(p) ||
|
| 183 |
+
p.length !== 2 || !p.every(Number.isFinite) || Math.abs(p[0]) > 90 || Math.abs(p[1]) > 180))) {
|
| 184 |
+
return NextResponse.json({}, { status: 400 });
|
| 185 |
+
}
|
| 186 |
+
const routes = body as RunPoint[][];
|
| 187 |
+
if (!activeCache || activeCache.until <= Date.now()) activeCache = { until: Date.now() + 10000, result: runnerCells() };
|
| 188 |
+
const key = await seoulApiKey();
|
| 189 |
+
const [areas, runners, historical] = await Promise.all([key ? seoulAreas() : [], activeCache.result, historicalAreas()]);
|
| 190 |
+
const time = koreanCrowdTime(Date.now());
|
| 191 |
+
const coverage = (risks: (number | undefined)[], source: string, weight: number) => {
|
| 192 |
+
const known = risks.filter((risk): risk is number => risk !== undefined);
|
| 193 |
+
return { risk: known.length ? known.reduce((a, b) => a + b, 0) / known.length : 0.5,
|
| 194 |
+
coverage: risks.length ? known.length / risks.length : 0, source, weight };
|
| 195 |
+
};
|
| 196 |
+
const results = await Promise.all(routes.map(async (route) => {
|
| 197 |
+
const road = await Promise.all(route.map(roadRisk));
|
| 198 |
+
const crowd = await Promise.all(route.map(async (p) => {
|
| 199 |
+
if (!key || p[0] < 37.35 || p[0] > 37.75 || p[1] < 126.7 || p[1] > 127.25) return undefined;
|
| 200 |
+
const codes = areas.filter(({ bounds: [south, west, north, east], polygons }) =>
|
| 201 |
+
p[0] >= south && p[0] <= north && p[1] >= west && p[1] <= east &&
|
| 202 |
+
polygons.some(([outer, ...holes]) => inside(p, outer) && !holes.some((hole) => inside(p, hole))))
|
| 203 |
+
.map((a) => a.code);
|
| 204 |
+
const values = (await Promise.all(codes.map((code) => liveRisk(code, key)))).filter((n): n is number => n !== undefined);
|
| 205 |
+
return values.length ? Math.max(...values) : undefined;
|
| 206 |
+
}));
|
| 207 |
+
const activityCells = new Set<string>();
|
| 208 |
+
let hasNearbyRunner = false;
|
| 209 |
+
const active = route.map((p) => {
|
| 210 |
+
if (!runners) return undefined;
|
| 211 |
+
let count = 0;
|
| 212 |
+
for (const cell of nearbyRunnerCells(p, (key) => !!runners.occupied?.has(key) || runners.counts[key] >= 3)) {
|
| 213 |
+
hasNearbyRunner = true;
|
| 214 |
+
const publicCount = runners.counts[cell];
|
| 215 |
+
if (!Number.isSafeInteger(publicCount) || publicCount < 3) continue;
|
| 216 |
+
activityCells.add(cell);
|
| 217 |
+
count += publicCount;
|
| 218 |
+
}
|
| 219 |
+
return count >= 3 ? Math.min(1, 0.5 + count / 20) : undefined;
|
| 220 |
+
});
|
| 221 |
+
// Partition the one crowd weight between real observations and fallback estimates.
|
| 222 |
+
const typical = route.map((p, i) => crowd[i] === undefined ? typicalRisk(p, historical, time) : undefined);
|
| 223 |
+
const live = coverage(crowd, "지역 실시간 인구", 0.35);
|
| 224 |
+
const history = coverage(typical.map((item) => item?.camera ? undefined : item?.risk), "과거 시간대 혼잡 추정", 0.35);
|
| 225 |
+
const pedestrian = coverage(typical.map((item) => item?.camera ? item.risk : undefined), "시간대별 보행자 센서 관측", 0.35);
|
| 226 |
+
// Broader estimates receive 65% of the evidence strength of a live reading.
|
| 227 |
+
const generalCoverage = live.coverage + history.coverage * 0.65 + pedestrian.coverage * 0.85;
|
| 228 |
+
const generalRisk = generalCoverage ? (live.risk * live.coverage + history.risk * history.coverage * 0.65
|
| 229 |
+
+ pedestrian.risk * pedestrian.coverage * 0.85) / generalCoverage : 0.5;
|
| 230 |
+
const result: EnvironmentScore = environmentScore([coverage(road.map((item) => item?.risk), "보행로 구조", 0.25),
|
| 231 |
+
{ risk: generalRisk, coverage: generalCoverage, source: "지역 인구", weight: 0.45 },
|
| 232 |
+
coverage(active, "서비스 활동", 0.30)]);
|
| 233 |
+
result.sources = result.sources.flatMap((source) => source === "지역 인구"
|
| 234 |
+
? [live, pedestrian, history].filter((signal) => signal.coverage > 0).map((signal) => signal.source) : [source]);
|
| 235 |
+
const nearbyCount = [...activityCells].reduce((sum, cell) => sum + (runners?.counts[cell] ?? 0), 0);
|
| 236 |
+
// Weak carriageway evidence can influence the score, but cannot diagnose a sidewalk.
|
| 237 |
+
const measuredRoad = road.filter((item) => item && item.priority > 0);
|
| 238 |
+
const caution = measuredRoad.filter((item) => item!.risk >= 0.65 || item!.reasons.length > 0);
|
| 239 |
+
const unclearSeparationReason = "보도 없음 또는 차량과 공간 공유";
|
| 240 |
+
const unclearSeparationCount = caution.filter((item) => item!.reasons.includes(unclearSeparationReason)).length;
|
| 241 |
+
result.details = {
|
| 242 |
+
...(nearbyCount > 0 ? { runners: nearbyCount } : {}),
|
| 243 |
+
...(route.length ? { runnerStatus: nearbyCount > 0 ? "reported" : hasNearbyRunner ? "present" : runners?.occupied ? "none" : "unavailable" } : {}),
|
| 244 |
+
...(measuredRoad.length > 0 ? { road: {
|
| 245 |
+
cautionPercent: Math.round(100 * caution.length / measuredRoad.length),
|
| 246 |
+
coveragePercent: Math.round(100 * measuredRoad.length / route.length),
|
| 247 |
+
...(unclearSeparationCount > 0 ? { unclearSeparationPercent: Math.round(1000 * unclearSeparationCount / route.length) / 10 } : {}),
|
| 248 |
+
reasons: [...new Set(caution.flatMap((item) => item!.reasons))].filter((reason) => reason !== unclearSeparationReason),
|
| 249 |
+
} } : {}),
|
| 250 |
+
...(generalCoverage > 0 ? { crowd: {
|
| 251 |
+
level: generalRisk >= 0.65 ? "높음" : generalRisk < 0.4 ? "낮음" : "보통",
|
| 252 |
+
basis: live.coverage > 0 ? (history.coverage + pedestrian.coverage > 0 ? "실시간·시간대별 자료" : "실시간 관측") : "시간대별 추정",
|
| 253 |
+
} } : {}),
|
| 254 |
+
};
|
| 255 |
+
return result;
|
| 256 |
+
}));
|
| 257 |
+
return NextResponse.json(results, { headers: { "Cache-Control": "no-store" } });
|
| 258 |
+
}
|
main/app/route-results/[id]/page.tsx
CHANGED
|
@@ -7,6 +7,7 @@ import RunStartNoticeModal from "../../_components/RunStartNoticeModal";
|
|
| 7 |
import { PageContainer, PageHeader, SectionCard, EmptyState } from "../../_components/RunShapeUI";
|
| 8 |
import { FLOW_KEYS, issueUiFlowPermit } from "../../_utils/uiFlowGuard";
|
| 9 |
import { readCoursePreview, type CoursePreview } from "../../_utils/coursePreview";
|
|
|
|
| 10 |
import {
|
| 11 |
findGeneratedRouteDetail,
|
| 12 |
formatGeneratedRouteLabel,
|
|
@@ -167,6 +168,11 @@ function GeneratedRouteDetailPageContent() {
|
|
| 167 |
}, [routeId, courseKey]);
|
| 168 |
|
| 169 |
const routeCoords = record?.route.route_coords ?? [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
const center = record?.route.center ?? routeCoords[0] ?? DEFAULT_MAP_CENTER;
|
| 171 |
const shapeScore = record ? getGeneratedRouteAiShapeScore(record.route) : null;
|
| 172 |
const features = record ? getRouteFeatures(record) : [];
|
|
@@ -401,6 +407,41 @@ function GeneratedRouteDetailPageContent() {
|
|
| 401 |
<DetailStat label="지도 지점" value={`${routeCoords.length}개`} />
|
| 402 |
</div>
|
| 403 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
{!externalCourse && features.length > 0 ? (
|
| 405 |
<div className="mt-6 border-t border-[#e5e5e5] pt-5">
|
| 406 |
<h3 className="text-base font-semibold text-black">경로 특징</h3>
|
|
|
|
| 7 |
import { PageContainer, PageHeader, SectionCard, EmptyState } from "../../_components/RunShapeUI";
|
| 8 |
import { FLOW_KEYS, issueUiFlowPermit } from "../../_utils/uiFlowGuard";
|
| 9 |
import { readCoursePreview, type CoursePreview } from "../../_utils/coursePreview";
|
| 10 |
+
import { useRunningEnvironment } from "../../_utils/useRunningEnvironment";
|
| 11 |
import {
|
| 12 |
findGeneratedRouteDetail,
|
| 13 |
formatGeneratedRouteLabel,
|
|
|
|
| 168 |
}, [routeId, courseKey]);
|
| 169 |
|
| 170 |
const routeCoords = record?.route.route_coords ?? [];
|
| 171 |
+
const environmentInputs = useMemo(() => record?.route.route_coords
|
| 172 |
+
? [{ id: record.id, route: record.route.route_coords }] : [], [record]);
|
| 173 |
+
const environment = useRunningEnvironment(environmentInputs);
|
| 174 |
+
const runningEnvironment = environment.scores?.get(record?.id ?? "");
|
| 175 |
+
const environmentDetails = runningEnvironment?.details;
|
| 176 |
const center = record?.route.center ?? routeCoords[0] ?? DEFAULT_MAP_CENTER;
|
| 177 |
const shapeScore = record ? getGeneratedRouteAiShapeScore(record.route) : null;
|
| 178 |
const features = record ? getRouteFeatures(record) : [];
|
|
|
|
| 407 |
<DetailStat label="지도 지점" value={`${routeCoords.length}개`} />
|
| 408 |
</div>
|
| 409 |
|
| 410 |
+
<div className="mt-6 border-t border-[#e5e5e5] pt-5">
|
| 411 |
+
<h3 className="text-base font-semibold text-black">
|
| 412 |
+
러닝 환경 점수 {runningEnvironment?.score != null
|
| 413 |
+
? `${runningEnvironment.score.toFixed(1)}점 / 10점`
|
| 414 |
+
: environment.loading ? "확인 중" : "자료 부족"}
|
| 415 |
+
</h3>
|
| 416 |
+
{environmentDetails && Object.keys(environmentDetails).length > 0 ? (
|
| 417 |
+
<ul className="mt-3 list-disc space-y-2 pl-5 text-sm leading-6 text-[#555]">
|
| 418 |
+
<li>{environmentDetails.runners != null
|
| 419 |
+
? `경로 주변 집계 구역에서 서비스 이용자 ${environmentDetails.runners}명이 러닝 중입니다.`
|
| 420 |
+
: environmentDetails.runnerStatus === "present"
|
| 421 |
+
? "경로 주변에서 러닝 중인 이용자가 있습니다."
|
| 422 |
+
: environmentDetails.runnerStatus === "none"
|
| 423 |
+
? "경로 주변 러닝 이용자가 없습니다."
|
| 424 |
+
: "경로 주변 러닝 이용자 수를 확인할 수 없습니다."}</li>
|
| 425 |
+
{environmentDetails.crowd && (
|
| 426 |
+
<li>
|
| 427 |
+
자료가 있는 경로 주변의 인구 혼잡도는 {environmentDetails.crowd.level} 수준입니다
|
| 428 |
+
({environmentDetails.crowd.basis}).
|
| 429 |
+
</li>
|
| 430 |
+
)}
|
| 431 |
+
{environmentDetails.road?.unclearSeparationPercent != null && (
|
| 432 |
+
<li>인도와 차도의 구분이 명확하지 않은 구간이 있어 주의가 필요합니다. (전체 경로의 약 {environmentDetails.road.unclearSeparationPercent}%)</li>
|
| 433 |
+
)}
|
| 434 |
+
{!!environmentDetails.road?.reasons.length && (
|
| 435 |
+
<li>그 밖에 주의가 필요한 도로 특성: {environmentDetails.road.reasons.join(", ")}.</li>
|
| 436 |
+
)}
|
| 437 |
+
</ul>
|
| 438 |
+
) : (
|
| 439 |
+
<p className="mt-3 text-sm text-[#555]">{environment.loading
|
| 440 |
+
? "경로 주변 러닝 이용자 수를 확인 중입니다."
|
| 441 |
+
: "경로 주변 러닝 이용자 수를 확인할 수 없습니다."}</p>
|
| 442 |
+
)}
|
| 443 |
+
</div>
|
| 444 |
+
|
| 445 |
{!externalCourse && features.length > 0 ? (
|
| 446 |
<div className="mt-6 border-t border-[#e5e5e5] pt-5">
|
| 447 |
<h3 className="text-base font-semibold text-black">경로 특징</h3>
|
main/app/route-results/page.tsx
CHANGED
|
@@ -7,6 +7,8 @@ import { motionPresets } from "../_utils/motion";
|
|
| 7 |
import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";
|
| 8 |
import LeafletMap from "../_components/LeafletMap";
|
| 9 |
import NearbySampleRoutesCard from "../_components/NearbySampleRoutesCard";
|
|
|
|
|
|
|
| 10 |
import { PageContainer, PageHeader, SectionCard, EmptyState } from "../_components/RunShapeUI";
|
| 11 |
import {
|
| 12 |
endNavigationLoading,
|
|
@@ -105,8 +107,8 @@ function getCompletionLabel(score: number | null): string {
|
|
| 105 |
return "일부 구간에서 모양이 달라질 수 있음";
|
| 106 |
}
|
| 107 |
|
| 108 |
-
function getRouteTitle(routeNumber: number, routeLabel: string): string {
|
| 109 |
-
return `${formatGeneratedRouteLabel(routeLabel)} 코스 ${routeNumber}`;
|
| 110 |
}
|
| 111 |
|
| 112 |
function BookmarkIcon({ filled }: { filled: boolean }) {
|
|
@@ -142,7 +144,9 @@ function RouteResultsPageContent() {
|
|
| 142 |
const fallbackLatitude = parseNumberParam(searchParams.get("fallbackLatitude"));
|
| 143 |
const fallbackLongitude = parseNumberParam(searchParams.get("fallbackLongitude"));
|
| 144 |
const requestedLabel = normalizeLabelKey(searchParams.get("label") || "dog");
|
|
|
|
| 145 |
const selectedLabel = AVAILABLE_LABELS.includes(requestedLabel) ? requestedLabel : "dog";
|
|
|
|
| 146 |
|
| 147 |
const [place, setPlace] = useState(initialPlace);
|
| 148 |
const [routeCountInput, setRouteCountInput] = useState(Number.isFinite(initialCount) ? String(initialCount) : "8");
|
|
@@ -190,7 +194,7 @@ function RouteResultsPageContent() {
|
|
| 190 |
}
|
| 191 |
const params = new URLSearchParams(searchParams.toString());
|
| 192 |
params.set("place", requestPlace);
|
| 193 |
-
params.set("label", selectedLabel);
|
| 194 |
params.set("routeCount", String(count));
|
| 195 |
if (shapePriority) params.delete("targetDistanceKm");
|
| 196 |
else params.set("targetDistanceKm", String(distance));
|
|
@@ -270,7 +274,8 @@ function RouteResultsPageContent() {
|
|
| 270 |
shapePriority,
|
| 271 |
experimentalCandidateRanker,
|
| 272 |
labels: AVAILABLE_LABELS,
|
| 273 |
-
selectedLabel,
|
|
|
|
| 274 |
fallbackLatitude: placeWasEdited ? null : routeFallbackLatitude,
|
| 275 |
fallbackLongitude: placeWasEdited ? null : routeFallbackLongitude,
|
| 276 |
// The production Space must use the bounded road-route generator.
|
|
@@ -328,7 +333,7 @@ function RouteResultsPageContent() {
|
|
| 328 |
const runnableRoutes = Array.isArray(parsed.routes)
|
| 329 |
? parsed.routes.filter((route) => Array.isArray(route.route_coords) && route.route_coords.length >= 2)
|
| 330 |
: [];
|
| 331 |
-
if (runnableRoutes.length === 0) {
|
| 332 |
throw new Error(ROUTE_GENERATION_ERROR_MESSAGE);
|
| 333 |
}
|
| 334 |
|
|
@@ -437,7 +442,7 @@ function RouteResultsPageContent() {
|
|
| 437 |
place: result.place,
|
| 438 |
routeLabel,
|
| 439 |
modelTopLabel: getModelTopGeneratedRouteLabel(route),
|
| 440 |
-
title: getRouteTitle(routeNumber, routeLabel),
|
| 441 |
distanceText: formatDistance(route.length_km),
|
| 442 |
runParams: params.toString(),
|
| 443 |
route,
|
|
@@ -465,7 +470,7 @@ function RouteResultsPageContent() {
|
|
| 465 |
const routeLabel = getPrimaryGeneratedRouteLabel(route);
|
| 466 |
const record: SavedRouteRecord = {
|
| 467 |
id: routeId,
|
| 468 |
-
title: getRouteTitle(routeNumber, routeLabel),
|
| 469 |
place: result.place,
|
| 470 |
distanceKm: route.length_km,
|
| 471 |
label: routeLabel,
|
|
@@ -479,6 +484,12 @@ function RouteResultsPageContent() {
|
|
| 479 |
};
|
| 480 |
|
| 481 |
const routes = result?.routes ?? [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
const placeTitle = result?.place.split(",")[0] ?? place.split(",")[0];
|
| 483 |
const nearbySampleCenter = routes.find((route) => route.center)?.center
|
| 484 |
?? routes.find((route) => route.route_coords && route.route_coords.length > 0)?.route_coords?.[0]
|
|
@@ -491,7 +502,7 @@ function RouteResultsPageContent() {
|
|
| 491 |
<PageHeader
|
| 492 |
className="mt-2"
|
| 493 |
title="추천 경로"
|
| 494 |
-
subtitle={`${placeTitle} 주변에서 ${
|
| 495 |
actions={
|
| 496 |
<button type="button" onClick={regenerateRoutes} disabled={loading} className="rts-secondary-button h-10">
|
| 497 |
{loading ? "찾는 중" : "다시 찾기"}
|
|
@@ -547,7 +558,7 @@ function RouteResultsPageContent() {
|
|
| 547 |
<span>{shapePriority ? "추천 기준" : "목표 거리"}</span>
|
| 548 |
</div>
|
| 549 |
<div>
|
| 550 |
-
<strong>{
|
| 551 |
<span>선택 모양</span>
|
| 552 |
</div>
|
| 553 |
</div>
|
|
@@ -577,8 +588,8 @@ function RouteResultsPageContent() {
|
|
| 577 |
exit={{ opacity: 0, y: 6 }}
|
| 578 |
transition={motionPresets.smooth}
|
| 579 |
>
|
| 580 |
-
{
|
| 581 |
-
const routeNumber =
|
| 582 |
const routeLabel = getPrimaryGeneratedRouteLabel(route);
|
| 583 |
const hasRouteCoords = Boolean(route.route_coords && route.route_coords.length > 1);
|
| 584 |
const score = getGeneratedRouteAiShapeScore(route);
|
|
@@ -587,7 +598,7 @@ function RouteResultsPageContent() {
|
|
| 587 |
|
| 588 |
return (
|
| 589 |
<motion.article
|
| 590 |
-
key={`${generationVersion}-${route.image_path}-${
|
| 591 |
className="rts-card rts-card-flush"
|
| 592 |
initial={{ opacity: 0, y: 12, scale: 0.992 }}
|
| 593 |
animate={{ opacity: 1, y: 0, scale: 1 }}
|
|
@@ -597,7 +608,7 @@ function RouteResultsPageContent() {
|
|
| 597 |
}}
|
| 598 |
>
|
| 599 |
<div className="rts-route-map-stage h-64 w-full bg-[#f5f5f5]">
|
| 600 |
-
<div className="rts-route-rank">추천 {
|
| 601 |
{hasRouteCoords ? (
|
| 602 |
<LeafletMap
|
| 603 |
center={route.center ?? route.route_coords![0]}
|
|
@@ -618,9 +629,9 @@ function RouteResultsPageContent() {
|
|
| 618 |
<div className="flex items-start justify-between gap-3">
|
| 619 |
<div>
|
| 620 |
<h2 className="text-xl font-bold text-black sm:text-2xl">
|
| 621 |
-
{getRouteTitle(routeNumber, routeLabel)}
|
| 622 |
</h2>
|
| 623 |
-
<p className="mt-1 text-sm text-[#666]">{formatGeneratedRouteLabel(routeLabel)} 모양</p>
|
| 624 |
</div>
|
| 625 |
<button
|
| 626 |
type="button"
|
|
@@ -633,7 +644,7 @@ function RouteResultsPageContent() {
|
|
| 633 |
</button>
|
| 634 |
</div>
|
| 635 |
|
| 636 |
-
<div className="
|
| 637 |
<div className="rts-data-item">
|
| 638 |
<span className="rts-data-value">{formatDistance(route.length_km)}</span>
|
| 639 |
<p className="rts-data-label">거리</p>
|
|
@@ -643,8 +654,14 @@ function RouteResultsPageContent() {
|
|
| 643 |
<p className="rts-data-label">예상 시간</p>
|
| 644 |
</div>
|
| 645 |
<div className="rts-data-item">
|
| 646 |
-
<span className="rts-data-value">{
|
| 647 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
</div>
|
| 649 |
</div>
|
| 650 |
|
|
|
|
| 7 |
import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";
|
| 8 |
import LeafletMap from "../_components/LeafletMap";
|
| 9 |
import NearbySampleRoutesCard from "../_components/NearbySampleRoutesCard";
|
| 10 |
+
import { compareEnvironment, environmentLabel } from "../_utils/runningEnvironment";
|
| 11 |
+
import { useRunningEnvironment } from "../_utils/useRunningEnvironment";
|
| 12 |
import { PageContainer, PageHeader, SectionCard, EmptyState } from "../_components/RunShapeUI";
|
| 13 |
import {
|
| 14 |
endNavigationLoading,
|
|
|
|
| 107 |
return "일부 구간에서 모양이 달라질 수 있음";
|
| 108 |
}
|
| 109 |
|
| 110 |
+
function getRouteTitle(routeNumber: number, routeLabel: string, templateName?: string): string {
|
| 111 |
+
return `${templateName || formatGeneratedRouteLabel(routeLabel)} 코스 ${routeNumber}`;
|
| 112 |
}
|
| 113 |
|
| 114 |
function BookmarkIcon({ filled }: { filled: boolean }) {
|
|
|
|
| 144 |
const fallbackLatitude = parseNumberParam(searchParams.get("fallbackLatitude"));
|
| 145 |
const fallbackLongitude = parseNumberParam(searchParams.get("fallbackLongitude"));
|
| 146 |
const requestedLabel = normalizeLabelKey(searchParams.get("label") || "dog");
|
| 147 |
+
const autoShape = requestedLabel === "auto";
|
| 148 |
const selectedLabel = AVAILABLE_LABELS.includes(requestedLabel) ? requestedLabel : "dog";
|
| 149 |
+
const shapeName = autoShape ? "모양 자동 추천" : formatGeneratedRouteLabel(selectedLabel);
|
| 150 |
|
| 151 |
const [place, setPlace] = useState(initialPlace);
|
| 152 |
const [routeCountInput, setRouteCountInput] = useState(Number.isFinite(initialCount) ? String(initialCount) : "8");
|
|
|
|
| 194 |
}
|
| 195 |
const params = new URLSearchParams(searchParams.toString());
|
| 196 |
params.set("place", requestPlace);
|
| 197 |
+
params.set("label", autoShape ? "auto" : selectedLabel);
|
| 198 |
params.set("routeCount", String(count));
|
| 199 |
if (shapePriority) params.delete("targetDistanceKm");
|
| 200 |
else params.set("targetDistanceKm", String(distance));
|
|
|
|
| 274 |
shapePriority,
|
| 275 |
experimentalCandidateRanker,
|
| 276 |
labels: AVAILABLE_LABELS,
|
| 277 |
+
selectedLabel: autoShape ? null : selectedLabel,
|
| 278 |
+
autoShape,
|
| 279 |
fallbackLatitude: placeWasEdited ? null : routeFallbackLatitude,
|
| 280 |
fallbackLongitude: placeWasEdited ? null : routeFallbackLongitude,
|
| 281 |
// The production Space must use the bounded road-route generator.
|
|
|
|
| 333 |
const runnableRoutes = Array.isArray(parsed.routes)
|
| 334 |
? parsed.routes.filter((route) => Array.isArray(route.route_coords) && route.route_coords.length >= 2)
|
| 335 |
: [];
|
| 336 |
+
if (runnableRoutes.length === 0 && parsed.generation_mode !== "automatic_art_shapes") {
|
| 337 |
throw new Error(ROUTE_GENERATION_ERROR_MESSAGE);
|
| 338 |
}
|
| 339 |
|
|
|
|
| 442 |
place: result.place,
|
| 443 |
routeLabel,
|
| 444 |
modelTopLabel: getModelTopGeneratedRouteLabel(route),
|
| 445 |
+
title: getRouteTitle(routeNumber, routeLabel, route.art_template_name),
|
| 446 |
distanceText: formatDistance(route.length_km),
|
| 447 |
runParams: params.toString(),
|
| 448 |
route,
|
|
|
|
| 470 |
const routeLabel = getPrimaryGeneratedRouteLabel(route);
|
| 471 |
const record: SavedRouteRecord = {
|
| 472 |
id: routeId,
|
| 473 |
+
title: getRouteTitle(routeNumber, routeLabel, route.art_template_name),
|
| 474 |
place: result.place,
|
| 475 |
distanceKm: route.length_km,
|
| 476 |
label: routeLabel,
|
|
|
|
| 484 |
};
|
| 485 |
|
| 486 |
const routes = result?.routes ?? [];
|
| 487 |
+
const environmentInputs = useMemo(() => (result?.routes ?? []).map((route, i) => ({
|
| 488 |
+
id: String(i), route: route.route_coords ?? [],
|
| 489 |
+
})), [result]);
|
| 490 |
+
const { scores, loading: environmentLoading } = useRunningEnvironment(environmentInputs);
|
| 491 |
+
const rankedRoutes = routes.map((route, originalIndex) => ({ route, originalIndex, environment: scores?.get(String(originalIndex)) }))
|
| 492 |
+
.sort((a, b) => compareEnvironment(a.environment, b.environment) || a.originalIndex - b.originalIndex);
|
| 493 |
const placeTitle = result?.place.split(",")[0] ?? place.split(",")[0];
|
| 494 |
const nearbySampleCenter = routes.find((route) => route.center)?.center
|
| 495 |
?? routes.find((route) => route.route_coords && route.route_coords.length > 0)?.route_coords?.[0]
|
|
|
|
| 502 |
<PageHeader
|
| 503 |
className="mt-2"
|
| 504 |
title="추천 경로"
|
| 505 |
+
subtitle={autoShape ? `${placeTitle} 주변 도로에 잘 맞는 모양을 찾고 있어요.` : `${placeTitle} 주변에서 ${shapeName} 모양에 가까운 경로를 찾고 있어요.`}
|
| 506 |
actions={
|
| 507 |
<button type="button" onClick={regenerateRoutes} disabled={loading} className="rts-secondary-button h-10">
|
| 508 |
{loading ? "찾는 중" : "다시 찾기"}
|
|
|
|
| 558 |
<span>{shapePriority ? "추천 기준" : "목표 거리"}</span>
|
| 559 |
</div>
|
| 560 |
<div>
|
| 561 |
+
<strong>{shapeName}</strong>
|
| 562 |
<span>선택 모양</span>
|
| 563 |
</div>
|
| 564 |
</div>
|
|
|
|
| 588 |
exit={{ opacity: 0, y: 6 }}
|
| 589 |
transition={motionPresets.smooth}
|
| 590 |
>
|
| 591 |
+
{rankedRoutes.map(({ route, originalIndex, environment }, index) => {
|
| 592 |
+
const routeNumber = originalIndex + 1;
|
| 593 |
const routeLabel = getPrimaryGeneratedRouteLabel(route);
|
| 594 |
const hasRouteCoords = Boolean(route.route_coords && route.route_coords.length > 1);
|
| 595 |
const score = getGeneratedRouteAiShapeScore(route);
|
|
|
|
| 598 |
|
| 599 |
return (
|
| 600 |
<motion.article
|
| 601 |
+
key={`${generationVersion}-${route.image_path}-${originalIndex}`}
|
| 602 |
className="rts-card rts-card-flush"
|
| 603 |
initial={{ opacity: 0, y: 12, scale: 0.992 }}
|
| 604 |
animate={{ opacity: 1, y: 0, scale: 1 }}
|
|
|
|
| 608 |
}}
|
| 609 |
>
|
| 610 |
<div className="rts-route-map-stage h-64 w-full bg-[#f5f5f5]">
|
| 611 |
+
<div className="rts-route-rank">추천 {index + 1}</div>
|
| 612 |
{hasRouteCoords ? (
|
| 613 |
<LeafletMap
|
| 614 |
center={route.center ?? route.route_coords![0]}
|
|
|
|
| 629 |
<div className="flex items-start justify-between gap-3">
|
| 630 |
<div>
|
| 631 |
<h2 className="text-xl font-bold text-black sm:text-2xl">
|
| 632 |
+
{getRouteTitle(routeNumber, routeLabel, route.art_template_name)}
|
| 633 |
</h2>
|
| 634 |
+
<p className="mt-1 text-sm text-[#666]">{route.art_template_name || formatGeneratedRouteLabel(routeLabel)} 모양</p>
|
| 635 |
</div>
|
| 636 |
<button
|
| 637 |
type="button"
|
|
|
|
| 644 |
</button>
|
| 645 |
</div>
|
| 646 |
|
| 647 |
+
<div className="grid grid-cols-2 gap-2">
|
| 648 |
<div className="rts-data-item">
|
| 649 |
<span className="rts-data-value">{formatDistance(route.length_km)}</span>
|
| 650 |
<p className="rts-data-label">거리</p>
|
|
|
|
| 654 |
<p className="rts-data-label">예상 시간</p>
|
| 655 |
</div>
|
| 656 |
<div className="rts-data-item">
|
| 657 |
+
<span className="rts-data-value">{autoShape && typeof route.route_quality?.shape_similarity === "number"
|
| 658 |
+
? `${(route.route_quality.shape_similarity * 100).toFixed(1)}점`
|
| 659 |
+
: getCompletionLabel(score)}</span>
|
| 660 |
+
<p className="rts-data-label">{autoShape ? "기준 윤곽 유사도" : "형태 완성도"}</p>
|
| 661 |
+
</div>
|
| 662 |
+
<div className="rts-data-item">
|
| 663 |
+
<span className="rts-data-value">{environmentLabel(environment, environmentLoading)}</span>
|
| 664 |
+
<p className="rts-data-label">러닝 환경 점수</p>
|
| 665 |
</div>
|
| 666 |
</div>
|
| 667 |
|
main/app/route-search/page.tsx
CHANGED
|
@@ -13,6 +13,8 @@ import { fetchCommunityPostsFromApi } from "../_utils/communityApi";
|
|
| 13 |
import { FLOW_KEYS, isUiFlowPermitValid, issueUiFlowPermit } from "../_utils/uiFlowGuard";
|
| 14 |
import { prepareCoursePreview } from "../_utils/coursePreview";
|
| 15 |
import { withSampleOrientation } from "../_utils/sampleRouteOrientation";
|
|
|
|
|
|
|
| 16 |
|
| 17 |
type Point = [number, number];
|
| 18 |
|
|
@@ -288,6 +290,7 @@ const REGION_OPTIONS: RegionOption[] = [
|
|
| 288 |
];
|
| 289 |
|
| 290 |
const SHAPE_OPTIONS: ShapeOption[] = [
|
|
|
|
| 291 |
{
|
| 292 |
key: "christmas_tree_trunk",
|
| 293 |
label: "트리",
|
|
@@ -484,7 +487,7 @@ function RouteSearchPageContent() {
|
|
| 484 |
const [selectedLabel, setSelectedLabel] = useState(
|
| 485 |
requestedLabel && SHAPE_OPTIONS.some((shape) => shape.key === requestedLabel)
|
| 486 |
? requestedLabel
|
| 487 |
-
: "
|
| 488 |
);
|
| 489 |
const [geoError, setGeoError] = useState<string | null>(null);
|
| 490 |
const [locationPermissionState, setLocationPermissionState] =
|
|
@@ -548,18 +551,21 @@ function RouteSearchPageContent() {
|
|
| 548 |
const selectedPost =
|
| 549 |
communityPosts.find((post) => post.id === selectedPostId) ?? null;
|
| 550 |
const selectedSample = sampleRuns.find((sample) => sample.id === selectedSampleId) ?? null;
|
|
|
|
|
|
|
| 551 |
const nearbySamples = useMemo(() =>
|
| 552 |
sampleRuns
|
| 553 |
.map((sample) => ({ sample, distanceKm: distanceBetweenKm(mapCenter, sample.center) }))
|
| 554 |
.filter(({ distanceKm }) => distanceKm <= Math.max(radiusKm, 1))
|
| 555 |
-
.sort((a, b) => a.distanceKm - b.distanceKm)
|
| 556 |
.slice(0, 12),
|
| 557 |
-
[sampleRuns, mapCenter, radiusKm]
|
| 558 |
);
|
| 559 |
const gallerySamples = sampleGalleryLabel
|
| 560 |
? sampleRuns
|
| 561 |
.filter((sample) => sample.label === sampleGalleryLabel)
|
| 562 |
-
.sort((a, b) =>
|
|
|
|
| 563 |
: [];
|
| 564 |
const galleryMapSamples = gallerySamples.filter((sample) => distanceBetweenKm(mapCenter, sample.center) <= 30);
|
| 565 |
const nearbyPosts = useMemo(() => {
|
|
@@ -625,7 +631,9 @@ function RouteSearchPageContent() {
|
|
| 625 |
const summaryPlace = selectedMapPoint ? "지도에서 선택한 지점" : source === "current" ? "현재 위치" : selectedDistrictLabel;
|
| 626 |
const shapePriority = true;
|
| 627 |
const selectedSummary = `${summaryPlace} · ${selectedShape.label}${shapePriority ? " · 모양 우선" : ` · ${targetDistanceInput || "-"}km`}`;
|
| 628 |
-
const routePlanText =
|
|
|
|
|
|
|
| 629 |
? `${summaryPlace}의 도로에서 ${selectedShape.label} 모양과 가장 닮은 경로를 찾아 ${routeCountInput || "-"}개 추천합니다. 거리는 생성 결과에서 확인할 수 있어요.`
|
| 630 |
: `${summaryPlace}에서 ${selectedShape.label} 모양에 가까운 ${targetDistanceInput || "-"}km 경로를 ${routeCountInput || "-"}개 추천합니다.`;
|
| 631 |
|
|
@@ -993,6 +1001,7 @@ function RouteSearchPageContent() {
|
|
| 993 |
className={`rounded-xl px-3 py-2 text-left text-xs font-bold ${selectedSampleId === sample.id ? "bg-black text-white" : "bg-[#f7f7f7] text-black"}`}
|
| 994 |
>
|
| 995 |
{sample.title} · {sample.distanceKm.toFixed(1)}km
|
|
|
|
| 996 |
<span className="block font-normal opacity-70">지도 중심에서 약 {Math.round(distanceBetweenKm(mapCenter, sample.center))}km</span>
|
| 997 |
</button>
|
| 998 |
))}
|
|
@@ -1012,6 +1021,7 @@ function RouteSearchPageContent() {
|
|
| 1012 |
className={`shrink-0 rounded-full border px-3 py-2 text-xs font-bold ${selectedSampleId === sample.id ? "border-black bg-black text-white" : "border-black/10 bg-white text-black"}`}
|
| 1013 |
>
|
| 1014 |
{sample.label === "dog" ? "🐕" : sample.label === "t_shirt" ? "👕" : sample.label === "heart" ? "♥" : "★"} {sample.distanceKm.toFixed(1)}km
|
|
|
|
| 1015 |
</button>
|
| 1016 |
))}
|
| 1017 |
</div>
|
|
|
|
| 13 |
import { FLOW_KEYS, isUiFlowPermitValid, issueUiFlowPermit } from "../_utils/uiFlowGuard";
|
| 14 |
import { prepareCoursePreview } from "../_utils/coursePreview";
|
| 15 |
import { withSampleOrientation } from "../_utils/sampleRouteOrientation";
|
| 16 |
+
import { compareEnvironment, environmentLabel } from "../_utils/runningEnvironment";
|
| 17 |
+
import { useRunningEnvironment } from "../_utils/useRunningEnvironment";
|
| 18 |
|
| 19 |
type Point = [number, number];
|
| 20 |
|
|
|
|
| 290 |
];
|
| 291 |
|
| 292 |
const SHAPE_OPTIONS: ShapeOption[] = [
|
| 293 |
+
{ key: "auto", label: "모양 상관없음 · 자동 추천", offsets: [] },
|
| 294 |
{
|
| 295 |
key: "christmas_tree_trunk",
|
| 296 |
label: "트리",
|
|
|
|
| 487 |
const [selectedLabel, setSelectedLabel] = useState(
|
| 488 |
requestedLabel && SHAPE_OPTIONS.some((shape) => shape.key === requestedLabel)
|
| 489 |
? requestedLabel
|
| 490 |
+
: "auto"
|
| 491 |
);
|
| 492 |
const [geoError, setGeoError] = useState<string | null>(null);
|
| 493 |
const [locationPermissionState, setLocationPermissionState] =
|
|
|
|
| 551 |
const selectedPost =
|
| 552 |
communityPosts.find((post) => post.id === selectedPostId) ?? null;
|
| 553 |
const selectedSample = sampleRuns.find((sample) => sample.id === selectedSampleId) ?? null;
|
| 554 |
+
const { scores, loading: environmentLoading } = useRunningEnvironment(sampleRuns);
|
| 555 |
+
const sampleEnvironment = (id: string) => environmentLabel(scores?.get(id), environmentLoading);
|
| 556 |
const nearbySamples = useMemo(() =>
|
| 557 |
sampleRuns
|
| 558 |
.map((sample) => ({ sample, distanceKm: distanceBetweenKm(mapCenter, sample.center) }))
|
| 559 |
.filter(({ distanceKm }) => distanceKm <= Math.max(radiusKm, 1))
|
| 560 |
+
.sort((a, b) => compareEnvironment(scores?.get(a.sample.id), scores?.get(b.sample.id)) || a.distanceKm - b.distanceKm)
|
| 561 |
.slice(0, 12),
|
| 562 |
+
[sampleRuns, mapCenter, radiusKm, scores]
|
| 563 |
);
|
| 564 |
const gallerySamples = sampleGalleryLabel
|
| 565 |
? sampleRuns
|
| 566 |
.filter((sample) => sample.label === sampleGalleryLabel)
|
| 567 |
+
.sort((a, b) => compareEnvironment(scores?.get(a.id), scores?.get(b.id)) ||
|
| 568 |
+
distanceBetweenKm(mapCenter, a.center) - distanceBetweenKm(mapCenter, b.center))
|
| 569 |
: [];
|
| 570 |
const galleryMapSamples = gallerySamples.filter((sample) => distanceBetweenKm(mapCenter, sample.center) <= 30);
|
| 571 |
const nearbyPosts = useMemo(() => {
|
|
|
|
| 631 |
const summaryPlace = selectedMapPoint ? "지도에서 선택한 지점" : source === "current" ? "현재 위치" : selectedDistrictLabel;
|
| 632 |
const shapePriority = true;
|
| 633 |
const selectedSummary = `${summaryPlace} · ${selectedShape.label}${shapePriority ? " · 모양 우선" : ` · ${targetDistanceInput || "-"}km`}`;
|
| 634 |
+
const routePlanText = selectedLabel === "auto"
|
| 635 |
+
? `${summaryPlace} 주변 도로에 잘 맞는 모양을 비교해 유사도가 높은 경로를 추천합니다.`
|
| 636 |
+
: shapePriority
|
| 637 |
? `${summaryPlace}의 도로에서 ${selectedShape.label} 모양과 가장 닮은 경로를 찾아 ${routeCountInput || "-"}개 추천합니다. 거리는 생성 결과에서 확인할 수 있어요.`
|
| 638 |
: `${summaryPlace}에서 ${selectedShape.label} 모양에 가까운 ${targetDistanceInput || "-"}km 경로를 ${routeCountInput || "-"}개 추천합니다.`;
|
| 639 |
|
|
|
|
| 1001 |
className={`rounded-xl px-3 py-2 text-left text-xs font-bold ${selectedSampleId === sample.id ? "bg-black text-white" : "bg-[#f7f7f7] text-black"}`}
|
| 1002 |
>
|
| 1003 |
{sample.title} · {sample.distanceKm.toFixed(1)}km
|
| 1004 |
+
<span className="block font-normal">러닝 환경 점수 {sampleEnvironment(sample.id)}</span>
|
| 1005 |
<span className="block font-normal opacity-70">지도 중심에서 약 {Math.round(distanceBetweenKm(mapCenter, sample.center))}km</span>
|
| 1006 |
</button>
|
| 1007 |
))}
|
|
|
|
| 1021 |
className={`shrink-0 rounded-full border px-3 py-2 text-xs font-bold ${selectedSampleId === sample.id ? "border-black bg-black text-white" : "border-black/10 bg-white text-black"}`}
|
| 1022 |
>
|
| 1023 |
{sample.label === "dog" ? "🐕" : sample.label === "t_shirt" ? "👕" : sample.label === "heart" ? "♥" : "★"} {sample.distanceKm.toFixed(1)}km
|
| 1024 |
+
<span className="block font-normal">러닝 환경 점수 {sampleEnvironment(sample.id)}</span>
|
| 1025 |
</button>
|
| 1026 |
))}
|
| 1027 |
</div>
|
main/next.config.js
CHANGED
|
@@ -4,6 +4,8 @@ const internalApiProxyTarget =
|
|
| 4 |
/** @type {import('next').NextConfig} */
|
| 5 |
const nextConfig = {
|
| 6 |
reactStrictMode: true,
|
|
|
|
|
|
|
| 7 |
async rewrites() {
|
| 8 |
return [
|
| 9 |
{
|
|
|
|
| 4 |
/** @type {import('next').NextConfig} */
|
| 5 |
const nextConfig = {
|
| 6 |
reactStrictMode: true,
|
| 7 |
+
// Local API rewrites should not cut off route generation at Next's 30s default.
|
| 8 |
+
experimental: { proxyTimeout: 300_000 },
|
| 9 |
async rewrites() {
|
| 10 |
return [
|
| 11 |
{
|
main/tests/runningEnvironment.cjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("node:assert/strict");
|
| 2 |
+
const { environmentScore, compareEnvironment, sampleEnvironmentRoute } = require("../app/_utils/runningEnvironment.ts");
|
| 3 |
+
|
| 4 |
+
const signal = (risk, coverage) => ({ risk, coverage, weight: 1, source: "test" });
|
| 5 |
+
assert.equal(environmentScore([signal(0, 0)]).score, null);
|
| 6 |
+
assert.equal(environmentScore([signal(0, 1)]).score, 10);
|
| 7 |
+
assert.equal(environmentScore([signal(1, 1)]).score, 0);
|
| 8 |
+
assert.equal(environmentScore([signal(0, 1), signal(0, 0)]).score, 7.5);
|
| 9 |
+
const quiet = environmentScore([signal(0.2, 1)]);
|
| 10 |
+
const crowded = environmentScore([signal(0.9, 1)]);
|
| 11 |
+
assert.deepEqual([crowded, quiet, undefined].sort(compareEnvironment), [quiet, crowded, undefined]);
|
| 12 |
+
assert.deepEqual(sampleEnvironmentRoute([[37, 127], [37, 127], [37.01, 127]], 2),
|
| 13 |
+
[[37.0025, 127], [37.0075, 127]]);
|
| 14 |
+
assert.deepEqual(sampleEnvironmentRoute([[37, 127], [37, 127]]), []);
|
main/tests/runningEnvironmentApi.cjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("node:assert/strict");
|
| 2 |
+
const { registerHooks } = require("node:module");
|
| 3 |
+
registerHooks({ resolve(specifier, context, next) {
|
| 4 |
+
if (specifier === "../../_utils/runningEnvironment") specifier += ".ts";
|
| 5 |
+
if (specifier === "../../_utils/regionalCrowd") specifier += ".ts";
|
| 6 |
+
if (specifier === "next/server") specifier += ".js";
|
| 7 |
+
return next(specifier, context);
|
| 8 |
+
} });
|
| 9 |
+
process.env.RUN_ENV_INTERNAL_KEY = "test-only";
|
| 10 |
+
process.env.RUN_ENV_SEOUL_API_KEY = "sample";
|
| 11 |
+
global.fetch = async (url) => {
|
| 12 |
+
if (String(url).includes("environment-density")) return Response.json({
|
| 13 |
+
cells: { "7513:25395": 4, "7513:25394": 3, "7513:25390": 5 }, occupiedCells: ["7200:25400"],
|
| 14 |
+
});
|
| 15 |
+
const time = new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 19).replace("T", " ");
|
| 16 |
+
return Response.json({ CITYDATA: { LIVE_PPLTN_STTS: [
|
| 17 |
+
{ AREA_CD: "POI009", AREA_CONGEST_LVL: "보통", PPLTN_TIME: time, REPLACE_YN: "N" },
|
| 18 |
+
] } });
|
| 19 |
+
};
|
| 20 |
+
const { POST } = require("../app/api/running-environment/route.ts");
|
| 21 |
+
|
| 22 |
+
async function test() {
|
| 23 |
+
const submit = (routes) => POST(new Request("http://localhost/api/running-environment", {
|
| 24 |
+
method: "POST", body: JSON.stringify(routes),
|
| 25 |
+
}));
|
| 26 |
+
assert.equal((await submit([[[NaN, 127]]])).status, 400);
|
| 27 |
+
const response = await submit([[[37.5759,126.9768],[37.5727,126.9769],[37.5695271,126.9768018]], [[0,0]], [[36,127]]]);
|
| 28 |
+
const [seoul, unknown, sparse] = await response.json();
|
| 29 |
+
assert.equal(unknown.score, null);
|
| 30 |
+
assert.deepEqual(unknown.details, { runnerStatus: "none" });
|
| 31 |
+
assert.equal(sparse.details.runnerStatus, "present");
|
| 32 |
+
assert.equal(sparse.details.runners, undefined);
|
| 33 |
+
if (process.env.RUN_ENV_DATA_DIR) {
|
| 34 |
+
assert.ok(seoul.sources.includes("보행로 구조"));
|
| 35 |
+
assert.ok(seoul.sources.includes("지역 실시간 인구"));
|
| 36 |
+
assert.ok(seoul.sources.includes("서비스 활동"));
|
| 37 |
+
assert.equal(seoul.details.runners, 7);
|
| 38 |
+
assert.equal(seoul.details.runnerStatus, "reported");
|
| 39 |
+
assert.equal(seoul.details.crowd.basis, "실시간 관측");
|
| 40 |
+
assert.ok(seoul.score >= 0 && seoul.score <= 10);
|
| 41 |
+
}
|
| 42 |
+
console.log(JSON.stringify({ seoul, unknown }));
|
| 43 |
+
if (process.env.RUN_ENV_TEST_REGIONAL_DATA === "1") {
|
| 44 |
+
const [bupyeong, elsewhere, liveSeoul, fallbackSeoul] = await (await submit([
|
| 45 |
+
[[37.4926, 126.7226]], [[37.52, 126.65]],
|
| 46 |
+
[[37.5695271, 126.9768018]], [[37.5, 127.03]],
|
| 47 |
+
])).json();
|
| 48 |
+
assert.ok(bupyeong.sources.includes("과거 시간대 혼잡 추정"));
|
| 49 |
+
assert.ok(!elsewhere.sources.includes("과거 시간대 혼잡 추정"));
|
| 50 |
+
assert.ok(liveSeoul.sources.includes("지역 실시간 인구"));
|
| 51 |
+
assert.ok(!liveSeoul.sources.includes("과거 시간대 혼잡 추정"));
|
| 52 |
+
assert.ok(fallbackSeoul.sources.includes("과거 시간대 혼잡 추정"));
|
| 53 |
+
}
|
| 54 |
+
if (process.env.RUN_ENV_TEST_PEDESTRIAN_DATA === "1") {
|
| 55 |
+
const realNow = Date.now;
|
| 56 |
+
Date.now = () => Date.parse("2026-11-08T15:00:00+09:00");
|
| 57 |
+
try {
|
| 58 |
+
const [camera, gwacheon] = await (await submit([[[37.488270837, 127.013908707]], [[37.433454, 127.009297]]])).json();
|
| 59 |
+
assert.ok(camera.sources.includes("시간대별 보행자 센서 관측"));
|
| 60 |
+
assert.ok(!camera.sources.includes("과거 시간대 혼잡 추정"));
|
| 61 |
+
assert.ok(!gwacheon.sources.includes("시간대별 보행자 센서 관측"));
|
| 62 |
+
Date.now = () => Date.parse("2027-03-01T15:00:00+09:00");
|
| 63 |
+
const [expired] = await (await submit([[[37.488270837, 127.013908707]]])).json();
|
| 64 |
+
assert.ok(!expired.sources.includes("시간대별 보행자 센서 관측"));
|
| 65 |
+
} finally { Date.now = realNow; }
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
test().catch((error) => { console.error(error); process.exitCode = 1; });
|
tools/import_regional_crowd.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prepare local historical crowd profiles; requires pandas and geopandas."""
|
| 2 |
+
import argparse
|
| 3 |
+
import csv
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import zipfile
|
| 7 |
+
|
| 8 |
+
import geopandas as gpd
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def profiles(observations, width, min_days):
|
| 13 |
+
# First aggregate by day and time; days then contribute equally.
|
| 14 |
+
values = observations.groupby(["id", "day", "hour"], as_index=False)["count"].sum(min_count=1)
|
| 15 |
+
values["weekend"] = pd.to_datetime(values.day, format="%Y%m%d").dt.dayofweek >= 5
|
| 16 |
+
summary = values.groupby(["id", "weekend", "hour"])["count"].agg(["mean", "count"])
|
| 17 |
+
result = {}
|
| 18 |
+
for (ident, weekend), group in summary.groupby(level=[0, 1]):
|
| 19 |
+
means = {hour: float(row["mean"]) for (_, _, hour), row in group.iterrows()
|
| 20 |
+
if row["count"] >= min_days and row["mean"] >= 0}
|
| 21 |
+
if len(means) < 24 // width:
|
| 22 |
+
continue
|
| 23 |
+
baseline = sum(means.values()) / len(means)
|
| 24 |
+
if baseline <= 0:
|
| 25 |
+
continue
|
| 26 |
+
profile = result.setdefault(ident, {"weekday": [None] * 24, "weekend": [None] * 24})
|
| 27 |
+
profile["weekend" if weekend else "weekday"] = [
|
| 28 |
+
round(means[hour // width * width] / baseline, 3) for hour in range(24)]
|
| 29 |
+
return result
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def seoul(zip_path, grid_path):
|
| 33 |
+
frames = []
|
| 34 |
+
with zipfile.ZipFile(zip_path) as archive:
|
| 35 |
+
for entry in archive.namelist():
|
| 36 |
+
if not entry.lower().endswith(".csv"):
|
| 37 |
+
continue
|
| 38 |
+
with archive.open(entry) as stream:
|
| 39 |
+
frame = pd.read_csv(stream, encoding="cp949", usecols=[0, 1, 3, 4],
|
| 40 |
+
dtype=str, keep_default_na=False)
|
| 41 |
+
frame.columns = ["day", "hour", "id", "count"]
|
| 42 |
+
frame["count"] = pd.to_numeric(frame["count"], errors="coerce")
|
| 43 |
+
frame["hour"] = pd.to_numeric(frame["hour"], errors="coerce")
|
| 44 |
+
frame["id"] = frame["id"].str.strip()
|
| 45 |
+
frames.append(frame.dropna())
|
| 46 |
+
if not frames:
|
| 47 |
+
raise ValueError("서울 ZIP에 CSV가 없습니다")
|
| 48 |
+
observations = pd.concat(frames, ignore_index=True)
|
| 49 |
+
profile = profiles(observations, 1, 4)
|
| 50 |
+
grid = gpd.read_file(grid_path).to_crs(4326)
|
| 51 |
+
for row in grid.itertuples():
|
| 52 |
+
ident = row.CELL_ID.strip()
|
| 53 |
+
if ident not in profile:
|
| 54 |
+
continue
|
| 55 |
+
geometry = row.geometry
|
| 56 |
+
parts = geometry.geoms if geometry.geom_type == "MultiPolygon" else [geometry]
|
| 57 |
+
polygons = [[[[round(y, 7), round(x, 7)] for x, y in ring.coords]
|
| 58 |
+
for ring in [part.exterior, *part.interiors]] for part in parts]
|
| 59 |
+
yield {"id": f"seoul:{ident}", "polygons": polygons, **profile[ident]}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def bupyeong(csv_path):
|
| 63 |
+
frame = pd.read_csv(csv_path, encoding="utf-8-sig", dtype=str)
|
| 64 |
+
frame.columns = ["id", "day", "hour", "count"]
|
| 65 |
+
frame["day"] = frame.day.str.replace("-", "", regex=False)
|
| 66 |
+
frame["hour"] = pd.to_numeric(frame.hour.str.extract(r"^(\d{2}):", expand=False), errors="coerce")
|
| 67 |
+
frame["count"] = pd.to_numeric(frame["count"], errors="coerce")
|
| 68 |
+
profile = profiles(frame.dropna(), 4, 4)
|
| 69 |
+
# Tourism association gives a shared POI for the market/culture street.
|
| 70 |
+
# 150m is a conservative recommendation proxy, not an official count boundary.
|
| 71 |
+
for ident in ("문화의 거리", "부평시장"):
|
| 72 |
+
if ident in profile:
|
| 73 |
+
yield {"id": f"bupyeong:{ident}", "center": [37.4926, 126.7226], "radiusM": 150, **profile[ident]}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def sdot(locations, observations):
|
| 77 |
+
# Peer-reviewed S-DoT study identifies codes 4001–4050 as the camera cohort.
|
| 78 |
+
# Do not infer the technology for newer codes or count Wi-Fi as pedestrians.
|
| 79 |
+
with locations.open("rb") as stream:
|
| 80 |
+
sites = pd.read_excel(stream)
|
| 81 |
+
sites = sites[sites["방문자 센서코드"].between(4001, 4050)]
|
| 82 |
+
allowed = set(sites["방문자 센서코드"])
|
| 83 |
+
records = []
|
| 84 |
+
for path in observations:
|
| 85 |
+
with path.open(encoding="cp949", newline="") as stream:
|
| 86 |
+
rows = csv.reader(stream)
|
| 87 |
+
header = next(rows)
|
| 88 |
+
if header[:3] != ["모델명", "시리얼", "센서시간"]:
|
| 89 |
+
raise ValueError(f"Unexpected S-DoT export header: {path}")
|
| 90 |
+
for row in rows:
|
| 91 |
+
# The 2026 download has an 8-column body, with count before model.
|
| 92 |
+
if len(row) == 8 and row[1] == "SDOT001":
|
| 93 |
+
count, _, code, timestamp = row[:4]
|
| 94 |
+
elif len(row) == 9 and row[0] == "SDOT001":
|
| 95 |
+
_, code, timestamp, _, _, _, count = row[:7]
|
| 96 |
+
else:
|
| 97 |
+
continue
|
| 98 |
+
if code.isdigit() and int(code) in allowed and count.isdigit():
|
| 99 |
+
records.append((int(code), timestamp, int(count)))
|
| 100 |
+
if not records:
|
| 101 |
+
raise ValueError("No camera observations found")
|
| 102 |
+
frame = pd.DataFrame(records, columns=["id", "timestamp", "count"])
|
| 103 |
+
frame["timestamp"] = pd.to_datetime(frame.timestamp, format="%Y-%m-%d_%H:%M:%S", errors="coerce")
|
| 104 |
+
frame = frame.dropna().drop_duplicates(["id", "timestamp"], keep=False)
|
| 105 |
+
frame["day"] = frame.timestamp.dt.strftime("%Y%m%d")
|
| 106 |
+
frame["hour"] = frame.timestamp.dt.hour
|
| 107 |
+
frame["slot"] = frame.timestamp.dt.floor("10min")
|
| 108 |
+
slots = frame.groupby(["id", "day", "hour", "slot"], as_index=False)["count"].mean()
|
| 109 |
+
hourly = slots.groupby(["id", "day", "hour"], as_index=False)["count"].agg(["mean", "size"])
|
| 110 |
+
hourly = hourly[hourly["size"] >= 4].rename(columns={"mean": "count"})
|
| 111 |
+
profile = profiles(hourly, 1, 4)
|
| 112 |
+
print(f"S-DoT observation period: {frame.day.min()}–{frame.day.max()}")
|
| 113 |
+
for _, site in sites.iterrows():
|
| 114 |
+
code = int(site["방문자 센서코드"])
|
| 115 |
+
if code in profile and pd.notna(site["위도"]) and pd.notna(site["경도"]):
|
| 116 |
+
yield {"id": f"sdot:{code}", "kind": "pedestrian-camera",
|
| 117 |
+
"observedTo": frame.loc[frame.id == code, "day"].max(),
|
| 118 |
+
"center": [float(site["위도"]), float(site["경도"])],
|
| 119 |
+
"radiusM": 45, **profile[code]}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def gyeonggi(csv_path, boundaries_path):
|
| 123 |
+
"""Import authorized hourly 50 m grid observations, not administrative inflow."""
|
| 124 |
+
columns = ["grid_id", "date", "hour", "count"]
|
| 125 |
+
frame = pd.read_csv(csv_path, usecols=columns, dtype={"grid_id": str, "date": str})
|
| 126 |
+
frame = frame.rename(columns={"grid_id": "id", "date": "day"}).dropna()
|
| 127 |
+
frame["day"] = pd.to_datetime(frame.day, format="%Y-%m-%d").dt.strftime("%Y%m%d")
|
| 128 |
+
frame = frame[frame.hour.between(0, 23) & (frame.hour % 1 == 0) & (frame["count"] >= 0)]
|
| 129 |
+
if frame.duplicated(["id", "day", "hour"]).any():
|
| 130 |
+
raise ValueError("Expected one measured count per grid/day/hour")
|
| 131 |
+
summaries = profiles(frame, 1, 4)
|
| 132 |
+
recent = frame.groupby("id").day.max()
|
| 133 |
+
geo = gpd.read_file(boundaries_path).to_crs(5179)
|
| 134 |
+
if not geo.grid_id.is_unique:
|
| 135 |
+
raise ValueError("Duplicate grid_id in grid boundaries")
|
| 136 |
+
# Reject administrative-dong polygons and other coarse substitutes.
|
| 137 |
+
if not geo.area.between(2000, 3000).all():
|
| 138 |
+
raise ValueError("Expected approximately 50 m × 50 m grid polygons")
|
| 139 |
+
for ident, geom in zip(geo.grid_id.astype(str), geo.to_crs(4326).geometry):
|
| 140 |
+
if ident not in summaries or geom.geom_type != "Polygon" or not geom.is_valid:
|
| 141 |
+
continue
|
| 142 |
+
x, y = geom.centroid.coords[0]
|
| 143 |
+
if not (36.8 <= y <= 38.4 and 126.3 <= x <= 128.0):
|
| 144 |
+
raise ValueError("Grid outside the expected Gyeonggi bounds")
|
| 145 |
+
yield {"id": f"gyeonggi:{ident}", "kind": "hourly-grid", "observedTo": recent.loc[ident],
|
| 146 |
+
"polygons": [[[[y, x] for x, y in ring.coords] for ring in [geom.exterior, *geom.interiors]]],
|
| 147 |
+
**summaries[ident]}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def main():
|
| 151 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 152 |
+
parser.add_argument("--seoul", nargs=2, type=Path, metavar=("ZIP", "GRID_SHP"))
|
| 153 |
+
parser.add_argument("--bupyeong", type=Path)
|
| 154 |
+
parser.add_argument("--sdot", nargs="+", type=Path, metavar="LOCATIONS_OR_CSV")
|
| 155 |
+
parser.add_argument("--gyeonggi-verified-grid", nargs=2, type=Path, metavar=("HOURLY_CSV", "GRID_FILE"))
|
| 156 |
+
parser.add_argument("--out", required=True, type=Path)
|
| 157 |
+
args = parser.parse_args()
|
| 158 |
+
if not (args.seoul or args.bupyeong or args.sdot or args.gyeonggi_verified_grid):
|
| 159 |
+
parser.error("at least one source is required")
|
| 160 |
+
areas = []
|
| 161 |
+
if args.seoul:
|
| 162 |
+
areas.extend(seoul(*args.seoul))
|
| 163 |
+
if args.bupyeong:
|
| 164 |
+
areas.extend(bupyeong(args.bupyeong))
|
| 165 |
+
if args.sdot:
|
| 166 |
+
if len(args.sdot) < 2:
|
| 167 |
+
parser.error("--sdot requires the location workbook and at least one observation CSV")
|
| 168 |
+
areas.extend(sdot(args.sdot[0], args.sdot[1:]))
|
| 169 |
+
if args.gyeonggi_verified_grid:
|
| 170 |
+
areas.extend(gyeonggi(*args.gyeonggi_verified_grid))
|
| 171 |
+
if not areas:
|
| 172 |
+
parser.error("no geographically matched profiles")
|
| 173 |
+
args.out.write_text(json.dumps({"areas": areas}, ensure_ascii=False, allow_nan=False,
|
| 174 |
+
separators=(",", ":")), encoding="utf-8")
|
| 175 |
+
print(f"wrote {len(areas)} profiles")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
main()
|
tools/import_running_environment.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build local route-environment data; see docs/running-environment.md."""
|
| 2 |
+
import argparse
|
| 3 |
+
from contextlib import closing
|
| 4 |
+
import itertools
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import re
|
| 9 |
+
import sqlite3
|
| 10 |
+
from tempfile import TemporaryDirectory
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def metres(value):
|
| 14 |
+
match = re.fullmatch(r"\s*(\d+(?:[.,]\d+)?)\s*(?:m)?\s*", str(value))
|
| 15 |
+
n = float(match[1].replace(",", ".")) if match else 0
|
| 16 |
+
return n if 0 < n <= 100 else None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def risk(width, separated=None, surface=None):
|
| 20 |
+
if width is None and separated is None and not surface:
|
| 21 |
+
return None
|
| 22 |
+
base = 0.52 if separated is None else (0.35 if separated else 0.76)
|
| 23 |
+
if width is not None:
|
| 24 |
+
base += max(-0.23, min(0.32, (2.4 - width) * 0.19))
|
| 25 |
+
if surface in {"gravel", "ground", "sand", "dirt", "unpaved", "비포장"}:
|
| 26 |
+
base += 0.09
|
| 27 |
+
return round(max(0.05, min(0.98, base)), 3)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def point(xy):
|
| 31 |
+
x, y = xy[:2]
|
| 32 |
+
if not (124 <= x <= 132 and 32 <= y <= 40):
|
| 33 |
+
raise ValueError("Expected Korean WGS84 (longitude, latitude) geometry")
|
| 34 |
+
return round(y, 7), round(x, 7)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def features(path):
|
| 38 |
+
if path.suffix.lower() == ".shp":
|
| 39 |
+
import geopandas
|
| 40 |
+
data = geopandas.read_file(path)
|
| 41 |
+
if not data.crs:
|
| 42 |
+
raise ValueError(f"Missing CRS for {path}")
|
| 43 |
+
return json.loads(data.to_crs(4326).to_json())["features"]
|
| 44 |
+
return json.loads(path.read_text(encoding="utf-8-sig"))["features"]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def caution_reasons(width=None, separated=None, surface=None):
|
| 48 |
+
reasons = []
|
| 49 |
+
if width is not None and width < 1.5:
|
| 50 |
+
reasons.append("보행로 폭 1.5m 미만")
|
| 51 |
+
if separated is False:
|
| 52 |
+
reasons.append("보도 없음 또는 차량과 공간 공유")
|
| 53 |
+
if surface in {"gravel", "ground", "sand", "dirt", "unpaved", "비포장"}:
|
| 54 |
+
reasons.append("비포장 노면")
|
| 55 |
+
return reasons
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def road_geometry(db, a, b, score, priority, polygon=None, reasons=None):
|
| 59 |
+
pad = 0 if polygon else 0.00019
|
| 60 |
+
points = polygon[0] if polygon else (a, b)
|
| 61 |
+
limits = [(math.floor((min(p[i] for p in points) - pad) * 1000),
|
| 62 |
+
math.floor((max(p[i] for p in points) + pad) * 1000)) for i in (0, 1)]
|
| 63 |
+
payload = json.dumps([a, b, score, priority] + ([polygon, reasons] if reasons else [polygon] if polygon else []), separators=(",", ":"))
|
| 64 |
+
db.executemany("INSERT INTO roads VALUES (?, ?, ?)", (
|
| 65 |
+
(f"{i // 100}_{j // 100}", f"{i}:{j}", payload)
|
| 66 |
+
for i in range(limits[0][0], limits[0][1] + 1)
|
| 67 |
+
for j in range(limits[1][0], limits[1][1] + 1)))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def line(db, coords, score, priority, reasons=None):
|
| 71 |
+
for a, b in itertools.pairwise(coords):
|
| 72 |
+
if a == b:
|
| 73 |
+
continue
|
| 74 |
+
# Split long segments before binning to bound bounding-box duplication.
|
| 75 |
+
steps = max(1, math.ceil(max(abs(a[0] - b[0]), abs(a[1] - b[1])) / 0.001))
|
| 76 |
+
previous = a
|
| 77 |
+
for i in range(1, steps + 1):
|
| 78 |
+
current = tuple(a[d] + (b[d] - a[d]) * i / steps for d in (0, 1))
|
| 79 |
+
road_geometry(db, previous, current, score, priority, reasons=reasons)
|
| 80 |
+
previous = current
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def load_osm(db, path):
|
| 84 |
+
import osmium
|
| 85 |
+
|
| 86 |
+
class Handler(osmium.SimpleHandler):
|
| 87 |
+
def way(self, way):
|
| 88 |
+
t = way.tags
|
| 89 |
+
highway = t.get("highway")
|
| 90 |
+
if not highway or highway in {"motorway", "motorway_link", "trunk", "trunk_link",
|
| 91 |
+
"construction", "proposed", "cycleway", "steps"} or t.get("foot") in {"no", "private"}:
|
| 92 |
+
return
|
| 93 |
+
if t.get("access") in {"no", "private"} and t.get("foot") not in {"yes", "designated", "permissive"}:
|
| 94 |
+
return
|
| 95 |
+
sidewalk = t.get("sidewalk")
|
| 96 |
+
explicit_path = highway in {"footway", "pedestrian", "path"} and t.get("footway") != "crossing"
|
| 97 |
+
reasons = []
|
| 98 |
+
if explicit_path:
|
| 99 |
+
score = risk(metres(t.get("width")), True, t.get("surface"))
|
| 100 |
+
reasons = caution_reasons(metres(t.get("width")), True, t.get("surface"))
|
| 101 |
+
elif sidewalk == "no":
|
| 102 |
+
score = risk(None, False)
|
| 103 |
+
reasons = caution_reasons(separated=False)
|
| 104 |
+
elif sidewalk in {"yes", "both", "left", "right", "separate"}:
|
| 105 |
+
score = risk(None, True)
|
| 106 |
+
elif highway == "living_street":
|
| 107 |
+
score = risk(None, False)
|
| 108 |
+
reasons = caution_reasons(separated=False)
|
| 109 |
+
else:
|
| 110 |
+
return
|
| 111 |
+
# Never interpret a carriageway's generic width as sidewalk width.
|
| 112 |
+
coords = [(n.lat, n.lon) for n in way.nodes if n.location.valid()]
|
| 113 |
+
if len(coords) == len(way.nodes) and score is not None:
|
| 114 |
+
line(db, coords, score, 1, reasons)
|
| 115 |
+
|
| 116 |
+
Handler().apply_file(str(path), locations=True, idx="flex_mem")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def load_roads(db, path, source, width_field, surface_field):
|
| 120 |
+
for f in features(path):
|
| 121 |
+
geom = f.get("geometry") or {}
|
| 122 |
+
props = f.get("properties") or {}
|
| 123 |
+
width = metres(props.get(width_field))
|
| 124 |
+
is_sidewalk = source in {"sidewalk-1000", "sidewalk-5000"}
|
| 125 |
+
reasons = caution_reasons(width, True, props.get(surface_field)) if is_sidewalk else []
|
| 126 |
+
priority = {"sidewalk-1000": 4, "sidewalk-5000": 3, "road-width": 0, "carriageway": 0}[source]
|
| 127 |
+
if is_sidewalk:
|
| 128 |
+
score = risk(width, True, props.get(surface_field))
|
| 129 |
+
elif source == "road-width":
|
| 130 |
+
# A wider street is weak supporting evidence, not pedestrian capacity.
|
| 131 |
+
if width is None:
|
| 132 |
+
continue
|
| 133 |
+
score = round(max(0.5, 0.72 - width * 0.025), 3)
|
| 134 |
+
else:
|
| 135 |
+
score = 0.65
|
| 136 |
+
kind, coordinates = geom.get("type"), geom.get("coordinates")
|
| 137 |
+
if kind in {"Polygon", "MultiPolygon"}:
|
| 138 |
+
for poly in (coordinates if kind == "MultiPolygon" else [coordinates]):
|
| 139 |
+
rings = [[point(p) for p in ring] for ring in poly]
|
| 140 |
+
road_geometry(db, rings[0][0], rings[0][0], score, priority, rings, reasons)
|
| 141 |
+
elif kind in {"LineString", "MultiLineString"}:
|
| 142 |
+
for coords in (coordinates if kind == "MultiLineString" else [coordinates]):
|
| 143 |
+
line(db, list(map(point, coords)), score, priority, reasons)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def load_areas(path, code_field):
|
| 147 |
+
areas = []
|
| 148 |
+
for f in features(path):
|
| 149 |
+
geom = f.get("geometry") or {}
|
| 150 |
+
code = str((f.get("properties") or {}).get(code_field, "")).strip()
|
| 151 |
+
if not re.fullmatch(r"POI\d{3,5}", code):
|
| 152 |
+
raise ValueError(f"Invalid Seoul POI code in {code_field}: {code!r}")
|
| 153 |
+
kind = geom.get("type")
|
| 154 |
+
if kind not in {"Polygon", "MultiPolygon"}:
|
| 155 |
+
continue
|
| 156 |
+
polygons = geom["coordinates"] if kind == "MultiPolygon" else [geom["coordinates"]]
|
| 157 |
+
areas.append({"code": code, "polygons": [[[point(p) for p in ring] for ring in poly] for poly in polygons]})
|
| 158 |
+
return areas
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def main():
|
| 162 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 163 |
+
parser.add_argument("--out", required=True, type=Path, help="New/empty output directory")
|
| 164 |
+
parser.add_argument("--osm", type=Path, help="Nationwide OSM PBF; requires osmium")
|
| 165 |
+
parser.add_argument("--roads", nargs=4, action="append", default=[],
|
| 166 |
+
metavar=("SOURCE", "GEOJSON", "WIDTH_FIELD", "SURFACE_FIELD"))
|
| 167 |
+
parser.add_argument("--seoul-areas", nargs=2, metavar=("GEOJSON", "POI_CODE_FIELD"))
|
| 168 |
+
args = parser.parse_args()
|
| 169 |
+
if not (args.osm or args.roads or args.seoul_areas):
|
| 170 |
+
parser.error("Supply at least one source")
|
| 171 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
if any(args.out.iterdir()):
|
| 173 |
+
parser.error("Output directory must be empty; build a fresh version")
|
| 174 |
+
(args.out / "roads").mkdir()
|
| 175 |
+
with TemporaryDirectory(dir=args.out.resolve().parent) as temp, closing(sqlite3.connect(Path(temp) / "import.db")) as db:
|
| 176 |
+
db.execute("CREATE TABLE roads(tile TEXT, cell TEXT, payload TEXT)")
|
| 177 |
+
if args.osm:
|
| 178 |
+
load_osm(db, args.osm)
|
| 179 |
+
for source, path, width, surface in args.roads:
|
| 180 |
+
load_roads(db, Path(path), source, width, surface)
|
| 181 |
+
db.commit()
|
| 182 |
+
rows = db.execute("SELECT tile, cell, payload FROM roads ORDER BY tile, cell")
|
| 183 |
+
for tile, records in itertools.groupby(rows, lambda row: row[0]):
|
| 184 |
+
cells = {}
|
| 185 |
+
for _, cell, payload in records:
|
| 186 |
+
cells.setdefault(cell, []).append(json.loads(payload))
|
| 187 |
+
(args.out / "roads" / f"{tile}.json").write_text(
|
| 188 |
+
json.dumps(cells, separators=(",", ":")), encoding="utf-8")
|
| 189 |
+
if args.seoul_areas:
|
| 190 |
+
path, field = args.seoul_areas
|
| 191 |
+
(args.out / "seoul-areas.json").write_text(json.dumps(load_areas(Path(path), field)), encoding="utf-8")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if __name__ == "__main__":
|
| 195 |
+
main()
|