Skip to content

armgit / Aleph

Public Imported from GitHub
0

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

Switch from overpass to Geofabrik

Belluxxa32002657306
diff --git a/README.md b/README.md
index 1bcbfc8..55ff788 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ This was born as a way to let LLMs quickly gather information from the physical
## Install
-Requires Python 3.11+. Pillow is the only dependency. No API keys required.
+Requires Python 3.11+. Pillow and the Python [osmium](https://osmcode.org/pyosmium/) package are installed automatically with Aleph. No API keys required.
```sh
python3 -m venv .venv
@@ -54,6 +54,8 @@ Here is an overview of the structure of the output dir after a capture:
- `map.osm`: OpenStreetMap roads, buildings, water, and other features
- `terrain.tif`: Elevation as a GeoTIFF (original tiles in `terrain/`)
+OSM data comes from [Geofabrik](https://download.geofabrik.de/). Aleph downloads the smallest regional file covering your selection, then extracts the selected rectangle locally with Python's `osmium` package. The first download can be hundreds of megabytes even for a small selection. Regional files are reused from `$XDG_CACHE_HOME/aleph/geofabrik` (usually `~/.cache/aleph/geofabrik`); use `--refresh` on CLI requests to download the latest snapshot. Map manifests record the source and snapshot date. Geofabrik omits contributor names, user IDs, and changeset IDs.
+
## From the terminal (for scripts and agents)
See the [CLI docs](docs/cli.md) for examples and details.
diff --git a/aleph.py b/aleph.py
index 8ac6fc4..5625e4c 100644
--- a/aleph.py
+++ b/aleph.py
@@ -8,7 +8,7 @@ import sys
from pathlib import Path
from src import capture, places, quick
-from src.common import CachedClient, Client, Progress, RequestError, now
+from src.common import DEFAULT_CACHE, CachedClient, Client, Progress, RequestError, now
from src.geo import MERCATOR_RADIUS, bounds
@@ -37,13 +37,15 @@ def parser():
def json_output(command):
command.add_argument("--json", action="store_true", help="one JSON result on stdout; progress on stderr")
+ 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")
+
def network(command):
command.add_argument("--geocoder", default=os.environ.get("ALEPH_GEOCODER_URL", places.GEOCODER),
metavar="URL", help="Photon server URL (or ALEPH_GEOCODER_URL)")
- command.add_argument("--cache-dir", type=Path,
- default=Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "aleph",
- help="response cache directory (default: %(default)s)")
- command.add_argument("--refresh", action="store_true", help="fetch fresh responses instead of cached responses")
+ cache_options(command)
json_output(command)
def locations(command):
@@ -99,6 +101,7 @@ def parser():
area.add_argument("--sources", dest="include", nargs="+", choices=capture.SOURCES,
help="sources to download (default: all; osm includes terrain)")
output(area)
+ cache_options(area)
json_output(area)
area.add_argument("--delay", type=float, help="pause between requests in seconds")
planning = area.add_mutually_exclusive_group()
@@ -127,6 +130,7 @@ def parser():
)
if name == "resume":
command.add_argument("--no-plan", action="store_true", help=no_plan_help)
+ cache_options(command)
json_output(command)
return root
@@ -189,7 +193,8 @@ def query(args, progress):
if args.streets and args.query is None:
raise ValueError("--streets requires a place name.")
if args.nearby:
- results = places.nearby(client, args.at, radius=100 if args.radius is None else args.radius, limit=args.limit)
+ results = places.nearby(client, args.at, radius=100 if args.radius is None else args.radius,
+ limit=args.limit, progress=progress)
mode = "nearby"
else:
results = places.geocode(client, query=args.query, at=args.at, limit=args.limit if args.query is not None else 1,
@@ -266,11 +271,12 @@ def main(argv=None):
if action in ("resume", "export"):
folder = args.folder.expanduser().resolve()
run = capture.load(folder)
- client = Client(run["options"]["delay"])
+ 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}
- client = Client(args.delay)
+ client = Client(args.delay, cache_dir=args.cache_dir, refresh=args.refresh)
with Progress() as progress:
run = capture.plan(client, area, options, progress)
save_only = action == "create" and args.plan
diff --git a/docs/cli.md b/docs/cli.md
index c5beb5f..1089293 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -22,7 +22,7 @@ alephgeo resolve --at 41.8902 12.4922 --nearby --radius 100 --limit 10 --json
Reverse lookup returns the nearest address or named feature. Nearby search returns POIs ordered by distance.
-Name lookup uses [Photon](https://github.com/komoot/photon). Set `ALEPH_GEOCODER_URL` or `--geocoder URL` to use another Photon server. Nearby POIs and street geometry use Overpass.
+Name lookup uses [Photon](https://github.com/komoot/photon). Set `ALEPH_GEOCODER_URL` or `--geocoder URL` to use another Photon server. Nearby POIs and street geometry use local Geofabrik extracts.
## Quick imagery
@@ -52,7 +52,7 @@ For example, `--stops 10` requests ten positions along the street. Choose a view
If Aleph finds several places or street branches, choose from the returned options with `--match ID` or `--route N`, respectively.
> [!TIP]
-> Quick requests start immediately and cache responses for 24 hours. Use `--refresh` to fetch fresh data or `--cache-dir PATH` to change the cache location (default: `$XDG_CACHE_HOME/aleph` or `~/.cache/aleph`).
+> Quick requests start immediately and cache imagery/geocoder responses for 24 hours. OSM roads, nearby POIs, and maps use Geofabrik regional downloads, processed locally with the Python `osmium` dependency. These regional files are retained until explicitly refreshed; the first request may download hundreds of megabytes. Use `--refresh` to fetch fresh responses and regional files, or `--cache-dir PATH` to change the cache location (default: `$XDG_CACHE_HOME/aleph` or `~/.cache/aleph`).
## Capture an area
@@ -64,4 +64,6 @@ alephgeo capture create --bbox 41.8895 12.4910 41.8910 12.4940 --no-plan -o capt
`--bbox` takes two opposite corners: `lat1 lon1 lat2 lon2`. All sources are included; use `--sources satellite osm` to download only satellite imagery, map data, and terrain.
+`capture create` and `capture resume` also accept `--cache-dir PATH` and `--refresh`. Geofabrik publishes daily snapshots; repeated captures reuse the regional file until you refresh it. Estimates do not include the first regional download. Map exports retain complete local ways and original relation references; distant relation members may be absent. Named-street routes are joined using OSM node IDs, and nearby ways/relations are represented by their bounding-box centers.
+
`--no-plan` starts downloading without confirmation (not recommended, as it may take a lot of time). Omit it to review the estimate first, or use `--plan` to save a plan without downloading. See `alephgeo capture create --help` for resolution and spacing options.
diff --git a/docs/osm-benchmark.json b/docs/osm-benchmark.json
new file mode 100644
index 0000000..5950da4
--- /dev/null
+++ b/docs/osm-benchmark.json
@@ -0,0 +1,333 @@
+{
+ "date": "2026-09-21",
+ "baseline_commit": "38aa50015fe347a71bcd1c0906376a8a46e3779d",
+ "environment": {
+ "python": "3.12.12 (main, Oct 16 2025, 14:57:37) [Clang 17.0.0 (clang-1700.3.19.1)]",
+ "platform": "macOS-15.7.1-arm64-arm-64bit",
+ "center": [
+ 41.8902,
+ 12.4922
+ ],
+ "regions": [
+ {
+ "requested_km2": 10,
+ "spherical_km2": 9.99999989734788,
+ "bbox_south_west_north_east": [
+ 41.875980496522295,
+ 12.473098695094054,
+ 41.904419503477705,
+ 12.511301304905947
+ ]
+ },
+ {
+ "requested_km2": 1000,
+ "spherical_km2": 999.9989734686736,
+ "bbox_south_west_north_east": [
+ 41.74800496522297,
+ 12.301186950940533,
+ 42.03239503477703,
+ 12.683213049059468
+ ]
+ }
+ ]
+ },
+ "network_deadline_seconds": 600,
+ "standalone_geofabrik_download": {
+ "http_code": 200,
+ "size_download": 383641858,
+ "time_total": 13.592244,
+ "url_effective": "https://download.geofabrik.de/europe/italy/centro-260920.osm.pbf"
+ },
+ "overpass": [
+ {
+ "provider": "current_overpass",
+ "kind": "roads",
+ "requested_km2": 10,
+ "spherical_km2": 9.99999989734788,
+ "bbox_south_west_north_east": [
+ 41.875980496522295,
+ 12.473098695094054,
+ 41.904419503477705,
+ 12.511301304905947
+ ],
+ "query": "[out:json][timeout:25][maxsize:1073741824];way[\"highway\"](41.875980496522295,12.473098695094054,41.904419503477705,12.511301304905947);out body geom;",
+ "started_at": "2026-09-21T12:02:22.944196+00:00",
+ "attempts": [
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 8.897348375001457
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 7.583786708000844
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 8.210137291000137
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 16.630713708000258
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 107.65975120900112
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "error": "TimeoutError('The read operation timed out')",
+ "headers_or_error_seconds": 240.06496191599945
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 86.85915491600099
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 102.47538841699861
+ },
+ {
+ "url": "https://maps.mail.ru/osm/tools/overpass/api/interpreter",
+ "headers_or_error_seconds": 7.599620124998182
+ }
+ ],
+ "status": "failed",
+ "error": "Deadline('Benchmark stopped this query after 600 seconds')",
+ "total_seconds": 600.0076005420015
+ },
+ {
+ "provider": "current_overpass",
+ "kind": "map",
+ "requested_km2": 10,
+ "spherical_km2": 9.99999989734788,
+ "bbox_south_west_north_east": [
+ 41.875980496522295,
+ 12.473098695094054,
+ 41.904419503477705,
+ 12.511301304905947
+ ],
+ "query": "[out:xml][timeout:180][maxsize:536870912];nwr(41.875980496522295,12.473098695094054,41.904419503477705,12.511301304905947);(._;node(w););out meta qt;",
+ "started_at": "2026-09-21T12:12:22.925162+00:00",
+ "attempts": [
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 200,
+ "headers_or_error_seconds": 2.9656944579983247
+ }
+ ],
+ "download_seconds": 7.840124750000541,
+ "bytes": 52404541,
+ "valid": true,
+ "counts": {
+ "node": 177570,
+ "way": 32788,
+ "relation": 3082
+ },
+ "highway_ways": 12412,
+ "validation_seconds": 1.7904330419987673,
+ "osm_timestamp": {
+ "osm_base": "2026-09-21T12:10:20Z"
+ },
+ "sha256": "74b078fa9f3d1ddc958969a814d83d62f9bea2adbd7182b1e9c38d83cd62fec8",
+ "status": "ok",
+ "total_seconds": 10.694375208000565
+ },
+ {
+ "provider": "current_overpass",
+ "kind": "roads",
+ "requested_km2": 1000,
+ "spherical_km2": 999.9989734686736,
+ "bbox_south_west_north_east": [
+ 41.74800496522297,
+ 12.301186950940533,
+ 42.03239503477703,
+ 12.683213049059468
+ ],
+ "query": "[out:json][timeout:25][maxsize:1073741824];way[\"highway\"](41.74800496522297,12.301186950940533,42.03239503477703,12.683213049059468);out body geom;",
+ "started_at": "2026-09-21T12:12:33.620171+00:00",
+ "attempts": [
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 8.826568917000259
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 9.151510834002693
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 8.84591270799865
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 16.052941875001125
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 92.31481312500182
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 98.98106058299891
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 224.4021728330008
+ },
+ {
+ "url": "https://overpass.private.coffee/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 99.43211099999826
+ },
+ {
+ "url": "https://maps.mail.ru/osm/tools/overpass/api/interpreter",
+ "headers_or_error_seconds": 27.963263708999875
+ }
+ ],
+ "status": "failed",
+ "error": "Deadline('Benchmark stopped this query after 600 seconds')",
+ "total_seconds": 600.0040845830008
+ },
+ {
+ "provider": "current_overpass",
+ "kind": "map",
+ "requested_km2": 1000,
+ "spherical_km2": 999.9989734686736,
+ "bbox_south_west_north_east": [
+ 41.74800496522297,
+ 12.301186950940533,
+ 42.03239503477703,
+ 12.683213049059468
+ ],
+ "query": "[out:xml][timeout:180][maxsize:536870912];nwr(41.74800496522297,12.301186950940533,42.03239503477703,12.683213049059468);(._;node(w););out meta qt;",
+ "started_at": "2026-09-21T12:22:33.619508+00:00",
+ "attempts": [
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 504,
+ "headers_or_error_seconds": 7.800043290997564
+ },
+ {
+ "url": "https://overpass-api.de/api/interpreter",
+ "status": 200,
+ "headers_or_error_seconds": 16.731868375001795
+ }
+ ],
+ "download_seconds": 62.22662429100092,
+ "bytes": 769374728,
+ "valid": true,
+ "counts": {
+ "node": 3172882,
+ "way": 469157,
+ "relation": 20521
+ },
+ "highway_ways": 163195,
+ "validation_seconds": 113.68387441699815,
+ "osm_timestamp": {
+ "osm_base": "2026-09-21T12:21:34Z"
+ },
+ "sha256": "62fd2a8206a9a2e090cce667d442cd2780539f9877610e6619545d27d0bdc9a5",
+ "status": "ok",
+ "total_seconds": 226.08120658299958
+ }
+ ],
+ "geofabrik": {
+ "results": [
+ {
+ "area_km2": 10,
+ "map_seconds": 15.256952792002267,
+ "map_bytes": 41319499,
+ "source_url": "https://download.geofabrik.de/europe/italy/centro-latest.osm.pbf",
+ "region": "Centro",
+ "osm_data_at": "2026-09-20T20:22:06Z",
+ "cached_map_seconds": 3.3866028749980615,
+ "road_seconds": 3.637508791998698,
+ "highway_ways": 12412
+ },
+ {
+ "area_km2": 1000,
+ "map_seconds": 3.6622887500016077,
+ "map_bytes": 571428870,
+ "source_url": "https://download.geofabrik.de/europe/italy/centro-latest.osm.pbf",
+ "region": "Centro",
+ "osm_data_at": "2026-09-20T20:22:06Z",
+ "road_seconds": 11.716084957999556,
+ "highway_ways": 163195
+ }
+ ],
+ "requests": [
+ [
+ "GET",
+ "https://download.geofabrik.de/index-v1.json",
+ 0
+ ],
+ [
+ "GET",
+ "https://download.geofabrik.de/europe/italy/centro-latest.osm.pbf",
+ 0
+ ]
+ ]
+ },
+ "checks": {
+ "missing_way_nodes": {
+ "10": 0,
+ "1000": 0
+ },
+ "highway_way_id_sets_match": {
+ "10": true,
+ "1000": true
+ },
+ "tests_passed": 44
+ },
+ "python_osmium": {
+ "version": "4.3.1",
+ "regional_file_cached": true,
+ "network_requests": 0,
+ "results": [
+ {
+ "area_km2": 10,
+ "map_seconds": 161.65,
+ "map_bytes": 41319502,
+ "source_url": "https://download.geofabrik.de/europe/italy/centro-latest.osm.pbf",
+ "region": "Centro",
+ "osm_data_at": "2026-09-20T20:22:06Z",
+ "counts": {
+ "nodes": 177525,
+ "ways": 32787,
+ "relations": 3219
+ },
+ "object_ids_match_native_cli": true,
+ "missing_way_nodes": 0
+ },
+ {
+ "area_km2": 1000,
+ "map_seconds": 173.88,
+ "map_bytes": 571428873,
+ "source_url": "https://download.geofabrik.de/europe/italy/centro-latest.osm.pbf",
+ "region": "Centro",
+ "osm_data_at": "2026-09-20T20:22:06Z",
+ "counts": {
+ "nodes": 3172834,
+ "ways": 469155,
+ "relations": 21004
+ },
+ "object_ids_match_native_cli": true,
+ "missing_way_nodes": 0
+ }
+ ]
+ }
+}
diff --git a/docs/osm-benchmark.md b/docs/osm-benchmark.md
new file mode 100644
index 0000000..2842f4c
--- /dev/null
+++ b/docs/osm-benchmark.md
@@ -0,0 +1,82 @@
+# OSM provider benchmark — 21 September 2026
+
+Aleph now uses the Python `osmium` dependency for Geofabrik extraction and local road geometry. The native Osmium CLI measurements below describe the earlier implementation, which has been replaced. No Overpass service is used by either Geofabrik implementation.
+
+## Method
+
+Both selections are centered on the Colosseum in Rome, at 41.8902° N, 12.4922° E. They are squares approximately 3.162 km and 31.623 km wide, with spherical areas of 10.000 and 999.999 km². Tests ran on macOS 15.7.1 ARM64 with Python 3.12.12. The original CLI comparison used Osmium 1.19.1; the current Python implementation uses `osmium` 4.3.1.
+
+The baseline is commit `38aa50015fe347a71bcd1c0906376a8a46e3779d`. Its road and map queries, memory budgets, HTTP retries, and three-server fallback were unchanged. Each network operation had an outer 600-second benchmark deadline. A deadline result means no usable response arrived within the test budget, not that the client exhausted every possible retry. Imagery and terrain downloads were excluded.
+
+These are single live trials, so network timings depend on server load. Local files were available in the filesystem cache. Software installation time is excluded.
+
+## Current Python Osmium results
+
+The Python implementation installs through `pip install .` and uses no external Osmium executable. It reads PBF files directly, preserves complete ways and parent relations, and completes nested POI relations. Roads and nearby places are read directly into Python without intermediate XML files.
+
+Both exports reused the same cached central Italy regional file, with network access disabled in the client:
+
+| Area | Map export | Map XML size |
+| --- | ---: | ---: |
+| 10 km² | 161.65 s | 41.3 MB |
+| 1,000 km² | 173.88 s | 571.4 MB |
+
+These single-trial timings exclude downloading the regional file and subsequent validation. Python scans the entire regional file to select the rectangle, so the regional file's size matters even for small selections. Capture estimates now allow about three minutes for local map extraction, based on this region.
+
+Both exports have identical node, way, and relation IDs to the earlier CLI exports, and both pass way-reference validation through Python Osmium. The 10 km² export's 12,412 highway ways match the earlier road geometry exactly. Nearby results around the Colosseum and Via del Corso's 11 connected ways also matched when read from the new export. All 44 tests pass with the native tool absent from `PATH`, including cancellation, nested relations, offline reuse, and preserving previous files on failure.
+
+## Earlier native Osmium CLI results
+
+Both selections use [central Italy's extract](https://download.geofabrik.de/europe/italy/centro.html), containing data through `2026-09-20T20:22:06Z`. The regional PBF is 383,641,858 bytes (383.6 MB). Its initial standalone download took 13.59 seconds.
+
+The earlier CLI-backed application path also completed a fresh index download, regional download, and 10 km² map export in **15.26 seconds total**. Its request log contained exactly two GETs, both to Geofabrik. Subsequent operations reused the same regional file:
+
+| Area | Map export | Road loading | Map XML size | Highway ways |
+| --- | ---: | ---: | ---: | ---: |
+| 10 km² | 3.39 s | 3.64 s | 41.3 MB | 12,412 |
+| 1,000 km² | 3.66 s | 11.72 s | 571.4 MB | 163,195 |
+
+Map timings include selecting the region and writing the selected rectangle as XML. Road timings include extracting the rectangle, filtering highways, and decoding geometry and OSM node IDs into Python. The larger area reused the first area's regional download; it did not require downloading a larger file. Each operation creates temporary local files, which are removed afterward. Only the regional PBF and region index are retained.
+
+## Baseline results
+
+The 10 km² road query reached the 600-second deadline after repeated HTTP 504 overload responses and a socket timeout. The 1,000 km² road query also reached the 600-second deadline after repeated HTTP 504 responses. Both reached the third endpoint before their deadlines.
+
+Both map queries succeeded:
+
+| Area | Download, including retries | Original validation | XML size |
+| --- | ---: | ---: | ---: |
+| 10 km² | 7.84 s | 1.79 s | 52.4 MB |
+| 1,000 km² | 62.23 s | 113.68 s | 769.4 MB |
+
+The smaller map succeeded on its first attempt. The larger map succeeded on its second attempt, after an HTTP 504 response. The recorded 10.69 and 226.08 second benchmark totals also include an additional XML parse for statistics, so they should not be presented as application timings. The new exporter streams Osmium's output to disk and uses its complete-way extraction, avoiding the original full-tree Python validation.
+
+## Data checks
+
+Both Geofabrik map exports passed `osmium check-refs`, with zero missing nodes in ways. Their counts were:
+
+| Area | Nodes | Ways | Relations |
+| --- | ---: | ---: | ---: |
+| 10 km² | 177,525 | 32,787 | 3,219 |
+| 1,000 km² | 3,172,834 | 469,155 | 21,004 |
+
+All highway way IDs matched between the baseline map and Geofabrik at both sizes: 12,412 and 163,195 respectively. The snapshots are approximately 16 hours apart, and Geofabrik omits contributor metadata. Osmium also retains parent relations, so the files are not expected to have identical object counts or bytes. Distant relation members may remain unresolved; local ways are complete.
+
+A real nearby search returned the Colosseum relation and surrounding POIs from the local file. Resolving Via del Corso's connected street geometry took 2.69 seconds. Offline fixtures cover boundary-crossing ways, disconnected streets with the same name, relation centers, empty nearby results, cancellation, and preserving existing files when refresh or extraction fails.
+
+All 44 tests passed with `python -m unittest discover -s tests -v`. [Machine-readable measurements](osm-benchmark.json) retain the recorded timings, bounds, source dates, and attempt outcomes.
+
+## Reproduce the historical CLI extraction
+
+With the central Italy PBF downloaded as `centro.osm.pbf`:
+
+```sh
+osmium extract centro.osm.pbf -s complete_ways --set-bounds \
+ -b 12.473098695094054,41.875980496522295,12.511301304905947,41.904419503477705 \
+ -o rome-10.osm
+osmium extract centro.osm.pbf -s complete_ways --set-bounds \
+ -b 12.301186950940533,41.74800496522297,12.683213049059468,42.03239503477703 \
+ -o rome-1000.osm
+osmium check-refs rome-10.osm
+osmium check-refs rome-1000.osm
+```
diff --git a/pyproject.toml b/pyproject.toml
index 5ca7dc8..8b1b033 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,7 +8,7 @@ version = "0.1.0"
description = "Capture Street View photos, satellite imagery, and OpenStreetMap data."
readme = "README.md"
requires-python = ">=3.11"
-dependencies = ["Pillow>=10"]
+dependencies = ["Pillow>=10", "osmium>=4.3,<5"]
[project.scripts]
alephgeo = "aleph:main"
diff --git a/requirements.txt b/requirements.txt
index a40d05d..2a75295 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1 +1,2 @@
Pillow>=10
+osmium>=4.3,<5
diff --git a/src/capture.py b/src/capture.py
index 9f48cae..6bacf12 100644
--- a/src/capture.py
+++ b/src/capture.py
@@ -9,13 +9,11 @@ import zlib
from datetime import datetime, timezone
from io import BytesIO
from pathlib import Path
-from xml.etree import ElementTree as ET
from PIL import Image
from . import streetview, terrain
from .common import (
- OVERPASS,
MissingImagery,
atomic_path,
contained,
@@ -44,7 +42,7 @@ DEFAULT_OPTIONS = dict(
)
OSM_NOTES = {
- "map": "Native OSM XML with original tags, metadata and topology; coordinates are WGS84.",
+ "map": "OSM XML from Geofabrik with original tags and topology; coordinates are WGS84. Contributor names, IDs and changeset IDs are omitted by Geofabrik.",
"selection": "Bounding-box selection with complete ways. Relations retain their original member references, but members outside the extract are not downloaded recursively. Objects may extend outside the rectangle; crossings without inside nodes and enclosing polygons may be absent.",
"terrain": "Float32 heights in meters, EPSG:3857. Original compressed blocks retained without resampling. Full edge tiles extend beyond the rectangle. Tiles are checkpointed individually; terrain.tif is built after all terrain tiles are saved.",
"quality": "Terrain resolution, dates, accuracy and vertical reference vary by source. Higher zoom does not guarantee more detail.",
@@ -141,9 +139,10 @@ def estimate(run):
2026-09-19 17:26:41 UTC: 66 Street View photos in 36 s,
including panorama metadata. 2026-09-19 17:09:18 UTC:
- 1,020 satellite tiles in 374 s, then 22 s for OSM and 9 terrain tiles
- in 10 s. Rounded per-item rates retain this baseline without requiring
- the original capture folders. Planning and final exports are excluded.
+ 1,020 satellite tiles in 374 s and 9 terrain tiles in 10 s.
+ 2026-09-21: Python Osmium extracted 10 km² from the 384 MB central Italy
+ region in 162 s; allow about 3 minutes per map. Region size affects this cost.
+ Planning, initial regional downloads and final exports are excluded.
"""
counts = dict(streetview_photos=0, streetview_stops=0, satellite_tiles=0,
terrain_tiles=0, osm_maps=0)
@@ -166,10 +165,10 @@ def estimate(run):
for item in stage["results"]))
counts["terrain_tiles"] = remaining - counts["osm_maps"]
requests = (counts["streetview_photos"] + metadata_requests
- + counts["satellite_tiles"] + counts["terrain_tiles"] + counts["osm_maps"])
+ + counts["satellite_tiles"] + counts["terrain_tiles"])
download_seconds = (counts["streetview_photos"] * 0.55
+ counts["satellite_tiles"] * 0.37
- + counts["terrain_tiles"] * 1.1 + counts["osm_maps"] * 22)
+ + counts["terrain_tiles"] * 1.1 + counts["osm_maps"] * 180)
delay_seconds = max(0, requests - 1) * run["options"]["delay"]
return dict(counts, seconds=math.ceil(download_seconds + delay_seconds))
@@ -285,40 +284,15 @@ def capture_satellite(stage, folder, client, progress):
progress("Satellite", i + 1, total(stage))
-def validate_osm(data):
- root = ET.fromstring(data)
- remark = root.find("remark")
- if root.tag != "osm" or remark is not None:
- raise ValueError(f"Incomplete OSM response: {remark.text if remark is not None else 'missing osm root'}")
- objects = [element for element in root if element.tag in ("node", "way", "relation")]
- identities = {(element.tag, element.attrib["id"]) for element in objects}
- if len(identities) != len(objects):
- raise ValueError("Duplicate OSM objects in the response.")
- for element in objects:
- if element.tag == "node" and not {"lat", "lon"} <= element.attrib.keys():
- raise ValueError("Missing OSM node coordinates.")
- if any(("node", child.attrib["ref"]) not in identities for child in element.findall("nd")):
- raise ValueError("Incomplete OSM way geometry. Retry or use a smaller area.")
- # An area extract intentionally leaves distant relation members unresolved.
-
-
def capture_osm(stage, area, folder, client, progress):
failure = None
if not any(item["filename"] == "map.osm" for item in stage["results"]):
- progress("Downloading OSM map")
try:
- bbox = ",".join(map(str, area))
- # Complete local ways, without following whole routes or relation trees.
- data = client.overpass(
- f"[out:xml][timeout:180][maxsize:536870912];nwr({bbox});(._;node(w););out meta qt;"
- )
- progress("Checking OSM map")
- validate_osm(data)
- write_bytes(folder / "map.osm", data)
- stage["results"].append(dict(filename="map.osm", source_url=OVERPASS, captured_at=now()))
+ metadata = client.maps.export(area, folder / "map.osm", progress)
+ stage["results"].append(dict(filename="map.osm", captured_at=now(), **metadata))
yield
- except (OSError, ValueError, ET.ParseError) as error:
- # Keep terrain usable if Overpass fails; report the error after saving it.
+ except (OSError, ValueError) as error:
+ # Keep terrain usable if the map fails; report the error after saving it.
failure = error
saved = sum("x" in item for item in stage["results"])
count = stage["grid"]["rows"] * stage["grid"]["columns"]
diff --git a/src/common.py b/src/common.py
index 1759cd8..8c4cbe4 100644
--- a/src/common.py
+++ b/src/common.py
@@ -10,18 +10,14 @@ import tempfile
import time
from contextlib import contextmanager
from datetime import datetime, timezone
+from functools import cached_property
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, urlopen
-OVERPASS_SERVERS = (
- "https://overpass-api.de/api/interpreter",
- "https://overpass.private.coffee/api/interpreter",
- "https://maps.mail.ru/osm/tools/overpass/api/interpreter",
-)
-OVERPASS = OVERPASS_SERVERS[0]
-APP_AGENT = "Terrain downloader"
+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"
@@ -59,17 +55,26 @@ def contained(parent, name):
class Client:
- def __init__(self, delay=0, cancel=None, request_log=None):
+ def __init__(self, delay=0, cancel=None, request_log=None, *, cache_dir=DEFAULT_CACHE, refresh=False):
self.delay = delay
self.cancel = cancel
self.request_log = request_log
self.finished = float("-inf")
+ self.cache_dir = Path(cache_dir).expanduser()
+ self.refresh = refresh
+
+ @cached_property
+ def maps(self):
+ from .osm import Source
+
+ return Source(self)
def check_cancel(self):
if self.cancel:
self.cancel()
- def get(self, address, *, missing_ok=False, data=None, timeout=60, user_agent=BROWSER_AGENT):
+ def get(self, address, *, missing_ok=False, timeout=60, user_agent=BROWSER_AGENT,
+ destination=None, progress=None):
for attempt in range(4):
backoff = 2 ** (attempt - 1) if attempt else 0
until = time.monotonic() + max(backoff, self.delay - (time.monotonic() - self.finished))
@@ -78,17 +83,32 @@ class Client:
time.sleep(min(remaining, 0.2) if self.cancel else remaining)
self.check_cancel()
if self.request_log:
- self.request_log("POST" if data is not None else "GET", address, attempt)
+ self.request_log("GET", address, attempt)
try:
with urlopen(
- Request(address, data=data, headers={"User-Agent": user_agent}), timeout=timeout
+ Request(address, headers={"User-Agent": user_agent}), timeout=timeout
) as response:
- result = response.read()
+ if destination is None:
+ result = response.read()
+ else:
+ expected = int(response.headers.get("Content-Length", 0))
+ downloaded = 0
+ with atomic_path(destination) as temporary, temporary.open("wb") as stream:
+ while chunk := response.read(1024 * 1024):
+ self.check_cancel()
+ stream.write(chunk)
+ downloaded += len(chunk)
+ if progress:
+ progress(downloaded, expected or None)
+ if expected and downloaded != expected:
+ raise OSError("Incomplete download; retrying.")
+ self.check_cancel()
+ result = Path(destination)
self.check_cancel()
return result
except Exception as error:
if self.request_log:
- self.request_log("POST" if data is not None else "GET", address, attempt, error)
+ self.request_log("GET", address, attempt, error)
if isinstance(error, HTTPError):
error.close()
if missing_ok and error.code == 404:
@@ -103,46 +123,24 @@ class Client:
finally:
self.finished = time.monotonic()
- def overpass(self, query):
- # POST avoids long query URLs; allow the query budget plus server queue time.
- # Overpass rejects browser UAs.
- data = urlencode({"data": query}).encode()
- for endpoint in OVERPASS_SERVERS:
- try:
- return self.get(endpoint, data=data, timeout=240, user_agent=APP_AGENT)
- except OSError as error:
- cause = error.__cause__
- if isinstance(cause, HTTPError) and cause.code < 500 and cause.code != 429:
- raise
- failure = error
- raise failure
-
class CachedClient(Client):
- """Cache successful quick-query responses for one day, including OSM queries."""
+ """Cache successful quick-query responses for one day."""
def __init__(self, directory, *, refresh=False):
- super().__init__(delay=1)
- self.directory = Path(directory).expanduser()
- self.refresh = refresh
+ super().__init__(delay=1, cache_dir=directory, refresh=refresh)
self.hits = 0
self.misses = 0
def get(self, address, **kwargs):
- payload = kwargs.get("data") or b""
- key = hashlib.sha256(address.encode() + b"\0" + payload).hexdigest()
- path = self.directory / key
+ if kwargs.get("destination") is not None:
+ return super().get(address, **kwargs)
+ key = hashlib.sha256(address.encode()).hexdigest()
+ path = self.cache_dir / key
if not self.refresh and path.is_file() and time.time() - path.stat().st_mtime < 86400:
self.hits += 1
return path.read_bytes()
result = super().get(address, **kwargs)
- # Do not retain Overpass's HTTP-200 timeout/error responses.
- if payload:
- try:
- if json.loads(result).get("remark"):
- return result
- except (ValueError, AttributeError):
- return result
write_bytes(path, result)
self.misses += 1
return result
diff --git a/src/dashboard_osm.py b/src/dashboard_osm.py
index 5c2a803..48d67b0 100644
--- a/src/dashboard_osm.py
+++ b/src/dashboard_osm.py
@@ -3,10 +3,9 @@
import math
import re
from collections import defaultdict
-from itertools import pairwise
-from xml.etree import ElementTree as ET
-from .geo import feature
+from .geo import feature, ring_contains, signed_area
+from .osm import objects
DISPLAY_TAGS = {"building", "landuse", "natural", "water", "highway", "waterway"}
TAGS = DISPLAY_TAGS | {"name", "height", "building:levels", "min_height", "type"}
@@ -68,33 +67,21 @@ def properties(tags, polygon):
def read_osm(path):
nodes, ways, relations = {}, {}, []
- try:
- with path.open("rb") as stream:
- parser = ET.iterparse(stream, events=("start", "end"))
- _, root = next(parser)
- if root.tag != "osm":
- raise ValueError("Saved OSM data contains no osm root.")
- for event, element in parser:
- if event != "end" or element.tag not in ("node", "way", "relation"):
- continue
- identity = int(element.attrib["id"])
- if element.tag == "node":
- nodes[identity] = [float(element.attrib["lon"]), float(element.attrib["lat"])]
- else:
- tags = {tag.attrib["k"]: tag.attrib["v"] for tag in element.findall("tag")}
- area = is_area(tags)
- tags = {key: value for key, value in tags.items() if key in TAGS}
- if element.tag == "way":
- refs = [int(nd.attrib["ref"]) for nd in element.findall("nd")]
- ways[identity] = refs, tags, area
- elif tags.get("type") in ("multipolygon", "boundary", "route", "waterway"):
- members = [(int(m.attrib["ref"]), m.get("role", ""))
- for m in element.findall("member") if m.get("type") == "way"]
- relations.append((tags, members))
- # Keep compact coordinates/references, never the complete XML tree.
- root.clear()
- except (ET.ParseError, StopIteration) as error:
- raise ValueError("Saved OSM data contains invalid XML.") from error
+ for element in objects(path):
+ identity = int(element.attrib["id"])
+ if element.tag == "node":
+ nodes[identity] = [float(element.attrib["lon"]), float(element.attrib["lat"])]
+ else:
+ tags = {tag.attrib["k"]: tag.attrib["v"] for tag in element.findall("tag")}
+ area = is_area(tags)
+ tags = {key: value for key, value in tags.items() if key in TAGS}
+ if element.tag == "way":
+ refs = [int(nd.attrib["ref"]) for nd in element.findall("nd")]
+ ways[identity] = refs, tags, area
+ elif tags.get("type") in ("multipolygon", "boundary", "route", "waterway"):
+ members = [(int(m.attrib["ref"]), m.get("role", ""))
+ for m in element.findall("member") if m.get("type") == "way"]
+ relations.append((tags, members))
return nodes, ways, relations
@@ -119,19 +106,6 @@ def rings(identities, ways, nodes):
yield [nodes[n] for n in ring], used
-def signed_area(ring):
- return sum(a[0] * b[1] - b[0] * a[1] for a, b in pairwise(ring)) / 2
-
-
-def contains(ring, point):
- x, y = point
- inside = False
- for (ax, ay), (bx, by) in pairwise(ring):
- if (ay > y) != (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax:
- inside = not inside
- return inside
-
-
def display_osm(path):
nodes, ways, relations = read_osm(path)
features, consumed = [], set()
@@ -159,7 +133,7 @@ def display_osm(path):
polygons.append([ring])
used.update(identities)
for ring, identities in rings([ref for ref, role in members if role == "inner"], ways, nodes):
- owners = [p for p in polygons if contains(p[0], ring[0])]
+ owners = [p for p in polygons if ring_contains(p[0], ring[0])]
if owners:
if signed_area(ring) > 0:
ring.reverse()
diff --git a/src/geo.py b/src/geo.py
index 6ccb9a7..2c7cc6d 100644
--- a/src/geo.py
+++ b/src/geo.py
@@ -14,6 +14,25 @@ def clamp(value, low, high):
return max(low, min(high, value))
+def ring_contains(ring, point):
+ x, y = point
+ inside = False
+ for (ax, ay), (bx, by) in pairwise(ring):
+ if (ay > y) != (by > y) and x < ax + (y - ay) * (bx - ax) / (by - ay):
+ inside = not inside
+ return inside
+
+
+def signed_area(ring):
+ return sum(a[0] * b[1] - b[0] * a[1] for a, b in pairwise(ring)) / 2
+
+
+def extent(points):
+ """Bounding box in south/west/north/east order, including degenerate boxes."""
+ latitudes, longitudes = zip(*points)
+ return min(latitudes), min(longitudes), max(latitudes), max(longitudes)
+
+
def distance(a, b):
lat1, lat2 = map(math.radians, (a[0], b[0]))
delta = math.radians(b[1] - a[1])
diff --git a/src/osm.py b/src/osm.py
new file mode 100644
index 0000000..5808027
--- /dev/null
+++ b/src/osm.py
@@ -0,0 +1,272 @@
+"""Download Geofabrik regions and select local OSM data with Osmium."""
+
+import hashlib
+import json
+from collections import defaultdict
+from contextlib import contextmanager, nullcontext
+from itertools import pairwise
+from xml.etree import ElementTree as ET
+
+import osmium
+
+from .common import APP_AGENT, RequestError, atomic_path, write_bytes
+from .geo import clip, extent, ring_contains, signed_area
+
+INDEX = "https://download.geofabrik.de/index-v1.json"
+POI_KEYS = ("amenity", "tourism", "shop", "leisure", "historic", "office")
+
+
+def polygons(geometry):
+ return [geometry["coordinates"]] if geometry["type"] == "Polygon" else geometry["coordinates"]
+
+
+def covers(geometry, area):
+ """Require the whole rectangle, including its interior, to lie in the region."""
+ south, west, north, east = area
+ shapes = polygons(geometry)
+ for point in ((west, south), (west, north), (east, south), (east, north)):
+ if not any(ring_contains(polygon[0], point) and not any(ring_contains(hole, point) for hole in polygon[1:])
+ for polygon in shapes):
+ return False
+ for polygon in shapes:
+ for ring in polygon:
+ for a, b in pairwise(ring):
+ segment = clip((a[1], a[0]), (b[1], b[0]), area)
+ if segment:
+ lat = (segment[0][0] + segment[1][0]) / 2
+ lon = (segment[0][1] + segment[1][1]) / 2
+ if south < lat < north and west < lon < east:
+ return False
+ return True
+
+
+def region_size(feature):
+ return sum(abs(signed_area(polygon[0])) for polygon in polygons(feature["geometry"]))
+
+
+def objects(path, cancel=lambda: None):
+ """Stream complete OSM elements without retaining the XML tree."""
+ try:
+ with path.open("rb") as stream:
+ parser = ET.iterparse(stream, events=("start", "end"))
+ _, root = next(parser)
+ if root.tag != "osm":
+ raise ValueError("OSM file contains no osm root.")
+ for index, (event, obj) in enumerate(parser):
+ if index % 65536 == 0:
+ cancel()
+ if event == "end" and obj.tag in ("node", "way", "relation"):
+ yield obj
+ root.clear()
+ except (ET.ParseError, StopIteration) as error:
+ raise ValueError("OSM file contains invalid XML.") from error
+
+
+def read_data(objects, *, centers=False):
+ """Copy selected Osmium objects, retaining node IDs for road topology."""
+ nodes, items, boxes, relations = {}, [], {}, []
+ kinds = {"n": "node", "w": "way", "r": "relation"}
+ for obj in objects:
+ identity, kind = obj.id, kinds[obj.type_str()]
+ if kind == "node":
+ lat, lon = obj.lat, obj.lon
+ nodes[identity] = (lat, lon)
+ if not centers:
+ continue
+ boxes[("node", identity)] = (lat, lon, lat, lon)
+ tags = dict(obj.tags)
+ item = dict(type=kind, id=identity, tags=tags)
+ if kind == "way":
+ refs = [n.ref for n in obj.nodes]
+ if any(ref not in nodes for ref in refs):
+ raise OSError("The Geofabrik extract contains incomplete way geometry.")
+ points = [nodes[ref] for ref in refs]
+ item.update(nodes=refs, points=points)
+ if centers and points:
+ boxes[("way", identity)] = extent(points)
+ elif kind == "relation":
+ item["members"] = [(kinds[m.type], m.ref) for m in obj.members]
+ relations.append(item)
+ if tags or kind != "node":
+ items.append(item)
+ pending = relations
+ while pending:
+ unresolved = []
+ for item in pending:
+ members = [boxes[ref] for ref in item["members"] if ref in boxes]
+ if not members or len(members) != len(item["members"]):
+ unresolved.append(item)
+ continue
+ boxes[("relation", item["id"])] = (min(b[0] for b in members), min(b[1] for b in members),
+ max(b[2] for b in members), max(b[3] for b in members))
+ if len(unresolved) == len(pending):
+ break
+ pending = unresolved
+ for item in items:
+ box = boxes.get((item["type"], item["id"]))
+ if box:
+ item["center"] = ((box[0] + box[2]) / 2, (box[1] + box[3]) / 2)
+ return items
+
+
+class Source:
+ def __init__(self, client):
+ self.client = client
+ self.directory = client.cache_dir / "geofabrik"
+ self.index = None
+ self.regions = {}
+
+ @contextmanager
+ def processing(self):
+ self.client.check_cancel()
+ try:
+ yield
+ except RuntimeError as error:
+ raise OSError(f"Osmium failed: {error}") from error
+ self.client.check_cancel()
+
+ def scan(self, source, *filters, entities=osmium.osm.OBJECT):
+ with self.processing(), osmium.io.Reader(source, entities) as reader:
+ for index, obj in enumerate(osmium.OsmFileIterator(reader, *filters)):
+ if index % 8192 == 0:
+ self.client.check_cancel()
+ yield obj
+
+ def region(self, area, progress):
+ if self.index is None:
+ path = self.directory / "index.json"
+ refresh = self.client.refresh or not path.is_file()
+ if refresh:
+ progress("Finding Geofabrik region")
+ data = self.client.get(INDEX, user_agent=APP_AGENT)
+ else:
+ data = path.read_bytes()
+ index = json.loads(data)
+ if not isinstance(index.get("features"), list):
+ raise OSError("Geofabrik returned an invalid region index.")
+ if refresh:
+ write_bytes(path, data)
+ self.index = sorted(index["features"], key=region_size)
+ feature = next((f for f in self.index if f["properties"].get("urls", {}).get("pbf")
+ and covers(f["geometry"], area)), None)
+ if feature is None:
+ raise OSError("No Geofabrik region covers this rectangle. Select a smaller area.")
+ props = feature["properties"]
+ url = props["urls"]["pbf"]
+ if url not in self.regions:
+ path = self.directory / (hashlib.sha256(url.encode()).hexdigest()[:16] + ".osm.pbf")
+ refresh = self.client.refresh or not path.is_file()
+ with (atomic_path(path) if refresh else nullcontext(path)) as local:
+ if refresh:
+ label = f"Downloading Geofabrik {props['name']} (regional file)"
+ progress(label)
+ self.client.get(url, destination=local, timeout=180, user_agent=APP_AGENT,
+ progress=lambda done, total: progress(label, done, total))
+ with self.processing(), osmium.io.Reader(osmium.io.File(local, "pbf"), osmium.osm.NOTHING) as reader:
+ stamp = reader.header().get("osmosis_replication_timestamp")
+ self.regions[url] = path, dict(source_url=url, region=props["name"], osm_data_at=stamp or None)
+ return self.regions[url]
+
+ def select(self, source, area):
+ """Select the rectangle, complete its ways, and retain parent relations."""
+ south, west, north, east = area
+ box = osmium.osm.Box(west, south, east, north)
+ spatial, selected = osmium.IdTracker(), osmium.IdTracker()
+ parents, pending = defaultdict(list), []
+ for obj in self.scan(source):
+ if obj.is_node():
+ if box.contains(obj.location):
+ spatial.add_node(obj.id)
+ selected.add_node(obj.id)
+ elif obj.is_way():
+ if spatial.contains_any_references(obj):
+ spatial.add_way(obj.id)
+ selected.add_way(obj.id)
+ selected.add_references(obj)
+ else:
+ if spatial.contains_any_references(obj):
+ pending.append(obj.id)
+ for member in obj.members:
+ if member.type == "r":
+ parents[member.ref].append(obj.id)
+ while pending:
+ identity = pending.pop()
+ if identity not in selected.relation_ids():
+ selected.add_relation(identity)
+ pending.extend(parents[identity])
+ return selected
+
+ def extract(self, source, area, output):
+ selected = self.select(source, area)
+ south, west, north, east = area
+ header = osmium.io.Header()
+ header.add_box(osmium.osm.Box(west, south, east, north))
+ with self.processing(), osmium.SimpleWriter(osmium.io.File(output, "osm"), header=header, overwrite=True) as writer:
+ for obj in self.scan(source, selected.id_filter()):
+ writer.add(obj)
+
+ def export(self, area, output, progress):
+ source, metadata = self.region(area, progress)
+ progress("Extracting OSM map")
+ with atomic_path(output) as temporary:
+ self.extract(source, area, temporary)
+ return metadata
+
+ def data(self, area, *, poi=False, progress=lambda *args: None):
+ source, metadata = self.region(area, progress)
+ progress("Reading nearby places" if poi else "Reading roads")
+ local = self.select(source, area)
+ selected = osmium.IdTracker()
+ entities = osmium.osm.OBJECT if poi else osmium.osm.WAY
+ keys = POI_KEYS if poi else ("highway",)
+ add = {"n": selected.add_node, "w": selected.add_way, "r": selected.add_relation}
+ for obj in self.scan(source, local.id_filter(), osmium.filter.KeyFilter(*keys), entities=entities):
+ add[obj.type_str()](obj.id)
+ selected.add_references(obj)
+ if poi and len(selected.relation_ids()):
+ # Complete only selected POIs, including nested relations outside the rectangle.
+ with self.processing():
+ while True:
+ self.client.check_cancel()
+ count = len(selected.relation_ids())
+ selected.complete_backward_references(source, relation_depth=1)
+ if len(selected.relation_ids()) == count:
+ break
+ return read_data(self.scan(source, selected.id_filter()), centers=poi), metadata
+
+ def street(self, place, progress=lambda *args: None):
+ identity = int(place["id"].split("/")[1])
+ lat, lon = place["lat"], place["lon"]
+ area = (lat - 1e-6, lon - 1e-6, lat + 1e-6, lon + 1e-6)
+ while True:
+ source, _ = self.region(area, progress)
+ progress("Reading named street")
+ tags = next((dict(w.tags) for w in self.scan(source, osmium.filter.IdFilter([identity]),
+ entities=osmium.osm.WAY)), {})
+ if not tags.get("highway") or not tags.get("name"):
+ raise RequestError("place_not_found", "The selected street is absent or unnamed in the Geofabrik snapshot.")
+ name = tags["name"]
+ selected = osmium.IdTracker()
+ for way in self.scan(source, osmium.filter.TagFilter(("name", name)), osmium.filter.KeyFilter("highway"),
+ entities=osmium.osm.WAY):
+ selected.add_way(way.id)
+ selected.add_references(way)
+ ways = {w["id"]: w for w in read_data(self.scan(source, selected.id_filter()))}
+ by_node = defaultdict(list)
+ for way in ways.values():
+ for node in way["nodes"]:
+ by_node[node].append(way["id"])
+ connected, pending = set(), [identity]
+ while pending:
+ current = pending.pop()
+ if current in connected:
+ continue
+ connected.add(current)
+ for node in ways[current]["nodes"]:
+ pending.extend(by_node.pop(node, ()))
+ selected = [ways[i] for i in sorted(connected)]
+ expanded = extent([area[:2], area[2:]] + [p for w in selected for p in w["points"]])
+ next_source, _ = self.region(expanded, progress)
+ if next_source == source:
+ return name, selected
+ area = expanded
diff --git a/src/places.py b/src/places.py
index 154521a..d4673b6 100644
--- a/src/places.py
+++ b/src/places.py
@@ -6,9 +6,9 @@ from urllib.parse import urlsplit
from .common import RequestError, url
from .geo import RADIUS, bounds, distance
+from .osm import POI_KEYS
GEOCODER = "https://photon.komoot.io"
-POI_KEYS = ("amenity", "tourism", "shop", "leisure", "historic", "office")
def number(value, name, low, high):
@@ -43,16 +43,6 @@ def around(center, size):
return bounds((lat - dy, lon - dx, lat + dy, lon + dx), minimum=0)
-def osm_data(client, query):
- try:
- data = json.loads(client.overpass(query))
- except (OSError, ValueError) as error:
- raise RequestError("provider_unavailable", f"Overpass request failed: {error}") from error
- if data.get("remark") or not isinstance(data.get("elements"), list):
- raise RequestError("provider_unavailable", "Overpass returned incomplete data; retry later.")
- return data
-
-
def geocode(client, *, query=None, at=None, limit=5, street=False, endpoint=GEOCODER):
number(limit, "limit", 1, 50)
endpoint = endpoint.rstrip("/")
@@ -112,27 +102,29 @@ def choose(client, query, *, match=None, street=False, endpoint=GEOCODER):
raise RequestError("ambiguous_place", "Choose a returned place with --match TYPE/ID.", candidates=candidates)
-def nearby(client, at, *, radius=100, limit=10):
+def 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)
- selection = "".join(f'nwr(around:{radius},{lat},{lon})["{key}"];' for key in POI_KEYS)
- data = osm_data(client, f"[out:json][timeout:25];({selection});out center tags;")
+ items, metadata = client.maps.data(around((lat, lon), radius * 2), poi=True, progress=progress)
results = []
- for item in data["elements"]:
- tags = item.get("tags", {})
- center = item if item["type"] == "node" else item.get("center")
- if not center:
+ for item in items:
+ tags = item["tags"]
+ if not any(key in tags for key in POI_KEYS):
+ continue
+ center = item.get("center")
+ if center is None:
continue
- separation = distance(at, point((center["lat"], center["lon"])))
+ separation = distance(at, center)
# Ways/relations are represented by their bounding-box center, not an entrance.
if separation > radius:
continue
identity = f"{item['type']}/{item['id']}"
categories = [f"{key}:{tags[key]}" for key in POI_KEYS if key in tags]
results.append(dict(id=identity, name=tags.get("name"), categories=categories,
- lat=center["lat"], lon=center["lon"], distance_m=round(separation, 2),
+ lat=center[0], lon=center[1], distance_m=round(separation, 2),
location_type="point" if item["type"] == "node" else "bbox_center",
- source="OpenStreetMap", source_url=f"https://www.openstreetmap.org/{identity}"))
+ source="OpenStreetMap", source_url=f"https://www.openstreetmap.org/{identity}",
+ osm_data_at=metadata["osm_data_at"]))
results.sort(key=lambda item: (item["distance_m"], item["id"]))
return results[:limit]
diff --git a/src/quick.py b/src/quick.py
index 6cd669e..1297006 100644
--- a/src/quick.py
+++ b/src/quick.py
@@ -5,7 +5,7 @@ from pathlib import Path
from . import capture, places, routes, streetview
from .common import MissingImagery, RequestError, atomic_path, now, url, write_json
-from .geo import bearing, bounds, coordinate, distance, grid, tiles
+from .geo import bearing, bounds, coordinate, distance, extent, grid, tiles
def coverage(client, area, progress):
@@ -48,17 +48,14 @@ def street_photos(client, output, progress, *, at=None, place=None, pano_id=None
gaps = []
if street is not None:
selected_place = places.choose(client, street, match=match, street=True, endpoint=endpoint)
- selected_route = routes.resolve(client, selected_place, route=route, reverse=reverse)
+ selected_route = routes.resolve(client, selected_place, route=route, reverse=reverse, progress=progress)
points = selected_route["points"]
- south, north = min(p[0] for p in points), max(p[0] for p in points)
- west, east = min(p[1] for p in points), max(p[1] for p in 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)
- identities = ",".join(map(str, selected_route["way_ids"]))
- data = places.osm_data(client, f'[out:json][timeout:25];way(id:{identities})->.street;'
- 'way(around.street:40)["highway"];out body geom;')
- context = streetview.roads(data, area, "all")
+ ways, _ = client.maps.data(area, progress=progress)
+ context = streetview.roads(ways, area, "all")
samples, gaps = routes.match_views(views, selected_route, context, stops)
elif pano_id:
if not streetview.PANO_ID.fullmatch(pano_id):
diff --git a/src/routes.py b/src/routes.py
index d26c894..376d429 100644
--- a/src/routes.py
+++ b/src/routes.py
@@ -1,10 +1,9 @@
"""Join named OSM ways into ordered, unbranched street routes."""
-import json
from collections import defaultdict
from itertools import pairwise
-from . import places, streetview
+from . import streetview
from .common import RequestError
from .geo import Line, RoadIndex, distance
@@ -13,11 +12,8 @@ def chains(ways):
"""Split at real OSM junctions; never join roads merely because they cross."""
points, edges, neighbors = {}, {}, defaultdict(set)
for way in sorted(ways, key=lambda item: item["id"]):
- nodes, geometry = way.get("nodes", []), way.get("geometry", [])
- if len(nodes) != len(geometry) or len(nodes) < 2:
- raise RequestError("provider_unavailable", "Incomplete street geometry.")
- for node, position in zip(nodes, geometry):
- points[node] = places.point((position["lat"], position["lon"]))
+ nodes = way["nodes"]
+ points.update(zip(nodes, way["points"]))
for a, b in pairwise(nodes):
if a == b or distance(points[a], points[b]) < 0.01:
continue
@@ -65,23 +61,12 @@ def describe(route, index):
closed=route["points"][0] == route["points"][-1])
-def resolve(client, place, *, route=None, reverse=False):
+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.")
- identity = int(place["id"].split("/")[1])
- seed = places.osm_data(client, f"[out:json][timeout:25];way({identity});out tags;")["elements"]
- if not seed or not seed[0].get("tags", {}).get("highway"):
- raise RequestError("place_not_found", "The selected OSM object is not a street.")
- name = seed[0]["tags"].get("name")
- if not name:
- raise RequestError("place_not_found", "The selected street has no mapped name.")
- # Follow all connected same-name sections, rather than cutting at a geocoder bbox.
- data = places.osm_data(client, f'[out:json][timeout:25][maxsize:33554432];way({identity});'
- f'complete {{ node(w); way(bn)["highway"]["name"={json.dumps(name)}]; }};'
- 'out body geom;')
- ways = [way for way in data["elements"] if way["type"] == "way"
- and way.get("tags", {}).get("area") != "yes"
- and not streetview.EXCLUDED.fullmatch(way.get("tags", {}).get("highway", ""))]
+ name, ways = client.maps.street(place, progress)
+ ways = [way for way in ways if way["tags"].get("area") != "yes"
+ and not streetview.EXCLUDED.fullmatch(way["tags"]["highway"])]
options = chains(ways)
if not options:
raise RequestError("place_not_found", "No usable street geometry was found.")
diff --git a/src/streetview.py b/src/streetview.py
index 9131a79..4edc4c2 100644
--- a/src/streetview.py
+++ b/src/streetview.py
@@ -104,31 +104,17 @@ def image_url(pano_id, heading, fov, pitch=0):
)
-def roads(data, area, depth):
- if data.get("remark") or not isinstance(data.get("elements"), list):
- raise ValueError(f"Incomplete Overpass response: {data.get('remark', 'missing elements')}")
- parts, seen_ways, seen_edges = [], set(), set()
- for way in sorted(data["elements"], key=lambda element: element["id"]):
- tags = way.get("tags", {})
+def roads(ways, area, depth):
+ parts, seen_edges = [], set()
+ for way in sorted(ways, key=lambda way: way["id"]):
+ tags = way["tags"]
highway = tags.get("highway", "")
- if (
- way["type"] != "way"
- or not highway
- or tags.get("area") == "yes"
- or EXCLUDED.fullmatch(highway)
- ):
+ if not highway or tags.get("area") == "yes" or EXCLUDED.fullmatch(highway):
continue
- if way["id"] in seen_ways or (DEPTHS[depth] and not DEPTHS[depth].fullmatch(highway)):
+ if DEPTHS[depth] and not DEPTHS[depth].fullmatch(highway):
continue
- seen_ways.add(way["id"])
- geometry = way.get("geometry", [])
- if len(geometry) < 2 or any(
- p is None or "lat" not in p or "lon" not in p for p in geometry
- ):
- raise ValueError("Overpass returned incomplete road geometry.")
- points = [(p["lat"], p["lon"]) for p in geometry]
+ points, nodes = way["points"], way["nodes"]
layer, run, part = str(tags.get("layer", "0")), [], 0
- nodes = way.get("nodes", [f"{p[0]:.7f},{p[1]:.7f}" for p in points])
def flush():
nonlocal run, part
@@ -150,7 +136,7 @@ def roads(data, area, depth):
if distance(a, b) <= 0.01:
continue
segment = clip(a, b, area)
- edge = layer, tuple(sorted((str(nodes[i]), str(nodes[i + 1]))))
+ edge = layer, tuple(sorted((nodes[i], nodes[i + 1])))
if segment is None or edge in seen_edges:
flush()
continue
@@ -247,13 +233,8 @@ def select_stops(candidates, spacing):
def plan(client, area, options, progress, *, allow_empty=False):
progress("Finding roads")
- bbox = ",".join(map(str, area))
- data = json.loads(
- client.overpass(
- f'[out:json][timeout:25][maxsize:1073741824];way["highway"]({bbox});out body geom;'
- )
- )
- parts = roads(data, area, options["depth"])
+ ways, metadata = client.maps.data(area, progress=progress)
+ 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)
@@ -305,7 +286,8 @@ def plan(client, area, options, progress, *, allow_empty=False):
results=[],
coverage=dict(available=len(found), excluded=excluded, gaps=gaps, spacing=spacing),
length=sum(line.length for line in lines),
- osm_data_at=data.get("osm3s", {}).get("timestamp_osm_base"),
+ osm_data_at=metadata["osm_data_at"],
+ osm_source_url=metadata["source_url"],
)
diff --git a/tests/test_capture.py b/tests/test_capture.py
index 395c598..0a8ac0e 100644
--- a/tests/test_capture.py
+++ b/tests/test_capture.py
@@ -36,7 +36,7 @@ class CaptureRecoveryTests(unittest.TestCase):
self.progress = Mock()
self.client = Mock(spec=Client)
self.client.get.side_effect = AssertionError("Unexpected image download")
- self.client.overpass.side_effect = AssertionError("Unexpected OSM download")
+ self.client.maps.export.side_effect = AssertionError("Unexpected OSM download")
def test_spacing_and_delay_require_valid_numbers_without_workload_caps(self):
for step in (0.5, 2000):
@@ -207,8 +207,8 @@ class CaptureRecoveryTests(unittest.TestCase):
def test_osm_failure_still_saves_terrain_and_resume_fetches_only_map(self):
run = capture.plan(self.client, [1, 1, 2, 2],
dict(include=["osm"], terrain_zoom=1), self.progress)
- failure = OSError("Overpass unavailable")
- self.client.overpass.side_effect = failure
+ failure = OSError("Geofabrik unavailable")
+ self.client.maps.export.side_effect = failure
self.client.get.side_effect = [terrain_bytes(1, 0, 1)]
with self.assertRaises(OSError) as raised:
capture.download(run, self.folder, self.client, self.progress)
@@ -221,7 +221,11 @@ class CaptureRecoveryTests(unittest.TestCase):
self.assertFalse((self.folder / "map.osm").exists())
osm = b'<osm version="0.6"><node id="1" lat="1" lon="1"/><way id="2"><nd ref="1"/></way></osm>'
- self.client.overpass.side_effect = [osm]
+ def export(area, path, progress):
+ path.write_bytes(osm)
+ return dict(source_url="https://download.geofabrik.de/test.osm.pbf", osm_data_at="2026-09-20T20:00:00Z")
+
+ self.client.maps.export.side_effect = export
self.client.get.reset_mock()
self.client.get.side_effect = AssertionError("Completed terrain must not be downloaded again")
capture.download(saved, self.folder, self.client, self.progress)
@@ -231,14 +235,3 @@ class CaptureRecoveryTests(unittest.TestCase):
completed = capture.load(self.folder)
self.assertEqual(completed["state"], "complete")
self.assertEqual(len(completed["stages"][0]["results"]), 2)
-
- def test_osm_rejects_incomplete_ways_but_allows_distant_relation_members(self):
- invalid = (
- b'<osm><remark>runtime error: timeout</remark></osm>',
- b'<osm><way id="1"><nd ref="99"/></way></osm>',
- b'<osm><node id="1" lat="0" lon="0"/><node id="1" lat="0" lon="0"/></osm>',
- )
- for data in invalid:
- with self.subTest(data=data), self.assertRaises(ValueError):
- capture.validate_osm(data)
- capture.validate_osm(b'<osm><relation id="1"><member type="way" ref="99" role="outer"/></relation></osm>')
diff --git a/tests/test_cli.py b/tests/test_cli.py
index e63fca6..b04f6a8 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
import aleph
from src.common import Client
+from src.osm import Source
from tests.fixtures import image_bytes
@@ -19,7 +20,7 @@ class ConfirmationTests(unittest.TestCase):
with (
patch("builtins.input", side_effect=[answer]),
patch.object(Client, "get", side_effect=AssertionError("Unexpected download")) as get,
- patch.object(Client, "overpass", side_effect=AssertionError("Unexpected OSM request")) as overpass,
+ patch.object(Source, "region", side_effect=AssertionError("Unexpected OSM request")) as region,
redirect_stdout(StringIO()) as stdout,
redirect_stderr(StringIO()) as stderr,
):
@@ -30,7 +31,7 @@ class ConfirmationTests(unittest.TestCase):
self.assertEqual(stdout.getvalue(), "")
self.assertFalse(output.exists())
get.assert_not_called()
- overpass.assert_not_called()
+ region.assert_not_called()
class CaptureCommandTests(unittest.TestCase):
diff --git a/tests/test_common.py b/tests/test_common.py
index 8a274d6..dcff97a 100644
--- a/tests/test_common.py
+++ b/tests/test_common.py
@@ -91,18 +91,25 @@ class NetworkTests(unittest.TestCase):
self.assertEqual(self.urlopen.call_count, 1)
self.assertLessEqual(self.elapsed, 0.2)
- def test_overpass_falls_back_for_service_errors_but_not_bad_queries(self):
- for code in (429, 503, 400):
- with self.subTest(code=code):
- error = OSError("Overpass failed")
- error.__cause__ = HTTPError("https://example.test", code, "failed", {}, None)
- client = common.Client()
- with patch.object(client, "get", side_effect=[error, b"osm"]) as get:
- if code == 400:
- with self.assertRaises(OSError) as raised:
- client.overpass("query")
- self.assertIs(raised.exception, error)
- self.assertEqual(get.call_count, 1)
- else:
- self.assertEqual(client.overpass("query"), b"osm")
- self.assertEqual([call.args[0] for call in get.call_args_list], list(common.OVERPASS_SERVERS[:2]))
+ def test_streamed_download_retries_truncation_and_preserves_old_file_on_cancellation(self):
+ def response(data):
+ value = BytesIO(data)
+ value.headers = {"Content-Length": "8"}
+ return value
+
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "region.pbf"
+ path.write_bytes(b"previous")
+ self.urlopen.side_effect = [response(b"short"), response(b"complete")]
+ common.Client().get("https://example.test/region.pbf", destination=path)
+ self.assertEqual(path.read_bytes(), b"complete")
+ self.assertEqual(self.urlopen.call_count, 2)
+ self.urlopen.side_effect = [response(b"replaced")]
+
+ def cancel(*args):
+ raise KeyboardInterrupt()
+
+ with self.assertRaises(KeyboardInterrupt):
+ common.Client().get("https://example.test/region.pbf", destination=path, progress=cancel)
+ self.assertEqual(path.read_bytes(), b"complete")
+ self.assertEqual(list(path.parent.iterdir()), [path])
diff --git a/tests/test_dashboard_osm.py b/tests/test_dashboard_osm.py
index 46ea99c..5c8f0f9 100644
--- a/tests/test_dashboard_osm.py
+++ b/tests/test_dashboard_osm.py
@@ -7,7 +7,8 @@ from types import SimpleNamespace
from xml.etree import ElementTree as ET
from src.dashboard import Catalog, Handler
-from src.dashboard_osm import display_osm, signed_area
+from src.dashboard_osm import display_osm
+from src.geo import signed_area
class DashboardOSMTests(unittest.TestCase):
diff --git a/tests/test_osm.py b/tests/test_osm.py
new file mode 100644
index 0000000..df5490d
--- /dev/null
+++ b/tests/test_osm.py
@@ -0,0 +1,120 @@
+import hashlib
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+from xml.etree import ElementTree as ET
+
+import osmium
+
+from src.common import Client
+from src.osm import Source, covers
+
+
+def polygon(ring, *holes):
+ return dict(type="Polygon", coordinates=[ring, *holes])
+
+
+class RegionTests(unittest.TestCase):
+ def test_region_must_cover_rectangle_interior_and_avoid_holes(self):
+ outer = [[-2, -2], [2, -2], [2, 2], [-2, 2], [-2, -2]]
+ hole = [[-.1, -.1], [.1, -.1], [.1, .1], [-.1, .1], [-.1, -.1]]
+ self.assertTrue(covers(polygon(outer), (-1, -1, 1, 1)))
+ self.assertFalse(covers(polygon(outer, hole), (-1, -1, 1, 1)))
+ notch = [[-2, -2], [2, -2], [2, 2], [.1, 2], [.1, 0], [-.1, 0], [-.1, 2], [-2, 2], [-2, -2]]
+ self.assertFalse(covers(polygon(notch), (-1, -1, 1, 1)))
+ self.assertFalse(covers(polygon(outer), (-3, -1, 1, 1)))
+
+
+class ExtractTests(unittest.TestCase):
+ def setUp(self):
+ self.folder = Path(self.enterContext(tempfile.TemporaryDirectory()))
+ self.client = Client(cache_dir=self.folder)
+ self.client.get = Mock(side_effect=AssertionError("Cached extracts must work offline"))
+ self.source = self.client.maps
+ self.source.directory.mkdir()
+ url = "https://download.geofabrik.de/test-latest.osm.pbf"
+ self.path = self.source.directory / (hashlib.sha256(url.encode()).hexdigest()[:16] + ".osm.pbf")
+ index = dict(features=[dict(type="Feature", properties=dict(name="Test region", urls=dict(pbf=url)),
+ geometry=polygon([[-2, -2], [2, -2], [2, 2], [-2, 2], [-2, -2]]))])
+ (self.source.directory / "index.json").write_text(json.dumps(index))
+ xml = self.folder / "fixture.osm"
+ xml.write_text('''<osm version="0.6">
+ <node id="1" lat="0" lon="0"><tag k="amenity" v="cafe"/></node>
+ <node id="2" lat="0" lon="0.001"/>
+ <node id="3" lat="0" lon="0.002"/>
+ <node id="4" lat="0.01" lon="0.01"/>
+ <node id="5" lat="0.01" lon="0.011"/>
+ <node id="6" lat="0" lon="-0.003"/>
+ <way id="10"><nd ref="1"/><nd ref="2"/><tag k="highway" v="residential"/><tag k="name" v="Main Street"/></way>
+ <way id="11"><nd ref="2"/><nd ref="3"/><tag k="highway" v="residential"/><tag k="name" v="Main Street"/></way>
+ <way id="12"><nd ref="4"/><nd ref="5"/><tag k="highway" v="residential"/><tag k="name" v="Main Street"/></way>
+ <way id="13"><nd ref="1"/><nd ref="6"/></way>
+ <relation id="19"><member type="relation" ref="20" role=""/>
+ <tag k="tourism" v="attraction"/><tag k="name" v="Museum complex"/></relation>
+ <relation id="20"><member type="way" ref="10" role=""/><member type="way" ref="11" role=""/>
+ <tag k="tourism" v="attraction"/><tag k="name" v="Museum"/></relation>
+ </osm>''')
+ header = osmium.io.Header()
+ header.set("osmosis_replication_timestamp", "2026-09-20T20:00:00Z")
+ with osmium.SimpleWriter(self.path, header=header) as writer:
+ osmium.apply(xml, writer)
+ self.area = (-.0001, -.0001, .0001, .0005)
+
+ def test_export_completes_ways_and_preserves_partial_relation_members(self):
+ output = self.folder / "map.osm"
+ metadata = self.source.export(self.area, output, lambda *args: None)
+ root = ET.parse(output).getroot()
+ self.assertEqual({int(n.attrib["id"]) for n in root.findall("node")}, {1, 2, 6})
+ self.assertEqual({int(w.attrib["id"]) for w in root.findall("way")}, {10, 13})
+ self.assertEqual({int(r.attrib["id"]) for r in root.findall("relation")}, {19, 20})
+ self.assertEqual(metadata["osm_data_at"], "2026-09-20T20:00:00Z")
+ self.client.get.assert_not_called()
+
+ def test_roads_pois_and_connected_street_use_cached_region(self):
+ ways, metadata = self.source.data(self.area)
+ self.assertEqual([way["id"] for way in ways], [10])
+ self.assertEqual(ways[0]["nodes"], [1, 2])
+ self.assertEqual(ways[0]["points"][-1], (0, .001))
+ self.assertEqual(metadata["osm_data_at"], "2026-09-20T20:00:00Z")
+ pois, _ = self.source.data(self.area, poi=True)
+ relations = {item["id"]: item["center"] for item in pois if item["type"] == "relation"}
+ self.assertEqual(relations, {19: (0, .001), 20: (0, .001)})
+ name, street = self.source.street(dict(id="way/10", lat=0, lon=0))
+ self.assertEqual(name, "Main Street")
+ self.assertEqual({w["id"] for w in street}, {10, 11})
+ self.assertEqual(self.source.data((1, 1, 1.1, 1.1), poi=True)[0], [])
+ self.client.get.assert_not_called()
+
+ def test_failed_extraction_keeps_previous_map(self):
+ output = self.folder / "map.osm"
+ output.write_bytes(b"previous")
+ with patch.object(Source, "extract", side_effect=OSError("failed")):
+ with self.assertRaises(OSError):
+ self.source.export(self.area, output, lambda *args: None)
+ self.assertEqual(output.read_bytes(), b"previous")
+ self.assertEqual(list(self.folder.glob(".map.osm-*")), [])
+
+ def test_refresh_rejects_invalid_download_without_replacing_cached_region(self):
+ original = self.path.read_bytes()
+ self.client.refresh = True
+ self.source.index = json.loads((self.source.directory / "index.json").read_bytes())["features"]
+
+ def download(url, **kwargs):
+ Path(kwargs["destination"]).write_bytes(b"not a PBF")
+
+ self.client.get.side_effect = download
+ with self.assertRaises(OSError):
+ self.source.region(self.area, lambda *args: None)
+ self.assertEqual(self.path.read_bytes(), original)
+
+ def test_cancellation_stops_local_processing(self):
+ output = self.folder / "map.osm"
+ output.write_bytes(b"previous")
+ self.source.region(self.area, lambda *args: None)
+ self.client.cancel = Mock(side_effect=[None, KeyboardInterrupt()])
+ with self.assertRaises(KeyboardInterrupt):
+ self.source.export(self.area, output, lambda *args: None)
+ self.assertEqual(output.read_bytes(), b"previous")
+ self.assertEqual(list(self.folder.glob(".map.osm-*")), [])
diff --git a/tests/test_queries.py b/tests/test_queries.py
index 4d7c235..fe69b3d 100644
--- a/tests/test_queries.py
+++ b/tests/test_queries.py
@@ -6,11 +6,12 @@ import unittest
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
from pathlib import Path
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from urllib.parse import parse_qs, urlsplit
import aleph
from src import capture, common, routes
+from src.osm import Source
from tests.fixtures import image_bytes, metadata
@@ -27,7 +28,7 @@ def place(identity=1, name="Test Street", lat=0, lon=0):
def way(identity, nodes, points, name="Test Street"):
return dict(type="way", id=identity, nodes=nodes,
tags=dict(highway="residential", name=name),
- geometry=[dict(lat=p[0], lon=p[1]) for p in points])
+ points=points)
def coverage(views):
@@ -57,12 +58,13 @@ class QueryTests(unittest.TestCase):
self.assertEqual(result["results"][0]["distance_m"], 0)
address = self.get.call_args.args[0]
self.assertEqual(parse_qs(urlsplit(address).query)["limit"], ["1"])
- self.get.return_value = encoded(dict(elements=[
- dict(type="node", id=2, lat=1, lon=2.0005, tags=dict(name="Cafe", amenity="cafe")),
- dict(type="way", id=3, center=dict(lat=1, lon=2.0001), tags=dict(name="Museum", tourism="museum")),
- dict(type="node", id=4, lat=1, lon=2.1, tags=dict(name="Far away", shop="books")),
- ]))
- status, result = self.invoke("resolve", "--at", "1", "2", "--nearby", "--radius", "100")
+ data = [
+ dict(type="node", id=2, center=(1, 2.0005), tags=dict(name="Cafe", amenity="cafe")),
+ dict(type="way", id=3, center=(1, 2.0001), tags=dict(name="Museum", tourism="museum")),
+ dict(type="node", id=4, center=(1, 2.1), tags=dict(name="Far away", shop="books")),
+ ]
+ with patch.object(Source, "data", return_value=(data, dict(osm_data_at="2026-09-20T20:00:00Z"))):
+ status, result = self.invoke("resolve", "--at", "1", "2", "--nearby", "--radius", "100")
self.assertEqual(status, 0)
self.assertEqual([item["id"] for item in result["results"]], ["way/3", "node/2"])
self.assertEqual(result["results"][0]["location_type"], "bbox_center")
@@ -125,14 +127,14 @@ class QueryTests(unittest.TestCase):
def test_street_sequence_orders_split_ways_and_saves_both_sides(self):
ways = [way(1, [2, 1], [(0, 0.001), (0, 0)]),
way(2, [2, 3], [(0, 0.001), (0, 0.002)])]
+ self.enterContext(patch.object(Source, "street", return_value=("Test Street", ways)))
+ self.enterContext(patch.object(Source, "data", return_value=(ways, {})))
failure, images = None, 0
def response(address, **kwargs):
nonlocal images
if "/api/?" in address:
return encoded(dict(features=[place()]))
- if kwargs.get("data"):
- return encoded(dict(elements=ways))
if "/ac/v1" in address:
return coverage([(f"panorama_{i:04d}", 0, lon) for i, lon in enumerate((0, 0.001, 0.002), 1)])
if "/photometa/v1" in address:
@@ -213,14 +215,13 @@ class RouteTests(unittest.TestCase):
ways = [way(1, [1, 2, 3], [(0, 0), (0, 0.001), (0, 0.002)]),
way(2, [2, 4], [(0, 0.001), (0.001, 0.001)])]
self.assertEqual(len(routes.chains(ways)), 3)
- responses = [dict(elements=[ways[0]]), dict(elements=ways)]
- with patch.object(routes.places, "osm_data", side_effect=responses):
- with self.assertRaises(common.RequestError) as raised:
- routes.resolve(None, dict(id="way/1"))
+ client = Mock()
+ client.maps.street.return_value = ("Test Street", ways)
+ with self.assertRaises(common.RequestError) as raised:
+ routes.resolve(client, dict(id="way/1"))
self.assertEqual(raised.exception.code, "ambiguous_route")
choices = raised.exception.details["candidates"]
- with patch.object(routes.places, "osm_data", side_effect=responses):
- selected = routes.resolve(None, dict(id="way/1"), route=2, reverse=True)
+ selected = routes.resolve(client, dict(id="way/1"), route=2, reverse=True)
self.assertEqual(selected["start"], choices[1]["end"])
self.assertEqual(selected["end"], choices[1]["start"])
ways[1] = way(2, [5, 4], [(0, 0.001), (0.001, 0.001)])
diff --git a/tests/test_streetview.py b/tests/test_streetview.py
index 522c334..7332aa4 100644
--- a/tests/test_streetview.py
+++ b/tests/test_streetview.py
@@ -34,8 +34,8 @@ class StreetViewTests(unittest.TestCase):
def test_roads_keep_crossings_but_do_not_bridge_outside_excursions(self):
points = [(0.25, -1), (0.25, 2), (0.75, 2), (0.75, -1)]
way = dict(type="way", id=1, tags=dict(highway="residential"),
- geometry=[dict(lat=lat, lon=lon) for lat, lon in points])
- roads = streetview.roads(dict(elements=[way]), (0, 0, 1, 1), "roads")
+ nodes=[1, 2, 3, 4], points=points)
+ roads = streetview.roads([way], (0, 0, 1, 1), "roads")
self.assertEqual([road["points"] for road in roads],
[[(0.25, 0), (0.25, 1)], [(0.75, 1), (0.75, 0)]])
@@ -46,7 +46,7 @@ class StreetViewTests(unittest.TestCase):
cases = (
("intersection", [horizontal, crossing], ["0", "0"], (0, 0), None),
("junction", [horizontal, connector], ["0", "0"], (0, 0), "through-road-at-connector"),
- ("overpass", [horizontal, connector], ["0", "1"], (0, 0), None),
+ ("bridge", [horizontal, connector], ["0", "1"], (0, 0), None),
("reversed joined sections", [[(0, -0.001), (0, 0)], [(0, 0.001), (0, 0)]],
["0", "0"], (0, 0), "joined-road-sections"),
("outside matching radius", [horizontal], ["0"], (0.001, 0), None),