// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * `osm`: OpenStreetMap address adapter for the countries no permissive source covers. * * Every row lists `ODbL-1.0`, whose recorded obligations include share-alike. * A build run under `LicensePolicy.ShareAlikeFree` refuses these rows at ingest, * so they reach only the open weights. * * That's why `defaultLicense` isn't an option on this adapter. */ import type { ComponentTag } from "@mailwoman/codex/component" import { countryDisplayNames } from "@mailwoman/codex/country/display-names" import { countriesDeclaredBy, hasCountry } from "@mailwoman/codex/country/sets" import { sha256Hex } from "@mailwoman/core/crypto/hash" import { extractDelimited } from "@mailwoman/core/scripting/arguments" import { tryParsingJSON } from "@mailwoman/core/values/json" import { stripCombiningMarks } from "@mailwoman/normalize/fold" import { acceptPostcode, statesPostcodeSyntax } from "@mailwoman/postcode/country-formats" import { TextSpliterator } from "spliterator" import { OSM_LICENSE } from "#adapters/osm/license" import { stableSourceID } from "#adapters/source-id" import { SourceRegister } from "#registers" import { formatCorpusRow } from "#surfaces/corpus-row" import { AddressRole, type AdapterOptions, type CanonicalRow, type CorpusAdapter, countDropped, SurfaceOrigin, } from "#types" /** * Registry id for this adapter, stamped into every row it emits. */ export const OSM_ADAPTER_ID = "osm" /** * The share of rows rendered with a trailing country name. * * An OpenStreetMap address holds no country token, and the country layouts print none. * Without a share that ends in the country's name, a country whose street rows all come * from this adapter has no `street, locality, country` row at all, and the model reads * such an address by the WOF shape `locality, region, country` (#2925). */ export const OSM_TRAILING_COUNTRY_SHARE = 0.3 /** * The shortest country name appended. * * A bare alpha-2 code collides with region abbreviations. */ const MIN_TRAILING_COUNTRY_LENGTH = 3 /** * The number of values a 32-bit unsigned integer takes. * A hash prefix divided by it falls in the unit interval. */ const UINT32_RANGE = 2 ** 32 /** * The row with `, ` appended when the source id's hash falls in the trailing-country share. * * The English name of {@linkcode MIN_TRAILING_COUNTRY_LENGTH} or more characters is used. * A country with no such name keeps the row unchanged. */ export function withTrailingCountry( raw: string, components: Partial>, country: string, sourceID: string ): { raw: string; components: Partial> } { // The salt keeps the draw independent of a sampler that kept the lowest source-id hashes. osm-ru's // 2,000,177 rows were kept that way, and unsalted, 96.6% of those ids fall under the share. const draw = Number.parseInt(sha256Hex(`trailing-country:${sourceID}`).slice(0, 8), 16) / UINT32_RANGE const name = countryDisplayNames(country, ["en"]).find((candidate) => candidate.length >= MIN_TRAILING_COUNTRY_LENGTH) if (draw >= OSM_TRAILING_COUNTRY_SHARE || !name || components.country) return { raw, components } return { raw: `${raw}, ${name}`, components: { ...components, country: name } } } /** * The per-row shape `@mailwoman/osm`'s `emit-corpus-jsonl` writes. */ interface OSMCorpusRow { street?: string | null number?: string | null postcode?: string | null suburb?: string | null city?: string | null unit?: string | null place?: string | null subdistrict?: string | null district?: string | null province?: string | null country?: string | null /** * `emit-corpus-jsonl --locality-level` uses the containing administrative area's * name writes for a record without `addr:city`. */ boundary_locality?: string | null /** * The same for a record without `addr:suburb`, from `--dependent-locality-level`. */ boundary_dependent_locality?: string | null } const MAX_STREET_WORDS = 8 /** * The countries whose mappers write the raion that contains the settlement in `addr:district`. * * Over the October 2026 extracts, every Moldovan `addr:district` value spans more than * three settlements (880,282 rows: `Raionul Ialoveni`, `Municipiul Chișinău`). * The Russian and Belarusian values do so on 182,210 and 3,042 rows (`Аксайский район`, `Кобрынскі раён`). * * In other countries the tag holds a part of the city: `Hoàn Kiếm` in Hà Nội, * `越秀区` in 广州, `Արաբկիր` in Yerevan. * A count of distinct settlements can't separate the two by itself. * * A city written several ways spans several names too (`黄浦区` under five spellings of Shanghai). */ // country-branch: what `addr:district` denotes is a per-country mapping convention of OpenStreetMap. // A WOF ancestry lookup of the district's name above the row's locality would replace this list. const OSM_DISTRICT_CONTAINS_LOCALITY = countriesDeclaredBy("OSM addr:district raion convention", ["BY", "MD", "RU"]) /** * Whether `addr:housenumber` holds a street designator — digits with an optional letter, * fraction or dash suffix (`12`, `188a`, `14/E`, `1/1146`, `167-c`) or a one- * or two-letter block prefix (`B-77`, `L58`, `R 948`) — rather than free text such * as `House 34, Road 4, Sector 9`, `Plot #27` or a name. */ export function housenumberIsDesignator(value: string): boolean { const trimmed = value.trim() if (longestDigitRun(trimmed) > MAX_HOUSE_NUMBER_DIGITS) return false return /^\d+[A-Za-z]?(?:[/-]\d*[A-Za-z]?)?$/u.test(trimmed) || /^[A-Za-z]{1,2}[-\s]?\d+[A-Za-z]?$/u.test(trimmed) } /** * The most digits in a row a house number holds. * * The longest the national registers write are six, the rural grid numbers of the US * National Address Database (`129504 US 65 Highway North, Gould, AR`). * A run of seven or more in `addr:housenumber` is a telephone number * (`22796800` in Costa Rica, `07505156040` in Iraq) or a postcode, in every country's extract alike. */ const MAX_HOUSE_NUMBER_DIGITS = 6 function longestDigitRun(value: string): number { let longest = 0 for (const run of value.match(/\d+/gu) ?? []) { longest = Math.max(longest, run.length) } return longest } /** * Whether `addr:street` matches the street-name shape. * * The value has no comma and contains at most {@link MAX_STREET_WORDS} words. * Direction phrases such as `Near Cozy Water Park`, `Opposite Askari Towers` or `Behind …` return false. */ export function isStreetName(value: string): boolean { const trimmed = value.trim() return ( trimmed.length > 0 && !trimmed.includes(",") && trimmed.split(/\s+/u).length <= MAX_STREET_WORDS && !/^(?:near|opp(?:osite)?|behind|beside|next to|adjacent)\b/iu.test(trimmed) ) } /** * Split an `addr:city` carrying a neighborhood ahead of the city (`Mirpur 10, Dhaka` → * locality `Dhaka`, head `Mirpur 10`); a value without a comma is only the locality. */ export function splitCityValue(value: string): { locality: string; head: string | null } { const parts = extractDelimited(value) if (parts.length < 2) { return { locality: value.trim(), head: null } } return { locality: parts.at(-1)!, head: parts.slice(0, -1).join(", ") } } const PLACEHOLDERS = new Set(["n/a", "na", "none", "-", "nil"]) function clean(value: string | null | undefined): string | null { const trimmed = value?.trim() ?? "" return trimmed && !PLACEHOLDERS.has(trimmed.toLowerCase()) ? trimmed : null } function parseLine(line: string): OSMCorpusRow | null { const trimmed = line.trim() if (!trimmed || trimmed.startsWith("#")) return null const parsed = tryParsingJSON(trimmed) return parsed && typeof parsed === "object" ? (parsed as OSMCorpusRow) : null } /** * Maps one jsonl row onto the components the corpus asserts, or returns null when the row is refused. * * A row with a street-shaped `addr:street` is a street address. * A row with no `addr:street` at all is admitted as a streetless premise when its house * number is designator-shaped and a tag that maps to `locality` or `dependent_locality` * (`addr:city`, `addr:place`, `addr:suburb`, `addr:subdistrict`, `addr:district`) * holds the identity the street would have held. * * That's OSM's documented scheme for addresses numbered within a place rather than * along a street, and it is the `streetless-premise-identity` shape. * A row whose `addr:street` holds a line rather than a name stays refused: * the mapper supplied a street, and the value is a line. * * A postcode is kept when the whole value has `country`'s postcode format. * * Each refusal and each discarded component increments its reason in `dropped`. */ export function componentsForOSMRow( row: OSMCorpusRow, country: string, dropped?: Pick ): CanonicalRow["components"] | null { const tally = dropped ?? {} const street = clean(row.street) const number = clean(row.number) const designator = number !== null && housenumberIsDesignator(number) if (street && !isStreetName(street)) { countDropped(tally, "row:street-not-a-name") return null } if (!street && !designator) { countDropped(tally, number ? "row:streetless-house-number-not-designator" : "row:streetless-no-house-number") return null } const components: CanonicalRow["components"] = street ? { street } : {} if (designator) { components.house_number = number } else if (number) { countDropped(tally, "component:house_number:not-designator") } const unit = clean(row.unit) if (unit) { components.unit = unit } const postcode = clean(row.postcode) if (postcode) { // The country's own format decides, so Argentina's `C1425ABC`, Brunei's `BS8811` and Chile's // seven digits stay postcodes, and a value outside the country's form is dropped by name. const matched = acceptPostcode(postcode, country) if (matched) { components.postcode = matched } else { countDropped( tally, statesPostcodeSyntax(country) ? "component:postcode:not-country-format" : "component:postcode:country-has-none" ) } } const city = clean(row.city) const split = city ? splitCityValue(city) : null if (split) { components.locality = split.locality } else { // The containing boundary's name stands in only where the mapper tagged no city, // so a tagged value is never replaced by a position. const boundary = clean(row.boundary_locality) if (boundary) { components.locality = boundary countDropped(tally, "kept:locality-from-boundary") } } // Where `addr:district` holds the raion that contains the locality, it is the locality's `subregion`. // The country's layout then places it, or drops it and counts the drop. const district = clean(row.district) const districtContainsLocality = hasCountry(OSM_DISTRICT_CONTAINS_LOCALITY, country) if (district && districtContainsLocality && (!components.locality || !sameName(district, components.locality))) { components.subregion = district } // Dependent-locality candidates in priority order (suburb, subdistrict, district, place, // city head, then the containing boundary's name); `district` never becomes `region`, // because Vietnam's country template renders it only when no city is present. const dependent = [ row.suburb, row.subdistrict, districtContainsLocality ? null : row.district, row.place, split?.head, row.boundary_dependent_locality, ] .map((value) => clean(value)) .find( (value) => value !== null && !value.includes(",") && (street === null || !sameName(value, street)) && (!components.locality || !sameName(value, components.locality)) ) if (dependent) { components.dependent_locality = dependent } const province = clean(row.province) if (province && (!components.locality || !sameName(province, components.locality))) { components.region = province } // A streetless premise is a house number within a place that has a name, so it needs // a locality or a dependent locality, from any of the tags that map to them. if (!street && !components.locality && !components.dependent_locality) { countDropped(tally, "row:streetless-no-locality") return null } // An address row needs another component alongside the street or the streetless house number. // Coarse adapters already teach bare names. // A subregion doesn't count. // The layouts of the countries that write one in `addr:district` print none. if (Object.keys(components).filter((tag) => tag !== "subregion").length === 1) { countDropped(tally, street ? "row:street-only" : "row:house-number-only") return null } return components } /** * Vietnamese admin-generic prefixes stripped before name comparison, so a province that * repeats the city with a prefix (`Thành phố Hà Nội`) is read as the repeat it is. */ const NAME_PREFIXES = /^(?:thanh pho|tinh|tp\.?|quan|phuong|huyen|thi xa)\s+/u /** * Whether two place names are the same name: case, whitespace, diacritics and a leading * admin generic folded (`Bắc Ninh` = `Bac Ninh`; `Hà Nội` = `Thành phố Hà Nội`). */ export function sameName(a: string, b: string): boolean { const fold = (value: string): string => stripCombiningMarks(value) .replaceAll("đ", "d") .replaceAll("Đ", "D") .toLowerCase() .replaceAll(/\s+/gu, " ") .trim() .replace(NAME_PREFIXES, "") return fold(a) === fold(b) } export function createOSMAdapter(): CorpusAdapter { return { id: OSM_ADAPTER_ID, defaultLicense: OSM_LICENSE, addressRole: AddressRole.Premise, register: SourceRegister.OpenStreetMap, surface: SurfaceOrigin.Rendered, description: "OpenStreetMap addresses (ODbL, share-alike): per-country JSONL from a Geofabrik extract, for the countries no permissive source covers.", async *rows(opts: AdapterOptions): AsyncIterable { if (!opts.country) { throw new Error("osm adapter: --country is required (the JSONL is per-country and rows omit a country field)") } const country = opts.country let emitted = 0 for await (const line of TextSpliterator.fromAsync(opts.inputPath)) { if (opts.signal?.aborted) break if (typeof opts.limit === "number" && emitted >= opts.limit) break const row = parseLine(line) if (!row) { if (line.trim() && !line.trim().startsWith("#")) { countDropped(opts, "row:unparseable-line") } continue } // A Geofabrik extract's polygon extends past the border, so its records // include addresses in the neighboring country. // A record whose own `addr:country` names another country is refused. // A record without the tag is kept and counted, so the size of the remaining // uncertainty is in the manifest rather than assumed to be zero. const tagged = clean(row.country)?.toUpperCase() if (tagged && tagged !== country) { countDropped(opts, "row:country-tag-mismatch") continue } if (!tagged) { countDropped(opts, "kept:country-untagged") } const components = componentsForOSMRow(row, country, opts) if (!components) continue const rendered = formatCorpusRow(components, country, { singleLine: true }) if (!rendered) { countDropped(opts, "row:render-failed") continue } for (const tag of rendered.unplaced) { countDropped(opts, `component:${tag}:not-rendered`) } // The source id is the rendered address's, so a row keeps its id and its split // whether or not it takes the trailing country. const sourceID = stableSourceID(OSM_ADAPTER_ID, rendered.components) const { raw, components: aligned } = withTrailingCountry(rendered.raw, rendered.components, country, sourceID) yield { raw, components: aligned, country, source: OSM_ADAPTER_ID, source_id: sourceID, license: OSM_LICENSE, } emitted++ } }, } } /** * The configured adapter instance registered with the corpus builder. */ export const osmAdapter = createOSMAdapter()