Skip to content

armgit / Aleph

Public Imported from GitHub
0

Give satellite imagery, terrain data, buildings, streetview photos to your LLM

Add step-based street sampling

Belluxx26d7cb34202b
diff --git a/aleph.py b/aleph.py
index ca9ef94..1002963 100644
--- a/aleph.py
+++ b/aleph.py
@@ -85,14 +85,17 @@ def query(args, progress):
raise ValueError("--match and --best-match require --place or --street.")
keys = ("at", "place", "match", "best_match")
if args.command == "streetview":
- if args.street is None and (args.stops is not None or args.view is not None
+ if args.street is None and (args.stops is not None or args.step is not None
+ or args.view is not None
or args.route is not None or args.reverse):
- raise ValueError("--stops, --view, --route, and --reverse require --street.")
+ raise ValueError("--stops, --step, --view, --route, and --reverse require --street.")
+ if args.street is not None and args.stops is None and args.step is None:
+ raise ValueError("--street requires --stops or --step.")
if args.street is not None and (args.heading is not None or args.look_at is not None or args.radius is not None):
raise ValueError("Use --view for a street sequence; --heading, --look-at, and --radius are for single views.")
if args.pano_id and args.radius is not None:
raise ValueError("--radius applies to coordinates or a place name.")
- keys += ("pano_id", "street", "route", "reverse", "stops", "view", "heading",
+ keys += ("pano_id", "street", "route", "reverse", "stops", "step", "view", "heading",
"look_at", "pitch", "fov", "radius", "streetview_format")
operation = quick.street_photos
else:
diff --git a/docs/cli.md b/docs/cli.md
index 967928e..85e3007 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -69,10 +69,15 @@ alephgeo resolve --at 41.8902 12.4922 --nearby --radius 200
# Request photos at ten stops, looking forward along the street
alephgeo streetview --street "Via del Corso, Rome" --best-match --stops 10 -o captures
-# Photograph both sides at each stop
-alephgeo streetview --street "Via del Corso, Rome" --best-match --stops 10 --view both -o captures
+# Photograph both sides, targeting no more than 10 meters between stops
+alephgeo 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.
+
`--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.
## Download an area
diff --git a/src/cli.py b/src/cli.py
index aef715c..6e4ec48 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -93,7 +93,9 @@ def _streetview_command(commands):
# 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("--stops", type=int, help="street positions (default: 10)")
+ sampling = street.add_mutually_exclusive_group()
+ sampling.add_argument("--stops", type=int, help="number of street positions")
+ 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)")
# Camera settings shared by single views and street sequences.
diff --git a/src/quick.py b/src/quick.py
index ec6f360..3bdd64b 100644
--- a/src/quick.py
+++ b/src/quick.py
@@ -34,14 +34,16 @@ def location(client, *, at=None, place=None, match=None, best_match=False, endpo
def street_photos(client, output, progress, *, at=None, place=None, pano_id=None,
street=None, match=None, best_match=False, endpoint=places.GEOCODER, route=None,
- reverse=False, stops=10, view="forward", heading=0, look_at=None,
+ reverse=False, stops=None, step=None, view="forward", heading=0, look_at=None,
pitch=0, fov=75, radius=50, streetview_format="jpg"):
streetview.validate_angle(heading, "heading")
streetview.validate_angle(pitch, "pitch")
fov = streetview.validate_fov(fov)
places.positive(radius, "radius")
- if type(stops) is not int or stops < 1:
+ if stops is not None and (type(stops) is not int or stops < 1):
raise ValueError("stops must be a positive whole number.")
+ if step is not None:
+ places.positive(step, "step")
if look_at is not None:
places.point(look_at)
selected_place, selected_route = None, None
@@ -49,6 +51,7 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=None
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"]
south, west, north, east = extent(points)
lower, upper = places.around((south, west), 80), places.around((north, east), 80)
@@ -56,7 +59,7 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=None
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, stops)
+ samples, gaps = routes.match_views(views, selected_route, context, spacing, targets)
elif pano_id:
if not streetview.PANO_ID.fullmatch(pano_id):
raise ValueError("Invalid panorama ID.")
@@ -75,8 +78,10 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=None
output.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=stops if street else 1, saved_stops=0,
+ requested_stops=len(targets) if street else 1, 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"}
offsets = {"forward": 0, "backward": 180, "left": -90, "right": 90}
diff --git a/src/routes.py b/src/routes.py
index 376d429..6c74e69 100644
--- a/src/routes.py
+++ b/src/routes.py
@@ -1,5 +1,6 @@
"""Join named OSM ways into ordered, unbranched street routes."""
+import math
from collections import defaultdict
from itertools import pairwise
@@ -61,6 +62,23 @@ def describe(route, index):
closed=route["points"][0] == route["points"][-1])
+def sampling(route, *, step=None, stops=None):
+ """Normalize a sampling request to meter spacing and target distances."""
+ line = Line(route["points"])
+ closed = line.points[0] == line.points[-1]
+ if stops == 1:
+ return line.length, [line.length / 2]
+ if stops is not None:
+ intervals = stops if closed else stops - 1
+ else:
+ # Fit complete intervals without exceeding the requested step.
+ intervals = max(1, math.ceil(line.length / step))
+ step = line.length / intervals
+ targets = [(i + 0.5) * step for i in range(intervals)] if closed else [
+ i * step for i in range(intervals)] + [line.length]
+ return step, targets
+
+
def resolve(client, place, *, route=None, reverse=False, progress=lambda *args: None):
if not place["id"].startswith("way/"):
raise RequestError("place_not_found", "Choose a street represented by an OSM way.")
@@ -83,43 +101,37 @@ def resolve(client, place, *, route=None, reverse=False, progress=lambda *args:
return selected
-def match_views(views, route, context, stops):
+def match_views(views, route, context, step, targets):
"""Keep distinct panoramas on the selected street, in target-distance order."""
line = Line(route["points"])
lines = [Line(part["points"]) for part in context]
index = RoadIndex(lines)
- closed = line.points[0] == line.points[-1]
- spacing = line.length / max(1, stops if closed else stops - 1)
candidates = []
for view in views:
location = (view["lat"], view["lon"])
- road = streetview.match_road(context, lines, index, location, spacing)
+ road = streetview.match_road(context, lines, index, location, step)
if road is None or context[road["path_index"]]["osm_id"] not in route["way_ids"]:
continue
meters, separation = line.project(location)
if separation <= 30:
candidates.append(dict(view, path_meters=meters, road_distance_m=separation,
- heading=line.heading(meters, spacing)))
+ heading=line.heading(meters, step)))
# Coverage can include different panorama IDs at the same physical position.
unique = []
for candidate in sorted(candidates, key=lambda item: (item["path_meters"], item["road_distance_m"], item["pano_id"])):
if not unique or candidate["path_meters"] - unique[-1]["path_meters"] >= 0.1:
unique.append(candidate)
selected, gaps, used = [], [], set()
- for stop in range(stops):
- if closed:
- target = (stop + 0.5) * spacing
- else:
- target = line.length / 2 if stops == 1 else stop * spacing
+ for stop, target in enumerate(targets, 1):
eligible = [view for view in unique if view["pano_id"] not in used
- and abs(view["path_meters"] - target) <= spacing / 2 + 0.01]
+ and abs(view["path_meters"] - target) <= step / 2 + 0.01]
if eligible:
chosen = min(eligible, key=lambda view: (abs(view["path_meters"] - target),
view["road_distance_m"], view["pano_id"]))
used.add(chosen["pano_id"])
- selected.append(dict(chosen, stop=stop + 1, target_meters=target,
+ selected.append(dict(chosen, stop=stop, target_meters=target,
requested_location=list(line.at(target))))
else:
- gaps.append(dict(stop=stop + 1, target_meters=target, reason="no_coverage"))
+ gaps.append(dict(stop=stop, target_meters=target, reason="no_coverage"))
selected.sort(key=lambda view: view["path_meters"])
return selected, gaps
diff --git a/tests/test_routes.py b/tests/test_routes.py
new file mode 100644
index 0000000..38f1909
--- /dev/null
+++ b/tests/test_routes.py
@@ -0,0 +1,51 @@
+"""Named-street route sampling behavior."""
+
+import unittest
+
+from src import routes
+from src.geo import Line, destination
+
+
+class RouteSamplingTests(unittest.TestCase):
+ 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
+ step, targets = routes.sampling(route, step=10)
+ self.assertEqual(len(targets), 12)
+ self.assertEqual(targets[0], 0)
+ self.assertEqual(targets[-1], length)
+ self.assertLessEqual(step, 10)
+ self.assertEqual(routes.sampling(route, stops=12), (step, targets))
+ self.assertEqual(routes.sampling(route, stops=1), (length, [length / 2]))
+ self.assertEqual(routes.sampling(route, step=200), (length, [0, length]))
+
+ def test_loop_sampling_does_not_duplicate_the_start(self):
+ route = dict(points=[(0, 0), (0, 0.001), (0.001, 0.001), (0, 0)])
+ length = Line(route["points"]).length
+ step, targets = routes.sampling(route, stops=4)
+ self.assertEqual(len(targets), 4)
+ self.assertAlmostEqual(step, length / 4)
+ self.assertEqual(targets[0], step / 2)
+ self.assertEqual(targets[-1], length - step / 2)
+
+ def test_matcher_uses_meter_targets_and_reports_missing_coverage(self):
+ points = [(0, 0), destination((0, 0), 90, 101)]
+ route = dict(points=points, way_ids=[1])
+ context = [dict(points=points, osm_id=1)]
+ line = Line(points)
+ views = [dict(pano_id=str(i), lat=line.at(meters)[0], lon=line.at(meters)[1])
+ for i, meters in enumerate([0, 50, 101])]
+ # A second panorama at the same position must not create another stop.
+ views.append(dict(views[1], pano_id="duplicate"))
+ step, targets = routes.sampling(route, step=10)
+ selected, gaps = routes.match_views(views, route, context, step, targets)
+ self.assertEqual(len(selected), 3)
+ self.assertEqual(len(gaps), len(targets) - 3)
+ self.assertEqual(sorted(item["stop"] for item in selected + gaps),
+ list(range(1, len(targets) + 1)))
+ for item in selected:
+ self.assertLessEqual(abs(item["path_meters"] - item["target_meters"]), step / 2 + 0.01)
+
+
+if __name__ == "__main__":
+ unittest.main()