Give satellite imagery, terrain data, buildings, streetview photos to your LLM
Cleanup code
Belluxxe67abb8844a5
diff --git a/aleph.py b/aleph.pyindex 8f12bee..ee916e8 100644--- a/aleph.py+++ b/aleph.py@@ -10,7 +10,7 @@ from pathlib import Pathfrom src import capture, places, quickfrom src.cli import parser-from src.common import DEFAULT_CACHE, CachedClient, Client, Progress, RequestError, now+from src.common import CachedClient, Client, Progress, RequestError, nowfrom src.geo import MERCATOR_RADIUS, bounds@@ -64,7 +64,7 @@ def proceed():def query(args, progress):"""Dispatch quick requests; reject conflicting options before network access."""- client = CachedClient(args.cache_dir, delay=args.delay, refresh=args.refresh)+ client = CachedClient(args.delay, cache_dir=args.cache_dir, refresh=args.refresh)if args.command == "resolve":if args.nearby and args.at is None:raise ValueError("--nearby requires --at LAT LON.")@@ -108,7 +108,7 @@ def query(args, progress):operation = quick.satellitevalues = {key: getattr(args, key) for key in keys if getattr(args, key) is not None}result = operation(client, args.output, progress, endpoint=args.geocoder, **values)- result["cache"] = client.stats()+ result["cache"] = dict(hits=client.hits, misses=client.misses)return result@@ -123,10 +123,6 @@ def rows(headers, values, stream):initial_indent=prefix, subsequent_indent=" " * len(prefix)), file=stream)-def coordinates(point):- return f"{point[0]:.5f}, {point[1]:.5f}"--def place_rows(items, stream, *, locations=False):values = []for item in items:@@ -135,17 +131,16 @@ def place_rows(items, stream, *, locations=False):kind = ", ".join(category.split(":", 1)[-1].replace("_", " ") for category in categories)description = name + (f" ({kind})" if kind else "")if locations:- description += f" · {coordinates((item['lat'], item['lon']))}"+ description += f" · {item['lat']:.5f}, {item['lon']:.5f}"if "distance_m" in item:description += f" · {item['distance_m']:.0f} m away"values.append((item["id"], description))rows(("ID", "PLACE"), values, stream)-def error_details(code, details):- candidates = details.get("candidates", [])- if code == "ambiguous_place" and candidates:- place_rows(candidates, sys.stderr)+def error_details(details):+ if details.get("candidates"):+ place_rows(details["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)@@ -190,31 +185,29 @@ def main(argv=None):return 0args = command.parse_args(argv)if args.command == "dashboard":- if not 1 <= args.port <= 65535:- command.error("--port must be from 1 to 65535")from src.dashboard import serveserve(args.root, args.port, open_browser=not args.no_browser)return 0- if args.command in ("resolve", "streetview", "satellite"):+ if args.command != "capture":with Progress() as progress:result = query(args, progress)if as_json and result["status"] == "partial":print(f"Saved {result['saved_stops']} of {result['requested_stops']} requested stops; see result.json for gaps.", file=sys.stderr)emit(result, as_json)return 0+action = args.action- if action in ("resume", "export"):- folder = args.folder.expanduser().resolve()- run = capture.load(folder)- client = Client(run["options"]["delay"], cache_dir=getattr(args, "cache_dir", DEFAULT_CACHE),- refresh=getattr(args, "refresh", False))- else:- area = bounds(args.bbox)- options = {key: getattr(args, key) for key in capture.DEFAULT_OPTIONS}+ if action == "create":client = Client(args.delay, cache_dir=args.cache_dir, refresh=args.refresh)+ options = {key: getattr(args, key) for key in capture.DEFAULT_OPTIONS}with Progress() as progress:- run = capture.plan(client, area, options, progress)+ run = capture.plan(client, bounds(args.bbox), options, progress)+ else:+ folder = args.folder.expanduser().resolve()+ run = capture.load(folder)+ if action == "resume":+ client = Client(run["options"]["delay"], cache_dir=args.cache_dir, refresh=args.refresh)save_only = action == "create" and args.planif action != "export":describe(run)@@ -235,9 +228,7 @@ def main(argv=None):else:with Progress() as progress:capture.download(run, folder, client, progress)- skipped = sum(- p.get("status") == "skipped" for stage in run["stages"] for p in stage["results"]- )+ skipped = sum(p.get("status") == "skipped" for stage in run["stages"] for p in stage["results"])if skipped:print(style(f"Skipped {skipped:,} unavailable Street View {'photo' if skipped == 1 else 'photos'}.", "33"),file=sys.stderr)@@ -248,15 +239,8 @@ def main(argv=None):emit(result, as_json)return 0except KeyboardInterrupt:- print(- "Stopped."- + (- f" Resume with: alephgeo capture resume '{folder}'"- if folder- else " Planning can be started again."- ),- file=sys.stderr,- )+ hint = f" Resume with: alephgeo capture resume '{folder}'" if folder else " Planning can be started again."+ print("Stopped." + hint, file=sys.stderr)if as_json:emit(dict(status="error", error=dict(code="interrupted", message="Stopped."),folder=str(folder) if folder else None), True)@@ -268,18 +252,12 @@ def main(argv=None):if folder:details = dict(details, folder=str(folder))print(f"{style('alephgeo:', '31')} {error}", file=sys.stderr)- if folder and as_json:- print(- f"Saved run: {folder}\nUse 'capture resume' to retry, or 'capture export' to rebuild saved outputs.",- file=sys.stderr,- )if as_json:emit(dict(status="error", error=dict(code=code, message=str(error), **details)), True)else:- error_details(code, details)- if folder:- print("Use 'capture resume' to retry, or 'capture export' to rebuild saved outputs.",- file=sys.stderr)+ error_details(details)+ if folder:+ print("Use 'capture resume' to retry, or 'capture export' to rebuild saved outputs.", file=sys.stderr)return {"interrupted": 130, "invalid_arguments": 2}.get(code, 1)diff --git a/requirements.txt b/requirements.txtdeleted file mode 100644index a40d05d..0000000--- a/requirements.txt+++ /dev/null@@ -1 +0,0 @@-Pillow>=10diff --git a/src/capture.py b/src/capture.pyindex 3845211..335d41e 100644--- a/src/capture.py+++ b/src/capture.py@@ -11,26 +11,8 @@ from pathlib import Pathfrom PIL import Imagefrom . import satellite, streetview, terrain-from .common import (- MissingImagery,- atomic_path,- contained,- now,- url,- write_bytes,- write_json,-)-from .geo import (- bounds,- collection,- coordinate,- distance,- feature,- grid,- pixel,- tile_ring,- tiles,-)+from .common import MissingImagery, contained, now, number, open_image, positive, write_bytes, write_json+from .geo import bounds, collection, coordinate, distance, feature, grid, pixel, tile_ring, tilesSOURCES = ("streetview", "satellite", "osm")FORMAT_VERSION = 3@@ -52,6 +34,26 @@ OSM_NOTES = {"quality": "Terrain resolution, dates, accuracy and vertical reference vary by source. Higher zoom does not guarantee more detail.",}+README = b"""Aleph capture++streetview/photos/ contains photos; streetview/ holds GeoJSON and plan.svg.+satellite/patches/ contains patches; satellite/ holds GeoJSON and plan.svg.+Open satellite.tif for satellite imagery and map.osm for native map data.+Photo headings are clockwise from north; left/right follow OSM node order.+GeoJSON files record paths, photo locations, or satellite patch footprints.+satellite.tif is a lossless RGBA Cloud Optimized GeoTIFF in EPSG:3857.+It is north-up, cropped to enclosing pixels, with internal overviews.+satellite.png contains the same full-resolution pixels for easy viewing.+Transparent pixels mark missing imagery or unfinished downloads.+terrain.tif is Float32 meters in EPSG:3857, without resampling.+Keep terrain/tiles/ for resume and offline export.+Filenames in the manifest and GeoJSON are relative to this run folder.+See manifest.json for settings, sources, imagery dates, and coverage notes.++Keep this folder together. Continue with: alephgeo capture resume FOLDER+Rebuild images and metadata offline with: alephgeo capture export FOLDER+"""+def settings(values=None):"""Validate settings shared by the CLI and dashboard."""@@ -59,32 +61,16 @@ def settings(values=None):if not isinstance(values, dict) or values.keys() - DEFAULT_OPTIONS.keys():raise ValueError("Unknown capture settings.")options = {**DEFAULT_OPTIONS, **values}- if not isinstance(options["include"], list) or not all(- isinstance(source, str) for source in options["include"]- ):- raise ValueError("Choose one or more capture sources.")- selected = set(options["include"])- if not selected or selected - set(SOURCES):+ include = options["include"]+ if not isinstance(include, list) or not include or any(source not in SOURCES for source in include):raise ValueError("Choose one or more sources: streetview, satellite, osm.")- options["include"] = [source for source in SOURCES if source in selected]- for key in ("step", "delay"):- value = options[key]- if (type(value) not in (int, float) or not math.isfinite(value)- or value < 0 or (key == "step" and value == 0)):- requirement = "positive" if key == "step" else "nonnegative"- raise ValueError(f"{key}: use a {requirement} finite number.")- options["fov"] = streetview.validate_fov(options["fov"])+ options["include"] = [source for source in SOURCES if source in include]+ positive(options["step"], "step")+ number(options["delay"], "delay", 0)+ for key, low, high in (("fov", 5, 175), ("sphere_zoom", 0, 5), ("satellite_zoom", 1, 21), ("terrain_zoom", 1, 14)):+ options[key] = number(options[key], key, low, high, whole=True)if type(options["full_sphere"]) is not bool:raise ValueError("full_sphere must be true or false.")- options["sphere_zoom"] = streetview.validate_sphere_zoom(options["sphere_zoom"])- for key, low, high in (- ("satellite_zoom", 1, 21), ("terrain_zoom", 1, 14),- ):- value = options[key]- if (type(value) not in (int, float) or not math.isfinite(value)- or not low <= value <= high or int(value) != value):- raise ValueError(f"{key}: use a whole number from {low} to {high}.")- options[key] = int(value)if options["depth"] not in ("main", "roads", "all"):raise ValueError("Choose main, roads, or all for depth.")for key in ("streetview_format", "satellite_format"):@@ -107,37 +93,18 @@ def plan(client, area, options, progress):options = settings(options)stages = []if "streetview" in options["include"]:- stages.append(- streetview.plan(- client,- area,- options,- progress,- allow_empty=len(options["include"]) > 1,- )- )+ stages.append(streetview.plan(client, area, options, progress, allow_empty=len(options["include"]) > 1))if "satellite" in options["include"]:- stages.append(- dict(mode="satellite", grid=grid(area, options["satellite_zoom"]), results=[])- )+ stages.append(dict(mode="satellite", grid=grid(area, options["satellite_zoom"]), results=[]))if "osm" in options["include"]:- stages.append(- dict(mode="osm", grid=grid(area, options["terrain_zoom"]), results=[], notes=OSM_NOTES)- )- return dict(- format="aleph-python",- version=FORMAT_VERSION,- bounds=area,- options=options,- started_at=now(),- state="planned",- stages=stages,- )+ stages.append(dict(mode="osm", grid=grid(area, options["terrain_zoom"]), results=[], notes=OSM_NOTES))+ return dict(format="aleph-python", version=FORMAT_VERSION, bounds=area, options=options,+ started_at=now(), state="planned", stages=stages)def total(stage):if stage["mode"] == "streetview":- return len(stage["samples"]) * (1 if stage.get("full_sphere") else 2)+ return len(stage["samples"]) * (1 if stage["full_sphere"] else 2)return stage["grid"]["rows"] * stage["grid"]["columns"] + (stage["mode"] == "osm")@@ -147,38 +114,28 @@ def estimate(run):Excludes planning, initial regional PBF downloads, and final merged exports.Partly downloaded spheres are counted in full; their cached tiles may save time."""- counts = dict(streetview_photos=0, streetview_stops=0, streetview_tiles=0, satellite_tiles=0,- terrain_tiles=0, osm_maps=0)- metadata_requests = thumbnail_requests = 0+ counts = dict(streetview_photos=0, streetview_stops=0, satellite_tiles=0, terrain_tiles=0, osm_maps=0)+ requests = dict.fromkeys(REQUEST_SECONDS, 0)for stage in run["stages"]:remaining = total(stage) - len(stage["results"])if stage["mode"] == "streetview":- counts["streetview_photos"] = remaining- per_stop = 1 if stage.get("full_sphere") else 2- if stage.get("full_sphere"):- counts["streetview_tiles"] = remaining * SPHERE_TILES[run["options"]["sphere_zoom"]]+ sphere = stage["full_sphere"]+ stops = len(stage["samples"]) - len(stage["results"]) // (1 if sphere else 2)+ counts.update(streetview_photos=remaining, streetview_stops=stops)+ requests["metadata"] = stops # Metadata is fetched again when resuming a run.+ if sphere:+ requests["sphere_tile"] = remaining * SPHERE_TILES[run["options"]["sphere_zoom"]]else:- thumbnail_requests = remaining- samples = stage["samples"][len(stage["results"]) // per_stop:]- counts["streetview_stops"] = len(samples)- previous = None # Metadata is fetched again when resuming a run.- for sample in samples:- if stage.get("full_sphere") or sample["pano_id"] != previous:- metadata_requests += 1- previous = sample["pano_id"]+ requests["photo"] = remainingelif stage["mode"] == "satellite":- counts["satellite_tiles"] = remaining+ counts["satellite_tiles"] = requests["satellite_tile"] = remainingelse:- counts["osm_maps"] = int(not any(item["filename"] == "map.osm"- for item in stage["results"]))- counts["terrain_tiles"] = remaining - counts["osm_maps"]- requests = dict(metadata=metadata_requests, photo=thumbnail_requests,- sphere_tile=counts["streetview_tiles"], satellite_tile=counts["satellite_tiles"],- terrain_tile=counts["terrain_tiles"])- download_seconds = sum(count * REQUEST_SECONDS[kind] for kind, count in requests.items())- download_seconds += counts["osm_maps"] * OSM_EXPORT_SECONDS- delay_seconds = max(0, sum(requests.values()) - 1) * run["options"]["delay"]- return dict(counts, seconds=math.ceil(download_seconds + delay_seconds))+ counts["osm_maps"] = int(not any(item["filename"] == "map.osm" for item in stage["results"]))+ counts["terrain_tiles"] = requests["terrain_tile"] = remaining - counts["osm_maps"]+ seconds = sum(count * REQUEST_SECONDS[kind] for kind, count in requests.items())+ seconds += counts["osm_maps"] * OSM_EXPORT_SECONDS+ seconds += max(0, sum(requests.values()) - 1) * run["options"]["delay"]+ return dict(counts, seconds=math.ceil(seconds))def photos(run, after=0):@@ -189,111 +146,40 @@ def photos(run, after=0):)-def open_image(data, size):- image = Image.open(BytesIO(data))- try:- if image.format not in ("JPEG", "PNG") or image.size != size:- raise ValueError(f"Expected a JPEG or PNG image of {size[0]} × {size[1]} pixels.")- image.load()- return image- except BaseException:- image.close()- raise---def capture_streets(stage, run, folder, client, progress):- options = run["options"]- if stage.get("full_sphere"):- yield from capture_spheres(stage, run, folder, client, progress)- return- cached_id, metadata = None, None- for index in range(len(stage["results"]), total(stage)):- sample = stage["samples"][index // 2]- part = stage["paths"][sample["path_index"]]- side = "left" if index % 2 == 0 else "right"- photo = dict(- sample,- side=side,- sequence=index + 1,- path_id=part["id"],- path_name=part["name"],- osm_id=part["osm_id"],- highway=part["highway"],- layer=part["layer"],- road_heading=sample["heading"],- heading=(sample["heading"] + (-90 if side == "left" else 90)) % 360,- pitch=0,- fov=options["fov"],- )- try:- if cached_id != sample["pano_id"]:- metadata = streetview.parse_metadata(- client.get(streetview.metadata_url(sample["pano_id"]))- )- if (- metadata["pano_id"] != sample["pano_id"]- or distance((sample["lat"], sample["lon"]), (metadata["lat"], metadata["lon"]))- > 0.1- ):- raise ValueError(- "The planned panorama identity or position changed. Plan a new run."- )- cached_id = sample["pano_id"]- photo.update(metadata)- photo["source_url"] = streetview.image_url(- photo["pano_id"], photo["heading"], photo["fov"]- )- data = client.get(photo["source_url"], missing_ok=True)- extension = options["streetview_format"]- photo["filename"] = "streetview/photos/" + streetview.photo_name(photo, extension)- with (- open_image(data, (1024, 576)) as image,- atomic_path(folder / photo["filename"]) as temporary,- ):- image.convert("RGB").save(- temporary, format="PNG" if extension == "png" else "JPEG", quality=80- )- photo.update(width=1024, height=576, captured_at=now(), status="saved")- photo["streetview_url"] = url(- "https://www.google.com/maps/@",- api=1,- map_action="pano",- viewpoint=f"{photo['lat']},{photo['lon']}",- heading=photo["heading"],- pitch=0,- # Maps links support 10–100°, unlike the thumbnail endpoint.- fov=max(10, min(100, photo["fov"])),- pano=photo["pano_id"],- )- except MissingImagery as error:- photo.update(status="skipped", reason=str(error))- stage["results"].append(photo)- yield- progress("Street View", index + 1, total(stage))---def capture_spheres(stage, run, folder, client, progress):+def capture_streetview(stage, run, folder, client, progress):+ """Save both roadside photos per stop, or one full sphere."""options = run["options"]+ sphere = stage["full_sphere"]+ metadata = None+ progress("Street View", len(stage["results"]), total(stage))for index in range(len(stage["results"]), total(stage)):- sample = stage["samples"][index]+ sample = stage["samples"][index if sphere else index // 2]part = stage["paths"][sample["path_index"]]- photo = dict(sample, sequence=index + 1, path_id=part["id"], path_name=part["name"],- osm_id=part["osm_id"], highway=part["highway"], layer=part["layer"],- road_heading=sample["heading"], projection="equirectangular")- photo.pop("heading") # A sphere has no single perspective camera heading.+ photo = dict(sample, sequence=index + 1, path_id=part["id"], path_name=part["name"], osm_id=part["osm_id"],+ highway=part["highway"], layer=part["layer"], road_heading=sample["heading"])try:- metadata = streetview.parse_metadata(- client.get(streetview.metadata_url(sample["pano_id"])), full_sphere=True)- if (metadata["pano_id"] != sample["pano_id"]- or distance((sample["lat"], sample["lon"]), (metadata["lat"], metadata["lon"])) > 0.1):- raise ValueError("The planned panorama identity or position changed. Plan a new run.")+ # Both sides of a stop share one panorama.+ if metadata is None or metadata["pano_id"] != sample["pano_id"]:+ fetched = streetview.fetch_metadata(client, sample["pano_id"], full_sphere=sphere)+ if (fetched["pano_id"] != sample["pano_id"]+ or distance((sample["lat"], sample["lon"]), (fetched["lat"], fetched["lon"])) > 0.1):+ raise ValueError("The planned panorama identity or position changed. Plan a new run.")+ metadata = fetchedphoto.update(metadata)- photo["filename"] = f"streetview/photos/{index + 1:06d}_sphere.{options['streetview_format']}"- photo.update(streetview.save_sphere(- client, metadata, options["sphere_zoom"], folder / photo["filename"]))- photo.update(captured_at=now(), status="saved", source_url=streetview.metadata_url(sample["pano_id"]),- streetview_url=url("https://www.google.com/maps/@", api=1, map_action="pano",- pano=sample["pano_id"], viewpoint=f"{photo['lat']},{photo['lon']}"))+ if sphere:+ del photo["heading"] # A sphere has no single perspective camera heading.+ photo["filename"] = f"streetview/photos/{index + 1:06d}_sphere.{options['streetview_format']}"+ photo.update(streetview.save_sphere(client, metadata, options["sphere_zoom"], folder / photo["filename"]),+ source_url=streetview.metadata_url(sample["pano_id"]))+ else:+ side = "left" if index % 2 == 0 else "right"+ photo.update(side=side, heading=(sample["heading"] + (-90 if side == "left" else 90)) % 360,+ pitch=0, fov=options["fov"])+ photo["source_url"] = streetview.image_url(photo["pano_id"], photo["heading"], photo["fov"])+ data = client.get(photo["source_url"], missing_ok=True)+ photo["filename"] = "streetview/photos/" + streetview.photo_name(photo, options["streetview_format"])+ photo.update(streetview.save_photo(data, folder / photo["filename"]))+ photo.update(captured_at=now(), status="saved", streetview_url=streetview.maps_url(photo))except MissingImagery as error:photo.update(status="skipped", reason=str(error))stage["results"].append(photo)@@ -301,12 +187,13 @@ def capture_spheres(stage, run, folder, client, progress):progress("Street View", index + 1, total(stage))-def capture_satellite(stage, folder, client, progress, satellite_format):+def capture_satellite(stage, run, folder, client, progress):+ progress("Satellite", len(stage["results"]), total(stage))for i, tile in enumerate(tiles(stage["grid"])):if i < len(stage["results"]):continueaddress = f"https://mt1.google.com/vt/lyrs=s&x={tile['x']}&y={tile['y']}&z={tile['zoom']}"- extension = satellite_format+ extension = run["options"]["satellite_format"]try:data = client.get(address, missing_ok=True)except MissingImagery:@@ -322,21 +209,19 @@ def capture_satellite(stage, folder, client, progress, satellite_format):with BytesIO() as buffer, image.convert("RGB" if extension == "jpg" else "RGBA") as converted:converted.save(buffer, format=target, quality=80)data = buffer.getvalue()- name = (- f"satellite/patches/satellite_z{tile['zoom']}_r{tile['row'] + 1:04d}_c{tile['column'] + 1:04d}"- f"_x{tile['x']}_y{tile['y']}.{extension}"- )+ name = (f"satellite/patches/satellite_z{tile['zoom']}_r{tile['row'] + 1:04d}_c{tile['column'] + 1:04d}"+ f"_x{tile['x']}_y{tile['y']}.{extension}")write_bytes(folder / name, data)stage["results"].append(dict(tile, filename=name, source_url=address, captured_at=now()))yieldprogress("Satellite", i + 1, total(stage))-def capture_osm(stage, area, folder, client, progress):+def capture_osm(stage, run, folder, client, progress):failure = Noneif not any(item["filename"] == "map.osm" for item in stage["results"]):try:- metadata = client.maps.export(area, folder / "map.osm", progress)+ metadata = client.maps.export(run["bounds"], folder / "map.osm", progress)stage["results"].append(dict(filename="map.osm", captured_at=now(), **metadata))yieldexcept (OSError, ValueError) as error:@@ -354,15 +239,16 @@ def capture_osm(stage, area, folder, client, progress):terrain.validate(terrain.TIFF(BytesIO(data)), tile)name = f"terrain/tiles/terrain_z{tile['zoom']}_x{tile['x']}_y{tile['y']}.tif"write_bytes(folder / name, data)- stage["results"].append(- dict(tile, filename=name, source_url=address, captured_at=now())- )+ stage["results"].append(dict(tile, filename=name, source_url=address, captured_at=now()))yieldprogress(label, i + 1, count)if failure is not None:raise failure+STAGES = dict(streetview=capture_streetview, satellite=capture_satellite, osm=capture_osm)++def export(run, folder, progress, *, rebuild=True):"""Also works offline, on partial runs, or after a failed final export."""# Commit capture progress before merging, which can fail or be interrupted.@@ -372,12 +258,10 @@ def export(run, folder, progress, *, rebuild=True):if stage["mode"] == "streetview":write_json(folder / "streetview/photos.geojson", photos(run))elif stage["mode"] == "satellite":- write_json(- folder / "satellite/patches.geojson",- collection(feature("Polygon", [tile_ring(p)], p) for p in stage["results"]),- )+ write_json(folder / "satellite/patches.geojson",+ collection(feature("Polygon", [tile_ring(p)], p) for p in stage["results"]))satellite.merge(stage, folder, progress)- elif stage["mode"] == "osm":+ else:terrain_results = [item for item in stage["results"] if "x" in item]count = stage["grid"]["rows"] * stage["grid"]["columns"]if len(terrain_results) == count and (rebuild or not (folder / "terrain.tif").is_file()):@@ -387,27 +271,10 @@ def export(run, folder, progress, *, rebuild=True):def save_preview(run, folder):+ """Write the README, planned street paths, and a north-up plan.svg per imagery stage."""if run["options"]["include"] == ["osm"]:return- write_bytes(- folder / "README.txt",- b"Aleph capture\n\n"- b"streetview/photos/ contains photos; streetview/ holds GeoJSON and plan.svg.\n"- b"satellite/patches/ contains patches; satellite/ holds GeoJSON and plan.svg.\n"- b"Open satellite.tif for satellite imagery and map.osm for native map data.\n"- b"Photo headings are clockwise from north; left/right follow OSM node order.\n"- b"GeoJSON files record paths, photo locations, or satellite patch footprints.\n"- b"satellite.tif is a lossless RGBA Cloud Optimized GeoTIFF in EPSG:3857.\n"- b"It is north-up, cropped to enclosing pixels, with internal overviews.\n"- b"satellite.png contains the same full-resolution pixels for easy viewing.\n"- b"Transparent pixels mark missing imagery or unfinished downloads.\n"- b"terrain.tif is Float32 meters in EPSG:3857, without resampling.\n"- b"Keep terrain/tiles/ for resume and offline export.\n"- b"Filenames in the manifest and GeoJSON are relative to this run folder.\n"- b"See manifest.json for settings, sources, imagery dates, and coverage notes.\n\n"- b"Keep this folder together. Continue with: alephgeo capture resume FOLDER\n"- b"Rebuild images and metadata offline with: alephgeo capture export FOLDER\n",- )+ write_bytes(folder / "README.txt", README)area = run["bounds"]left, top = pixel((area[2], area[1]), 17)right, bottom = pixel((area[0], area[3]), 17)@@ -417,59 +284,34 @@ def save_preview(run, folder):x, y = pixel(point, 17)return f"{25 + (x - left) * scale:.2f},{45 + (y - top) * scale:.2f}"+ def corner(x, y, zoom):+ return xy(coordinate(x * 256, y * 256, zoom))+for stage in run["stages"]:- if stage["mode"] == "osm":- continue- drawing = []if stage["mode"] == "streetview":- write_json(- folder / "streetview/paths.geojson",- collection(- feature(- "LineString",- [[p[1], p[0]] for p in part["points"]],- {k: v for k, v in part.items() if k != "points"},- )- for part in stage["paths"]- ),- )- roads = "".join(- "M" + "L".join(xy(p) for p in part["points"]) for part in stage["paths"]- )- gaps = "".join(- f"M{xy(gap['start'])}L{xy(gap['end'])}" for gap in stage["coverage"]["gaps"]- )+ write_json(folder / "streetview/paths.geojson", collection(+ feature("LineString", [[p[1], p[0]] for p in part["points"]],+ {k: v for k, v in part.items() if k != "points"})+ for part in stage["paths"]))+ roads = "".join("M" + "L".join(xy(p) for p in part["points"]) for part in stage["paths"])+ gaps = "".join(f"M{xy(gap['start'])}L{xy(gap['end'])}" for gap in stage["coverage"]["gaps"])stops = "".join(f"M{xy((p['lat'], p['lon']))}h.1" for p in stage["samples"])- drawing.extend(- [- f'<path d="{roads}" stroke="#888" stroke-width="2"/>',- f'<path d="{gaps}" stroke="#a32632" stroke-width="4" stroke-dasharray="3 5"/>',- f'<path d="{stops}" stroke="#a32632" stroke-width="6" stroke-linecap="round"/>',- ]- )+ drawing = [+ f'<path d="{roads}" stroke="#888" stroke-width="2"/>',+ f'<path d="{gaps}" stroke="#a32632" stroke-width="4" stroke-dasharray="3 5"/>',+ f'<path d="{stops}" stroke="#a32632" stroke-width="6" stroke-linecap="round"/>',+ ]caption = "Planned stops. Dotted red lines show spacing gaps. North is up."- else:+ elif stage["mode"] == "satellite":g = stage["grid"]- lines = []- for x in range(g["x0"], g["x0"] + g["columns"] + 1):- lines.append(- "M"- + xy(coordinate(x * 256, g["y0"] * 256, g["zoom"]))- + "L"- + xy(coordinate(x * 256, (g["y0"] + g["rows"]) * 256, g["zoom"]))- )- for y in range(g["y0"], g["y0"] + g["rows"] + 1):- lines.append(- "M"- + xy(coordinate(g["x0"] * 256, y * 256, g["zoom"]))- + "L"- + xy(coordinate((g["x0"] + g["columns"]) * 256, y * 256, g["zoom"]))- )- drawing.append(f'<path d="{"".join(lines)}" stroke="#888" stroke-width="1"/>')+ x0, y0, x1, y1, z = g["x0"], g["y0"], g["x0"] + g["columns"], g["y0"] + g["rows"], g["zoom"]+ lines = [f"M{corner(x, y0, z)}L{corner(x, y1, z)}" for x in range(x0, x1 + 1)]+ lines += [f"M{corner(x0, y, z)}L{corner(x1, y, z)}" for y in range(y0, y1 + 1)]+ drawing = [f'<path d="{"".join(lines)}" stroke="#888" stroke-width="1"/>']caption = f"Satellite zoom {g['zoom']}, {g['columns']} × {g['rows']} patches. North is up."- drawing.append(- f'<rect x="25" y="45" width="{(right - left) * scale}" height="{(bottom - top) * scale}" stroke="#a32632"/>'- )+ else:+ continue+ drawing.append(f'<rect x="25" y="45" width="{(right - left) * scale}" height="{(bottom - top) * scale}" stroke="#a32632"/>')svg = (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 580" role="img">'f'<title>{caption}</title><rect width="900" height="580" fill="#faf8f4"/>'@@ -480,51 +322,39 @@ def save_preview(run, folder):def download(run, folder, client, progress):+ """Resume every stage, then export; a failed run keeps its checkpoint and partial exports."""run.update(state="running", exports_saved=False)run.pop("error", None)run.pop("finished_at", None)- saved_at, saved_count = time.monotonic(), 0- failure = None+ errors = []try:write_json(folder / "manifest.json", run)+ saved_at, unsaved = time.monotonic(), 0for stage in run["stages"]:if len(stage["results"]) == total(stage):continue- if stage["mode"] != "osm":- label = "Street View" if stage["mode"] == "streetview" else "Satellite"- progress(label, len(stage["results"]), total(stage))- if stage["mode"] == "streetview":- work = capture_streets(stage, run, folder, client, progress)- elif stage["mode"] == "satellite":- work = capture_satellite(stage, folder, client, progress, run["options"]["satellite_format"])- else:- work = capture_osm(stage, run["bounds"], folder, client, progress)- for _ in work:- saved_count += 1- if stage["mode"] == "osm" or stage.get("full_sphere") or saved_count >= 50 or time.monotonic() - saved_at >= 30:+ # Checkpoint slow items every time and quick ones in batches.+ slow = stage["mode"] == "osm" or stage.get("full_sphere")+ for _ in STAGES[stage["mode"]](stage, run, folder, client, progress):+ unsaved += 1+ if slow or unsaved >= 50 or time.monotonic() - saved_at >= 30:write_json(folder / "manifest.json", run)- saved_at, saved_count = time.monotonic(), 0+ saved_at, unsaved = time.monotonic(), 0write_json(folder / "manifest.json", run)except (Exception, KeyboardInterrupt) as error:- failure = error- run.update(- state="stopped" if isinstance(error, KeyboardInterrupt) else "failed",- error=str(error) or "Interrupted",- )+ errors.append(error)try:export(run, folder, progress, rebuild=False)except (Exception, KeyboardInterrupt) as error:- if failure is None:- failure = error- run.update(state="stopped" if isinstance(error, KeyboardInterrupt) else "failed",- error=str(error) or "Interrupted")- else:- run["error"] += f" Export also failed: {error}"- if failure is None:+ errors.append(error)+ if errors:+ run.update(state="stopped" if isinstance(errors[0], KeyboardInterrupt) else "failed",+ error=" Export also failed: ".join(str(error) or "Interrupted" for error in errors))+ else:run.update(state="complete", finished_at=now())write_json(folder / "manifest.json", run)- if failure is not None:- raise failure+ if errors:+ raise errors[0]def load(folder, *, check_files=True):@@ -538,9 +368,7 @@ def load(folder, *, check_files=True):raise ValueError("Invalid saved stages.")for stage in run["stages"]:if stage["mode"] != "streetview":- zoom = options[- "satellite_zoom" if stage["mode"] == "satellite" else "terrain_zoom"- ]+ zoom = options["satellite_zoom" if stage["mode"] == "satellite" else "terrain_zoom"]if stage["grid"] != grid(run["bounds"], zoom):raise ValueError("Invalid saved tile grid.")if len(stage["results"]) > total(stage):@@ -550,11 +378,10 @@ def load(folder, *, check_files=True):for result in stage["results"]:if result.get("status") == "skipped":continue- name = result["filename"]try:- path = contained(folder, name)+ path = contained(folder, result["filename"])except FileNotFoundError as error:raise ValueError("Invalid output filename in checkpoint.") from errorif not path.is_file():- raise ValueError(f"Missing saved file: {name}. Restore it before resuming.")+ raise ValueError(f"Missing saved file: {result['filename']}. Restore it before resuming.")return rundiff --git a/src/cli.py b/src/cli.pyindex 1dc2214..d12aa69 100644--- a/src/cli.py+++ b/src/cli.py@@ -34,12 +34,15 @@ def parser():return root-def _output_options(command, *, directory=False):- if directory:- command.add_argument("-o", "--output", type=Path, default=Path("."), help="parent output directory")+def _json_option(command):command.add_argument("--json", action="store_true", help="one JSON result on stdout; progress on stderr")+def _output_options(command):+ command.add_argument("-o", "--output", type=Path, default=Path("."), help="parent output directory")+ _json_option(command)++def _cache_options(command):command.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE, help="data cache directory (default: %(default)s)")command.add_argument("--refresh", action="store_true", help="refresh responses and Geofabrik regional files")@@ -51,6 +54,12 @@ def _network_options(command):_cache_options(command)+def _sphere_options(command):+ command.add_argument("--full-sphere", action="store_true", help="save one full 360° panorama per stop; camera direction and fov do not apply")+ command.add_argument("--sphere-zoom", type=int, choices=range(6), default=3,+ help="panorama resolution level, 0–5 (default: 3); capped at the highest available")++def _locations(command):group = command.add_mutually_exclusive_group(required=True)group.add_argument("--at", nargs=2, type=float, metavar=("LAT", "LON"), help="coordinates")@@ -75,7 +84,7 @@ def _resolve_command(commands):resolve.add_argument("--limit", type=int, default=10, help="maximum results (default: 10; max: 50)")_network_options(resolve)- _output_options(resolve)+ _json_option(resolve)def _streetview_command(commands):@@ -105,7 +114,7 @@ def _streetview_command(commands):_network_options(street)street.add_argument("--streetview-format", choices=("jpg", "png"), default="jpg")- _output_options(street, directory=True)+ _output_options(street)def _satellite_command(commands):@@ -120,7 +129,7 @@ def _satellite_command(commands):_network_options(satellite)satellite.add_argument("--tile-format", dest="satellite_format", choices=("jpg", "png"), default="jpg", help="saved tile format; merged PNG and COG are always produced (default: jpg)")- _output_options(satellite, directory=True)+ _output_options(satellite)def _capture_command(commands):@@ -153,7 +162,7 @@ def _capture_command(commands):# Requests, cache, and output shared by all capture sources.area.add_argument("--delay", type=float, help="pause between requests in seconds (default: 0)")_cache_options(area)- _output_options(area, directory=True)+ _output_options(area)area.set_defaults(**capture.DEFAULT_OPTIONS)resume_help = "Continue a saved or planned run"@@ -161,18 +170,12 @@ def _capture_command(commands):resume.add_argument("folder", type=Path, help="timestamped run directory containing manifest.json")resume.add_argument("--yes", action="store_true", help=yes_help)_cache_options(resume)- _output_options(resume)+ _json_option(resume)export_help = "Rebuild images and metadata from saved files, offline"export = actions.add_parser("export", help=export_help, description=export_help)export.add_argument("folder", type=Path, help="timestamped run directory containing manifest.json")- _output_options(export)---def _sphere_options(command):- command.add_argument("--full-sphere", action="store_true", help="save one full 360° panorama per stop; camera direction and fov do not apply")- command.add_argument("--sphere-zoom", type=int, choices=range(6), default=3,- help="panorama resolution level, 0–5 (default: 3); capped at the highest available")+ _json_option(export)def _dashboard_command(commands):diff --git a/src/common.py b/src/common.pyindex 6eff520..475bc06 100644--- a/src/common.py+++ b/src/common.py@@ -11,11 +11,14 @@ import timefrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom functools import cached_property+from io import BytesIOfrom pathlib import Pathfrom urllib.error import HTTPErrorfrom urllib.parse import urlencode, urlsplitfrom urllib.request import Request, urlopen+from PIL import Image+DEFAULT_CACHE = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "aleph"APP_AGENT = "Aleph/0.1"BROWSER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15"@@ -42,6 +45,44 @@ def url(base, **params):return base + "?" + urlencode(params)+def number(value, name, low=-math.inf, high=math.inf, *, whole=False):+ """Check a number from JSON or the command line; whole numbers come back as int."""+ if (type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high+ or (whole and value != int(value))):+ kind = "a whole number" if whole else "a number"+ if math.isfinite(high):+ kind += f" from {low:g} to {high:g}"+ elif math.isfinite(low):+ kind += f" of at least {low:g}"+ raise ValueError(f"{name}: use {kind}.")+ return int(value) if whole else value+++def positive(value, name):+ if number(value, name) <= 0:+ raise ValueError(f"{name}: use a positive number.")+ return value+++def open_image(data, size):+ """Decode a provider JPEG or PNG, rejecting anything of an unexpected size."""+ image = Image.open(BytesIO(data))+ try:+ if image.format not in ("JPEG", "PNG") or image.size != size:+ raise ValueError(f"Expected a JPEG or PNG image of {size[0]} × {size[1]} pixels.")+ image.load()+ return image+ except BaseException:+ image.close()+ raise+++def save_image(image, path, quality):+ """Save atomically, choosing PNG or JPEG from the file extension."""+ with atomic_path(path) as temporary:+ image.save(temporary, format="PNG" if Path(path).suffix == ".png" else "JPEG", quality=quality)++def contained(parent, name):"""Resolve a relative filename without allowing it to escape its directory."""if (not isinstance(name, str) or not name or "\\" in name or "\0" in name@@ -85,9 +126,7 @@ class Client:if self.request_log:self.request_log("GET", address, attempt)try:- with urlopen(- Request(address, headers={"User-Agent": user_agent}), timeout=timeout- ) as response:+ with urlopen(Request(address, headers={"User-Agent": user_agent}), timeout=timeout) as response:if destination is None:result = response.read()else:@@ -116,9 +155,7 @@ class Client:if attempt < 3:continueif isinstance(error, HTTPError):- raise OSError(- f"{urlsplit(address).hostname}: HTTP {error.code}. Resume to retry."- ) from error+ raise OSError(f"{urlsplit(address).hostname}: HTTP {error.code}. Resume to retry.") from errorraisefinally:self.finished = time.monotonic()@@ -127,10 +164,7 @@ class Client:class CachedClient(Client):"""Cache successful quick-query responses for one week."""- def __init__(self, directory, *, delay=0, refresh=False):- super().__init__(delay=delay, cache_dir=directory, refresh=refresh)- self.hits = 0- self.misses = 0+ hits = misses = 0def get(self, address, **kwargs):if kwargs.get("destination") is not None:@@ -145,9 +179,6 @@ class CachedClient(Client):self.misses += 1return result- def stats(self):- return dict(hits=self.hits, misses=self.misses)-class Progress:def __init__(self):@@ -191,16 +222,10 @@ class Progress:if done >= total:eta = "00:00"elif done > self.initial:- seconds = math.ceil(- (current - self.started) / (done - self.initial) * (total - done)- )+ seconds = math.ceil((current - self.started) / (done - self.initial) * (total - done))minutes, seconds = divmod(seconds, 60)hours, minutes = divmod(minutes, 60)- eta = (- f"{hours}:{minutes:02d}:{seconds:02d}"- if hours- else f"{minutes:02d}:{seconds:02d}"- )+ eta = f"{hours}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes:02d}:{seconds:02d}"percent = f"{math.floor(fraction * 100)}%" if total is not None else "—%"prefix = f"{phase} ["@@ -212,12 +237,7 @@ class Progress:self.line = prefix + bar + suffixif self.terminal:self.line = self.line[:columns]- print(- "\r" + self.line.ljust(min(self.width, columns)),- end="",- file=self.stream,- flush=True,- )+ print("\r" + self.line.ljust(min(self.width, columns)), end="", file=self.stream, flush=True)self.width = len(self.line)self.printed = currentdiff --git a/src/geo.py b/src/geo.pyindex 85c995d..0ca68f6 100644--- a/src/geo.py+++ b/src/geo.py@@ -5,6 +5,8 @@ from bisect import bisect_rightfrom collections import defaultdictfrom itertools import pairwise+from .common import number, positive+RADIUS = 6_371_008.8MERCATOR_RADIUS = 6_378_137MAX_LATITUDE = 85.0511287798066@@ -36,44 +38,32 @@ def extent(points):def distance(a, b):lat1, lat2 = map(math.radians, (a[0], b[0]))delta = math.radians(b[1] - a[1])- h = (- math.sin((lat2 - lat1) / 2) ** 2- + math.cos(lat1) * math.cos(lat2) * math.sin(delta / 2) ** 2- )+ h = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(delta / 2) ** 2return 2 * RADIUS * math.asin(math.sqrt(min(1, h)))def bearing(a, b):lat1, lat2 = map(math.radians, (a[0], b[0]))delta = math.radians(b[1] - a[1])- return (- math.degrees(- math.atan2(- math.sin(delta) * math.cos(lat2),- math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(delta),- )- )- % 360- )+ y = math.sin(delta) * math.cos(lat2)+ x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(delta)+ return math.degrees(math.atan2(y, x)) % 360def destination(point, heading, meters):lat, lon = map(math.radians, point)angle, heading = meters / RADIUS, math.radians(heading)- end = math.asin(- clamp(- math.sin(lat) * math.cos(angle) + math.cos(lat) * math.sin(angle) * math.cos(heading),- -1,- 1,- )- )- delta = math.atan2(- math.sin(heading) * math.sin(angle) * math.cos(lat),- math.cos(angle) - math.sin(lat) * math.sin(end),- )+ end = math.asin(clamp(math.sin(lat) * math.cos(angle) + math.cos(lat) * math.sin(angle) * math.cos(heading), -1, 1))+ delta = math.atan2(math.sin(heading) * math.sin(angle) * math.cos(lat),+ math.cos(angle) - math.sin(lat) * math.sin(end))return math.degrees(end), (math.degrees(lon + delta) + 180) % 360 - 180+def point(values):+ lat, lon = values+ return number(lat, "latitude", -90, 90), number(lon, "longitude", -180, 180)++def bounds(values, *, minimum=1):lat1, lon1, lat2, lon2 = valuesif not all(math.isfinite(v) for v in values):@@ -91,6 +81,19 @@ def bounds(values, *, minimum=1):return south, west, north, east+def around(center, size):+ """A square in ground meters, returned in south/west/north/east order."""+ lat, lon = point(center)+ positive(size, "size")+ dy = math.degrees(size / (2 * RADIUS))+ if abs(lat) + dy >= 90:+ raise ValueError("The area cannot cross a pole.")+ dx = dy / math.cos(math.radians(lat))+ if lon - dx < -180 or lon + dx > 180:+ raise ValueError("Split areas crossing the date line into two rectangles.")+ return bounds((lat - dy, lon - dx, lat + dy, lon + dx), minimum=0)++def inside(point, area):south, west, north, east = areareturn south - 1e-9 <= point[0] <= north + 1e-9 and west - 1e-9 <= point[1] <= east + 1e-9@@ -111,10 +114,7 @@ def clip(a, b, area):leave = min(leave, q / p)if enter > leave:return None- start, end = [- (clamp(a[0] + t * dy, south, north), clamp(a[1] + t * dx, west, east))- for t in (enter, leave)- ]+ start, end = [(clamp(a[0] + t * dy, south, north), clamp(a[1] + t * dx, west, east)) for t in (enter, leave)]return (start, end) if distance(start, end) > 0.01 else None@@ -148,11 +148,8 @@ class Line:offset = RADIUS * math.atan2(math.sin(angle) * math.cos(delta), math.cos(angle))meters = clamp(self.cumulative[i] + offset, self.cumulative[i], self.cumulative[i + 1])separation = distance(self.at(meters), point)- if (- nearest is None- or separation < nearest[1] - 0.1- or (abs(separation - nearest[1]) <= 0.1 and meters < nearest[0])- ):+ if (nearest is None or separation < nearest[1] - 0.1+ or (abs(separation - nearest[1]) <= 0.1 and meters < nearest[0])):nearest = meters, separationreturn nearest@@ -170,13 +167,8 @@ class RoadIndex:lat, lon = destination(line.points[segment], heading, length / 2)angle = (length / 2 + radius + 0.2) / RADIUSdy = math.degrees(angle)- dx = (- 180- if abs(lat) + dy >= 90- else math.degrees(- math.asin(clamp(math.sin(angle) / math.cos(math.radians(lat)), -1, 1))- )- )+ dx = 180 if abs(lat) + dy >= 90 else math.degrees(+ math.asin(clamp(math.sin(angle) / math.cos(math.radians(lat)), -1, 1)))x0, x1 = (math.floor(x / self.size) for x in (lon - dx, lon + dx))y0, y1 = (math.floor(y / self.size) for y in (lat - dy, lat + dy))entry = road, segment@@ -198,9 +190,7 @@ class RoadIndex:def pixel(point, zoom):size = 256 * 2**zoomlatitude = math.radians(clamp(point[0], -MAX_LATITUDE, MAX_LATITUDE))- return (point[1] + 180) / 360 * size, clamp(- (1 - math.asinh(math.tan(latitude)) / math.pi) / 2 * size, 0, size- )+ return (point[1] + 180) / 360 * size, clamp((1 - math.asinh(math.tan(latitude)) / math.pi) / 2 * size, 0, size)def coordinate(x, y, zoom):@@ -221,25 +211,15 @@ def grid(area, zoom):left, top = (math.floor(snap(v)) for v in pixel((north, west), zoom))right, bottom = (math.ceil(snap(v)) for v in pixel((south, east), zoom))- return dict(- zoom=zoom,- left=left,- top=top,- width=right - left,- height=bottom - top,- x0=left // 256,- y0=top // 256,- columns=math.ceil(right / 256) - left // 256,- rows=math.ceil(bottom / 256) - top // 256,- )+ return dict(zoom=zoom, left=left, top=top, width=right - left, height=bottom - top,+ x0=left // 256, y0=top // 256,+ columns=math.ceil(right / 256) - left // 256, rows=math.ceil(bottom / 256) - top // 256)def tiles(grid):for row in range(grid["rows"]):for column in range(grid["columns"]):- yield dict(- x=grid["x0"] + column, y=grid["y0"] + row, zoom=grid["zoom"], row=row, column=column- )+ yield dict(x=grid["x0"] + column, y=grid["y0"] + row, zoom=grid["zoom"], row=row, column=column)def tile_ring(tile):@@ -249,9 +229,7 @@ def tile_ring(tile):def feature(geometry, coordinates, properties):- return dict(- type="Feature", geometry=dict(type=geometry, coordinates=coordinates), properties=properties- )+ return dict(type="Feature", geometry=dict(type=geometry, coordinates=coordinates), properties=properties)def collection(features):diff --git a/src/pbf.py b/src/pbf.pyindex 0ad0f48..e5bd7bd 100644--- a/src/pbf.py+++ b/src/pbf.py@@ -1,18 +1,15 @@-"""Standalone, standard-library reader/extractor for sorted OSM snapshot PBFs.+"""Standard-library reader/extractor for sorted OSM snapshot PBFs.-Run: python src/pbf.py REGION.osm.pbf S W N E -o map.osmSchema: https://github.com/openstreetmap/OSM-binary/tree/master/osmpbfSupports raw/zlib blobs, ordinary/dense nodes, ways, relations and OSM metadata."""-import argparseimport bisectimport mathimport osimport reimport structimport sys-import tempfileimport zlibfrom array import arrayfrom collections import defaultdict, deque@@ -24,6 +21,8 @@ from multiprocessing import get_contextfrom pathlib import Pathfrom xml.sax.saxutils import quoteattr+from .common import atomic_path+MAX_BLOB = 32 * 1024 * 1024MEMBERS = ("node", "way", "relation")SIGNED_SMALL = tuple((v >> 1) ^ -(v & 1) for v in range(128))@@ -813,45 +812,19 @@ class PBF:def export(self, area, output):selected = self.select(area, xml=True)- output = Path(output)- output.parent.mkdir(parents=True, exist_ok=True)- fd, name = tempfile.mkstemp(prefix=f".{output.name}-", dir=output.parent)- try:- with os.fdopen(fd, "wb") as stream:- south, west, north, east = area- stream.write((f'<?xml version="1.0" encoding="UTF-8"?>\n<osm version="0.6" generator="Aleph">\n'- f'<bounds minlat="{south}" minlon="{west}" maxlat="{north}" maxlon="{east}"/>\n').encode())- written = 0- for chunk in self.nodes(selected[0], "xml"):- stream.write(chunk)- written += chunk.count(b"<node ")- if written != len(selected[0]):- raise ValueError("PBF extract contains incomplete way geometry.")- for _, chunk in self.way_xml.values():- stream.write(chunk)- for item in self.relations(selected[2]):- stream.write(xml_object(item).encode("utf-8"))- stream.write(b"</osm>\n")+ south, west, north, east = area+ with atomic_path(output) as temporary, temporary.open("wb") as stream:+ stream.write((f'<?xml version="1.0" encoding="UTF-8"?>\n<osm version="0.6" generator="Aleph">\n'+ f'<bounds minlat="{south}" minlon="{west}" maxlat="{north}" maxlon="{east}"/>\n').encode())+ written = 0+ for chunk in self.nodes(selected[0], "xml"):+ stream.write(chunk)+ written += chunk.count(b"<node ")+ if written != len(selected[0]):+ raise ValueError("PBF extract contains incomplete way geometry.")+ for _, chunk in self.way_xml.values():+ stream.write(chunk)+ for item in self.relations(selected[2]):+ stream.write(xml_object(item).encode("utf-8"))+ stream.write(b"</osm>\n")self.cancel()- os.replace(name, output)- finally:- Path(name).unlink(missing_ok=True)---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("source", type=Path)- parser.add_argument("bbox", nargs=4, type=float, metavar="COORD")- parser.add_argument("-o", "--output", type=Path, required=True)- args = parser.parse_args()- south, west, north, east = args.bbox- if not all(math.isfinite(v) for v in args.bbox) or not (-90 <= south < north <= 90 and -180 <= west < east <= 180):- parser.error("Use a nonempty bounding box in south west north east order.")- try:- PBF(args.source).export(args.bbox, args.output)- except (OSError, ValueError, zlib.error, KeyError, IndexError) as error:- parser.exit(1, f"PBF extraction failed: {error}\n")---if __name__ == "__main__":- main()diff --git a/src/places.py b/src/places.pyindex 9a66ca9..dab03e5 100644--- a/src/places.py+++ b/src/places.py@@ -1,50 +1,17 @@"""Place search, reverse lookup, and nearby OSM points of interest."""import json-import mathfrom urllib.parse import urlsplit-from .common import RequestError, url-from .geo import RADIUS, bounds, distance+from .common import APP_AGENT, RequestError, number, url+from .geo import around, distance, pointfrom .osm import POI_KEYSGEOCODER = "https://photon.komoot.io"-def number(value, name, low, high):- if not math.isfinite(value) or not low <= value <= high:- raise ValueError(f"{name} must be from {low} to {high}.")- return value---def positive(value, name):- if not math.isfinite(value) or value <= 0:- raise ValueError(f"{name} must be a positive finite number.")- return value---def point(values):- lat, lon = values- number(lat, "latitude", -90, 90)- number(lon, "longitude", -180, 180)- return lat, lon---def around(center, size):- """A square in ground meters, returned in south/west/north/east order."""- lat, lon = point(center)- positive(size, "size")- dy = math.degrees(size / (2 * RADIUS))- if abs(lat) + dy >= 90:- raise ValueError("The area cannot cross a pole.")- dx = dy / math.cos(math.radians(lat))- if lon - dx < -180 or lon + dx > 180:- raise ValueError("Split areas crossing the date line into two rectangles.")- return bounds((lat - dy, lon - dx, lat + dy, lon + dx), minimum=0)--def geocode(client, *, query=None, at=None, limit=5, street=False, endpoint=GEOCODER):- number(limit, "limit", 1, 50)+ number(limit, "limit", 1, 50, whole=True)endpoint = endpoint.rstrip("/")address = urlsplit(endpoint)if address.scheme not in ("http", "https") or not address.netloc:@@ -61,7 +28,7 @@ def geocode(client, *, query=None, at=None, limit=5, street=False, endpoint=GEOCparams["lat"], params["lon"] = point(at)path = "/reverse/"try:- data = json.loads(client.get(url(endpoint + path, **params), user_agent="Aleph/1.0"))+ data = json.loads(client.get(url(endpoint + path, **params), user_agent=APP_AGENT))except (OSError, ValueError) as error:raise RequestError("provider_unavailable", f"Geocoder request failed: {error}") from errorif not isinstance(data.get("features"), list):@@ -105,7 +72,7 @@ def choose(client, query, *, match=None, best_match=False, street=False, endpoindef nearby(client, at, *, radius=100, limit=10, progress=lambda *args: None):lat, lon = point(at)number(radius, "radius", 1, 5000)- number(limit, "limit", 1, 50)+ number(limit, "limit", 1, 50, whole=True)items, metadata = client.maps.data(around((lat, lon), radius * 2), poi=True, progress=progress)results = []for item in items:diff --git a/src/quick.py b/src/quick.pyindex a989b25..fb82763 100644--- a/src/quick.py+++ b/src/quick.py@@ -4,75 +4,70 @@ import tempfilefrom pathlib import Pathfrom . import capture, places, routes, streetview-from .common import MissingImagery, RequestError, atomic_path, now, url, write_json-from .geo import bearing, bounds, coordinate, distance, extent, grid, tiles+from .common import MissingImagery, RequestError, now, number, positive, write_json+from .geo import around, bearing, bounds, coordinate, distance, extent, point++VIEW_OFFSETS = {"forward": 0, "backward": 180, "left": -90, "right": 90}def coverage(client, area, progress):- g = grid(area, 17)- count = g["rows"] * g["columns"]- found = {}- for i, tile in enumerate(tiles(g), 1):- address = url("https://www.google.com/maps/photometa/ac/v1",- pb=f"!1m1!1smaps_sv.tactile!6m3!1i{tile['x']}!2i{tile['y']}!3i17!8b1")- try:- views = streetview.parse_coverage(client.get(address))- except (OSError, ValueError) as error:- raise RequestError("provider_unavailable", f"Street View coverage request failed: {error}") from error- for view in views:- found[view["pano_id"]] = view- progress("Finding panoramas", i, count)- return list(found.values())+ try:+ return streetview.coverage(client, area, progress)+ except (OSError, ValueError) as error:+ raise RequestError("provider_unavailable", f"Street View coverage request failed: {error}") from errordef location(client, *, at=None, place=None, match=None, best_match=False, endpoint=places.GEOCODER):if at is not None:- return places.point(at), None+ return point(at), Noneselected = places.choose(client, place, match=match, best_match=best_match, endpoint=endpoint)return (selected["lat"], selected["lon"]), selected-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=None, step=None, view="forward", heading=0, look_at=None,- pitch=0, fov=75, radius=50, streetview_format="jpg", full_sphere=False, sphere_zoom=3):- streetview.validate_sphere_zoom(sphere_zoom)- streetview.validate_angle(heading, "heading")- streetview.validate_angle(pitch, "pitch")- fov = streetview.validate_fov(fov)- places.positive(radius, "radius")- if stops is not None and (type(stops) is not int or stops < 1):- raise ValueError("stops must be a positive whole number.")+def street_samples(client, sections, stops, step, progress):+ """Match panoramas to target positions along every selected street section."""+ south, west, north, east = extent([p for section in sections for p in section["points"]])+ lower, upper = around((south, west), 80), 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, requested = [], [], 0+ counts = routes.allocate_stops(sections, stops) if stops is not None else [None] * len(sections)+ for section, count in zip(sections, 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.update(route=section["route"], stop=item["stop"] + requested)+ samples += section_samples+ gaps += section_gaps+ requested += len(targets)+ return samples, gaps, requested+++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=None, step=None,+ view="forward", heading=0, look_at=None, pitch=0, fov=75, radius=50, streetview_format="jpg",+ full_sphere=False, sphere_zoom=3):+ number(sphere_zoom, "sphere_zoom", 0, 5, whole=True)+ streetview.angle(heading, "heading")+ streetview.angle(pitch, "pitch")+ fov = number(fov, "fov", 5, 175, whole=True)+ positive(radius, "radius")+ if stops is not None:+ number(stops, "stops", 1, whole=True)if step is not None:- places.positive(step, "step")+ positive(step, "step")if look_at is not None:- places.point(look_at)- selected_place, selected_routes = None, []- requested_stops = 1- gaps = []+ point(look_at)++ selected_place, sections, gaps, requested_stops = None, [], [], 1if street is not None:selected_place = places.choose(client, street, match=match, best_match=best_match, street=True, endpoint=endpoint)- 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, 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)+ sections = routes.resolve(client, selected_place, route=route, reverse=reverse, progress=progress)+ samples, gaps, requested_stops = street_samples(client, sections, stops, step, progress)elif pano_id:if not streetview.PANO_ID.fullmatch(pano_id):raise ValueError("Invalid panorama ID.")@@ -80,13 +75,14 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=Noneelse:requested, selected_place = location(client, at=at, place=place, match=match,best_match=best_match, endpoint=endpoint)- views = coverage(client, places.around(requested, radius * 2), progress)+ views = coverage(client, around(requested, radius * 2), progress)nearest = min(views, key=lambda v: (distance(requested, (v["lat"], v["lon"])), v["pano_id"]), default=None)samples = []if nearest and distance(requested, (nearest["lat"], nearest["lon"])) <= radius:samples = [dict(nearest, stop=1, requested_location=list(requested))]if not samples:raise RequestError("no_coverage", "No matching Street View panoramas were found.", gaps=gaps)+output = Path(output).expanduser().resolve()output.mkdir(parents=True, exist_ok=True)folder = Path(tempfile.mkdtemp(prefix="aleph-streetview-", dir=output))@@ -95,48 +91,42 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=Noneplace=selected_place, source="Google Street View", captured_at=now())if street and step is not None:result["requested_step_m"] = step- 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}+ if sections:+ result["routes"] = [{key: value for key, value in section.items() if key != "points"} for section in sections]directions = ("left", "right") if view == "both" else (view,)try:progress("Street View", 0, len(samples))for index, sample in enumerate(samples, 1):try:- metadata = streetview.parse_metadata(client.get(streetview.metadata_url(sample["pano_id"])),- full_sphere=full_sphere)+ metadata = streetview.fetch_metadata(client, sample["pano_id"], full_sphere=full_sphere)if metadata["pano_id"] != sample["pano_id"]:raise ValueError("The provider returned a different panorama.")actual = (metadata["lat"], metadata["lon"])if "lat" in sample and distance(actual, (sample["lat"], sample["lon"])) > 1:raise MissingImagery("Panorama position changed; retry with --refresh.")- for direction in directions if street and not full_sphere else (None,):- if full_sphere:- name = f"{len(result['photos']) + 1:03d}_sphere.{streetview_format}"- photo = {**sample, **metadata}- if "heading" in photo:- photo["road_heading"] = photo.pop("heading")- photo.update(streetview.save_sphere(client, metadata, sphere_zoom, folder / name))- photo.update(path=str(folder / name), source_url=streetview.metadata_url(sample["pano_id"]))- result["photos"].append(photo)- continue- angle = (sample["heading"] + offsets[direction]) % 360 if street else heading- if look_at is not None:- angle = bearing(actual, look_at)- address = streetview.image_url(sample["pano_id"], angle, fov, pitch)- data = client.get(address, missing_ok=True)- name = f"{len(result['photos']) + 1:03d}.{streetview_format}"- with capture.open_image(data, (1024, 576)) as image, atomic_path(folder / name) as temporary:- image.convert("RGB").save(temporary, format="PNG" if streetview_format == "png" else "JPEG", quality=80)+ if full_sphere:+ path = folder / f"{len(result['photos']) + 1:03d}_sphere.{streetview_format}"photo = {**sample, **metadata}- photo.update(heading=angle, pitch=pitch, fov=fov,- path=str(folder / name), source_url=address, width=1024, height=576)- if street:- photo["view"] = direction- if "requested_location" in sample:- photo["distance_m"] = round(distance(sample["requested_location"], actual), 2)+ if "heading" in photo:+ photo["road_heading"] = photo.pop("heading")+ photo.update(streetview.save_sphere(client, metadata, sphere_zoom, path), path=str(path),+ source_url=streetview.metadata_url(sample["pano_id"]))result["photos"].append(photo)+ else:+ for direction in directions if street else (None,):+ angle = (sample["heading"] + VIEW_OFFSETS[direction]) % 360 if street else heading+ if look_at is not None:+ angle = bearing(actual, look_at)+ address = streetview.image_url(sample["pano_id"], angle, fov, pitch)+ data = client.get(address, missing_ok=True)+ path = folder / f"{len(result['photos']) + 1:03d}.{streetview_format}"+ photo = {**sample, **metadata, **streetview.save_photo(data, path)}+ photo.update(heading=angle, pitch=pitch, fov=fov, path=str(path), source_url=address)+ if street:+ photo["view"] = direction+ if "requested_location" in sample:+ photo["distance_m"] = round(distance(sample["requested_location"], actual), 2)+ result["photos"].append(photo)result["saved_stops"] += 1except MissingImagery as error:gap = dict(stop=sample["stop"], reason="no_coverage", message=str(error))@@ -162,11 +152,11 @@ def satellite(client, output, progress, *, at=None, place=None, match=None, bestendpoint=places.GEOCODER, bbox=None, tile=None, size=200, zoom=19, satellite_format="jpg"):if tile is not None:zoom, x, y = tile- places.number(zoom, "zoom", 1, 21)+ number(zoom, "zoom", 1, 21, whole=True)selected_place = Noneif tile is not None:- places.number(x, "tile x", 0, 2 ** zoom - 1)- places.number(y, "tile y", 0, 2 ** zoom - 1)+ number(x, "tile x", 0, 2 ** zoom - 1)+ number(y, "tile y", 0, 2 ** zoom - 1)north, west = coordinate(x * 256, y * 256, zoom)south, east = coordinate((x + 1) * 256, (y + 1) * 256, zoom)area = (south, west, north, east)@@ -175,8 +165,7 @@ def satellite(client, output, progress, *, at=None, place=None, match=None, bestelse:center, selected_place = location(client, at=at, place=place, match=match,best_match=best_match, endpoint=endpoint)- area = places.around(center, size)- g = grid(area, zoom)+ area = around(center, size)run = capture.plan(client, area, dict(include=["satellite"], satellite_zoom=zoom,satellite_format=satellite_format), progress)folder = capture.create_folder(run, output)@@ -187,6 +176,7 @@ def satellite(client, output, progress, *, at=None, place=None, match=None, bestexcept KeyboardInterrupt as error:raise RequestError("interrupted", "Stopped. Use 'capture resume' to continue this capture.", folder=str(folder)) from error# Pixel rounding means actual bounds can extend slightly beyond the request.+ g = run["stages"][0]["grid"]north, west = coordinate(g["left"], g["top"], zoom)south, east = coordinate(g["left"] + g["width"], g["top"] + g["height"], zoom)result = dict(command="satellite", status="complete", folder=str(folder),diff --git a/src/routes.py b/src/routes.pyindex 40c89be..17c4adb 100644--- a/src/routes.py+++ b/src/routes.py@@ -56,12 +56,6 @@ def chains(ways):return routes-def describe(route, index):- return dict(route=index, start=list(route["points"][0]), end=list(route["points"][-1]),- length_m=round(route["length_m"], 2), way_ids=route["way_ids"],- 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]@@ -107,9 +101,12 @@ def resolve(client, place, *, route=None, reverse=False, progress=lambda *args:for index, section in enumerate(options, 1):if route is not None and index != route:continue+ points = section["points"]if reverse:- section["points"].reverse()- section.update(describe(section, index), name=name, scope="connected_same_name_ways")+ points.reverse()+ section.update(route=index, start=list(points[0]), end=list(points[-1]),+ length_m=round(section["length_m"], 2), closed=points[0] == points[-1],+ name=name, scope="connected_same_name_ways")selected.append(section)return selecteddiff --git a/src/streetview.py b/src/streetview.pyindex 1d7bf3d..d4ca378 100644--- a/src/streetview.py+++ b/src/streetview.py@@ -5,13 +5,12 @@ import mathimport reimport shutilimport unicodedata-from io import BytesIOfrom itertools import pairwisefrom pathlib import Pathfrom PIL import Image-from .common import MissingImagery, atomic_path, url, write_bytes+from .common import MissingImagery, number, open_image, save_image, url, write_bytesfrom .geo import Line, RoadIndex, clip, distance, grid, inside, tilesEXCLUDED = re.compile(r"^(construction|proposed|planned|abandoned|razed|demolished)$")@@ -22,6 +21,13 @@ DEPTHS = {"all": None,}PANO_ID = re.compile(r"[\w-]{10,200}", re.ASCII)+PHOTO_SIZE = (1024, 576)+FLOAT32_MAX = float.fromhex("0x1.fffffep+127")+++def angle(value, name):+ # Google's pitch and yaw fields use protobuf TYPE_FLOAT.+ return number(value, name, -FLOAT32_MAX, FLOAT32_MAX)def panorama(identity, position):@@ -41,7 +47,7 @@ def google_json(data):def parse_coverage(data):try:response = google_json(data)- if response[1] is None or response[1] == []:+ if not response[1]:return []found = []for row in response[1][1]:@@ -51,9 +57,22 @@ def parse_coverage(data):found.append(panorama(identity, row[0][2][0]))return foundexcept (ValueError, TypeError, IndexError, KeyError) as error:- raise ValueError(- "Unreadable Google panorama coverage; the endpoint may have changed."- ) from error+ raise ValueError("Unreadable Google panorama coverage; the endpoint may have changed.") from error+++def coverage(client, area, progress):+ """Every Google panorama listed in the zoom-17 tiles that cover the area."""+ coverage_grid = grid(area, 17)+ count = coverage_grid["rows"] * coverage_grid["columns"]+ found = {}+ progress("Finding panoramas", 0, count)+ for i, tile in enumerate(tiles(coverage_grid), 1):+ address = url("https://www.google.com/maps/photometa/ac/v1",+ pb=f"!1m1!1smaps_sv.tactile!6m3!1i{tile['x']}!2i{tile['y']}!3i17!8b1")+ for view in parse_coverage(client.get(address)):+ found[view["pano_id"]] = view+ progress("Finding panoramas", i, count)+ return list(found.values())def parse_metadata(data, *, full_sphere=False):@@ -65,125 +84,90 @@ def parse_metadata(data, *, full_sphere=False):if code not in (1, 3):raise ValueError("Unexpected response code.")result = panorama(message[1], message[5][0][1][0])- date = (- message[6][7]- if len(message) > 6 and isinstance(message[6], list) and len(message[6]) > 7- else None- )+ date = message[6][7] if len(message) > 6 and isinstance(message[6], list) and len(message[6]) > 7 else Noneresult["imagery_date"] = None- if (- isinstance(date, list)- and len(date) >= 2- and all(type(v) is int for v in date[:2])- and 1900 <= date[0] <= 2200- and 1 <= date[1] <= 12- ):+ if (isinstance(date, list) and len(date) >= 2 and all(type(v) is int for v in date[:2])+ and 1900 <= date[0] <= 2200 and 1 <= date[1] <= 12):result["imagery_date"] = f"{date[0]:04d}-{date[1]:02d}"if full_sphere:sizes, tile_size = message[2][3][:2]sizes = [[size[0][1], size[0][0]] for size in sizes]if (not sizes or len(sizes) > 6 or len(tile_size) != 2- or any(type(v) is not int or not 1 <= v <= 32768- for size in sizes + [tile_size] for v in size)+ or any(type(v) is not int or not 1 <= v <= 32768 for size in sizes + [tile_size] for v in size)or any(w * h > 150_000_000 for w, h in sizes)):raise ValueError("Invalid panorama dimensions.")orientation = message[5][0][1][2][:3]if len(orientation) != 3:raise ValueError("Missing panorama orientation.")- for angle in orientation:- validate_angle(angle, "panorama orientation")- result.update(image_sizes=sizes, tile_size=tile_size,- panorama_heading=orientation[0],+ for value in orientation:+ angle(value, "panorama orientation")+ result.update(image_sizes=sizes, tile_size=tile_size, panorama_heading=orientation[0],panorama_pitch=90 - orientation[1], panorama_roll=orientation[2])return resultexcept (ValueError, TypeError, IndexError, KeyError) as error:- raise ValueError(- "Unreadable Google panorama metadata; resume to retry this view."- ) from error+ raise ValueError("Unreadable Google panorama metadata; resume to retry this view.") from errordef metadata_url(pano_id):- return url(- "https://www.google.com/maps/photometa/v1",- authuser=0,- hl="en",- gl="US",- pb=f"!1m1!1smaps_sv.tactile!2m2!1sen!2sUS!3m3!1m2!1e2!2s{pano_id}!4m6!1e1!1e2!1e3!1e4!2m1!1e1",- )+ return url("https://www.google.com/maps/photometa/v1", authuser=0, hl="en", gl="US",+ pb=f"!1m1!1smaps_sv.tactile!2m2!1sen!2sUS!3m3!1m2!1e2!2s{pano_id}!4m6!1e1!1e2!1e3!1e4!2m1!1e1")-def validate_angle(value, name):- # Google's pitch and yaw fields use protobuf TYPE_FLOAT.- if (type(value) not in (int, float) or not math.isfinite(value)- or abs(value) > float.fromhex("0x1.fffffep+127")):- raise ValueError(f"{name}: use a finite 32-bit float in degrees.")- return value---def validate_fov(value):- if (type(value) not in (int, float) or not math.isfinite(value)- or not 5 <= value <= 175 or int(value) != value):- raise ValueError("fov: use a whole number from 5 to 175.")- return int(value)+def fetch_metadata(client, pano_id, *, full_sphere=False):+ return parse_metadata(client.get(metadata_url(pano_id)), full_sphere=full_sphere)def image_url(pano_id, heading, fov, pitch=0):- return url(- "https://streetviewpixels-pa.googleapis.com/v1/thumbnail",- panoid=pano_id,- cb_client="maps_sv.tactile",- w=1024,- h=576,- yaw=validate_angle(heading, "heading"),- # The thumbnail service uses positive-down; Aleph uses positive-up.- pitch=-validate_angle(pitch, "pitch"),- thumbfov=validate_fov(fov),- )+ # The thumbnail service uses positive-down pitch; Aleph uses positive-up.+ return url("https://streetviewpixels-pa.googleapis.com/v1/thumbnail", panoid=pano_id,+ cb_client="maps_sv.tactile", w=PHOTO_SIZE[0], h=PHOTO_SIZE[1], yaw=heading, pitch=-pitch, thumbfov=fov)-def validate_sphere_zoom(zoom):- if type(zoom) is not int or not 0 <= zoom <= 5:- raise ValueError("sphere_zoom: use a whole number from 0 to 5.")- return zoom+def maps_url(photo):+ """A Google Maps link to the panorama, facing the photo's view when it has one."""+ params = dict(api=1, map_action="pano", pano=photo["pano_id"], viewpoint=f"{photo['lat']},{photo['lon']}")+ if "fov" in photo:+ # Maps links support 10–100°, unlike the thumbnail endpoint.+ params.update(heading=photo["heading"], pitch=photo["pitch"], fov=max(10, min(100, photo["fov"])))+ return url("https://www.google.com/maps/@", **params)-def tile_url(pano_id, zoom, x, y):- return url("https://streetviewpixels-pa.googleapis.com/v1/tile",- cb_client="maps_sv.tactile", panoid=pano_id, zoom=zoom, x=x, y=y)+def save_photo(data, path):+ with open_image(data, PHOTO_SIZE) as image, image.convert("RGB") as rgb:+ save_image(rgb, path, quality=80)+ return dict(width=PHOTO_SIZE[0], height=PHOTO_SIZE[1])def save_sphere(client, metadata, zoom, target):"""Assemble native panorama tiles; retain partial tiles for retry/resume."""- zoom = min(validate_sphere_zoom(zoom), len(metadata["image_sizes"]) - 1)+ zoom = min(zoom, len(metadata["image_sizes"]) - 1)width, height = metadata["image_sizes"][zoom]tw, th = metadata["tile_size"]columns, rows = math.ceil(width / tw), math.ceil(height / th)target = Path(target)cache = target.parent / ".sphere-tiles" / metadata["pano_id"] / f"{zoom}-{width}x{height}-{tw}x{th}"- count = columns * rowswith Image.new("RGB", (width, height)) as sphere:for y in range(rows):for x in range(columns):client.check_cancel()path = cache / f"{x}-{y}.tile"- data = path.read_bytes() if path.is_file() else client.get(- tile_url(metadata["pano_id"], zoom, x, y), missing_ok=True)- with Image.open(BytesIO(data)) as tile:- if tile.format not in ("JPEG", "PNG") or tile.size != (tw, th):- raise ValueError(f"Expected a panorama tile of {tw} × {th} pixels.")- tile.load()- if not path.is_file():+ cached = path.is_file()+ data = path.read_bytes() if cached else client.get(+ url("https://streetviewpixels-pa.googleapis.com/v1/tile", cb_client="maps_sv.tactile",+ panoid=metadata["pano_id"], zoom=zoom, x=x, y=y), missing_ok=True)+ with open_image(data, (tw, th)) as tile:+ if not cached:write_bytes(path, data)sphere.paste(tile, (x * tw, y * th))client.check_cancel()- with atomic_path(target) as temporary:- sphere.save(temporary, format="PNG" if target.suffix == ".png" else "JPEG", quality=90)+ save_image(sphere, target, quality=90)shutil.rmtree(cache)- return dict(projection="equirectangular", width=width, height=height,- sphere_zoom=zoom, tile_count=count)+ return dict(projection="equirectangular", width=width, height=height, sphere_zoom=zoom,+ tile_count=columns * rows)def roads(ways, area, depth):+ """Clip mapped roads to the area, splitting them wherever they leave it or repeat an edge."""parts, seen_edges = [], set()for way in sorted(ways, key=lambda way: way["id"]):tags = way["tags"]@@ -193,41 +177,26 @@ def roads(ways, area, depth):if DEPTHS[depth] and not DEPTHS[depth].fullmatch(highway):continuepoints, nodes = way["points"], way["nodes"]- layer, run, part = str(tags.get("layer", "0")), [], 0-- def flush():- nonlocal run, part- if len(run) > 1:- part += 1- parts.append(- dict(- id=f"way-{way['id']}-{part}",- osm_id=way["id"],- name=tags.get("name", ""),- highway=highway,- layer=layer,- points=run,- )- )- run = []-+ layer, runs = str(tags.get("layer", "0")), [[]]for i, (a, b) in enumerate(pairwise(points)):if distance(a, b) <= 0.01:continuesegment = clip(a, b, area)edge = layer, tuple(sorted((nodes[i], nodes[i + 1])))if segment is None or edge in seen_edges:- flush()+ runs.append([])continueseen_edges.add(edge)- if run and distance(run[-1], segment[0]) > 0.01:- flush()- if not run:- run.append(segment[0])- run.append(segment[1])+ if runs[-1] and distance(runs[-1][-1], segment[0]) > 0.01:+ runs.append([])+ if not runs[-1]:+ runs[-1].append(segment[0])+ runs[-1].append(segment[1])if not inside(b, area):- flush()- flush()+ runs.append([])+ for part, run in enumerate((run for run in runs if len(run) > 1), 1):+ parts.append(dict(id=f"way-{way['id']}-{part}", osm_id=way["id"], name=tags.get("name", ""),+ highway=highway, layer=layer, points=run))return parts@@ -236,14 +205,8 @@ def match_road(parts, lines, index, point, spacing):for i, segments in index.near(point).items():meters, separation = lines[i].project(point, segments)if separation <= 30:- candidates.append(- dict(- path_index=i,- path_meters=meters,- road_distance=separation,- heading=lines[i].heading(meters, spacing),- )- )+ candidates.append(dict(path_index=i, path_meters=meters, road_distance=separation,+ heading=lines[i].heading(meters, spacing)))candidates.sort(key=lambda c: (c["road_distance"], c["path_index"]))if not candidates:return None@@ -253,34 +216,24 @@ def match_road(parts, lines, index, point, spacing):def endpoint(candidate):line = lines[candidate["path_index"]]meters = candidate["path_meters"]- return min(meters, line.length - meters), line.points[- 0 if meters <= line.length / 2 else -1- ]+ return min(meters, line.length - meters), line.points[0 if meters <= line.length / 2 else -1]def connected(other, winner):a, b = other["path_index"], winner["path_index"]end_distance, end = endpoint(other)return other is winner or (- parts[a]["layer"] == parts[b]["layer"]- and end_distance < 5- and lines[b].project(end)[1] <= 0.5- )+ parts[a]["layer"] == parts[b]["layer"] and end_distance < 5 and lines[b].project(end)[1] <= 0.5)def joined(other):first, part = parts[nearest["path_index"]], parts[other["path_index"]]same_road = first["osm_id"] == part["osm_id"] or (- first["name"] and first["name"] == part["name"] and first["highway"] == part["highway"]- )+ first["name"] and first["name"] == part["name"] and first["highway"] == part["highway"])a, start = endpoint(nearest)b, end = endpoint(other)- angle = abs((nearest["heading"] - other["heading"] + 180) % 360 - 180)+ turn = abs((nearest["heading"] - other["heading"] + 180) % 360 - 180)return other is nearest or (- same_road- and first["layer"] == part["layer"]- and max(a, b) < 5- and distance(start, end) <= 0.5- and min(angle, 180 - angle) <= 15- )+ same_road and first["layer"] == part["layer"] and max(a, b) < 5+ and distance(start, end) <= 0.5 and min(turn, 180 - turn) <= 15)method = "nearest-road"if len(plausible) > 1:@@ -302,12 +255,11 @@ def select_stops(candidates, spacing):index = 0while index < len(positions):yield positions[index]- next_index = index + 1- while next_index + 1 < len(positions) and positions[next_index + 1][- "path_meters"- ] - positions[index]["path_meters"] <= spacing * (1 + 1e-7):- next_index += 1- index = next_index+ following = index + 1+ while (following + 1 < len(positions) and positions[following + 1]["path_meters"]+ - positions[index]["path_meters"] <= spacing * (1 + 1e-7)):+ following += 1+ index = followingdef plan(client, area, options, progress, *, allow_empty=False):@@ -316,25 +268,13 @@ def plan(client, area, options, progress, *, allow_empty=False):parts = roads(ways, area, options["depth"])if not parts and not allow_empty:raise ValueError("No mapped roads at this path depth. Choose another area or depth.")- coverage_grid = grid(area, 17)- total = coverage_grid["rows"] * coverage_grid["columns"]- found = {}- progress("Finding panoramas", 0, total)- for i, tile in enumerate(tiles(coverage_grid), 1):- address = url(- "https://www.google.com/maps/photometa/ac/v1",- pb=f"!1m1!1smaps_sv.tactile!6m3!1i{tile['x']}!2i{tile['y']}!3i17!8b1",- )- for view in parse_coverage(client.get(address)):- if inside((view["lat"], view["lon"]), area):- found[view["pano_id"]] = view- progress("Finding panoramas", i, total)+ found = [view for view in coverage(client, area, progress) if inside((view["lat"], view["lon"]), area)]progress("Indexing roads")lines = [Line(part["points"]) for part in parts]index = RoadIndex(lines)groups = [[] for _ in parts]excluded, spacing = 0, options["step"]- for i, view in enumerate(found.values(), 1):+ for i, view in enumerate(found, 1):road = match_road(parts, lines, index, (view["lat"], view["lon"]), spacing)if road is None:excluded += 1@@ -342,44 +282,24 @@ def plan(client, area, options, progress, *, allow_empty=False):groups[road["path_index"]].append(dict(view, **road))progress("Matching panoramas", i, len(found))samples, gaps = [], []- for i, (line, group) in enumerate(zip(lines, groups)):+ for part, line, group in zip(parts, lines, groups):selected = list(select_stops(group, spacing))positions = [0] + [view["path_meters"] for view in selected] + [line.length]for j, (start, end) in enumerate(pairwise(positions)):limit = spacing / 2 if j in (0, len(positions) - 2) else spacingif not selected or end - start > limit * (1 + 1e-7):- gaps.append(- dict(- path_id=parts[i]["id"],- start=line.at(start),- end=line.at(end),- meters=end - start,- )- )- for stop, view in enumerate(selected, 1):- samples.append(dict(view, stop_in_path=stop))+ gaps.append(dict(path_id=part["id"], start=line.at(start), end=line.at(end), meters=end - start))+ samples.extend(dict(view, stop_in_path=stop) for stop, view in enumerate(selected, 1))return dict(- mode="streetview",- full_sphere=options["full_sphere"],- paths=parts,- samples=samples,- results=[],+ mode="streetview", full_sphere=options["full_sphere"], paths=parts, samples=samples, results=[],coverage=dict(available=len(found), excluded=excluded, gaps=gaps, spacing=spacing),length=sum(line.length for line in lines),- osm_data_at=metadata["osm_data_at"],- osm_source_url=metadata["source_url"],+ osm_data_at=metadata["osm_data_at"], osm_source_url=metadata["source_url"],)def photo_name(photo, extension):- slug = (- unicodedata.normalize("NFKD", photo["path_name"] or photo["highway"])- .encode("ascii", "ignore")- .decode()- .lower()- )- slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")[:36].rstrip("-") or "path"- return (- f"{photo['sequence']:06d}_{slug}_p{photo['path_index'] + 1:04d}_s{photo['stop_in_path']:04d}_"- f"{photo['side']}_h{math.floor(photo['heading'] + 0.5) % 360:03d}.{extension}"- )+ slug = unicodedata.normalize("NFKD", photo["path_name"] or photo["highway"]).encode("ascii", "ignore").decode()+ slug = re.sub(r"[^a-z0-9]+", "-", slug.lower()).strip("-")[:36].rstrip("-") or "path"+ return (f"{photo['sequence']:06d}_{slug}_p{photo['path_index'] + 1:04d}_s{photo['stop_in_path']:04d}_"+ f"{photo['side']}_h{math.floor(photo['heading'] + 0.5) % 360:03d}.{extension}")diff --git a/src/terrain.py b/src/terrain.pyindex 1bd9463..904d39f 100644--- a/src/terrain.py+++ b/src/terrain.py@@ -35,9 +35,7 @@ class TIFF:raw = entry[8 : 8 + size] if size <= 4 else self.read(location, size)self.tags[code] = kind, length, rawrequired = {258: 32, 339: 3, 277: 1, 262: 1}- if any(self.value(key) != value for key, value in required.items()) or self.value(- 259- ) not in (1, 8, 32946):+ if any(self.value(key) != value for key, value in required.items()) or self.value(259) not in (1, 8, 32946):raise ValueError("Expected tiled Float32 terrain.")if (self.value(322), self.value(323)) not in ((256, 256), (512, 512)):raise ValueError("Expected 256- or 512-pixel terrain blocks.")@@ -46,11 +44,7 @@ class TIFF:if any(key not in self.tags for key in (33550, 33922, 34735, 42113, 324, 325)):raise ValueError("Missing terrain georeferencing or blocks.")keys = self.values(34735)- self.keys = {- keys[i]: keys[i + 3]- for i in range(4, len(keys) - 3, 4)- if keys[i + 1 : i + 3] == (0, 1)- }+ self.keys = {keys[i]: keys[i + 3] for i in range(4, len(keys) - 3, 4) if keys[i + 1:i + 3] == (0, 1)}if self.keys.get(3072) != 3857 or self.keys.get(1025) not in (1, 2):raise ValueError("Expected EPSG:3857 terrain.")@@ -107,9 +101,7 @@ class TIFF:def header(tags, order):- directory = bytearray(- (b"II" if order == "<" else b"MM") + struct.pack(order + "HIH", 42, 8, len(tags))- )+ directory = bytearray((b"II" if order == "<" else b"MM") + struct.pack(order + "HIH", 42, 8, len(tags)))data = bytearray()start = 8 + 2 + len(tags) * 12 + 4for code, (kind, count, raw) in sorted(tags.items()):@@ -133,15 +125,10 @@ def origin(source, tile):def validate(source, tile):scale, west, north = origin(source, tile)pixel, tie = source.values(33550), source.values(33922)- if not (- (source.value(256), source.value(257)) == (512, 512)- and len(pixel) == 3 and len(tie) == 6- and all(math.isfinite(v) for v in pixel + tie)- and all(abs(pixel[i] - scale) <= scale * 1e-8 for i in (0, 1))- and tie[:3] == (0, 0, 0)- and abs(tie[3] - west) <= scale * 1e-5- and abs(tie[4] - north) <= scale * 1e-5- ):+ if not ((source.value(256), source.value(257)) == (512, 512) and len(pixel) == 3 and len(tie) == 6+ and all(math.isfinite(v) for v in pixel + tie)+ and all(abs(pixel[i] - scale) <= scale * 1e-8 for i in (0, 1))+ and tie[:3] == (0, 0, 0) and abs(tie[3] - west) <= scale * 1e-5 and abs(tie[4] - north) <= scale * 1e-5):raise ValueError("Terrain georeferencing does not match the download grid.")offsets, sizes = source.values(324), source.values(325)count = (512 // source.value(322)) ** 2diff --git a/tests/test_capture.py b/tests/test_capture.pyindex 4a53c31..7ec91db 100644--- a/tests/test_capture.py+++ b/tests/test_capture.py@@ -114,7 +114,7 @@ class CaptureTests(unittest.TestCase):bounds=[44.99, 8.99, 45.01, 9.01],options=capture.settings({"include": ["streetview"]}),state="planned", stages=[dict(- mode="streetview", results=[],+ mode="streetview", full_sphere=False, results=[],paths=[dict(id="way-1-1", name="Test street", osm_id=1, highway="residential", layer="0")],samples=[dict(pano_id="test_panorama_123", lat=45.0, lon=9.0,heading=350, path_index=0, stop_in_path=1)],@@ -210,7 +210,7 @@ class CaptureTests(unittest.TestCase):client = Mock()client.get.side_effect = [sphere_metadata(), tile]if state == "failed":- with self.assertRaisesRegex(ValueError, "panorama tile"):+ with self.assertRaisesRegex(ValueError, "4 × 2 pixels"):capture.download(run, self.folder, client, self.progress)else:capture.download(run, self.folder, client, self.progress)