scripts/maps: PMTiles generator (base + safety layers + admin borders, replaces v4 + fgb)
- Commit
d59a7559ced23de04079123d827e60befe3f3550- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 23:41 UTC (3 months ago)
- Parents
ab076db
Diff
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdnew file mode 100644index 0000000000..172d29aab7--- /dev/null+++ b/scripts/maps/README.md@@ -0,0 +1,235 @@+# scripts/maps — PMTiles generator (`v5.pmtiles`)++Builds the custom **`v5.pmtiles`** consumed by the `maps` app. This single file+**replaces two things** the app ships/streams today:++| Old | New |+|-----|-----|+| `https://data.vayunmathur.com/v4.pmtiles` (base tiles) | `v5.pmtiles` base layers (identical schema) |+| `maps/src/main/assets/admin0.fgb` + `admin1.fgb` (border masks) | `v5.pmtiles` `admin_country` / `admin_region` / `admin_city` layers |++On top of the base it also **bakes safety / road-furniture** data (speed+cameras, ALPR/surveillance, stop signs, traffic signals) so the app never needs+a runtime Overpass query.++> This directory is the **generator**. Running the full planet build is an infra+> step (large + long-running); the scripts are designed to be correct, modular+> and runnable, and to support a small metro dry run for validation.++---++## What was there before (investigation summary)++* **Base tiles** = Protomaps' prebuilt basemap. `v4.pmtiles` (137 GB) is just+ downloaded from `demo-bucket.protomaps.com` and re-hosted on Cloudflare R2 by+ [`vendor_pmtiles.sh`](vendor_pmtiles.sh). There was **no** local tile-building+ pipeline. The style (`maps/src/main/assets/style.json`) expects the Protomaps+ schema (source-layers below).+* **Borders** = two vendored FlatGeobuf files read by+ `maps/src/main/java/com/vayunmathur/maps/data/CountryMap.kt`:+ * `admin0.fgb` — countries, matched by property **`ISO_A2`**+ * `admin1.fgb` — states/provinces, matched by property **`iso_3166_2`**+ Used to draw a dimming *inverted mask* around a selected country/state+ (`ui/MyMapLayers.kt` → `createInvertedMask`). No city-level file existed.+ Attribute schema (`ISO_A2`, `iso_3166_2`) is Natural-Earth-derived.+* **Offline packs / routing** (context for later phases, **not built here**):+ * `extract_pmtiles.sh` slices the world pmtiles into 64 Morton-grid+ `zone_$i.pmtiles` offline packs.+ * `generator.cpp` + `run_generator.sh` build the **routing graph** binaries+ (`nodes_zone_*.bin`, `edges_zone_*.bin`, `transit_voyages_zone_*.bin`, …)+ with libosmium. **This is the offline-region-pack / routing-graph generator+ that P11 edits for GTFS** — it already has transit/GTFS scaffolding.++---++## Output schema (source-layers)++The base layers keep the **exact** Protomaps names so `style.json` works+unchanged; the new layers are additive.++**Base (unchanged, from Protomaps schema):**++```+earth landcover landuse water roads buildings boundaries pois places+```++**New layers added by this generator (for P13 to reference in `style.json`):**++| source-layer | geometry | key attributes |+|---|---|---|+| `safety` | Point | `kind` ∈ {`speed_camera`,`alpr`,`surveillance`,`stop_sign`,`traffic_signals`}, `name?`, `direction?`, `operator?`, `ref?`, `osm_id` |+| `admin_country` | Polygon/MultiPolygon | `admin_level=2`, `name`, `name_en`, **`ISO_A2`**, `iso_a3` |+| `admin_region` | Polygon/MultiPolygon | `admin_level=4`, `name`, `name_en`, **`iso_3166_2`**, `country_iso` |+| `admin_city` | Polygon/MultiPolygon | `admin_level=8`, `name`, `name_en` |++The admin layers deliberately preserve `ISO_A2` (countries) and `iso_3166_2`+(regions) — the same keys `CountryMap.kt` matches on — so P13 can repoint the+mask lookup at the PMTiles source with **no attribute changes**.++---++## Data sources & rationale++* **Base** — Protomaps basemaps. Either **regenerate** with Planetiler + the+ official Protomaps basemap profile (reproducible), or **reuse** the upstream+ prebuilt file (fast; identical schema). See `--base-mode` below.+* **Safety** — OpenStreetMap. Tag → `kind` mapping:+ * `highway=speed_camera` or `enforcement=maxspeed` → `speed_camera`+ * `man_made=surveillance` + ALPR signals → `alpr`+ (DeFlock / [deflock.me] tag ALPRs as `surveillance:type=ALPR`, or+ `camera:type=alpr`; Flock Safety is the dominant operator/manufacturer)+ * `man_made=surveillance` (any other) → `surveillance`+ * `highway=stop` → `stop_sign`+ * `highway=traffic_signals` → `traffic_signals`+* **Admin borders**:+ * country + region → **Natural Earth 10m** (`ne_10m_admin_0_countries`,+ `ne_10m_admin_1_states_provinces`). Chosen because the current `.fgb` are+ Natural-Earth-derived and keyed by `ISO_A2` / `iso_3166_2` → byte-for-byte+ attribute compatibility, plus clean generalized geometry that is ideal for+ the dimming mask.+ * city → **OSM `boundary=administrative` + `admin_level=8`** (Natural Earth+ has no city polygons).++---++## Files++| File | Purpose |+|---|---|+| `build_v5_pmtiles.sh` | **Top-level orchestrator**: base + safety + admin → merge → `v5.pmtiles` |+| `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse upstream `v4.pmtiles`) |+| `build_safety_layer.sh` | osmium → GeoJSON → `normalize_safety.py` → tippecanoe → `safety.pmtiles` |+| `build_admin_layers.sh` | Natural Earth / OSM → `normalize_admin.py` → tippecanoe → `admin_*.pmtiles` |+| `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested) |+| `normalize_admin.py` | NE/OSM attrs → admin layer schema (pure stdlib, unit-tested) |+| `test/test_normalize.py` | Dry-run unit test of the schema mapping (no external tools) |+| `test/fixtures/*` | Tiny sample inputs for the test |++---++## Prerequisites (tools)++Full build needs (all are existing off-the-shelf tools — no C++ authored here):++* **tippecanoe** ≥ 2.x (provides `tippecanoe` + `tile-join`, both write `.pmtiles`)+* **osmium-tool** (`osmium`)+* **GDAL** (`ogr2ogr`)+* **python3** (stdlib only)+* Base build mode only: **Java 21** + the Protomaps basemap jar+ (build once from `github.com/protomaps/basemaps`, `tiles/` → `mvn package`)+* Base reuse mode only: `curl`, and `go-pmtiles` (`pmtiles`) if using `--bbox`++Install (Fedora/Amazon Linux, matching `run_generator.sh` conventions):++```bash+sudo dnf install -y osmium-tool gdal python3 curl unzip+# tippecanoe: build from github.com/felt/tippecanoe (make && make install)+```++The **dry-run test** needs only `python3`.++---++## Run commands++### 1. Dry run (single metro — validates safety + border layers)++Prove a valid `.pmtiles` with the new layers without a planet build. Example+San Francisco Bay Area, reusing the upstream base clipped to the bbox:++```bash+# small OSM extract, e.g. from geofabrik norcal, or osmium extract yourself+./build_v5_pmtiles.sh \+ --pbf norcal-latest.osm.pbf \+ --bbox -122.6,37.2,-121.7,37.9 \+ --base-mode reuse \+ --out v5-sf.pmtiles --workdir ./v5_work_sf++# inspect+pmtiles show v5-sf.pmtiles # lists layers: ... safety admin_country ...+```++### 2. Full planet build++```bash+# Base built from OSM with Planetiler (reproducible):+./build_v5_pmtiles.sh \+ --pbf planet-latest.osm.pbf \+ --base-mode build \+ --base-jar protomaps-basemap-HEAD-with-deps.jar \+ --base-area planet \+ --out v5.pmtiles++# …or reuse the upstream prebuilt base and only refresh overlays (much faster):+./build_v5_pmtiles.sh --pbf planet-latest.osm.pbf --base-mode reuse --out v5.pmtiles+```++Individual layers can also be built standalone — see each script's `--help`.++---++## Expected output & size++| Artifact | Extent | Approx size |+|---|---|---|+| `safety.pmtiles` | planet | ~0.3–1 GB (point features only) |+| `admin_country/region/city.pmtiles` | planet | ~50–300 MB combined |+| **`v5.pmtiles`** | planet | ≈ **137 GB** (dominated by the base; overlays add < 1%) |+| `v5-sf.pmtiles` | one metro | tens of MB |++The base dominates; the safety + admin overlays are a rounding error on top.++---++## Publish to data.vayunmathur.com++Upload with a bumped key so the app can switch atomically:++```bash+R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com \+AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... \+R2_KEY=v5.pmtiles ./scripts/maps/vendor_pmtiles.sh --local v5.pmtiles --source v5.pmtiles+```++(`vendor_pmtiles.sh` handles multipart upload, cache headers and a Range-request+verification against the public custom domain.)++Then **P13** (separate task, app code) points the style at the new file:++```jsonc+// maps/src/main/assets/style.json — protomaps + protomapsOnline sources+"url": "pmtiles://https://data.vayunmathur.com/v5.pmtiles"+```++…adds style layers for `safety`, and switches the country/state mask in+`CountryMap.kt` / `MyMapLayers.kt` from the `.fgb` assets to the+`admin_country` / `admin_region` PMTiles layers (matching on `ISO_A2` /+`iso_3166_2`, which are preserved).++> **Mask caveat for P13:** vector tiles clip polygons at tile boundaries. The+> admin layers are tiled with `--no-tile-size-limit --no-feature-limit+> --coalesce-densest-as-needed` and start at low zoom to keep country/region+> polygons as whole as possible for mask reassembly, but for a pixel-perfect+> full-country mask the app may still prefer querying the layer at a low zoom+> level. Evaluate during P13.++---++## Dry-run result (this checkout)++`tippecanoe`/`osmium`/`ogr2ogr` are not installed on the dev box, so the+tile-level build was not executed here. The **schema-mapping core** (the part+that defines the new `safety` + admin layers) was dry-run via the unit test and+passes:++```+$ python3 scripts/maps/test/test_normalize.py+...+26 passed, 0 failed+```++This validates: all five `kind` classifications (incl. DeFlock ALPR detection),+non-safety/non-point features dropped, `admin_level` mapping (2/4/8),+`ISO_A2` / `iso_3166_2` preservation, county-vs-city `admin_level` filtering, and+that every emitted line is valid GeoJSON (tippecanoe input). Run the metro dry+run above on a box with the toolchain installed for a full end-to-end check.
scripts/maps/build_admin_layers.sh
diff --git a/scripts/maps/build_admin_layers.sh b/scripts/maps/build_admin_layers.shnew file mode 100644index 0000000000..36bc2f6764--- /dev/null+++ b/scripts/maps/build_admin_layers.sh@@ -0,0 +1,123 @@+#!/bin/bash+set -euo pipefail++# build_admin_layers.sh — bake country/region/city admin borders into .pmtiles+#+# REPLACES the vendored FlatGeobuf assets maps/src/main/assets/admin0.fgb+# (countries, keyed by ISO_A2) and admin1.fgb (states/provinces, keyed by+# iso_3166_2), and adds a city layer. The normalized attributes keep those+# exact ISO keys so P13 can point CountryMap.kt at the PMTiles instead of .fgb+# with no attribute changes.+#+# Source layers produced (one .pmtiles each; merged later by build_v5_pmtiles.sh):+# admin_country admin_level=2 attr: name, name_en, ISO_A2, iso_a3+# admin_region admin_level=4 attr: name, name_en, iso_3166_2, country_iso+# admin_city admin_level=8 attr: name, name_en+#+# Data sources (documented choice, see README.md):+# country/region -> Natural Earth 10m (matches .fgb schema, clean geometry)+# city -> OSM boundary=administrative admin_level=8 (NE has no cities)+#+# Usage:+# ./build_admin_layers.sh --outdir out/ [--pbf planet.osm.pbf] [--ne-dir ne/] \+# [--bbox minlon,minlat,maxlon,maxlat] [--no-city]+#+# Tools required: ogr2ogr (GDAL), tippecanoe, python3; osmium + a --pbf for cities.++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+OUTDIR="."+PBF=""+NE_DIR="ne"+BBOX=""+WITH_CITY=1++NE_COUNTRIES_URL="https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_countries.zip"+NE_REGIONS_URL="https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_1_states_provinces.zip"++while [[ $# -gt 0 ]]; do+ case "$1" in+ --outdir) OUTDIR="$2"; shift 2 ;;+ --pbf) PBF="$2"; shift 2 ;;+ --ne-dir) NE_DIR="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ --no-city) WITH_CITY=0; shift ;;+ -h|--help) sed -n '4,32p' "$0" | sed 's/^# \?//'; exit 0 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++command -v ogr2ogr >/dev/null || { echo "ERROR: ogr2ogr (GDAL) not installed" >&2; exit 1; }+command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe not installed" >&2; exit 1; }+mkdir -p "$OUTDIR" "$NE_DIR"++# --- Fetch Natural Earth shapefiles if missing ---+fetch_ne() {+ local url="$1" zip="$2" shp="$3"+ if [[ -f "$NE_DIR/$shp" ]]; then return; fi+ echo "[admin] downloading $(basename "$url")"+ curl -fL --retry 3 -o "$NE_DIR/$zip" "$url"+ ( cd "$NE_DIR" && unzip -o "$zip" >/dev/null )+}+fetch_ne "$NE_COUNTRIES_URL" ne_admin0.zip ne_10m_admin_0_countries.shp+fetch_ne "$NE_REGIONS_URL" ne_admin1.zip ne_10m_admin_1_states_provinces.shp++# ogr2ogr optional bbox clip: -spat minx miny maxx maxy+SPAT=()+if [[ -n "$BBOX" ]]; then+ IFS=',' read -r X0 Y0 X1 Y1 <<< "$BBOX"+ SPAT=(-spat "$X0" "$Y0" "$X1" "$Y1")+fi++build_layer() { # level layer_name minzoom maxzoom input_geojson+ local level="$1" layer="$2" minz="$3" maxz="$4" geojson="$5"+ echo "[admin] tiling $layer (z$minz-$maxz)"+ # Admin polygons must stay whole enough to reassemble for the dimming mask,+ # so we disable size/feature limits and avoid aggressive dropping.+ tippecanoe --force \+ -o "$OUTDIR/$layer.pmtiles" \+ -l "$layer" \+ --minimum-zoom="$minz" \+ --maximum-zoom="$maxz" \+ --no-tile-size-limit \+ --no-feature-limit \+ --coalesce-densest-as-needed \+ --detect-shared-borders \+ --simplification=4 \+ "$geojson"+}++echo "[admin] country (Natural Earth admin_0)"+ogr2ogr -f GeoJSON "${SPAT[@]}" /vsistdout/ "$NE_DIR/ne_10m_admin_0_countries.shp" \+ | python3 "$HERE/normalize_admin.py" --level country > "$OUTDIR/admin_country.geojsonseq"+build_layer 2 admin_country 0 8 "$OUTDIR/admin_country.geojsonseq"++echo "[admin] region (Natural Earth admin_1)"+ogr2ogr -f GeoJSON "${SPAT[@]}" /vsistdout/ "$NE_DIR/ne_10m_admin_1_states_provinces.shp" \+ | python3 "$HERE/normalize_admin.py" --level region > "$OUTDIR/admin_region.geojsonseq"+build_layer 4 admin_region 3 9 "$OUTDIR/admin_region.geojsonseq"++if [[ "$WITH_CITY" == "1" ]]; then+ if [[ -z "$PBF" ]]; then+ echo "[admin] --no-city not set but no --pbf given; skipping city layer" >&2+ else+ command -v osmium >/dev/null || { echo "ERROR: osmium needed for city layer" >&2; exit 1; }+ [[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }+ TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT+ SRC="$PBF"+ if [[ -n "$BBOX" ]]; then+ osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+ SRC="$TMP/metro.osm.pbf"+ fi+ echo "[admin] city (OSM admin_level=8 boundaries)"+ # Keep boundary relations/ways; osmium export assembles the polygon areas+ # from closed ways + multipolygon/boundary relations automatically.+ osmium tags-filter --overwrite "$SRC" \+ r/boundary=administrative w/boundary=administrative \+ -o "$TMP/admin_raw.osm.pbf"+ osmium export -f geojsonseq --overwrite "$TMP/admin_raw.osm.pbf" \+ | python3 "$HERE/normalize_admin.py" --level city > "$OUTDIR/admin_city.geojsonseq"+ build_layer 8 admin_city 6 12 "$OUTDIR/admin_city.geojsonseq"+ fi+fi++echo "[admin] done -> $OUTDIR/admin_{country,region,city}.pmtiles"
scripts/maps/build_base_layers.sh
diff --git a/scripts/maps/build_base_layers.sh b/scripts/maps/build_base_layers.shnew file mode 100644index 0000000000..b4a59b5440--- /dev/null+++ b/scripts/maps/build_base_layers.sh@@ -0,0 +1,90 @@+#!/bin/bash+set -euo pipefail++# build_base_layers.sh — produce the Protomaps-schema base map as .pmtiles+#+# The app's style.json (maps/src/main/assets/style.json) expects the Protomaps+# basemaps schema, i.e. these source-layers:+# earth, landcover, landuse, water, roads, buildings, boundaries, pois, places+# We MUST keep those exact names so the style keeps working unchanged.+#+# Two supported paths:+#+# (A) build — regenerate from OSM with Planetiler + the official Protomaps+# basemaps profile (produces the exact schema above). This is the+# clean, reproducible path. Requires Java 21 + the protomaps+# basemaps jar (built once from github.com/protomaps/basemaps).+#+# (B) reuse — download the upstream prebuilt Protomaps v4.pmtiles and use it+# verbatim as the base. Fast; identical schema. Use when you only+# want to refresh the safety/admin overlays on top of a known base.+#+# Usage:+# ./build_base_layers.sh --mode build --area planet --out base.pmtiles \+# --jar protomaps-basemap-HEAD-with-deps.jar+# ./build_base_layers.sh --mode build --area california --out base.pmtiles --jar ...+# ./build_base_layers.sh --mode reuse --out base.pmtiles+#+# Options:+# --mode build|reuse (default: reuse)+# --out FILE output base .pmtiles (default base.pmtiles)+# --area NAME|FILE Planetiler --area (a geofabrik name like "california",+# "planet", or a path to a .osm.pbf). build mode only.+# --jar FILE Protomaps basemap planetiler jar. build mode only.+# --source URL upstream base for reuse mode+# (default https://demo-bucket.protomaps.com/v4.pmtiles)+# --bbox BOX optional metro bbox for a small build/extract dry run++MODE="reuse"+OUT="base.pmtiles"+AREA="planet"+JAR=""+SOURCE_URL="https://demo-bucket.protomaps.com/v4.pmtiles"+BBOX=""++while [[ $# -gt 0 ]]; do+ case "$1" in+ --mode) MODE="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --area) AREA="$2"; shift 2 ;;+ --jar) JAR="$2"; shift 2 ;;+ --source) SOURCE_URL="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ -h|--help) sed -n '4,40p' "$0" | sed 's/^# \?//'; exit 0 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++case "$MODE" in+ build)+ command -v java >/dev/null || { echo "ERROR: java (21+) required for build mode" >&2; exit 1; }+ [[ -n "$JAR" && -f "$JAR" ]] || {+ echo "ERROR: --jar protomaps basemap jar required for build mode." >&2+ echo " Build it once:" >&2+ echo " git clone https://github.com/protomaps/basemaps && cd basemaps/tiles" >&2+ echo " mvn -q clean package" >&2+ echo " # -> target/protomaps-basemap-HEAD-with-deps.jar" >&2+ exit 1+ }+ ARGS=(--force --download --output="$OUT")+ # --area accepts a geofabrik name or a local .osm.pbf path.+ if [[ -f "$AREA" ]]; then ARGS+=(--osm-path="$AREA"); else ARGS+=(--area="$AREA"); fi+ [[ -n "$BBOX" ]] && ARGS+=(--bounds="$BBOX")+ echo "[base] planetiler build: area=$AREA -> $OUT"+ java -Xmx${JAVA_XMX:-8g} -jar "$JAR" "${ARGS[@]}"+ ;;+ reuse)+ command -v pmtiles >/dev/null || echo "[base] note: install go-pmtiles for --bbox reuse extracts"+ if [[ -n "$BBOX" ]]; then+ command -v pmtiles >/dev/null || { echo "ERROR: pmtiles CLI required for --bbox reuse" >&2; exit 1; }+ echo "[base] reuse+extract $SOURCE_URL bbox=$BBOX -> $OUT"+ pmtiles extract "$SOURCE_URL" "$OUT" --bbox="$BBOX"+ else+ echo "[base] downloading upstream base $SOURCE_URL -> $OUT (137 GB for planet!)"+ curl -fL --retry 3 -o "$OUT" "$SOURCE_URL"+ fi+ ;;+ *) echo "ERROR: --mode must be build or reuse" >&2; exit 1 ;;+esac++echo "[base] done: $OUT"
scripts/maps/build_safety_layer.sh
diff --git a/scripts/maps/build_safety_layer.sh b/scripts/maps/build_safety_layer.shnew file mode 100644index 0000000000..645295733b--- /dev/null+++ b/scripts/maps/build_safety_layer.sh@@ -0,0 +1,92 @@+#!/bin/bash+set -euo pipefail++# build_safety_layer.sh — bake the `safety` road-furniture layer into a .pmtiles+#+# Extracts speed cameras, ALPR/surveillance (DeFlock), stop signs and traffic+# signals from an OSM extract and tiles them into a single-layer PMTiles file.+# These are baked at build time so the app never needs a runtime Overpass query.+#+# Source layer produced: safety (attr: kind, name?, direction?, operator?, ref?)+# kind ∈ { speed_camera, alpr, surveillance, stop_sign, traffic_signals }+#+# Usage:+# ./build_safety_layer.sh --pbf planet.osm.pbf --out safety.pmtiles+# ./build_safety_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --out safety.pmtiles+#+# Options:+# --pbf FILE Input OSM .pbf (required)+# --out FILE Output .pmtiles (default: safety.pmtiles)+# --bbox BOX Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)+# --minzoom N tippecanoe minzoom (default 10)+# --maxzoom N tippecanoe maxzoom (default 16)+# --keep-tmp Don't delete intermediate files+#+# Tools required: osmium (osmium-tool), tippecanoe (>=2.x, writes .pmtiles), python3++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PBF=""+OUT="safety.pmtiles"+BBOX=""+MINZOOM=10+MAXZOOM=16+KEEP_TMP=0++while [[ $# -gt 0 ]]; do+ case "$1" in+ --pbf) PBF="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ --minzoom) MINZOOM="$2"; shift 2 ;;+ --maxzoom) MAXZOOM="$2"; shift 2 ;;+ --keep-tmp) KEEP_TMP=1; shift ;;+ -h|--help) sed -n '4,30p' "$0" | sed 's/^# \?//'; exit 0 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++[[ -n "$PBF" ]] || { echo "ERROR: --pbf required" >&2; exit 1; }+[[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }+command -v osmium >/dev/null || { echo "ERROR: osmium-tool not installed" >&2; exit 1; }+command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe not installed" >&2; exit 1; }++TMP="$(mktemp -d)"+cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; }+trap cleanup EXIT++SRC="$PBF"+if [[ -n "$BBOX" ]]; then+ echo "[safety] extracting metro bbox $BBOX"+ osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+ SRC="$TMP/metro.osm.pbf"+fi++echo "[safety] filtering safety/road-furniture nodes"+# Keep only the node types we bake. `enforcement=maxspeed` catches speed-camera+# nodes tagged via the enforcement relation scheme.+osmium tags-filter --overwrite "$SRC" \+ n/highway=speed_camera,stop,traffic_signals \+ n/man_made=surveillance \+ n/enforcement=maxspeed \+ -o "$TMP/safety_raw.osm.pbf"++echo "[safety] exporting to GeoJSON + normalizing kinds"+osmium export -f geojsonseq --overwrite "$TMP/safety_raw.osm.pbf" \+ | python3 "$HERE/normalize_safety.py" \+ > "$TMP/safety.geojsonseq"++FEATURES="$(wc -l < "$TMP/safety.geojsonseq" | tr -d ' ')"+echo "[safety] $FEATURES normalized feature(s)"+[[ "$FEATURES" -gt 0 ]] || echo "[safety] WARNING: 0 features — check bbox/extract"++echo "[safety] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"+tippecanoe --force \+ -o "$OUT" \+ -l safety \+ --minimum-zoom="$MINZOOM" \+ --maximum-zoom="$MAXZOOM" \+ --drop-densest-as-needed \+ --extend-zooms-if-still-dropping \+ "$TMP/safety.geojsonseq"++echo "[safety] done: $OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shnew file mode 100644index 0000000000..156ef78fab--- /dev/null+++ b/scripts/maps/build_v5_pmtiles.sh@@ -0,0 +1,132 @@+#!/bin/bash+set -euo pipefail++# build_v5_pmtiles.sh — build the custom v5.pmtiles for the maps app.+#+# v5.pmtiles = Protomaps base schema (unchanged, style.json-compatible)+# + safety (baked road-furniture: cameras/ALPR/stops/signals)+# + admin_country / admin_region / admin_city (borders; replaces .fgb)+#+# This single file REPLACES both:+# * https://data.vayunmathur.com/v4.pmtiles (base tiles)+# * maps/src/main/assets/admin0.fgb + admin1.fgb (border masks)+#+# Pipeline (each step is a standalone script in this dir):+# 1. build_base_layers.sh -> base.pmtiles (planetiler OR reuse v4)+# 2. build_safety_layer.sh -> safety.pmtiles (osmium + tippecanoe)+# 3. build_admin_layers.sh -> admin_*.pmtiles (Natural Earth/OSM + tippecanoe)+# 4. tile-join -> v5.pmtiles (merge all layers)+#+# Full planet build is the user's infra step (large + long). Prove correctness+# first with a metro dry run:+# ./build_v5_pmtiles.sh --pbf norcal.osm.pbf --bbox -122.6,37.2,-121.7,37.9 \+# --base-mode reuse --out v5-sf.pmtiles+#+# Planet build:+# ./build_v5_pmtiles.sh --pbf planet.osm.pbf --base-mode build \+# --base-jar protomaps-basemap-HEAD-with-deps.jar --out v5.pmtiles+#+# Options:+# --pbf FILE OSM extract for safety + city layers (required unless --skip-*)+# --out FILE final output (default v5.pmtiles)+# --workdir DIR scratch dir for intermediates (default ./v5_work)+# --bbox BOX metro bbox "minlon,minlat,maxlon,maxlat" (dry runs)+# --base-mode M build|reuse (passed to build_base_layers.sh; default reuse)+# --base-jar FILE protomaps basemap jar (base-mode build)+# --base-area A planetiler area name/path (base-mode build; default planet)+# --skip-base don't (re)build base; expects <workdir>/base.pmtiles present+# --skip-safety omit safety layer+# --skip-admin omit admin layers+# --keep-work keep intermediates+#+# Tools: tile-join + tippecanoe, osmium, ogr2ogr (GDAL), python3, and either+# java+planetiler (base build) or curl/pmtiles (base reuse). See README.md.++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PBF=""+OUT="v5.pmtiles"+WORK="./v5_work"+BBOX=""+BASE_MODE="reuse"+BASE_JAR=""+BASE_AREA="planet"+SKIP_BASE=0+SKIP_SAFETY=0+SKIP_ADMIN=0+KEEP_WORK=0++while [[ $# -gt 0 ]]; do+ case "$1" in+ --pbf) PBF="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --workdir) WORK="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ --base-mode) BASE_MODE="$2"; shift 2 ;;+ --base-jar) BASE_JAR="$2"; shift 2 ;;+ --base-area) BASE_AREA="$2"; shift 2 ;;+ --skip-base) SKIP_BASE=1; shift ;;+ --skip-safety) SKIP_SAFETY=1; shift ;;+ --skip-admin) SKIP_ADMIN=1; shift ;;+ --keep-work) KEEP_WORK=1; shift ;;+ -h|--help) sed -n '4,55p' "$0" | sed 's/^# \?//'; exit 0 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++command -v tile-join >/dev/null || { echo "ERROR: tile-join (tippecanoe pkg) not installed" >&2; exit 1; }+mkdir -p "$WORK"++INPUTS=()++# --- 1. base ---+BASE="$WORK/base.pmtiles"+if [[ "$SKIP_BASE" == "1" ]]; then+ [[ -f "$BASE" ]] || { echo "ERROR: --skip-base but $BASE missing" >&2; exit 1; }+ echo "[v5] using existing base $BASE"+else+ BASE_ARGS=(--mode "$BASE_MODE" --out "$BASE")+ [[ -n "$BBOX" ]] && BASE_ARGS+=(--bbox "$BBOX")+ [[ "$BASE_MODE" == "build" ]] && BASE_ARGS+=(--jar "$BASE_JAR" --area "$BASE_AREA")+ "$HERE/build_base_layers.sh" "${BASE_ARGS[@]}"+fi+INPUTS+=("$BASE")++# --- 2. safety ---+if [[ "$SKIP_SAFETY" == "0" ]]; then+ [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for safety layer (or --skip-safety)" >&2; exit 1; }+ SAFETY_ARGS=(--pbf "$PBF" --out "$WORK/safety.pmtiles")+ [[ -n "$BBOX" ]] && SAFETY_ARGS+=(--bbox "$BBOX")+ "$HERE/build_safety_layer.sh" "${SAFETY_ARGS[@]}"+ INPUTS+=("$WORK/safety.pmtiles")+fi++# --- 3. admin ---+if [[ "$SKIP_ADMIN" == "0" ]]; then+ ADMIN_ARGS=(--outdir "$WORK/admin")+ [[ -n "$PBF" ]] && ADMIN_ARGS+=(--pbf "$PBF")+ [[ -n "$BBOX" ]] && ADMIN_ARGS+=(--bbox "$BBOX")+ [[ -z "$PBF" ]] && ADMIN_ARGS+=(--no-city)+ "$HERE/build_admin_layers.sh" "${ADMIN_ARGS[@]}"+ for l in admin_country admin_region admin_city; do+ [[ -f "$WORK/admin/$l.pmtiles" ]] && INPUTS+=("$WORK/admin/$l.pmtiles")+ done+fi++# --- 4. merge ---+echo "[v5] merging ${#INPUTS[@]} source(s) -> $OUT"+printf ' + %s\n' "${INPUTS[@]}"+# --no-tile-size-limit: don't drop features when combining dense base + overlays.+tile-join --force --no-tile-size-limit -o "$OUT" "${INPUTS[@]}"++SIZE="$(stat -c%s "$OUT" 2>/dev/null || stat -f%z "$OUT" 2>/dev/null || echo '?')"+echo "[v5] done: $OUT (${SIZE} bytes)"+echo ""+echo "Layers now in $OUT:"+echo " base : earth landcover landuse water roads buildings boundaries pois places"+echo " new : safety admin_country admin_region admin_city"+echo ""+echo "Publish (bump key to v5.pmtiles):"+echo " R2_KEY=v5.pmtiles ./scripts/maps/vendor_pmtiles.sh --local $OUT --source $OUT"+echo "Then P13 updates style.json url -> pmtiles://https://data.vayunmathur.com/v5.pmtiles"++[[ "$KEEP_WORK" == "1" ]] || echo "(intermediates kept in $WORK; pass --keep-work to silence)"
scripts/maps/normalize_admin.py
diff --git a/scripts/maps/normalize_admin.py b/scripts/maps/normalize_admin.pynew file mode 100644index 0000000000..d6d58ded74--- /dev/null+++ b/scripts/maps/normalize_admin.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""normalize_admin.py — normalize admin-boundary polygons for the admin PMTiles layers.++Produces the country / region / city border layers that REPLACE the bundled+FlatGeobuf assets (maps/src/main/assets/admin0.fgb, admin1.fgb). The current+app (data/CountryMap.kt) queries those files by `ISO_A2` (countries) and+`iso_3166_2` (states/provinces) to draw a dimming inverted mask; we preserve+those exact attribute keys so P13 can swap the data source with no schema change.++Source of truth (documented choice — see README.md):+ * country (admin_level=2) Natural Earth ne_10m_admin_0_countries+ * region (admin_level=4) Natural Earth ne_10m_admin_1_states_provinces+ * city (admin_level=8) OpenStreetMap boundary=administrative admin_level=8+Rationale: the vendored .fgb are Natural-Earth-derived and keyed by ISO_A2 /+iso_3166_2, so NE gives byte-for-byte attribute compatibility + clean+generalized geometry ideal for the mask. City polygons don't exist in NE, so+those come from OSM admin_level=8.++Reads GeoJSON (FeatureCollection or geojsonseq) on stdin; writes geojsonseq.++Usage:+ ogr2ogr -f GeoJSON /vsistdout/ ne_10m_admin_0_countries.shp \+ | python3 normalize_admin.py --level country > admin_country.geojsonseq+ ogr2ogr -f GeoJSON /vsistdout/ ne_10m_admin_1_states_provinces.shp \+ | python3 normalize_admin.py --level region > admin_region.geojsonseq+ osmium export -f geojsonseq city_raw.osm.pbf \+ | python3 normalize_admin.py --level city > admin_city.geojsonseq++Pure stdlib — no GDAL/pyosmium needed to run or test.+"""+from __future__ import annotations++import argparse+import json+import sys+from typing import Any, Iterable, Iterator, Optional++LEVELS = {"country": 2, "region": 4, "city": 8}+++def _get(tags: dict[str, Any], *keys: str) -> Optional[Any]:+ for k in keys:+ v = tags.get(k)+ if v not in (None, ""):+ return v+ return None+++def build_country(tags: dict[str, Any]) -> dict[str, Any]:+ props: dict[str, Any] = {"admin_level": 2}+ name = _get(tags, "NAME_EN", "name:en", "NAME", "name")+ if name:+ props["name"] = name+ name_en = _get(tags, "NAME_EN", "name:en")+ if name_en:+ props["name_en"] = name_en+ iso_a2 = _get(tags, "ISO_A2", "ISO_A2_EH", "iso_a2", "ISO3166-1:alpha2")+ if iso_a2:+ props["ISO_A2"] = str(iso_a2).upper()+ iso_a3 = _get(tags, "ISO_A3", "ISO_A3_EH", "iso_a3")+ if iso_a3:+ props["iso_a3"] = str(iso_a3).upper()+ return props+++def build_region(tags: dict[str, Any]) -> dict[str, Any]:+ props: dict[str, Any] = {"admin_level": 4}+ name = _get(tags, "name_en", "NAME_EN", "name", "NAME")+ if name:+ props["name"] = name+ name_en = _get(tags, "name_en", "NAME_EN", "name:en")+ if name_en:+ props["name_en"] = name_en+ # Natural Earth admin_1 exposes ISO 3166-2 as `iso_3166_2`.+ iso = _get(tags, "iso_3166_2", "ISO_3166_2", "iso3166_2")+ if iso:+ props["iso_3166_2"] = str(iso)+ parent = _get(tags, "iso_a2", "ISO_A2", "adm0_a3")+ if parent:+ props["country_iso"] = str(parent).upper()+ return props+++def build_city(tags: dict[str, Any]) -> dict[str, Any]:+ props: dict[str, Any] = {"admin_level": 8}+ name = _get(tags, "name:en", "name", "NAME_EN", "NAME")+ if name:+ props["name"] = name+ name_en = _get(tags, "name:en", "NAME_EN")+ if name_en:+ props["name_en"] = name_en+ return props+++BUILDERS = {"country": build_country, "region": build_region, "city": build_city}+++def keep_geometry(geom: dict[str, Any]) -> bool:+ return geom.get("type") in ("Polygon", "MultiPolygon")+++def is_admin_level(tags: dict[str, Any], level: int) -> bool:+ """For OSM city input, filter to boundary=administrative + matching admin_level."""+ if "admin_level" not in tags and "boundary" not in tags:+ return True # Natural Earth rows: no OSM admin tagging, accept.+ if str(tags.get("boundary", "administrative")) != "administrative":+ return False+ try:+ return int(str(tags.get("admin_level", level))) == level+ except ValueError:+ return False+++def iter_features(raw: str) -> Iterator[dict[str, Any]]:+ stripped = raw.lstrip()+ if stripped.startswith("{") and '"FeatureCollection"' in stripped[:200]:+ try:+ obj = json.loads(raw)+ if obj.get("type") == "FeatureCollection":+ yield from obj.get("features", [])+ return+ except json.JSONDecodeError:+ pass+ for line in raw.splitlines():+ line = line.strip().lstrip("\x1e").strip()+ if not line:+ continue+ try:+ obj = json.loads(line)+ except json.JSONDecodeError:+ continue+ if obj.get("type") == "Feature":+ yield obj+ elif obj.get("type") == "FeatureCollection":+ yield from obj.get("features", [])+++def normalize(features: Iterable[dict[str, Any]], level_name: str) -> Iterator[dict[str, Any]]:+ level = LEVELS[level_name]+ build = BUILDERS[level_name]+ for feature in features:+ geom = feature.get("geometry") or {}+ if not keep_geometry(geom):+ continue+ tags = feature.get("properties") or {}+ if level_name == "city" and not is_admin_level(tags, level):+ continue+ props = build(tags)+ if "name" not in props:+ continue # unnamed borders are useless for the mask/labels+ yield {"type": "Feature", "geometry": geom, "properties": props}+++def main(argv: list[str]) -> int:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--level", required=True, choices=sorted(LEVELS))+ args = ap.parse_args(argv)++ raw = sys.stdin.read()+ count = 0+ out = sys.stdout+ for feature in normalize(iter_features(raw), args.level):+ out.write(json.dumps(feature, separators=(",", ":"), ensure_ascii=False))+ out.write("\n")+ count += 1+ sys.stderr.write(f"normalize_admin[{args.level}]: emitted {count} feature(s)\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))
scripts/maps/normalize_safety.py
diff --git a/scripts/maps/normalize_safety.py b/scripts/maps/normalize_safety.pynew file mode 100644index 0000000000..2d7eb9d77b--- /dev/null+++ b/scripts/maps/normalize_safety.py@@ -0,0 +1,147 @@+#!/usr/bin/env python3+"""normalize_safety.py — map OSM road-furniture/safety tags to the `safety` PMTiles layer.++Reads GeoJSON features (a FeatureCollection on stdin, or newline-delimited+GeoJSON a.k.a. geojsonseq, optionally RS-prefixed as produced by+`osmium export -f geojsonseq -r`) and writes newline-delimited GeoJSON+containing only the features that belong in the baked `safety` source-layer.++Every emitted feature carries a normalized `kind` attribute so the app can+style them without any runtime Overpass query:++ speed_camera highway=speed_camera | enforcement=maxspeed+ alpr man_made=surveillance + ALPR signals (DeFlock / Flock Safety)+ surveillance man_made=surveillance (any other camera)+ stop_sign highway=stop+ traffic_signals highway=traffic_signals++Usage:+ osmium export -f geojsonseq safety_raw.osm.pbf | python3 normalize_safety.py > safety.geojsonseq+ python3 normalize_safety.py < features.geojson > safety.geojsonseq++The script is pure stdlib so it can run (and be unit-tested) without pyosmium,+GDAL, or tippecanoe installed.+"""+from __future__ import annotations++import json+import sys+from typing import Any, Iterable, Iterator, Optional+++def _truthy(v: Optional[str]) -> bool:+ return v not in (None, "", "no", "false", "0")+++def classify(tags: dict[str, Any]) -> Optional[str]:+ """Return the `safety` layer `kind` for a set of OSM tags, or None to drop."""+ highway = tags.get("highway")+ man_made = tags.get("man_made")++ if highway == "speed_camera":+ return "speed_camera"+ # A node on an enforcement=maxspeed relation is often tagged directly.+ if tags.get("enforcement") == "maxspeed":+ return "speed_camera"++ if man_made == "surveillance":+ # DeFlock (deflock.me) tags automated license-plate readers as+ # man_made=surveillance with surveillance:type=ALPR (or camera:type=alpr).+ # Flock Safety hardware is the dominant operator/manufacturer.+ surv_type = str(tags.get("surveillance:type", "")).lower()+ cam_type = str(tags.get("camera:type", "")).lower()+ operator = str(tags.get("operator", "")).lower()+ manufacturer = str(tags.get("manufacturer", "")).lower()+ if (+ "alpr" in surv_type+ or "anpr" in surv_type+ or cam_type in ("alpr", "anpr")+ or "flock" in operator+ or "flock" in manufacturer+ ):+ return "alpr"+ return "surveillance"++ if highway == "stop":+ return "stop_sign"+ if highway == "traffic_signals":+ return "traffic_signals"++ return None+++def build_properties(kind: str, tags: dict[str, Any], feature: dict[str, Any]) -> dict[str, Any]:+ props: dict[str, Any] = {"kind": kind}+ # Carry a small, stable set of attributes useful for display / dedup.+ for src, dst in (+ ("name", "name"),+ ("direction", "direction"),+ ("operator", "operator"),+ ("ref", "ref"),+ ("surveillance:type", "surveillance_type"),+ ):+ val = tags.get(src)+ if _truthy(val):+ props[dst] = val+ osm_id = feature.get("id") or tags.get("@id") or tags.get("id") or tags.get("osm_id")+ if osm_id is not None:+ props["osm_id"] = str(osm_id)+ return props+++def iter_features(raw: str) -> Iterator[dict[str, Any]]:+ """Yield GeoJSON features from either a FeatureCollection or geojsonseq text."""+ stripped = raw.lstrip()+ if stripped.startswith("{") and '"FeatureCollection"' in stripped[:200]:+ try:+ obj = json.loads(raw)+ if obj.get("type") == "FeatureCollection":+ yield from obj.get("features", [])+ return+ except json.JSONDecodeError:+ pass # fall through to line mode+ for line in raw.splitlines():+ line = line.strip().lstrip("\x1e").strip() # drop RS separator + ws+ if not line:+ continue+ try:+ obj = json.loads(line)+ except json.JSONDecodeError:+ continue+ if obj.get("type") == "Feature":+ yield obj+ elif obj.get("type") == "FeatureCollection":+ yield from obj.get("features", [])+++def normalize(features: Iterable[dict[str, Any]]) -> Iterator[dict[str, Any]]:+ for feature in features:+ geom = feature.get("geometry") or {}+ # Safety furniture is node-based; keep only points.+ if geom.get("type") != "Point":+ continue+ tags = feature.get("properties") or {}+ kind = classify(tags)+ if kind is None:+ continue+ yield {+ "type": "Feature",+ "geometry": geom,+ "properties": build_properties(kind, tags, feature),+ }+++def main(argv: list[str]) -> int:+ raw = sys.stdin.read()+ count = 0+ out = sys.stdout+ for feature in normalize(iter_features(raw)):+ out.write(json.dumps(feature, separators=(",", ":"), ensure_ascii=False))+ out.write("\n")+ count += 1+ sys.stderr.write(f"normalize_safety: emitted {count} feature(s)\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))
scripts/maps/test/fixtures/admin_city_sample.geojsonseq
diff --git a/scripts/maps/test/fixtures/admin_city_sample.geojsonseq b/scripts/maps/test/fixtures/admin_city_sample.geojsonseqnew file mode 100644index 0000000000..5829d6577b--- /dev/null+++ b/scripts/maps/test/fixtures/admin_city_sample.geojsonseq@@ -0,0 +1,3 @@+{"type":"Feature","properties":{"boundary":"administrative","admin_level":"8","name":"San Francisco","name:en":"San Francisco"},"geometry":{"type":"Polygon","coordinates":[[[-122.52,37.70],[-122.35,37.70],[-122.35,37.83],[-122.52,37.83],[-122.52,37.70]]]}}+{"type":"Feature","properties":{"boundary":"administrative","admin_level":"6","name":"Some County"},"geometry":{"type":"Polygon","coordinates":[[[-122.9,37.1],[-121.2,37.1],[-121.2,38.5],[-122.9,38.5],[-122.9,37.1]]]}}+{"type":"Feature","properties":{"boundary":"administrative","admin_level":"8","name":"Oakland"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-122.35,37.70],[-122.10,37.70],[-122.10,37.90],[-122.35,37.90],[-122.35,37.70]]]]}}
scripts/maps/test/fixtures/admin_country_sample.geojson
diff --git a/scripts/maps/test/fixtures/admin_country_sample.geojson b/scripts/maps/test/fixtures/admin_country_sample.geojsonnew file mode 100644index 0000000000..eacc2a6627--- /dev/null+++ b/scripts/maps/test/fixtures/admin_country_sample.geojson@@ -0,0 +1,15 @@+{+ "type": "FeatureCollection",+ "features": [+ {+ "type": "Feature",+ "properties": {"NAME": "United States of America", "NAME_EN": "United States of America", "ISO_A2": "US", "ISO_A3": "USA"},+ "geometry": {"type": "Polygon", "coordinates": [[[-124.7,32.5],[-114.1,32.5],[-114.1,42.0],[-124.7,42.0],[-124.7,32.5]]]}+ },+ {+ "type": "Feature",+ "properties": {"NAME": "Antarctica sliver", "ISO_A2": "-99"},+ "geometry": {"type": "Point", "coordinates": [0, -89]}+ }+ ]+}
scripts/maps/test/fixtures/admin_region_sample.geojsonseq
diff --git a/scripts/maps/test/fixtures/admin_region_sample.geojsonseq b/scripts/maps/test/fixtures/admin_region_sample.geojsonseqnew file mode 100644index 0000000000..0db757529a--- /dev/null+++ b/scripts/maps/test/fixtures/admin_region_sample.geojsonseq@@ -0,0 +1,2 @@+{"type":"Feature","properties":{"name":"California","name_en":"California","iso_3166_2":"US-CA","iso_a2":"US"},"geometry":{"type":"Polygon","coordinates":[[[-124.4,32.5],[-114.1,32.5],[-114.1,42.0],[-124.4,42.0],[-124.4,32.5]]]}}+{"type":"Feature","properties":{"name":"Nevada","iso_3166_2":"US-NV","iso_a2":"US"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-120.0,35.0],[-114.0,35.0],[-114.0,42.0],[-120.0,42.0],[-120.0,35.0]]]]}}
scripts/maps/test/fixtures/safety_sample.geojsonseq
diff --git a/scripts/maps/test/fixtures/safety_sample.geojsonseq b/scripts/maps/test/fixtures/safety_sample.geojsonseqnew file mode 100644index 0000000000..ff192da6c3--- /dev/null+++ b/scripts/maps/test/fixtures/safety_sample.geojsonseq@@ -0,0 +1,9 @@+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4194,37.7749]},"properties":{"highway":"speed_camera","direction":"forward","id":"node/1001"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4180,37.7760]},"properties":{"enforcement":"maxspeed","id":"node/1002"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4170,37.7770]},"properties":{"man_made":"surveillance","surveillance:type":"ALPR","operator":"Flock Safety","id":"node/1003"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4160,37.7780]},"properties":{"man_made":"surveillance","camera:type":"alpr","id":"node/1004"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4150,37.7790]},"properties":{"man_made":"surveillance","surveillance:type":"camera","id":"node/1005"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4140,37.7800]},"properties":{"highway":"stop","id":"node/1006"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4130,37.7810]},"properties":{"highway":"traffic_signals","id":"node/1007"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.4120,37.7820]},"properties":{"amenity":"cafe","name":"Not Safety","id":"node/1008"}}+{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.41,37.78],[-122.40,37.79]]},"properties":{"highway":"stop","id":"way/2001"}}
scripts/maps/test/test_normalize.py
diff --git a/scripts/maps/test/test_normalize.py b/scripts/maps/test/test_normalize.pynew file mode 100644index 0000000000..ee71e6b528--- /dev/null+++ b/scripts/maps/test/test_normalize.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""test_normalize.py — dry-run / unit test for the safety + admin normalizers.++Runs the pure-Python schema-mapping core of the PMTiles pipeline against tiny+fixtures and asserts the emitted feature schema (source-layer attributes, `kind`+values, admin_level, ISO keys). This proves the safety + border layers are+generated correctly WITHOUT needing tippecanoe / osmium / GDAL installed.++Run:+ python3 scripts/maps/test/test_normalize.py+Exit code 0 = all assertions passed.+"""+from __future__ import annotations++import json+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+ROOT = HERE.parent+FIX = HERE / "fixtures"+sys.path.insert(0, str(ROOT))++import normalize_admin # noqa: E402+import normalize_safety # noqa: E402+++def _load(path: Path) -> str:+ return path.read_text(encoding="utf-8")+++def _features(raw: str) -> list[dict]:+ return list(normalize_safety.iter_features(raw))+++passed = 0+failed = 0+++def check(name: str, cond: bool, detail: str = "") -> None:+ global passed, failed+ if cond:+ passed += 1+ print(f" PASS {name}")+ else:+ failed += 1+ print(f" FAIL {name} {detail}")+++def test_safety() -> None:+ print("safety layer:")+ feats = list(normalize_safety.normalize(_features(_load(FIX / "safety_sample.geojsonseq"))))+ kinds = [f["properties"]["kind"] for f in feats]+ # 7 point safety features; cafe + LineString stop dropped.+ check("emits 7 features", len(feats) == 7, f"got {len(feats)}")+ check("speed_camera from highway", "speed_camera" in kinds)+ check("speed_camera from enforcement", kinds.count("speed_camera") == 2, f"kinds={kinds}")+ check("alpr (surveillance:type=ALPR)", "alpr" in kinds)+ check("alpr count == 2 (ALPR + camera:type)", kinds.count("alpr") == 2, f"kinds={kinds}")+ check("generic surveillance", "surveillance" in kinds)+ check("stop_sign", "stop_sign" in kinds)+ check("traffic_signals", "traffic_signals" in kinds)+ check("no non-safety leaked", "cafe" not in kinds and None not in kinds)+ check("all geometry Point", all(f["geometry"]["type"] == "Point" for f in feats))+ alpr = next(f for f in feats if f["properties"]["kind"] == "alpr" and f["properties"].get("operator"))+ check("alpr keeps operator", alpr["properties"]["operator"] == "Flock Safety")+ check("osm_id carried", all("osm_id" in f["properties"] for f in feats))+++def test_admin_country() -> None:+ print("admin_country layer:")+ raw = _load(FIX / "admin_country_sample.geojson")+ feats = list(normalize_admin.normalize(normalize_admin.iter_features(raw), "country"))+ check("only polygon kept (point dropped)", len(feats) == 1, f"got {len(feats)}")+ p = feats[0]["properties"]+ check("admin_level == 2", p["admin_level"] == 2)+ check("name present", p.get("name") == "United States of America")+ check("ISO_A2 preserved (matches admin0.fgb key)", p.get("ISO_A2") == "US")+ check("iso_a3 present", p.get("iso_a3") == "USA")+++def test_admin_region() -> None:+ print("admin_region layer:")+ raw = _load(FIX / "admin_region_sample.geojsonseq")+ feats = list(normalize_admin.normalize(normalize_admin.iter_features(raw), "region"))+ check("2 regions", len(feats) == 2, f"got {len(feats)}")+ p = feats[0]["properties"]+ check("admin_level == 4", p["admin_level"] == 4)+ check("iso_3166_2 preserved (matches admin1.fgb key)", p.get("iso_3166_2") == "US-CA")+ check("name present", p.get("name") == "California")+ check("country_iso derived", p.get("country_iso") == "US")+ check("MultiPolygon kept", feats[1]["geometry"]["type"] == "MultiPolygon")+++def test_admin_city() -> None:+ print("admin_city layer:")+ raw = _load(FIX / "admin_city_sample.geojsonseq")+ feats = list(normalize_admin.normalize(normalize_admin.iter_features(raw), "city"))+ names = sorted(f["properties"]["name"] for f in feats)+ check("only admin_level=8 kept (county dropped)", names == ["Oakland", "San Francisco"], f"got {names}")+ check("admin_level == 8", all(f["properties"]["admin_level"] == 8 for f in feats))+++def test_valid_geojson_output() -> None:+ """Every emitted line must be independently valid JSON (tippecanoe input)."""+ print("output validity:")+ raw = _load(FIX / "safety_sample.geojsonseq")+ lines = []+ for f in normalize_safety.normalize(_features(raw)):+ lines.append(json.dumps(f, separators=(",", ":")))+ ok = all(json.loads(l)["type"] == "Feature" for l in lines)+ check("geojsonseq lines re-parse as Features", ok)+++def main() -> int:+ test_safety()+ test_admin_country()+ test_admin_region()+ test_admin_city()+ test_valid_geojson_output()+ print(f"\n{passed} passed, {failed} failed")+ return 1 if failed else 0+++if __name__ == "__main__":+ raise SystemExit(main())