Give satellite imagery, terrain data, buildings, streetview photos to your LLM
Better street section management
Belluxx502667d0b46e
diff --git a/aleph.py b/aleph.pyindex 1002963..320dc18 100644--- a/aleph.py+++ b/aleph.py@@ -145,12 +145,6 @@ def error_details(code, details):candidates = details.get("candidates", [])if code == "ambiguous_place" and candidates:place_rows(candidates, sys.stderr)- elif code == "ambiguous_route" and candidates:- rows(("ROUTE", "SECTION"), [- (item["route"], f"{item['length_m']:.0f} m · {coordinates(item['start'])} → "- f"{coordinates(item['end'])}" + (" (loop)" if item["closed"] else ""))- for item in candidates- ], sys.stderr)if details.get("gaps"):count = len(details["gaps"])print(f" Missing coverage at {count} {'stop' if count == 1 else 'stops'}.", file=sys.stderr)diff --git a/docs/cli.md b/docs/cli.mdindex 85e3007..1231521 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -66,19 +66,18 @@ alephgeo resolve --at 41.8902 12.4922 --nearby --radius 200## Take photos along a street```sh-# Request photos at ten stops, looking forward along the street+# Ten stops total, looking forwardalephgeo streetview --street "Via del Corso, Rome" --best-match --stops 10 -o captures-# Photograph both sides, targeting no more than 10 meters between stops+# Both sides, targeting 10-meter spacingalephgeo streetview --street "Via del Corso, Rome" --best-match --step 10 --view both -o captures```-Every street sequence requires either `--stops N` or `--step METERS`.-With `--step`, positions are distributed evenly along the selected route with-no interval longer than the requested distance between target positions.-Actual photo spacing depends on available panoramas and can be larger.+Use `--stops N` for a total count or `--step METERS` for target spacing.-`--view` accepts `forward`, `backward`, `left`, `right`, or `both`. Add `--reverse` to travel in the opposite direction. If the street has multiple branches, repeat with `--route N` using a returned route number. Stops without coverage are skipped.+All street sections are included by default. Use `--route N` to select one (section numbers are in `result.json`).++`--view` accepts `forward`, `backward`, `left`, `right`, or `both`. Add `--reverse` to reverse each section's direction.## Download an areadiff --git a/src/cli.py b/src/cli.pyindex 6e4ec48..318b983 100644--- a/src/cli.py+++ b/src/cli.py@@ -91,10 +91,10 @@ def _streetview_command(commands):angle.add_argument("--look-at", nargs=2, type=float, metavar=("LAT", "LON"), help="turn a single view toward this point")# Street route, sampling, and orientation.- street.add_argument("--route", type=int, help="choose a returned branch of a street")- street.add_argument("--reverse", action="store_true", help="reverse the street traversal order")+ street.add_argument("--route", type=int, help="capture only this numbered street section (default: all sections)")+ street.add_argument("--reverse", action="store_true", help="reverse traversal within each street section")sampling = street.add_mutually_exclusive_group()- sampling.add_argument("--stops", type=int, help="number of street positions")+ sampling.add_argument("--stops", type=int, help="total number of positions across the selected street sections")sampling.add_argument("--step", type=float, help="target spacing between street positions in meters")street.add_argument("--view", choices=("forward", "backward", "left", "right", "both"), help="street orientation; both saves left and right (default: forward)")diff --git a/src/quick.py b/src/quick.pyindex 3bdd64b..2c64f35 100644--- a/src/quick.py+++ b/src/quick.py@@ -46,20 +46,32 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=Noneplaces.positive(step, "step")if look_at is not None:places.point(look_at)- selected_place, selected_route = None, None+ selected_place, selected_routes = None, []+ requested_stops = 1gaps = []if street is not None:selected_place = places.choose(client, street, match=match, best_match=best_match, street=True, endpoint=endpoint)- selected_route = routes.resolve(client, selected_place, route=route, reverse=reverse, progress=progress)- spacing, targets = routes.sampling(selected_route, step=step, stops=stops)- points = selected_route["points"]+ selected_routes = routes.resolve(client, selected_place, route=route, reverse=reverse, progress=progress)+ points = [point for section in selected_routes for point in section["points"]]south, west, north, east = extent(points)lower, upper = places.around((south, west), 80), places.around((north, east), 80)area = bounds((lower[0], lower[1], upper[2], upper[3]))views = coverage(client, area, progress)ways, _ = client.maps.data(area, progress=progress)context = streetview.roads(ways, area, "all")- samples, gaps = routes.match_views(views, selected_route, context, spacing, targets)+ samples, requested_stops = [], 0+ counts = routes.allocate_stops(selected_routes, stops) if stops is not None else [None] * len(selected_routes)+ for section, count in zip(selected_routes, counts):+ if count == 0:+ continue+ spacing, targets = routes.sampling(section, step=step, stops=count)+ section_samples, section_gaps = routes.match_views(views, section, context, spacing, targets)+ for item in section_samples + section_gaps:+ item["route"] = section["route"]+ item["stop"] += requested_stops+ samples.extend(section_samples)+ gaps.extend(section_gaps)+ requested_stops += len(targets)elif pano_id:if not streetview.PANO_ID.fullmatch(pano_id):raise ValueError("Invalid panorama ID.")@@ -78,12 +90,13 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=Noneoutput.mkdir(parents=True, exist_ok=True)folder = Path(tempfile.mkdtemp(prefix="aleph-streetview-", dir=output))result = dict(command="streetview", status="partial", folder=str(folder), photos=[], gaps=gaps,- requested_stops=len(targets) if street else 1, saved_stops=0,+ requested_stops=requested_stops, saved_stops=0,place=selected_place, source="Google Street View", captured_at=now())if street and step is not None:result["requested_step_m"] = step- if selected_route:- result["route"] = {key: value for key, value in selected_route.items() if key != "points"}+ if selected_routes:+ result["routes"] = [{key: value for key, value in section.items() if key != "points"}+ for section in selected_routes]offsets = {"forward": 0, "backward": 180, "left": -90, "right": 90}directions = ("left", "right") if view == "both" else (view,)try:@@ -114,7 +127,10 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=Noneresult["photos"].append(photo)result["saved_stops"] += 1except MissingImagery as error:- gaps.append(dict(stop=sample["stop"], reason="no_coverage", message=str(error)))+ gap = dict(stop=sample["stop"], reason="no_coverage", message=str(error))+ if street:+ gap["route"] = sample["route"]+ gaps.append(gap)progress("Street View", index, len(samples))if not result["photos"]:raise RequestError("no_coverage", "The selected panoramas are no longer available.", folder=str(folder))diff --git a/src/routes.py b/src/routes.pyindex 6c74e69..40c89be 100644--- a/src/routes.py+++ b/src/routes.py@@ -62,6 +62,18 @@ def describe(route, index):closed=route["points"][0] == route["points"][-1])+def allocate_stops(sections, stops):+ """Divide a total stop count by section length, rounding largest remainders up."""+ lengths = [Line(section["points"]).length for section in sections]+ total = sum(lengths)+ quotas = [stops * length / total for length in lengths]+ counts = [math.floor(quota) for quota in quotas]+ order = sorted(range(len(sections)), key=lambda i: quotas[i] - counts[i], reverse=True)+ for index in order[:stops - sum(counts)]:+ counts[index] += 1+ return counts++def sampling(route, *, step=None, stops=None):"""Normalize a sampling request to meter spacing and target distances."""line = Line(route["points"])@@ -80,6 +92,7 @@ def sampling(route, *, step=None, stops=None):def resolve(client, place, *, route=None, reverse=False, progress=lambda *args: None):+ """Return every section by default, or one explicitly selected section."""if not place["id"].startswith("way/"):raise RequestError("place_not_found", "Choose a street represented by an OSM way.")name, ways = client.maps.street(place, progress)@@ -88,16 +101,16 @@ def resolve(client, place, *, route=None, reverse=False, progress=lambda *args:options = chains(ways)if not options:raise RequestError("place_not_found", "No usable street geometry was found.")- if route is None and len(options) > 1:- raise RequestError("ambiguous_route", "The street branches. Choose an ordered section with --route N.",- candidates=[describe(item, i) for i, item in enumerate(options, 1)])- choice = 1 if route is None else route- if not 1 <= choice <= len(options):+ if route is not None and not 1 <= route <= len(options):raise ValueError(f"--route must be from 1 to {len(options)}.")- selected = options[choice - 1]- if reverse:- selected["points"].reverse()- selected.update(describe(selected, choice), name=name, scope="connected_same_name_ways")+ selected = []+ for index, section in enumerate(options, 1):+ if route is not None and index != route:+ continue+ if reverse:+ section["points"].reverse()+ section.update(describe(section, index), name=name, scope="connected_same_name_ways")+ selected.append(section)return selecteddiff --git a/tests/test_routes.py b/tests/test_routes.pyindex 38f1909..44622ab 100644--- a/tests/test_routes.py+++ b/tests/test_routes.py@@ -1,12 +1,27 @@"""Named-street route sampling behavior."""+import jsonimport unittest+from io import BytesIO+from pathlib import Path+from tempfile import TemporaryDirectory+from unittest.mock import Mock, patch-from src import routes+from PIL import Image++from src import quick, routesfrom src.geo import Line, destinationclass RouteSamplingTests(unittest.TestCase):+ def test_total_stops_are_distributed_by_length_with_exact_rounding(self):+ sections = [dict(points=[(0, 0), (0, lon)]) for lon in (0.007, 0.002, 0.001)]+ for total, expected in ((10, [7, 2, 1]), (4, [3, 1, 0]), (1, [1, 0, 0])):+ with self.subTest(stops=total):+ self.assertEqual(routes.allocate_stops(sections, total), expected)+ self.assertEqual(routes.allocate_stops([sections[1]], 10), [10])+ self.assertEqual(routes.allocate_stops([sections[1]] * 3, 2), [1, 1, 0])+def test_meter_sampling_covers_endpoints_and_handles_short_routes(self):route = dict(points=[(0, 0), destination((0, 0), 90, 101)])length = Line(route["points"]).length@@ -47,5 +62,73 @@ class RouteSamplingTests(unittest.TestCase):self.assertLessEqual(abs(item["path_meters"] - item["target_meters"]), step / 2 + 0.01)+class BranchedStreetTests(unittest.TestCase):+ def setUp(self):+ self.ways = [dict(id=i, nodes=[0, i], points=[(0, 0), end],+ tags=dict(highway="residential", name="Test Street"))+ for i, end in enumerate([(0, -0.001), (0, 0.001), (0.001, 0)], 1)]+ self.client = Mock()+ self.client.maps.street.return_value = ("Test Street", self.ways)+ self.client.maps.data.return_value = (self.ways, [])+ self.place = dict(id="way/1", lat=0, lon=0, label="Test Street")++ def test_all_sections_default_and_optional_selection_with_reverse(self):+ sections = routes.resolve(self.client, self.place)+ self.assertEqual([section["route"] for section in sections], [1, 2, 3])+ self.assertEqual([section["way_ids"] for section in sections], [[1], [2], [3]])+ for section in sections:+ with self.subTest(route=section["route"]):+ selected = routes.resolve(self.client, self.place, route=section["route"], reverse=True)+ self.assertEqual(len(selected), 1)+ self.assertEqual(selected[0]["route"], section["route"])+ self.assertEqual(selected[0]["points"], section["points"][::-1])+ self.assertEqual(selected[0]["start"], section["end"])+ self.assertEqual(selected[0]["end"], section["start"])+ for invalid in (0, -1, 4):+ with self.subTest(route=invalid), self.assertRaisesRegex(ValueError, "--route must be from 1 to 3"):+ routes.resolve(self.client, self.place, route=invalid)++ def test_capture_combines_sections_and_tracks_missing_coverage(self):+ # Panoramas halfway along two branches; the third has no coverage.+ views = {str(i): dict(pano_id=str(i), lat=0, lon=lon)+ for i, lon in enumerate([-0.0005, 0.0005], 1)}+ with BytesIO() as buffer, Image.new("RGB", (1024, 576)) as image:+ image.save(buffer, format="PNG")+ pixels = buffer.getvalue()+ self.client.get.side_effect = lambda address, **kwargs: pixels if kwargs.get("missing_ok") else views[address]+ cases = [({"stops": 1}, [1, 2, 3], 1, [1]),+ ({"stops": 2}, [1, 2, 3], 2, [1, 2]),+ ({"stops": 3}, [1, 2, 3], 3, [1, 2]),+ ({"step": 70}, [1, 2, 3], 9, [1, 2]),+ ({"stops": 1, "route": 2}, [2], 1, [2])]+ for options, section_ids, requested, photographed in cases:+ with (self.subTest(options=options), TemporaryDirectory() as directory,+ patch("src.quick.places.choose", return_value=self.place),+ patch("src.quick.coverage", return_value=list(views.values())) as coverage,+ patch("src.quick.streetview.metadata_url", side_effect=lambda pano_id: pano_id),+ patch("src.quick.streetview.parse_metadata", side_effect=lambda data: data)):+ result = quick.street_photos(self.client, directory, lambda *args: None,+ street="Test Street", view="both", **options)+ self.assertEqual([section["route"] for section in result["routes"]], section_ids)+ self.assertEqual(result["requested_stops"], requested)+ self.assertEqual(result["saved_stops"], len(photographed))+ self.assertEqual([photo["route"] for photo in result["photos"]],+ [route for route in photographed for _ in range(2)])+ self.assertEqual([photo["view"] for photo in result["photos"]],+ [view for _ in photographed for view in ("left", "right")])+ self.assertEqual(len(result["gaps"]), requested - len(photographed))+ self.assertEqual(result["status"], "partial" if result["gaps"] else "complete")+ stops = {photo["stop"] for photo in result["photos"]}+ stops.update(gap["stop"] for gap in result["gaps"])+ self.assertEqual(stops, set(range(1, requested + 1)))+ if result["gaps"]:+ self.assertIn(3, {gap["route"] for gap in result["gaps"]})+ coverage.assert_called_once()+ folder = Path(result["folder"])+ self.assertEqual(list(Path(directory).resolve().iterdir()), [folder])+ self.assertEqual(len(list(folder.glob("*.jpg"))), 2 * len(photographed))+ self.assertEqual(json.loads((folder / "result.json").read_text()), result)++if __name__ == "__main__":unittest.main()