Spaces:
Sleeping
Sleeping
Sync DemoService 42773efa3fee367a7ac26de8f7f0006519a6e1e8
Browse filesFiles changed (6)
- api/ai-service/app/api/v1/endpoints/route_generation.py+2-2
- api/ai-service/tests/test_gpx_shape_templates.py+15
- api/ai-service/tests/test_route_generation_recovery.py+4-3
- router/ai/data/dog_shape_templates_all.jsonAdded
- router/ai/scripts/build_dog_shape_templates.pyAdded+43
- router/ai/scripts/clip_osm_region_test.py+1-1
436 unmodified lines437438439440441442443444436 unmodified linesrank_projections = getattr(module, "rank_road_template_projections", None)for search_distance_km in (6.0, 11.0, 18.0):template_kwargs = {}if selected_label == "symbol_star" and callable(rank_projections):# Screen every supplied star outline against this road graph;# only the best fits enter the expensive shortest-path stage.template_kwargs["template_examples"] = rank_projections(graph, examples, search_distance_km * 1000.0,436 unmodified lines437438439440441442443444436 unmodified linesrank_projections = getattr(module, "rank_road_template_projections", None)for search_distance_km in (6.0, 11.0, 18.0):template_kwargs = {}if selected_label in {"symbol_star", "dog"} and callable(rank_projections):# Screen every supplied animal/shape outline against this road graph;# only the best fits enter the expensive shortest-path stage.template_kwargs["template_examples"] = rank_projections(graph, examples, search_distance_km * 1000.0,
10 unmodified lines11121314151652 unmodified lines69707172737410 unmodified linesTSHIRT_TEMPLATES = ROOT / "router" / "ai" / "data" / "tshirt_shape_templates.json"STAR_TEMPLATES = ROOT / "router" / "ai" / "data" / "star_shape_templates.json"ALL_STAR_TEMPLATES = ROOT / "router" / "ai" / "data" / "star_shape_templates_all.json"def test_dog_and_star_gpx_examples_are_normalized_and_closed():52 unmodified linesassert all([tuple(point) for point in outline] in loaded["symbol_star"] for outline in all_outlines)def test_every_star_outline_is_screened_before_road_pathfinding():import mathimport networkx as nx10 unmodified lines1112131415161752 unmodified lines707172737475767778798081828384858687888910 unmodified linesTSHIRT_TEMPLATES = ROOT / "router" / "ai" / "data" / "tshirt_shape_templates.json"STAR_TEMPLATES = ROOT / "router" / "ai" / "data" / "star_shape_templates.json"ALL_STAR_TEMPLATES = ROOT / "router" / "ai" / "data" / "star_shape_templates_all.json"ALL_DOG_TEMPLATES = ROOT / "router" / "ai" / "data" / "dog_shape_templates_all.json"def test_dog_and_star_gpx_examples_are_normalized_and_closed():52 unmodified linesassert all([tuple(point) for point in outline] in loaded["symbol_star"] for outline in all_outlines)def test_new_dog_gpx_examples_are_available_for_road_generation():outlines = json.loads(ALL_DOG_TEMPLATES.read_text(encoding="utf-8"))["dog"]assert len(outlines) == 998assert len({tuple(map(tuple, outline)) for outline in outlines}) == 998assert all(outline[0] == outline[-1] for outline in outlines)script = ROOT / "router" / "ai" / "scripts" / "clip_osm_region_test.py"tree = ast.parse(script.read_text(encoding="utf-8-sig"))loader = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_load_gpx_shape_templates")scope = {"__file__": str(script), "Path": Path, "json": json}exec(compile(ast.Module(body=[loader], type_ignores=[]), str(script), "exec"), scope)loaded = scope["_load_gpx_shape_templates"]()assert all([tuple(point) for point in outline] in loaded["dog"] for outline in outlines)def test_every_star_outline_is_screened_before_road_pathfinding():import mathimport networkx as nx
156 unmodified lines1571581591601611621638 unmodified lines1721731741751761771782 unmodified lines181182183184185186187156 unmodified linesassert result["target_distance_km"] == 0def test_star_search_screens_all_outlines_before_road_routing(monkeypatch):examples = [[(index, 0), (index, 1), (index + 1, 1), (index, 0)] for index in range(1000)]screened = []routed = []8 unmodified lines"shape_quality": 0.6, "is_loop": True}]module = SimpleNamespace(GPX_SHAPE_TEMPLATES={"symbol_star": examples},_build_or_get_walk_graph=lambda *_: (object(), "test"),rank_road_template_projections=screen,generate_candidate_routes=candidates,2 unmodified linesmonkeypatch.setattr(routes, "_route_nodes_to_coords", lambda _graph, nodes: [[nodes[0], 0], [nodes[1], 1]])monkeypatch.setattr(routes, "best_gpx_shape_match", lambda _coords, templates: (0.9, len(templates) - 1))routes._run_fast_road_pipeline(module, place=None, center_lat=37, center_lon=127,radius_km=5, route_count=2, target_distance_km=6, selected_label="symbol_star", shape_priority=True)assert screened == [(1000, 6000), (1000, 11000), (1000, 18000)]assert len(routed) == 3assert all(len(templates) == 36 and templates[-1] == examples[-1] for templates in routed)156 unmodified lines1571581591601611621631648 unmodified lines1731741751761771781792 unmodified lines182183184185186187188156 unmodified linesassert result["target_distance_km"] == 0@pytest.mark.parametrize("label", ["symbol_star", "dog"])def test_gpx_search_screens_all_outlines_before_road_routing(monkeypatch, label):examples = [[(index, 0), (index, 1), (index + 1, 1), (index, 0)] for index in range(1000)]screened = []routed = []8 unmodified lines"shape_quality": 0.6, "is_loop": True}]module = SimpleNamespace(GPX_SHAPE_TEMPLATES={label: examples},_build_or_get_walk_graph=lambda *_: (object(), "test"),rank_road_template_projections=screen,generate_candidate_routes=candidates,2 unmodified linesmonkeypatch.setattr(routes, "_route_nodes_to_coords", lambda _graph, nodes: [[nodes[0], 0], [nodes[1], 1]])monkeypatch.setattr(routes, "best_gpx_shape_match", lambda _coords, templates: (0.9, len(templates) - 1))routes._run_fast_road_pipeline(module, place=None, center_lat=37, center_lon=127,radius_km=5, route_count=2, target_distance_km=6, selected_label=label, shape_priority=True)assert screened == [(1000, 6000), (1000, 11000), (1000, 18000)]assert len(routed) == 3assert all(len(templates) == 36 and templates[-1] == examples[-1] for templates in routed)
12345678910111213141516171819202122232425262728293031323334353637383940414243"""Package location-free dog outlines from a multi-track GPX file.
Usage: python build_dog_shape_templates.py DOG_ALL.gpx OUTPUT_JSON"""
from __future__ import annotations
import jsonimport sysimport xml.etree.ElementTree as ETfrom pathlib import Path
from build_gpx_shape_templates import normalized_outline_from_track
def build(source: Path) -> dict[str, list[list[list[float]]]]: outlines = [] seen = set() root = ET.parse(source).getroot() for index, track in enumerate(node for node in root if node.tag.rsplit("}", 1)[-1] == "trk"): points = [ (float(node.attrib["lat"]), float(node.attrib["lon"])) for node in track.iter() if node.tag.rsplit("}", 1)[-1] == "trkpt" ] outline = normalized_outline_from_track(points, f"{source.name}:{index}") signature = tuple(map(tuple, outline)) if signature not in seen: seen.add(signature) outlines.append(outline) if not outlines: raise ValueError("No dog outlines found") return {"dog": outlines}
if __name__ == "__main__": if len(sys.argv) != 3: raise SystemExit("Usage: build_dog_shape_templates.py DOG_ALL.gpx OUTPUT_JSON") output = Path(sys.argv[2]) templates = build(Path(sys.argv[1])) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(templates, separators=(",", ":")) + "\n", encoding="utf-8") print({label: len(items) for label, items in templates.items()})146 unmodified lines147148149150151152153146 unmodified linesdata_dir = Path(__file__).resolve().parents[1] / "data"templates: dict[str, list[list[tuple[float, float]]]] = {"dog": [], "symbol_star": [], "t_shirt": []}seen: dict[str, set[tuple[tuple[float, float], ...]]] = {label: set() for label in templates}for filename in ("gpx_shape_templates.json", "approved_road_shape_templates.json", "tshirt_shape_templates.json", "star_shape_templates.json", "star_shape_templates_all.json"):try:payload = json.loads((data_dir / filename).read_text(encoding="utf-8"))except (OSError, ValueError, TypeError):146 unmodified lines147148149150151152153146 unmodified linesdata_dir = Path(__file__).resolve().parents[1] / "data"templates: dict[str, list[list[tuple[float, float]]]] = {"dog": [], "symbol_star": [], "t_shirt": []}seen: dict[str, set[tuple[tuple[float, float], ...]]] = {label: set() for label in templates}for filename in ("gpx_shape_templates.json", "approved_road_shape_templates.json", "tshirt_shape_templates.json", "star_shape_templates.json", "star_shape_templates_all.json", "dog_shape_templates_all.json"):try:payload = json.loads((data_dir / filename).read_text(encoding="utf-8"))except (OSError, ValueError, TypeError):
api/ai-service/app/api/v1/endpoints/route_generation.py+2-2
api/ai-service/tests/test_gpx_shape_templates.py+15
api/ai-service/tests/test_route_generation_recovery.py+4-3
router/ai/data/dog_shape_templates_all.jsonAdded
router/ai/scripts/build_dog_shape_templates.pyAdded+43
router/ai/scripts/clip_osm_region_test.py+1-1