Initial public NavFrame release with global regional package pipeline

This commit is contained in:
dasemu committed 2026-09-30 17:34:58 +02:00
commit d863f2b940
143 files changed
+17906

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# Build-time network downloads only. Never called by the Android application.
set -eu
cd "$(dirname "$0")/../.."
mkdir -p build/offline
navframe_jar=build/offline/planetiler-0.10.2.jar
navframe_pbf=build/offline/asturias.osm.pbf
if [ ! -f "$navframe_jar" ]; then
curl --fail --location --output "$navframe_jar.part" https://github.com/onthegomap/planetiler/releases/download/v0.10.2/planetiler.jar
mv "$navframe_jar.part" "$navframe_jar"
fi
if [ ! -f "$navframe_pbf" ]; then
curl --fail --location --output "$navframe_pbf.part" https://download.geofabrik.de/europe/spain/asturias-latest.osm.pbf
mv "$navframe_pbf.part" "$navframe_pbf"
fi
# Existing source is preserved; remove it deliberately to update to today's extract.
java -Xmx2g -jar "$navframe_jar" generate-custom \
--schema=tools/offline/navframe.yaml \
--output=build/offline/asturias.pmtiles \
--bounds=-7.2,42.9,-4.45,43.75 \
--tmpdir=build/offline/tmp --force --download-osm-tile-weights=false
sha256sum "$navframe_pbf" build/offline/asturias.pmtiles
# Explicit packaging: cp build/offline/asturias.pmtiles app/src/main/assets/offline/asturias.pmtiles
# When replacing the bundled pack, update its byte-count/date constants and notices as well.
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Original OSM regional POI extraction. Build tools only: osmium4.3.1/shapely2.1.2.
No Nominatim/Overpass requests; supplied PBF is the only input.
"""
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import sqlite3
import unicodedata
from urllib.parse import urlsplit
BOUNDS = (42.9, -7.2, 43.75, -4.45) # south west north east, regional coverage is Geofabrik's polygon
LABELS = {"FUEL": "Gasolinera", "WORKSHOP": "Taller", "FOOD": "Comida", "LODGING": "Alojamiento", "SHOPPING": "Comercio"}
def clean(value, limit=200):
if not value:
return None
# Normalize controls/format characters to whitespace, never executable markup.
value = "".join(" " if unicodedata.category(c) in {"Cc", "Cf", "Zl", "Zp"} else c for c in str(value))
return " ".join(value.split())[:limit].strip() or None
def normalize(value):
decomposed = unicodedata.normalize("NFD", value)
letters = "".join(c for c in decomposed if not unicodedata.category(c).startswith("M"))
return clean(letters.lower(), 1000) or ""
def category(tags):
# Reject lifecycle-prefixed objects and explicitly inactive businesses.
if any(tags.get(key) in {"yes", "true", "1"} for key in ["disused", "abandoned", "demolished", "razed", "construction"]):
return None
if any(tags.get(key, "") for key in ["disused:shop", "abandoned:shop", "disused:amenity", "abandoned:amenity", "disused:tourism", "abandoned:tourism"]):
return None
amenity, shop, tourism = tags.get("amenity"), tags.get("shop"), tags.get("tourism")
if amenity == "fuel": return "FUEL"
if shop in {"motorcycle_repair", "car_repair", "tyres"}: return "WORKSHOP"
if tags.get("motorcycle:repair") in {"yes", "only"} or (shop == "motorcycle" and tags.get("repair") in {"yes", "only"}): return "WORKSHOP"
if amenity in {"restaurant", "fast_food", "cafe", "food_court", "pub", "bar"}: return "FOOD"
if tourism in {"hotel", "motel", "hostel", "guest_house", "camp_site", "caravan_site", "chalet", "apartment"}: return "LODGING"
if shop and shop not in {"no", "vacant", "disused", "abandoned", "closed", "yes"}: return "SHOPPING"
return None
def safe_website(value):
value = clean(value, 500)
if not value: return None
if value.startswith("www."): value = "https://" + value
try:
uri = urlsplit(value)
if uri.scheme.lower() not in {"https", "http"} or not uri.hostname or uri.username or uri.password or " " in value:
return None
if any(c in value for c in ["<", ">", '"', "\\"]): return None
_ = uri.port
return value
except ValueError:
return None
def safe_phone(value):
value = clean(value, 100)
return value if value and re.fullmatch(r"[+0-9 ()/;,.-]+", value) and any(c.isdigit() for c in value) else None
def address(tags):
street = clean(tags.get("addr:street") or tags.get("addr:place"))
number = clean(tags.get("addr:housenumber"), 30)
postal = clean(tags.get("addr:postcode"), 20)
city = clean(tags.get("addr:city") or tags.get("addr:town") or tags.get("addr:village"))
return clean(", ".join(x for x in [" ".join(x for x in [street, number] if x), " ".join(x for x in [postal, city] if x)] if x), 300)
def row(osm_id, tags, lat, lon, bounds=BOUNDS, coverage=None):
group = category(tags)
if group is None or not math.isfinite(lat) or not math.isfinite(lon) or not (bounds[0] <= lat <= bounds[2] and bounds[1] <= lon <= bounds[3]):
return None
if coverage is not None and not coverage.covers(__import__("shapely.geometry", fromlist=["Point"]).Point(lon, lat)):
return None
name = clean(tags.get("name") or tags.get("name:es") or tags.get("brand") or tags.get("operator")) or LABELS[group] + " sin nombre"
return (osm_id, name, normalize(name), group, lat, lon, address(tags), clean(tags.get("opening_hours"), 500),
safe_website(tags.get("website") or tags.get("contact:website")), safe_phone(tags.get("phone") or tags.get("contact:phone")))
def camera_row(osm_id, tags, lat, lon, bounds=BOUNDS, coverage=None):
fixed = tags.get("highway") == "speed_camera" or (
tags.get("man_made") == "surveillance"
and tags.get("surveillance:type") in {"camera", "ALPR"}
and tags.get("surveillance:zone") == "traffic"
and tags.get("enforcement") in {"maxspeed", "speed"})
if not fixed or any(tags.get(k) in {"yes", "true", "1"} for k in ("disused", "abandoned", "demolished", "construction")):
return None
if not math.isfinite(lat) or not math.isfinite(lon) or not (bounds[0] <= lat <= bounds[2] and bounds[1] <= lon <= bounds[3]):
return None
if coverage is not None and not coverage.covers(__import__("shapely.geometry", fromlist=["Point"]).Point(lon, lat)):
return None
# OSM direction is ambiguously used for lens/traffic direction. Keep raw evidence;
# do not invent an enforced travel bearing or interpret forward/backward without a way.
return (osm_id, lat, lon, clean(tags.get("direction"), 40))
def read_poly(path):
from coverage import read_geojson
from shapely.geometry import shape
geometry = shape(read_geojson(path))
if geometry.is_empty or not geometry.is_valid:
raise ValueError("Invalid Geofabrik polygon")
return geometry
def build(source, target, date, region="asturias", bounds=BOUNDS, source_url="https://download.geofabrik.de/europe/spain/asturias-latest.osm.pbf", coverage_poly=None):
import osmium
from shapely import from_wkb
from shapely.geometry import LineString
coverage = read_poly(coverage_poly) if coverage_poly else None
rows = {}
cameras = {}
failed_geometry = 0
factory = osmium.geom.WKBFactory()
class Handler(osmium.SimpleHandler):
def node(self, node):
tags = dict(node.tags)
if node.location.valid():
camera = camera_row(f"n/{node.id}", tags, node.location.lat, node.location.lon, bounds, coverage)
if camera: cameras[camera[0]] = camera
if category(tags) and node.location.valid():
record = row(f"n/{node.id}", tags, node.location.lat, node.location.lon, bounds, coverage)
if record: rows[record[0]] = record
def way(self, way):
nonlocal failed_geometry
tags = dict(way.tags)
if not category(tags) or way.is_closed(): return # closed ways are handled as assembled areas
try:
coordinates = [(node.lon, node.lat) for node in way.nodes if node.location.valid()]
if len(coordinates) < 2: raise ValueError("Incomplete geometry")
point = LineString(coordinates).interpolate(0.5, normalized=True)
record = row(f"w/{way.id}", tags, point.y, point.x, bounds, coverage)
if record: rows[record[0]] = record
except (ValueError, RuntimeError):
failed_geometry += 1
def area(self, area):
nonlocal failed_geometry
tags = dict(area.tags)
if not category(tags): return
try:
shape = from_wkb(bytes.fromhex(factory.create_multipolygon(area)))
if shape.is_empty or not shape.is_valid: raise ValueError("Invalid area")
point = shape.representative_point() # on-surface, not a centroid outside a concave business polygon
record = row(f"{'w' if area.from_way() else 'r'}/{area.orig_id()}", tags, point.y, point.x, bounds, coverage)
if record: rows[record[0]] = record
except (ValueError, RuntimeError):
failed_geometry += 1
# Area callbacks assemble closed ways + multipolygon relations; nodes are cached for geometry.
Handler().apply_file(str(source), locations=True, idx="flex_mem")
target.parent.mkdir(parents=True, exist_ok=True)
staging = target.with_suffix(target.suffix + ".part")
staging.unlink(missing_ok=True)
db = sqlite3.connect(staging)
try:
db.executescript("""
PRAGMA page_size=4096;
PRAGMA user_version=1;
CREATE TABLE metadata(key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL);
CREATE TABLE places(id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, search_name TEXT NOT NULL,
category TEXT NOT NULL CHECK(category IN ('FUEL','WORKSHOP','FOOD','LODGING','SHOPPING')),
latitude REAL NOT NULL CHECK(latitude BETWEEN -90 AND 90),
longitude REAL NOT NULL CHECK(longitude BETWEEN -180 AND 180),
address TEXT, opening_hours TEXT, website TEXT, phone TEXT);
CREATE TABLE speed_cameras(id TEXT PRIMARY KEY NOT NULL, latitude REAL NOT NULL CHECK(latitude BETWEEN -90 AND 90),
longitude REAL NOT NULL CHECK(longitude BETWEEN -180 AND 180), direction TEXT);
CREATE INDEX speed_cameras_position ON speed_cameras(latitude,longitude);
CREATE INDEX places_category_position ON places(category,latitude,longitude);
CREATE INDEX places_position ON places(latitude,longitude);
CREATE INDEX places_search_name ON places(search_name);
""")
# Ten columns, all values parameterized; apostrophes and SQL wildcard characters remain data.
db.executemany("INSERT INTO places VALUES(?,?,?,?,?,?,?,?,?,?)", sorted(rows.values(), key=lambda value: value[0]))
db.executemany("INSERT INTO speed_cameras VALUES(?,?,?,?)", sorted(cameras.values()))
metadata = {
"camera_schema": "1", "camera_count": str(len(cameras)), "camera_recipe": "NavFrame fixed cameras 1.1.0",
"schema_version": "1", "region": region, "source": "OpenStreetMap / Geofabrik",
"source_url": source_url,
"osm_timestamp": date, "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
"bounds": json.dumps(bounds, separators=(",", ":")), "attribution": "© OpenStreetMap contributors",
"license": "ODbL-1.0", "recipe": "NavFrame POI 1.1.0", "count": str(len(rows)),
"failed_geometry": str(failed_geometry), "categories": json.dumps(LABELS, ensure_ascii=False, sort_keys=True),
}
db.executemany("INSERT INTO metadata VALUES(?,?)", sorted(metadata.items()))
db.commit()
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
db.execute("VACUUM")
print(json.dumps({"count": len(rows), "categories": dict(db.execute("SELECT category,count(*) FROM places GROUP BY category")), "failed_geometry": failed_geometry}, ensure_ascii=False))
finally:
db.close()
staging.replace(target)
print(f"bytes={target.stat().st_size} sha256={hashlib.sha256(target.read_bytes()).hexdigest()}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--pbf", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--osm-date", required=True, help="UTC timestamp read from this source's PBF header")
parser.add_argument("--region", default="asturias")
parser.add_argument("--bounds", default="42.9,-7.2,43.75,-4.45", help="south,west,north,east")
parser.add_argument("--source-url", default="https://download.geofabrik.de/europe/spain/asturias-latest.osm.pbf")
parser.add_argument("--coverage-poly", type=Path, help="Geofabrik .poly region boundary; restricts catalog to actual coverage")
args = parser.parse_args()
bounds = tuple(float(value) for value in args.bounds.split(","))
if len(bounds) != 4 or not all(math.isfinite(value) for value in bounds) or not (bounds[0] < bounds[2] and bounds[1] < bounds[3]):
parser.error("Invalid bounds")
build(args.pbf, args.output, args.osm_date, args.region, bounds, args.source_url, args.coverage_poly)
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Build one local NavFrame region archive from an existing Geofabrik extract.
Network is not used by this script. Inputs (PBF, matching .poly and Planetiler jar)
must be supplied by the operator; output is a deterministic ZIP-compatible .navframe.
"""
import argparse
import hashlib
import json
import struct
from pathlib import Path
import re
import subprocess
import zipfile
import shutil
ROOT = Path(__file__).resolve().parents[2]
POI_BUILDER = ROOT / "tools/offline/build-pois.py"
POI_VERSION = "NavFrame POI 1.1.0"
RECIPE = "NavFrame regional pack 1.1.0"
def sha(path):
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def pmtiles_bounds(path):
with path.open("rb") as stream:
header = stream.read(127)
if len(header) != 127 or header[:7] != b"PMTiles" or header[7] != 3:
raise ValueError("Map input is not a PMTiles v3 archive")
west, south, east, north = struct.unpack_from("<iiii", header, 102)
result = {"south": south / 1e7, "west": west / 1e7, "north": north / 1e7, "east": east / 1e7}
if not (result["south"] < result["north"] and result["west"] < result["east"]):
raise ValueError("PMTiles has invalid bounds")
return result
def bounds_for_poly(path):
points = []
for line in path.read_text().splitlines()[1:]:
fields = line.strip().split()
if len(fields) == 2:
try:
points.append((float(fields[0]), float(fields[1])))
except ValueError:
pass
if not points:
raise ValueError("Coverage polygon has no coordinate pairs")
west, south = min(x for x, _ in points), min(y for _, y in points)
east, north = max(x for x, _ in points), max(y for _, y in points)
return south, west, north, east
def geojson_for_poly(path):
from coverage import read_geojson
return read_geojson(path)
def header_timestamp(pbf, python):
code = "import osmium,sys; r=osmium.io.Reader(sys.argv[1]); h=r.header(); print(h.get('osmosis_replication_timestamp')); r.close()"
value = subprocess.check_output([python, "-c", code, str(pbf)], text=True).strip()
if not re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", value):
raise ValueError("PBF header is missing its UTC replication timestamp")
return value
def write_archive(archive, manifest, map_file, poi_file):
archive.parent.mkdir(parents=True, exist_ok=True)
temp = archive.with_suffix(archive.suffix + ".part")
with zipfile.ZipFile(temp, "w", compression=zipfile.ZIP_STORED, allowZip64=False) as output:
for name, source in (("manifest.json", None), ("map.pmtiles", map_file), ("pois.sqlite", poi_file)):
info = zipfile.ZipInfo(name, (2020, 1, 1, 0, 0, 0))
info.create_system = 3
info.external_attr = 0o100644 << 16
info.compress_type = zipfile.ZIP_STORED
if source is None:
output.writestr(info, manifest)
else:
with source.open("rb") as stream, output.open(info, "w") as target:
while block := stream.read(1024 * 1024):
target.write(block)
temp.replace(archive)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--java-heap", default="2g", help="Planetiler heap (e.g. 5g for a CI runner)")
parser.add_argument("--id", required=True, help="Stable slug, for example es-cantabria")
parser.add_argument("--name", required=True)
parser.add_argument("--version", required=True, help="Immutable region version")
parser.add_argument("--pbf", type=Path, required=True)
parser.add_argument("--coverage-poly", type=Path, required=True)
parser.add_argument("--coverage-url", required=True, help="Official Geofabrik .poly URL matching this extract")
parser.add_argument("--planetiler-jar", type=Path, help="Planetiler 0.10.2 jar; required when --map-pmtiles is omitted")
parser.add_argument("--map-pmtiles", type=Path, help="Reuse a previously built compatible NavFrame PMTiles archive")
parser.add_argument("--pois-sqlite", type=Path, help="Reuse a previously built NavFrame POI SQLite catalog")
parser.add_argument("--output", type=Path, required=True, help="Target .navframe archive")
parser.add_argument("--source-url", required=True, help="Official immutable Geofabrik extract URL")
parser.add_argument("--python", default="python3", help="Python with tools/offline/poi-requirements.txt installed")
parser.add_argument("--work", type=Path, help="Build workspace (defaults beside output)")
args = parser.parse_args()
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", args.id) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", args.version):
parser.error("Invalid id or version")
for path in (args.pbf, args.coverage_poly):
if not path.is_file():
parser.error(f"Missing input: {path}")
if args.map_pmtiles is None and (args.planetiler_jar is None or not args.planetiler_jar.is_file()):
parser.error("Provide --planetiler-jar to generate the map, or --map-pmtiles to reuse one")
if args.map_pmtiles and not args.map_pmtiles.is_file():
parser.error(f"Missing map input: {args.map_pmtiles}")
if args.pois_sqlite and not args.pois_sqlite.is_file():
parser.error(f"Missing POI input: {args.pois_sqlite}")
work = args.work or args.output.parent / f".{args.id}-build"
work.mkdir(parents=True, exist_ok=True)
map_file, poi_file = work / "map.pmtiles", work / "pois.sqlite"
south, west, north, east = bounds_for_poly(args.coverage_poly)
osm_timestamp = header_timestamp(args.pbf, args.python)
source_url = args.source_url
if not re.fullmatch(r"https://download\.geofabrik\.de/[a-z0-9._/-]+\.osm\.pbf", source_url) or ".." in source_url or "//" in source_url.removeprefix("https://"):
parser.error("Source must be a regional Geofabrik PBF URL")
coverage_url = args.coverage_url
if not re.fullmatch(r"https://download\.geofabrik\.de/[a-z0-9._/-]+\.poly", coverage_url) or ".." in coverage_url or "//" in coverage_url.removeprefix("https://"):
parser.error("Coverage must be a regional Geofabrik .poly URL")
if args.map_pmtiles:
shutil.copyfile(args.map_pmtiles, map_file)
else:
schema_file = work / "navframe-region.yaml"
schema_file.write_text((ROOT / "tools/offline/navframe.yaml").read_text().replace("build/offline/asturias.osm.pbf", str(args.pbf.resolve())))
subprocess.run(["java", f"-Xmx{args.java_heap}", "-jar", str(args.planetiler_jar), "generate-custom",
f"--schema={schema_file}", f"--output={map_file}",
f"--bounds={west},{south},{east},{north}", f"--tmpdir={work / 'tmp'}",
"--force", "--download-osm-tile-weights=false"], cwd=ROOT, check=True)
if args.pois_sqlite:
shutil.copyfile(args.pois_sqlite, poi_file)
else:
subprocess.run([args.python, str(POI_BUILDER), "--pbf", str(args.pbf), "--output", str(poi_file),
"--osm-date", osm_timestamp, "--region", args.id, "--bounds",
f"{south},{west},{north},{east}", "--source-url", source_url,
"--coverage-poly", str(args.coverage_poly)], cwd=ROOT, check=True)
manifest = {
"schemaVersion": 1, "id": args.id, "name": args.name, "version": args.version,
"osmTimestamp": osm_timestamp,
"bounds": pmtiles_bounds(map_file),
"minZoom": 6, "maxZoom": 14, "attribution": "© OpenStreetMap contributors",
"mapSchema": "NavFrame Offline/1.0.0", "poiSchema": 1,
"glyphs": "noto-sans-regular-0-2047", "capabilities": ["map", "poi"],
"source": {"provider": "Geofabrik", "extractUrl": source_url, "pbfSha256": sha(args.pbf),
"coverageUrl": coverage_url, "coverageSha256": sha(args.coverage_poly),
"planetilerJarSha256": sha(args.planetiler_jar) if args.planetiler_jar else None,
"license": "ODbL-1.0", "recipe": RECIPE, "planetiler": "0.10.2", "poiBuilder": POI_VERSION},
"coverage": geojson_for_poly(args.coverage_poly),
"map": {"path": "map.pmtiles", "bytes": map_file.stat().st_size, "sha256": sha(map_file)},
"pois": {"path": "pois.sqlite", "bytes": poi_file.stat().st_size, "sha256": sha(poi_file)},
}
manifest_bytes = (json.dumps(manifest, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
write_archive(args.output, manifest_bytes, map_file, poi_file)
catalog = {"schemaVersion": 1, "regions": [{"manifest": manifest, "archive": {
"path": args.output.name, "bytes": args.output.stat().st_size, "sha256": sha(args.output)}}]}
catalog_path = args.output.parent / "regional-catalog.json"
catalog_path.write_text(json.dumps(catalog, ensure_ascii=False, sort_keys=True, indent=2) + "\n")
print(json.dumps({"archive": str(args.output), "bytes": args.output.stat().st_size,
"sha256": sha(args.output), "catalog": str(catalog_path), "osmTimestamp": osm_timestamp,
"pbfSha256": sha(args.pbf), "mapSha256": manifest["map"]["sha256"],
"poiSha256": manifest["pois"]["sha256"]}, indent=2))
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
"""Read Geofabrik's Osmosis polygon format, preserving islands and holes."""
import math
def read_geojson(path):
polygons, current, hole = [], None, False
for raw in path.read_text().splitlines()[1:]:
value = raw.strip()
if not value:
continue
if value == '!': # historical local fixture separator
if current:
_finish(polygons, current, hole)
current = None
continue
if value == 'END':
if current is None:
break
_finish(polygons, current, hole)
current = None
continue
parts = value.split()
if len(parts) == 1:
if current:
_finish(polygons, current, hole)
hole, current = value.startswith('!'), []
elif len(parts) == 2:
point = [float(parts[0]), float(parts[1])]
if not all(math.isfinite(v) for v in point):
raise ValueError('Non-finite polygon coordinate')
if current is None:
current, hole = [], False
current.append(point)
else:
raise ValueError('Invalid polygon line')
if current:
_finish(polygons, current, hole)
if not polygons:
raise ValueError('Empty coverage polygon')
return {'type': 'Polygon', 'coordinates': polygons[0]} if len(polygons) == 1 else {'type': 'MultiPolygon', 'coordinates': polygons}
def _finish(polygons, ring, hole):
if len(ring) < 4 or ring[0] != ring[-1]:
raise ValueError('Unclosed coverage ring')
if hole:
if not polygons:
raise ValueError('Hole before exterior ring')
polygons[-1].append(ring)
else:
polygons.append([ring])
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Discover/build bounded Geofabrik regions and merge immutable catalog fragments."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import sqlite3
import subprocess
import sys
from urllib.request import urlopen
INDEX = 'https://download.geofabrik.de/index-v1-nogeom.json'
ROOT = Path(__file__).resolve().parents[2]
def official_url(url):
if not re.fullmatch(r'https://download\.geofabrik\.de/[a-z0-9._/-]+', url) or '..' in url or '//' in url[8:]:
raise ValueError('Expected official Geofabrik HTTPS URL')
return url
def download(url, path, maximum):
path.parent.mkdir(parents=True, exist_ok=True)
staging = path.with_suffix(path.suffix + '.part')
try:
with urlopen(url, timeout=120) as source, staging.open('wb') as target:
if int(source.headers.get('Content-Length', 0)) > maximum:
raise ValueError('Extract exceeds input budget; select a smaller region or larger runner')
total = 0
while block := source.read(1024 * 1024):
total += len(block)
if total > maximum:
raise ValueError('Download exceeds configured size budget')
target.write(block)
staging.replace(path)
finally:
staging.unlink(missing_ok=True)
def regions(index):
properties = {f['properties']['id']: f['properties'] for f in index['features']}
result = []
for identifier, props in sorted(properties.items()):
source = props.get('urls', {}).get('pbf')
if not source:
continue
official_url(source)
if not source.endswith('-latest.osm.pbf'):
raise ValueError('Unsupported Geofabrik PBF URL')
ancestor, seen = props, set()
while not ancestor.get('iso3166-1:alpha2') and ancestor.get('parent') in properties:
if ancestor['id'] in seen:
raise ValueError('Cycle in region ancestry')
seen.add(ancestor['id'])
ancestor = properties[ancestor['parent']]
codes = ancestor.get('iso3166-1:alpha2', [])
result.append({'id': identifier, 'name': props['name'], 'parent': props.get('parent'),
'source': source, 'coverage': source.removesuffix('-latest.osm.pbf') + '.poly',
'countryCode': codes[0] if len(codes) == 1 else None,
'country': ancestor['name'] if codes else None})
return result
def matrix(value):
ids = [item.strip() for item in value.split(',') if item.strip()]
if not ids or len(ids) > 32 or len(ids) != len(set(ids)):
raise ValueError('Select 1–32 distinct region IDs per batch')
if any(not re.fullmatch(r'[a-z0-9]+(?:[-/][a-z0-9]+)*', item) for item in ids):
raise ValueError('Invalid region ID')
return {'region': ids}
def merge(paths):
entries = {}
for path in paths:
catalog = json.loads(path.read_text())
if catalog['schemaVersion'] != 1:
raise ValueError('Unsupported catalog')
for entry in catalog['regions']:
key = (entry['manifest']['id'], entry['manifest']['version'])
if key in entries and entries[key] != entry:
raise ValueError('Conflicting immutable catalog entries')
url = entry['archive'].get('url', '')
if not re.fullmatch(r'https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/releases/download/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\.navframe', url):
raise ValueError('Missing immutable GitHub package URL')
entries[key] = entry
return {'schemaVersion': 1, 'regions': [entries[key] for key in sorted(entries)]}
def build(args, selected):
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', args.version):
raise ValueError('Invalid immutable version')
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', args.repository):
raise ValueError('Invalid repository')
work = args.output / 'work'
work.mkdir(parents=True, exist_ok=True)
pbf, poly = work / 'region.osm.pbf', work / 'region.poly'
download(selected['source'], pbf, args.max_input_mib * 1024 * 1024)
checksum = work / 'region.osm.pbf.md5'
download(selected['source'] + '.md5', checksum, 4096)
expected = checksum.read_text().split()[0]
digest = hashlib.md5()
with pbf.open('rb') as stream:
while block := stream.read(1024 * 1024):
digest.update(block)
if not re.fullmatch(r'[a-fA-F0-9]{32}', expected) or digest.hexdigest() != expected.lower():
raise ValueError('Geofabrik PBF checksum mismatch (possibly daily rotation); rerun')
download(selected['coverage'], poly, 16 * 1024 * 1024)
slug = selected['id'].replace('/', '-')
archive = args.output / f"gf-{slug}-{args.version}.navframe"
subprocess.run([sys.executable, str(ROOT / 'tools/offline/build-region.py'),
'--id', f"gf-{slug}", '--name', selected['name'], '--version', args.version,
'--pbf', str(pbf), '--coverage-poly', str(poly), '--coverage-url', selected['coverage'],
'--planetiler-jar', str(args.planetiler_jar), '--java-heap', args.java_heap,
'--source-url', selected['source'], '--output', str(archive), '--work', str(work)], check=True)
if archive.stat().st_size >= args.max_package_mib * 1024 * 1024:
raise ValueError('Package exceeds publication budget; select a smaller region')
catalog_path = args.output / 'regional-catalog.json'
catalog = json.loads(catalog_path.read_text())
entry = catalog['regions'][0]
tag = f"offline-gf-{slug}-{args.version}"
entry['archive']['url'] = f'https://github.com/{args.repository}/releases/download/{tag}/{archive.name}'
entry.update({key: selected[key] for key in ('countryCode', 'country') if selected[key]})
entry['region'] = selected['id']
with sqlite3.connect(work / 'pois.sqlite') as db:
entry['cameraCount'] = db.execute('SELECT count(*) FROM speed_cameras').fetchone()[0]
catalog_path.write_text(json.dumps(catalog, ensure_ascii=False, indent=2) + '\n')
print(json.dumps({'archive': str(archive), 'catalog': str(catalog_path), 'tag': tag}))
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
discover = sub.add_parser('discover')
discover.add_argument('--index', type=Path)
discover.add_argument('--output', type=Path, required=True)
plan = sub.add_parser('matrix')
plan.add_argument('regions')
combine = sub.add_parser('merge')
combine.add_argument('catalogs', type=Path, nargs='+')
combine.add_argument('--output', type=Path, required=True)
builder = sub.add_parser('build')
builder.add_argument('--region', required=True)
builder.add_argument('--version', required=True)
builder.add_argument('--repository', default=os.environ.get('GITHUB_REPOSITORY', 'Dasemu/NavFrame'))
builder.add_argument('--planetiler-jar', type=Path, required=True)
builder.add_argument('--output', type=Path, required=True)
builder.add_argument('--index', type=Path)
builder.add_argument('--max-input-mib', type=int, default=1024)
builder.add_argument('--max-package-mib', type=int, default=500)
builder.add_argument('--java-heap', default='4g')
args = parser.parse_args()
if args.command == 'matrix':
print(json.dumps(matrix(args.regions)))
return
if args.command == 'merge':
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(merge(args.catalogs), ensure_ascii=False, indent=2) + '\n')
return
if args.index:
index = json.loads(args.index.read_text())
else:
with urlopen(INDEX, timeout=60) as response:
index = json.load(response)
available = regions(index)
if args.command == 'discover':
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps({'schemaVersion': 1, 'sourceIndex': INDEX, 'regions': available}, ensure_ascii=False, indent=2) + '\n')
else:
selected = next((r for r in available if r['id'] == args.region), None)
if selected is None:
raise ValueError('Region not present in official Geofabrik index')
build(args, selected)
if __name__ == '__main__':
main()
+86
View File
@@ -0,0 +1,86 @@
# Original NavFrame schema: OSM data only, no OpenMapTiles design/code reused.
schema_name: NavFrame Offline
schema_description: Regional motorcycle map context from OpenStreetMap. Not routing data.
version: 1.0.0
attribution: '<a href="https://www.openstreetmap.org/copyright">© OpenStreetMap contributors</a>'
args:
osm_local_path: build/offline/asturias.osm.pbf
minzoom: 6
maxzoom: 14
threads: 4
sources:
osm:
type: osm
local_path: '${ args.osm_local_path }'
layers:
- id: roads
features:
- source: osm
geometry: line
min_zoom: 6
include_when:
highway: [motorway, motorway_link, trunk, trunk_link, primary, primary_link, secondary, secondary_link, tertiary, tertiary_link]
attributes:
- { key: class, tag_value: highway }
- { key: name, tag_value: name }
- { key: ref, tag_value: ref }
- source: osm
geometry: line
min_zoom: 11
include_when:
highway: [unclassified, residential, living_street, service, track, road]
attributes:
- { key: class, tag_value: highway }
- { key: name, tag_value: name }
- source: osm
geometry: line
min_zoom: 13
include_when:
highway: [path, footway, cycleway, steps, pedestrian]
attributes:
- { key: class, tag_value: highway }
- { key: name, tag_value: name }
- id: water
features:
- source: osm
geometry: polygon
min_zoom: 6
include_when: { natural: water }
- id: waterway
features:
- source: osm
geometry: line
min_zoom: 8
include_when: { waterway: [river, stream, canal] }
- id: landuse
features:
- source: osm
geometry: polygon
min_zoom: 7
include_when:
__any__:
- { landuse: [forest, meadow, grass, farmland, orchard, vineyard] }
- { natural: [wood, scrub, heath, grassland] }
- { leisure: park }
- id: building
features:
- source: osm
geometry: polygon
min_zoom: 13
include_when: { building: __any__ }
- id: place
features:
- source: osm
geometry: point
min_zoom: 6
include_when: { place: [city, town] }
attributes:
- { key: class, tag_value: place }
- { key: name, tag_value: name }
- source: osm
geometry: point
min_zoom: 10
include_when: { place: [village, hamlet, suburb, neighbourhood, locality] }
attributes:
- { key: class, tag_value: place }
- { key: name, tag_value: name }
+2
View File
@@ -0,0 +1,2 @@
osmium==4.3.1
shapely==2.1.2
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Rebuild the mutable discovery index from immutable regional release fragments."""
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import tempfile
def main():
repository = os.environ['GITHUB_REPOSITORY']
# gh --paginate --slurp preserves page boundaries; avoid the default 30-release limit.
pages = json.loads(subprocess.check_output(['gh', 'api', '--paginate', '--slurp',
f'repos/{repository}/releases?per_page=100'], text=True))
releases = [release for page in pages for release in page]
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
fragments = []
for release in releases:
tag = release['tag_name']
if release['draft'] or not tag.startswith('offline-gf-'):
continue
destination = root / str(release['id'])
subprocess.run(['gh', 'release', 'download', tag, '--repo', repository,
'--pattern', 'regional-catalog.json', '--dir', str(destination)], check=True)
fragments.append(destination / 'regional-catalog.json')
if not fragments:
raise ValueError('No published regional packages')
spec = importlib.util.spec_from_file_location('global_regions', Path(__file__).with_name('global-regions.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
combined = module.merge(fragments)
# Browser catalog shows the newest publication per region; old URLs remain usable.
newest = {}
for entry in combined['regions']:
identifier = entry['manifest']['id']
version = entry['manifest']['version']
key = tuple(int(part) for part in version.split('.'))
if identifier not in newest or key > newest[identifier][0]:
newest[identifier] = (key, entry)
combined['regions'] = [newest[key][1] for key in sorted(newest)]
output = root / 'regional-catalog.json'
payload = (json.dumps(combined, ensure_ascii=False, separators=(',', ':')) + '\n').encode()
if len(payload) > 32 * 1024 * 1024 or len(combined['regions']) > 4096:
raise ValueError('Catalog exceeds Android discovery limits; split the catalog before publication')
output.write_bytes(payload)
existing = subprocess.run(['gh', 'release', 'view', 'offline-catalog', '--repo', repository],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if existing.returncode:
subprocess.run(['gh', 'release', 'create', 'offline-catalog', str(output), '--repo', repository,
'--title', 'Offline regional catalog', '--notes',
'Mutable package discovery index. Regional package releases are immutable.', '--latest=false'], check=True)
else:
subprocess.run(['gh', 'release', 'upload', 'offline-catalog', str(output), '--repo', repository,
'--clobber'], check=True)
if __name__ == '__main__':
main()
+28
View File
@@ -0,0 +1,28 @@
{
"schemaVersion": 1,
"regions": [
{
"id": "es-cantabria",
"name": "Cantabria",
"version": "20260928.1",
"source": "https://download.geofabrik.de/europe/spain/cantabria-latest.osm.pbf",
"coverage": "https://download.geofabrik.de/europe/spain/cantabria.poly",
"osmTimestamp": "2026-09-28T20:23:05Z",
"bounds": {
"south": 42.7,
"west": -4.9,
"north": 43.9,
"east": -3.1
},
"pbfSha256": "0036ed2762d2ef7833362f15b5e09904dacbea47d0a2381bbc1fab80a92d0731",
"mapSha256": "5fa6d6ec7ce4d1b7199581c2e27cf28aff17ff013e9ca09b9c5c4740a2cb4a90",
"poiSha256": "42471d1606138a60f189429511c7a9e4b4741adb87d420d891343600a0c45270",
"archive": "dist/es-cantabria-20260928.1.navframe",
"archiveBytes": 27782594,
"archiveSha256": "b4f8e8075301a645e33511642119997dc27b1fb8e52ae0caa14519ebd3b79ce9",
"license": "ODbL-1.0",
"recipe": "NavFrame regional pack 1.0.0 / Planetiler 0.10.2 / NavFrame POI 1.0.0",
"coverageSha256": "64cc9cb3ad43b301eae6d347150de6e529b1a7b9f0af54e7a5dbdcf82f213a5b"
}
]
}
+81
View File
@@ -0,0 +1,81 @@
"""Original extraction tests, plus integrity checks on the generated real Asturias asset."""
import importlib.util
import sqlite3
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location("build_pois", Path(__file__).with_name("build-pois.py"))
pipeline = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pipeline)
class PoiPipelineTest(unittest.TestCase):
def test_categories_do_not_claim_every_motorcycle_shop_repairs(self):
self.assertEqual("FUEL", pipeline.category({"amenity": "fuel"}))
self.assertEqual("SHOPPING", pipeline.category({"shop": "motorcycle", "motorcycle:repair": "no"}))
self.assertEqual("WORKSHOP", pipeline.category({"shop": "motorcycle", "motorcycle:repair": "yes"}))
self.assertEqual("WORKSHOP", pipeline.category({"shop": "motorcycle_repair"}))
self.assertEqual("WORKSHOP", pipeline.category({"shop": "car_repair"}))
self.assertEqual("LODGING", pipeline.category({"tourism": "camp_site"}))
self.assertIsNone(pipeline.category({"shop": "bakery", "disused": "yes"}))
self.assertIsNone(pipeline.category({"shop": "bakery", "abandoned:shop": "bakery"}))
self.assertIsNone(pipeline.category({"shop": "vacant"}))
def test_metadata_is_optional_and_links_are_sanitized(self):
self.assertEqual("cafe alvaro", pipeline.normalize(" CAFÉ\u00a0ÁLVARO\n"))
self.assertEqual("a b", pipeline.normalize("A\u200bB"))
self.assertEqual("καφες", pipeline.normalize("Καφές"))
self.assertEqual("https://www.example.org", pipeline.safe_website("www.example.org"))
for url in ["javascript:alert(1)", "file:///tmp/x", "https://user:secret@example.org", "http://example.org:bad", "https://example.org/\npath"]:
self.assertIsNone(pipeline.safe_website(url))
self.assertIsNone(pipeline.safe_phone("javascript:123"))
self.assertEqual("+34 985 123 456", pipeline.safe_phone("+34 985 123 456"))
record = pipeline.row("n/1", {"amenity": "fuel"}, 43.36, -5.85)
self.assertEqual("Gasolinera sin nombre", record[1])
self.assertIsNone(record[6])
self.assertIsNone(record[7])
self.assertIsNone(pipeline.row("n/1", {"amenity": "fuel"}, 0.0, 0.0))
def test_real_catalog_integrity_counts_identity_and_utf8(self):
target = Path(__file__).parents[2] / "app/src/main/assets/offline/asturias-pois.sqlite"
with sqlite3.connect(f"file:{target}?mode=ro", uri=True) as db:
self.assertEqual("ok", db.execute("PRAGMA integrity_check").fetchone()[0])
self.assertEqual(1, db.execute("PRAGMA user_version").fetchone()[0])
metadata = dict(db.execute("SELECT key,value FROM metadata"))
self.assertEqual("ODbL-1.0", metadata["license"])
self.assertEqual("2026-09-28T20:23:05Z", metadata["osm_timestamp"])
self.assertEqual("1ab5967cc162027f0d05b2b603b65ad3f5d3b5466551613054cf5e6b28b9eb5d", metadata["source_sha256"])
self.assertEqual(int(metadata["count"]), db.execute("SELECT COUNT(*) FROM places").fetchone()[0])
self.assertEqual(set(pipeline.LABELS), {row[0] for row in db.execute("SELECT DISTINCT category FROM places")})
self.assertEqual(0, db.execute("SELECT COUNT(*) FROM places WHERE latitude NOT BETWEEN 42.9 AND 43.75 OR longitude NOT BETWEEN -7.2 AND -4.45").fetchone()[0])
seen = set()
for osm_id, name, search_name, lat, lon in db.execute("SELECT id,name,search_name,latitude,longitude FROM places"):
self.assertRegex(osm_id, r"^[nwr]/[1-9][0-9]*$")
self.assertNotIn(osm_id, seen)
seen.add(osm_id)
self.assertEqual(pipeline.normalize(name), search_name)
self.assertGreater(db.execute("SELECT COUNT(*) FROM places WHERE name LIKE '%é%' OR name LIKE '%ñ%'").fetchone()[0], 100)
def test_build_extracts_original_fixture_nodes_closed_ways_and_relation_areas(self):
# Synthetic local coordinates, original OSM fixture. No user/GPS data or claimed real businesses.
xml = '''<?xml version="1.0"?><osm version="0.6" generator="NavFrame test">
<node id="1" lat="43.36" lon="-5.85"><tag k="amenity" v="fuel"/><tag k="name" v="Fuel fixture"/></node>
<node id="2" lat="43.3600" lon="-5.8500"/><node id="3" lat="43.3600" lon="-5.8499"/>
<node id="4" lat="43.3601" lon="-5.8499"/><node id="5" lat="43.3601" lon="-5.8500"/>
<way id="1"><nd ref="2"/><nd ref="3"/><nd ref="4"/><nd ref="5"/><nd ref="2"/><tag k="amenity" v="cafe"/><tag k="name" v="O'Connor %_ fixture"/></way>
<way id="2"><nd ref="2"/><nd ref="3"/><nd ref="4"/><nd ref="5"/><nd ref="2"/></way>
<relation id="1"><member type="way" ref="2" role="outer"/><tag k="type" v="multipolygon"/><tag k="tourism" v="hotel"/><tag k="name" v="Hotel fixture"/></relation>
</osm>'''
with tempfile.TemporaryDirectory() as folder:
source, target = Path(folder) / "input.osm", Path(folder) / "places.sqlite"
source.write_text(xml)
pipeline.build(source, target, "2026-09-28T20:23:05Z")
with sqlite3.connect(target) as db:
self.assertEqual({"n/1", "w/1", "r/1"}, {row[0] for row in db.execute("SELECT id FROM places")})
self.assertEqual("O'Connor %_ fixture", db.execute("SELECT name FROM places WHERE id='w/1'").fetchone()[0])
self.assertEqual(0, db.execute("SELECT COUNT(*) FROM places WHERE latitude NOT BETWEEN 43.36 AND 43.3601 OR longitude NOT BETWEEN -5.85 AND -5.8499").fetchone()[0])
if __name__ == "__main__":
unittest.main()
+54
View File
@@ -0,0 +1,54 @@
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from coverage import read_geojson
spec = importlib.util.spec_from_file_location('global_regions', Path(__file__).with_name('global-regions.py'))
global_regions = importlib.util.module_from_spec(spec)
spec.loader.exec_module(global_regions)
class GlobalPipelineTest(unittest.TestCase):
def test_global_index_and_ancestry(self):
index = {'features': [{'properties': {'id': 'australia', 'name': 'Australia', 'iso3166-1:alpha2': ['AU'], 'urls': {'pbf': 'https://download.geofabrik.de/australia-oceania/australia-latest.osm.pbf'}}},
{'properties': {'id': 'act', 'name': 'ACT', 'parent': 'australia', 'urls': {'pbf': 'https://download.geofabrik.de/australia-oceania/australia/act-latest.osm.pbf'}}}]}
region = global_regions.regions(index)[0]
self.assertEqual(region['countryCode'], 'AU')
self.assertEqual(region['coverage'], 'https://download.geofabrik.de/australia-oceania/australia/act.poly')
def test_matrix_limits_and_injection(self):
self.assertEqual(global_regions.matrix('act,us/california'), {'region': ['act', 'us/california']})
for value in ('', 'act,act', '$(id)', ','.join('r' + str(i) for i in range(33))):
with self.assertRaises(ValueError):
global_regions.matrix(value)
def test_untrusted_sources(self):
for url in ('http://download.geofabrik.de/a.poly', 'https://evil.example/a.poly', 'https://download.geofabrik.de/../a.poly', 'https://download.geofabrik.de//a.poly'):
with self.assertRaises(ValueError):
global_regions.official_url(url)
def test_polygon_islands_holes_and_final_end(self):
text = 'example\n1\n0 0\n4 0\n4 4\n0 0\nEND\n!1\n1 1\n2 1\n2 2\n1 1\nEND\n2\n10 10\n11 10\n11 11\n10 10\nEND\nEND\n'
with tempfile.TemporaryDirectory() as temporary:
path = Path(temporary) / 'region.poly'
path.write_text(text)
geometry = read_geojson(path)
self.assertEqual(geometry['type'], 'MultiPolygon')
self.assertEqual([len(p) for p in geometry['coordinates']], [2, 1])
path.write_text('bad\n1\n0 0\n1 0\n1 1\nEND\nEND\n')
with self.assertRaises(ValueError):
read_geojson(path)
def test_merge_conflicting_immutable_entries(self):
entry = {'manifest': {'id': 'gf-act', 'version': '1.1'}, 'archive': {'url': 'https://github.com/Dasemu/NavFrame/releases/download/offline-gf-act-1.1/gf-act-1.1.navframe', 'sha256': 'a'}}
with tempfile.TemporaryDirectory() as temporary:
first, second = Path(temporary) / '1.json', Path(temporary) / '2.json'
first.write_text(json.dumps({'schemaVersion': 1, 'regions': [entry]}))
second.write_text(first.read_text())
self.assertEqual(len(global_regions.merge([first, second])['regions']), 1)
entry['archive']['sha256'] = 'b'
second.write_text(json.dumps({'schemaVersion': 1, 'regions': [entry]}))
with self.assertRaises(ValueError):
global_regions.merge([first, second])
+19
View File
@@ -0,0 +1,19 @@
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location('pois', Path(__file__).with_name('build-pois.py'))
pois = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pois)
class CameraExtractionTest(unittest.TestCase):
def test_international_speed_surveillance(self):
tags = {'man_made': 'surveillance', 'surveillance:type': 'camera', 'surveillance:zone': 'traffic', 'enforcement': 'maxspeed'}
self.assertIsNotNone(pois.camera_row('n/2', tags, -35, 149, (-36,148,-34,150)))
self.assertIsNone(pois.camera_row('n/2', {'man_made': 'surveillance', 'surveillance:type': 'camera'}, -35,149,(-36,148,-34,150)))
def test_fixed_nodes_only(self):
self.assertEqual(pois.camera_row('n/1', {'highway':'speed_camera','direction':'forward'},43,-5), ('n/1',43,-5,'forward'))
self.assertIsNone(pois.camera_row('n/1', {'highway':'speed_camera','disused':'yes'},43,-5))
self.assertIsNone(pois.camera_row('n/1', {'highway':'speed_display'},43,-5))
self.assertIsNone(pois.camera_row('n/1', {'highway':'speed_camera'},float('nan'),-5))
self.assertIsNone(pois.camera_row('n/1', {'highway':'speed_camera'},40,-5))
if __name__ == '__main__': unittest.main()
File diff suppressed because it is too large. Load diff