garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /tools/id_presets.py

raw

#!/usr/bin/env python3
"""Flatten iD's tagging schema into the Rust table `presets::TABLE` reads.

Why this exists
---------------
`places::CATEGORY_TABLE` is a hand-written 37-row map from OSM tags to twelve
coarse buckets, and it is the only thing that ever looked at a POI's tags: a
bakery, a butcher and a phone shop all arrive as `Shop`, the specific tag is
dropped at the classifier, and the proximity prompt says "(shop)" for all three.

The vocabulary that names those things properly already exists and is
maintained by the OSM community: `@openstreetmap/id-tagging-schema`, the
catalog behind the iD editor on openstreetmap.org (ISC licensed). It carries
~1,700 presets, each a tag pattern plus a human name and a list of search
synonyms, translated into 30-odd languages.

So this is an *import*, not an invention, and it runs at build-authoring time
rather than in the client: the output is a `const` Rust array, so there is no
asset to ship, no runtime parse, no fetch, and it works offline like every
other compiled-in table.

What is deliberately dropped
----------------------------
- **The edit fields** (`fields`, `moreFields`, and the whole `fields.json`).
  They describe forms for *editing* OSM, which this client does not do. They
  are also most of the schema's bulk.
- **Icon names.** iD's are maki/temaki/fontawesome sprite ids and this client
  has no icon atlas — its glyphs must be characters the bundled font stack
  actually has, which is what `PoiCategory::glyph` was so painfully tuned for
  (see its doc comment). Importing icon *names* we cannot draw would be a table
  of tofu. The glyph still comes from the coarse category; only the label gets
  more specific.
- **Non-English labels.** The client has no language setting yet, so shipping
  30 locales would be 30x the table for one that can be reached. `LOCALES`
  below is the single place that changes when it does.
- **Presets that are not a single `key=value`.** A tile POI carries raw OSM
  tags and we match one pair against them; iD's multi-tag presets (`amenity=
  fast_food` *and* `cuisine=burger`) need a matcher this table does not have,
  and their parent single-tag preset already covers the common case.
- **The search synonyms** (`terms`: "bistro", "coffee", "espresso" for a cafe).
  They are the natural fuel for searching the POIs already loaded around you,
  which this client cannot do yet — its search is Nominatim-only. Emitting them
  now would put 660 unread string arrays in the binary, so `terms()` below
  builds them and `render()` drops them: switch the two back on together when
  there is something to search.
- **`searchable: false` presets.** iD marks deprecated and internal entries
  that way; they exist to match old data, not to be shown to a person.

Usage
-----
    python3 tools/id_presets.py            # rewrite crates/geo/src/preset_table.rs
    python3 tools/id_presets.py --check    # non-zero exit if regeneration differs

Pin the version: a silent upstream bump would rewrite 1,700 labels under a diff
nobody reviewed.
"""

from __future__ import annotations

import argparse
import io
import json
import re
import sys
import tarfile
import urllib.request
from pathlib import Path

# Pinned on purpose — see the module docstring.
SCHEMA_VERSION = "7.1.1"
TARBALL = (
    "https://registry.npmjs.org/@openstreetmap/id-tagging-schema/-/"
    f"id-tagging-schema-{SCHEMA_VERSION}.tgz"
)

# Only the locales the client can actually select. One entry today.
LOCALES = ["en"]

# The OSM keys the Shortbread `pois` layer carries through. A preset keyed on
# anything else can never match a feature we read, so it would be dead weight in
# the binary. This list is verified against the real tile by
# `presets::tests::every_generated_key_is_one_the_tile_can_carry`.
POI_KEYS = [
    "aeroway",
    "amenity",
    "craft",
    "emergency",
    "healthcare",
    "historic",
    "leisure",
    "man_made",
    "natural",
    "office",
    "public_transport",
    "railway",
    "shop",
    "sport",
    "tourism",
]

OUT = Path(__file__).resolve().parent.parent / "crates/geo/src/preset_table.rs"

HEADER = '''\
//! Generated by `tools/id_presets.py` from `@openstreetmap/id-tagging-schema`
//! v{version} (ISC). **Do not edit by hand** — rerun the script.
//!
//! One row per single-tag iD preset whose key the `pois` tile layer can carry:
//! the OSM `key=value` it matches and the human label for it. Sorted by
//! `(key, value)` so lookup is a binary search.
//!
//! See the script's module docstring for what was dropped on the way in and
//! why — in particular the icons, which this client cannot draw, and the search
//! synonyms, which nothing reads yet.

/// `(key, value, label)`, sorted by `(key, value)`.
///
/// `rustfmt::skip` because this is generated: left to itself rustfmt explodes
/// the two dozen rows that overrun the width into five lines each, so the file
/// on disk stops matching what the script emits and `--check` reports drift on
/// every run for the rest of time.
#[rustfmt::skip]
pub(crate) const TABLE: &[(&str, &str, &str)] = &[
'''

FOOTER = "];\n"


def fetch_schema() -> tuple[dict, dict]:
    """Return `(presets, en_translations)` from the pinned npm tarball."""
    with urllib.request.urlopen(TARBALL) as response:
        blob = response.read()
    with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tar:

        def load(name: str) -> dict:
            member = tar.extractfile(f"package/dist/{name}")
            if member is None:
                raise SystemExit(f"{name} missing from the tarball")
            return json.load(member)

        presets = load("presets.json")
        names = {loc: load(f"translations/{loc}.json") for loc in LOCALES}
    return presets, names


def rust_str(value: str) -> str:
    escaped = value.replace("\\", "\\\\").replace('"', '\\"')
    return f'"{escaped}"'


def rows(presets: dict, names: dict) -> list[tuple[str, str, str, list[str]]]:
    labels = names["en"]["en"]["presets"]["presets"]
    keys = set(POI_KEYS)
    out = []
    for preset_id, preset in presets.items():
        if preset.get("searchable") is False:
            continue
        tags = preset.get("tags") or {}
        if len(tags) != 1:
            continue
        (key, value), = tags.items()
        if key not in keys or value == "*":
            continue
        translated = labels.get(preset_id) or {}
        label = translated.get("name")
        if not label:
            continue
        # iD's synonyms are for a search box; they are lower-cased here so a
        # future lookup can compare without allocating.
        terms = sorted({t.strip().lower() for t in translated.get("terms", []) if t.strip()})
        out.append((key, value, label, terms))
    out.sort(key=lambda row: (row[0], row[1]))
    return out


def render(table: list[tuple[str, str, str, list[str]]]) -> str:
    """`terms` is carried this far and dropped here — see the module docstring."""
    body = [
        f"    ({rust_str(key)}, {rust_str(value)}, {rust_str(label)}),\n"
        for key, value, label, _terms in table
    ]
    return HEADER.format(version=SCHEMA_VERSION) + "".join(body) + FOOTER


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--check",
        action="store_true",
        help="exit non-zero if the generated file is out of date",
    )
    args = parser.parse_args()

    presets, names = fetch_schema()
    table = rows(presets, names)
    # A floor, not a target: v7.1.1 yields 660. This only has to catch the
    # schema changing shape under the pin (a renamed dist file, `tags` moving),
    # which would otherwise emit a plausible-looking near-empty table.
    if len(table) < 500:
        raise SystemExit(f"only {len(table)} rows — the schema shape probably moved")
    rendered = render(table)

    if args.check:
        current = OUT.read_text(encoding="utf-8") if OUT.exists() else ""
        if current != rendered:
            print(f"{OUT} is out of date — rerun tools/id_presets.py", file=sys.stderr)
            return 1
        print(f"{OUT} is up to date ({len(table)} presets)")
        return 0

    OUT.write_text(rendered, encoding="utf-8")
    present = {row[0] for row in table}
    print(f"wrote {OUT} — {len(table)} presets over {len(present)} keys")
    # Not an error: a key can be legitimately empty because iD describes it only
    # through multi-tag presets. Reported so the list doesn't quietly rot into a
    # set of keys that stopped meaning anything.
    if barren := sorted(set(POI_KEYS) - present):
        print(f"  no single-tag presets for: {', '.join(barren)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())