Spaces:
Sleeping
Sleeping
Sync DemoService 778e066c9915dd0ec1a6d9a620a99adbf50c2f31
Browse filesFiles changed (6)
- api/ai-service/app/api/v1/endpoints/route_generation.py+7-3
- api/ai-service/app/services/gpx_shape_similarity.py+17
- api/ai-service/app/services/walking_route_fallback.py+9-5
- api/ai-service/tests/test_gpx_shape_similarity.py+11-1
- api/ai-service/tests/test_walking_route_fallback.py+17
- router/ai/scripts/clip_osm_region_test.py+4-4
10 unmodified lines11121314151617455 unmodified lines4734744754764774789 unmodified lines48848949049149249349410 unmodified lines50550650750850951051151210 unmodified linesfrom pydantic import BaseModel, Field, field_validatorfrom app.core.config import settingsfrom app.services.gpx_shape_similarity import best_gpx_shape_matchfrom app.services.walking_route_fallback import generate_walking_fallbackrouter = APIRouter(prefix="/ai", tags=["ai"])455 unmodified linescontinueshape_quality = float(route.get("shape_quality", 0.0))similarity, example_index = best_gpx_shape_match(coords, examples) if examples else (0.0, None)route_label = selected_label or "nearby_route"maneuvers = maneuvers_for_route(graph, route["nodes"]) if callable(maneuvers_for_route) else []routes.append(9 unmodified lines"is_loop": bool(route.get("is_loop")),"route_quality": {"art_ready": generation_mode == "fast_walk_roads" and bool(selected_label),**({"gpx_similarity": similarity, "gpx_example_index": example_index} if examples else {}),"target_shape": {"score": shape_quality,"route_coverage": shape_quality,10 unmodified linesif examples:routes.sort(key=lambda route: (-route["route_quality"]["gpx_similarity"],abs(route["length_km"] - target_distance_km),))routes = routes[:route_count]elif auto_distance:10 unmodified lines11121314151617455 unmodified lines4734744754764774784799 unmodified lines48949049149249349449549649710 unmodified lines50850951051151251351451551610 unmodified linesfrom pydantic import BaseModel, Field, field_validatorfrom app.core.config import settingsfrom app.services.gpx_shape_similarity import best_gpx_shape_match, gpx_route_rank_score, route_footprint_kmfrom app.services.walking_route_fallback import generate_walking_fallbackrouter = APIRouter(prefix="/ai", tags=["ai"])455 unmodified linescontinueshape_quality = float(route.get("shape_quality", 0.0))similarity, example_index = best_gpx_shape_match(coords, examples) if examples else (0.0, None)footprint_km = route_footprint_km(coords) if examples else 0.0route_label = selected_label or "nearby_route"maneuvers = maneuvers_for_route(graph, route["nodes"]) if callable(maneuvers_for_route) else []routes.append(9 unmodified lines"is_loop": bool(route.get("is_loop")),"route_quality": {"art_ready": generation_mode == "fast_walk_roads" and bool(selected_label),**({"gpx_similarity": similarity, "gpx_example_index": example_index,"gpx_footprint_km": footprint_km,"gpx_rank_score": gpx_route_rank_score(similarity, footprint_km)} if examples else {}),"target_shape": {"score": shape_quality,"route_coverage": shape_quality,10 unmodified linesif examples:routes.sort(key=lambda route: (-route["route_quality"]["gpx_rank_score"],-route["route_quality"]["gpx_similarity"],0 if auto_distance else abs(route["length_km"] - target_distance_km),))routes = routes[:route_count]elif auto_distance:
4 unmodified lines56789104 unmodified linesimport mathdef _sample_outline(points: list[tuple[float, float]], count: int = 24) -> list[complex]:if len(points) < 3:return []4 unmodified lines567891011121314151617181920212223242526274 unmodified linesimport mathdef route_footprint_km(coords: list[tuple[float, float]] | list[list[float]]) -> float:"""Balanced geographic span; a long narrow detour should not look wide."""if len(coords) < 2:return 0.0latitudes = [point[0] for point in coords]longitudes = [point[1] for point in coords]center_lat = (min(latitudes) + max(latitudes)) / 2width_km = (max(longitudes) - min(longitudes)) * 111.32 * math.cos(math.radians(center_lat))height_km = (max(latitudes) - min(latitudes)) * 111.32return math.sqrt(max(0.0, width_km * height_km))def gpx_route_rank_score(similarity: float, footprint_km: float) -> float:"""Prefer a broad drawing when GPX fit is close, without rewarding distance alone."""return similarity + 0.04 * min(max(footprint_km, 0.0) / 7.0, 1.0)def _sample_outline(points: list[tuple[float, float]], count: int = 24) -> list[complex]:if len(points) < 3:return []
10 unmodified lines1112131415161798 unmodified lines11611711811912012112217 unmodified lines14014114214314414514620 unmodified lines1671681691701711728 unmodified lines1811821831841851861871 unmodified line18919019119219319419510 unmodified linesimport requestsfrom app.services.gpx_shape_similarity import best_gpx_shape_matchPROVIDER_URL = os.getenv("WALK_ROUTE_PROVIDER_URL", "https://valhalla1.openstreetmap.de/route")HEADERS = {"User-Agent": "RunTheShape/1.0 (+https://github.com/hwangtutu/Tranimal_Run)"}98 unmodified linescontinue# Auto mode searches several sizes of the same GPX drawing. The# result's measured length, rather than a hidden default, is shown.requested_size_km = (3, 5, 8, 12, 16, 20, 6, 10)[attempt] if auto_distance else target_distance_kmscale = requested_size_km * 1000 / perimeter / 1.2angle = generation_angle(generation_id) + attempt * math.pi * (3 - math.sqrt(5))# Shorter retries also work near a coast or on a small island.17 unmodified linestrip = response.json().get("trip", {})summary = trip.get("summary", {})length = float(summary.get("length", 0))if summary.get("has_ferry") or not math.isfinite(length) or length <= 0 or (auto_distance and not 1.5 <= length <= 20):continuecoords = []leg_shapes = []20 unmodified lines# Matching any unrelated dog example could give a misleadingly# high score even when the placed contour was badly distorted.similarity, _ = best_gpx_shape_match(coords, [source_example]) if templates else (0.0, None)waypoint_error_m = Noneif templates and len(leg_shapes) == len(locations) - 1:snapped = [leg_shapes[0][0]] + [leg[-1] for leg in leg_shapes]8 unmodified lines"estimated_route":False,"results":[{"label":label,"score":0.0,"shape":0.0}],"route_quality":{"art_ready":False,**({"gpx_similarity":similarity,"gpx_example_index":source_example_index,"road_waypoint_error_m":waypoint_error_m} if templates else {})}})except requests.RequestException as exc:if not isinstance(exc, requests.HTTPError) or (exc.response is not None and exc.response.status_code in {429,502,503,504}):break1 unmodified linecontinueif not routes:return Noneroutes.sort(key=lambda route: (-route["route_quality"].get("gpx_similarity", 0.0),route["route_quality"].get("road_waypoint_error_m") or 0.0,0 if auto_distance else abs(route["length_km"]-target_distance_km)))routes = routes[:route_count]10 unmodified lines1112131415161798 unmodified lines11611711811912012112217 unmodified lines14014114214314414514620 unmodified lines1671681691701711721738 unmodified lines1821831841851861871881891901 unmodified line19219319419519619719819910 unmodified linesimport requestsfrom app.services.gpx_shape_similarity import best_gpx_shape_match, gpx_route_rank_score, route_footprint_kmPROVIDER_URL = os.getenv("WALK_ROUTE_PROVIDER_URL", "https://valhalla1.openstreetmap.de/route")HEADERS = {"User-Agent": "RunTheShape/1.0 (+https://github.com/hwangtutu/Tranimal_Run)"}98 unmodified linescontinue# Auto mode searches several sizes of the same GPX drawing. The# result's measured length, rather than a hidden default, is shown.requested_size_km = (6, 10, 14, 18, 24, 30, 36, 42)[attempt] if auto_distance else target_distance_kmscale = requested_size_km * 1000 / perimeter / 1.2angle = generation_angle(generation_id) + attempt * math.pi * (3 - math.sqrt(5))# Shorter retries also work near a coast or on a small island.17 unmodified linestrip = response.json().get("trip", {})summary = trip.get("summary", {})length = float(summary.get("length", 0))if summary.get("has_ferry") or not math.isfinite(length) or length <= 0 or (auto_distance and not 1.5 <= length <= 45):continuecoords = []leg_shapes = []20 unmodified lines# Matching any unrelated dog example could give a misleadingly# high score even when the placed contour was badly distorted.similarity, _ = best_gpx_shape_match(coords, [source_example]) if templates else (0.0, None)footprint_km = route_footprint_km(coords) if templates else 0.0waypoint_error_m = Noneif templates and len(leg_shapes) == len(locations) - 1:snapped = [leg_shapes[0][0]] + [leg[-1] for leg in leg_shapes]8 unmodified lines"estimated_route":False,"results":[{"label":label,"score":0.0,"shape":0.0}],"route_quality":{"art_ready":False,**({"gpx_similarity":similarity,"gpx_example_index":source_example_index,"road_waypoint_error_m":waypoint_error_m,"gpx_footprint_km":footprint_km,"gpx_rank_score":gpx_route_rank_score(similarity, footprint_km)} if templates else {})}})except requests.RequestException as exc:if not isinstance(exc, requests.HTTPError) or (exc.response is not None and exc.response.status_code in {429,502,503,504}):break1 unmodified linecontinueif not routes:return Noneroutes.sort(key=lambda route: (-route["route_quality"].get("gpx_rank_score", 0.0),-route["route_quality"].get("gpx_similarity", 0.0),route["route_quality"].get("road_waypoint_error_m") or 0.0,0 if auto_distance else abs(route["length_km"]-target_distance_km)))routes = routes[:route_count]
3 unmodified lines4567891013 unmodified lines2425263 unmodified linessys.path.insert(0, str(Path(__file__).resolve().parents[1]))from app.services.gpx_shape_similarity import best_gpx_shape_matchdef test_finds_closest_gpx_outline_independent_of_rotation_and_location():13 unmodified linesdef test_empty_or_short_route_has_no_match():assert best_gpx_shape_match([[37.5, 127.0]], [[(0, 0), (1, 0), (0, 1)]]) == (0.0, None)3 unmodified lines4567891013 unmodified lines242526272829303132333435363 unmodified linessys.path.insert(0, str(Path(__file__).resolve().parents[1]))from app.services.gpx_shape_similarity import best_gpx_shape_match, gpx_route_rank_score, route_footprint_kmdef test_finds_closest_gpx_outline_independent_of_rotation_and_location():13 unmodified linesdef test_empty_or_short_route_has_no_match():assert best_gpx_shape_match([[37.5, 127.0]], [[(0, 0), (1, 0), (0, 1)]]) == (0.0, None)def test_wide_gpx_contour_wins_close_fit_but_not_poor_fit():narrow = [[37.5, 127.0], [37.55, 127.001], [37.5, 127.0]]wide = [[37.5, 127.0], [37.55, 127.06], [37.5, 127.0]]narrow_span = route_footprint_km(narrow)wide_span = route_footprint_km(wide)assert wide_span > narrow_spanassert gpx_route_rank_score(0.96, wide_span) > gpx_route_rank_score(0.97, narrow_span)assert gpx_route_rank_score(0.96, wide_span) < gpx_route_rank_score(0.99, narrow_span)
184 unmodified lines185186187184 unmodified linesfirst = json.loads(get.call_args_list[0].kwargs['params']['json'])['locations']second = json.loads(get.call_args_list[1].kwargs['params']['json'])['locations']assert first[1] != second[1]184 unmodified lines185186187188189190191192193194195196197198199200201202203204184 unmodified linesfirst = json.loads(get.call_args_list[0].kwargs['params']['json'])['locations']second = json.loads(get.call_args_list[1].kwargs['params']['json'])['locations']assert first[1] != second[1]def test_auto_distance_keeps_wide_measured_road_route(monkeypatch):import jsondef following_provider(_url, *, params, **_kwargs):locations = json.loads(params['json'])['locations']legs = [{'shape': encode([[a['lat'], a['lon']], [b['lat'], b['lon']]])}for a, b in zip(locations, locations[1:])]return SimpleNamespace(raise_for_status=lambda: None,json=lambda: {'trip': {'summary': {'length': 30.0, 'has_ferry': False}, 'legs': legs}})monkeypatch.setattr(requests, 'get', following_provider)example = [(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]result = walking.generate_walking_fallback(**options(), templates=[example],generation_id='wide-gpx', auto_distance=True)assert result['best_route']['length_km'] == 30.0assert result['best_route']['route_quality']['gpx_footprint_km'] > 0assert result['target_distance_km'] == 30.0
2415 unmodified lines24162417241824192420242124228 unmodified lines243124322433243424352436243786 unmodified lines252425252526252725282529253072 unmodified lines26032604260526062607260826092415 unmodified linesshuffled_examples = random.sample(examples, len(examples)) if examples else []for attempt in range(guided_attempts):try:guided_target_m = (3000.0, 5000.0, 8000.0, 12000.0, 16000.0)[attempt % 5] if auto_distance else target_distance_mgeo_points = guided_geo_waypoints(graph=graph,label=str(selected_label),8 unmodified linesif len(route_nodes) < 18:continuelength_m = route_length_m(graph, route_nodes)if length_m <= 0 or (auto_distance and not 1500.0 <= length_m <= 20000.0):continueunique_ratio = len(set(route_nodes)) / len(route_nodes)if unique_ratio < 0.50:86 unmodified linescontinuelength_m = route_length_m(graph, route_nodes)if length_m <= 0 or (auto_distance and not 1500.0 <= length_m <= 20000.0):continueunique_ratio = len(set(route_nodes)) / len(route_nodes)if unique_ratio < 0.55:72 unmodified linesif len(route_nodes) < 10:continuelength_m = route_length_m(graph, route_nodes)if length_m <= 0 or (auto_distance and not 1500.0 <= length_m <= 20000.0):continuepts = route_points(graph, route_nodes)shape_quality, shape_metrics = route_shape_quality_with_metrics(pts, close_loop=False)2415 unmodified lines24162417241824192420242124228 unmodified lines243124322433243424352436243786 unmodified lines252425252526252725282529253072 unmodified lines26032604260526062607260826092415 unmodified linesshuffled_examples = random.sample(examples, len(examples)) if examples else []for attempt in range(guided_attempts):try:guided_target_m = (6000.0, 10000.0, 14000.0, 18000.0, 24000.0, 30000.0, 36000.0)[attempt % 7] if auto_distance else target_distance_mgeo_points = guided_geo_waypoints(graph=graph,label=str(selected_label),8 unmodified linesif len(route_nodes) < 18:continuelength_m = route_length_m(graph, route_nodes)if length_m <= 0 or (auto_distance and not 1500.0 <= length_m <= 45000.0):continueunique_ratio = len(set(route_nodes)) / len(route_nodes)if unique_ratio < 0.50:86 unmodified linescontinuelength_m = route_length_m(graph, route_nodes)if length_m <= 0 or (auto_distance and not 1500.0 <= length_m <= 45000.0):continueunique_ratio = len(set(route_nodes)) / len(route_nodes)if unique_ratio < 0.55:72 unmodified linesif len(route_nodes) < 10:continuelength_m = route_length_m(graph, route_nodes)if length_m <= 0 or (auto_distance and not 1500.0 <= length_m <= 45000.0):continuepts = route_points(graph, route_nodes)shape_quality, shape_metrics = route_shape_quality_with_metrics(pts, close_loop=False)
api/ai-service/app/api/v1/endpoints/route_generation.py+7-3
api/ai-service/app/services/gpx_shape_similarity.py+17
api/ai-service/app/services/walking_route_fallback.py+9-5
api/ai-service/tests/test_gpx_shape_similarity.py+11-1
api/ai-service/tests/test_walking_route_fallback.py+17
router/ai/scripts/clip_osm_region_test.py+4-4