// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * `german` recipe: German coverage rows from real OpenAddresses tuples (Berlin and Saxony, cached zips). * * Each sampled tuple renders through {@link renderGermanRow} in idiomatic German order. * Generate mode builds a tuple pool from the cached zips, then draws `--count` * rows with the passed `random`. * * The postcode on the far side of the locality is the training-time `postcode_move` * augmentation's job (#2750), so the recipe writes no reversed rows. * * Two registers are absent from the OA tuples. A comma-free single line (`Neusser Str. 12 Nippes 50733 * Köln`) segments as one unit at stage 2. With one segment, the placetype-pair prior never fires. * The model then reads `Nippes` as a second street. The one-value-per-tag projection deletes it. * `--comma-free-fraction` renders that share of rows with `" "` as the line separator. OA * rows also lack a district, so `--ortsteil-fraction` rows borrow a WOF Ortsteil of the tuple's * own locality as `dependent_locality`. The German spelling is recovered from the `names` table * ({@link ortsteilSurface}) because WOF's `spr.name` for DE neighborhoods is the ascii-folded label. * * A Saxon tuple whose street is an Ortsteil of its locality is a streetless hamlet (`Loga 13, 02699 * Neschwitz`). A row the renderer writes without the number tags the hamlet `dependent_locality` * ({@link ortsteilStreetComponents}). */ import { currentSourcePath } from "@mailwoman/core/data-root" import { pathExists } from "@mailwoman/core/fs/readers/stat" import { mulberry32 as makeMulberry32 } from "@mailwoman/core/utils" import { stringifyJSON } from "@mailwoman/core/values/json" import { wofDatabasePath } from "@mailwoman/resolver-wof-sqlite/paths" import type { WOFDatabase } from "@mailwoman/resolver-wof-sqlite/schema" import { DatabaseClient } from "@mailwoman/sqlite/client" import type { PathBuilderLike } from "path-ts" import { RenderedRowIDs } from "#adapters/record-id" import { stableSourceID } from "#adapters/source-id" import { isOrtsteilStreet, ortsteilStreetComponents, ortsteilSurface } from "#de/recipes/ortsteil" import { readZippedCSVRecords, type CorpusRecipe } from "#recipes/scaffold" import { defaultRecipeSource } from "#recipes/sources" import { regionDrawRandom, renderGermanRow, type LocaleBaseTuple } from "#surfaces/locale" import { alignRow } from "#utils" /** * The share of rows that write the Bundesland as `region` after the postcode and locality. * * Deutsche Post prints no Land. * Every example in its UPU description ends ` ` (`Wacholderweg 52a / 26133 OLDENBURG`). * * A typed query still writes one (`04860 Torgau, Sachsen`). * A minority of rows keep it, so the operator's form stays the majority. * * A Berlin row never takes one, because the Land is the city (see `renderLocaleRow`). */ const BUNDESLAND_REGION_FRACTION = 0.2 /** * A German OA source (cached zip) + the Bundesland the file covers (OA's region column is empty for DE). */ interface GermanSource { zip: PathBuilderLike csv: string region: string } /** * Each source's `region` is the Bundesland the file covers. * * OA's region column is empty for DE, so the region comes from the per-state file. * * The Berlin file is a city-state whose region equals its locality. * The Saxony file is Sachsen. */ const SOURCES: GermanSource[] = [ { zip: currentSourcePath("openaddresses", "de__berlin.zip"), csv: "de/berlin.csv", region: "Berlin" }, { zip: currentSourcePath("openaddresses", "de__sn__statewide.zip"), csv: "de/sn/statewide.csv", region: "Sachsen" }, ] /** * Every current DE neighborhood with a locality ancestor, keyed by the folded * locality name → Ortsteil surfaces. * * Empty when the admin database isn't readable. * The recipe then emits no Ortsteil rows and reports that result, rather than * failing a build over an optional register. */ async function readOrtsteilPool(adminDB: PathBuilderLike): Promise> { const pool = new Map() if (!(await pathExists(adminDB))) return pool using db = new DatabaseClient(adminDB, { readOnly: true }) const rows = await db .selectFrom("spr as s") .innerJoin("ancestors as a", "a.id", "s.id") .innerJoin("spr as p", "p.id", "a.ancestor_id") .select(["s.id as id", "s.name as name", "p.name as locality"]) .where("s.country", "=", "DE") .where("s.placetype", "=", "neighbourhood") .where("s.is_current", "=", 1) .where("s.is_deprecated", "=", 0) .where("a.ancestor_placetype", "=", "locality") .execute() const deuNames = new Map() for (const row of await db .selectFrom("names") .select(["id", "name"]) .where("country", "=", "DE") .where("placetype", "=", "neighbourhood") .where("language", "=", "deu") .execute()) { const list = deuNames.get(row.id) ?? [] list.push(row.name) deuNames.set(row.id, list) } for (const row of rows) { if (!row.name || !row.locality) continue const surface = ortsteilSurface(row.name, deuNames.get(row.id) ?? [], row.locality) const key = row.locality.toLowerCase() const list = pool.get(key) ?? [] if (!list.includes(surface)) { list.push(surface) } pool.set(key, list) } return pool } /** * Stream real German tuples out of a cached OA zip. */ async function readGermanTuples(source: GermanSource): Promise { const tuples: LocaleBaseTuple[] = [] const seen = new Set() for await (const row of readZippedCSVRecords(source.zip, source.csv)) { const street = row.street ?? "" const locality = row.city ?? "" if (!street || !locality) continue const house_number = row.number ?? "" const postcode = row.postcode ?? "" // OA's region column is empty for DE — fall back to the source's Bundesland (set per file). const region = row.region || source.region || "" const key = `${house_number}|${street}|${locality}|${postcode}`.toLowerCase() if (seen.has(key)) continue seen.add(key) tuples.push({ house_number, street, locality, region, postcode }) } return tuples } /** * Recipe registered with the corpus builder. */ export const germanRecipe: CorpusRecipe = { name: "german", description: "German coverage rows from real OA tuples (Berlin/Saxony) → renderGermanRow", mode: "generate", options: [ { flag: "--comma-free-fraction ", description: "Fraction of rows rendered with no commas (the single-line register, #1946). Default 0.3", }, { flag: "--region-fraction ", description: "Fraction of rows that write the Bundesland as region after the locality. Default 0.2", }, { flag: "--ortsteil-fraction ", description: "Fraction of rows carrying a WOF Ortsteil of the locality as dependent_locality. Default 0.3", }, { flag: "--admin-db ", description: "WOF admin database for the Ortsteil pool. Default $MAILWOMAN_DATA_ROOT/db/wof/admin-global-priority.db", }, ], async run(opts, write) { const random = makeMulberry32(opts.seed) const regionRandom = regionDrawRandom(opts.seed) const source = opts.sourceName ?? defaultRecipeSource("synth-german") const commaFreeFraction = opts.commaFreeFraction ?? 0.3 const ortsteilFraction = opts.ortsteilFraction ?? 0.3 const regionFraction = opts.regionFraction ?? BUNDESLAND_REGION_FRACTION for (const [flag, value] of [ ["--comma-free-fraction", commaFreeFraction], ["--ortsteil-fraction", ortsteilFraction], ] as const) { if (!(value >= 0 && value <= 1)) { throw new Error(`${flag} must be in [0, 1], got ${value}`) } } // The pool reads `spr` and `ancestors` only, so the admin database itself serves. const adminDB = opts.adminDB ?? wofDatabasePath("admin-global-priority.db") const ortsteile = ortsteilFraction > 0 ? await readOrtsteilPool(adminDB) : new Map() if (ortsteilFraction > 0) { console.error( ortsteile.size ? ` Ortsteil pool: ${[...ortsteile.values()].reduce((n, list) => n + list.length, 0)} surfaces under ${ortsteile.size} localities (${adminDB})` : ` Ortsteil pool: none — ${adminDB} is not readable, so no row carries a dependent_locality` ) } const count = opts.count ?? 4000 const pool: LocaleBaseTuple[] = [] for (const s of SOURCES) { const t = await readGermanTuples(s) console.error(` ${s.csv}: ${t.length} unique tuples`) for (const x of t) { pool.push(x) } // not pool.push(...t) — spreading ~840K args overflows the stack } if (!pool.length) { throw new Error(`No German tuples found — are the cached zips present in ${currentSourcePath("openaddresses")}?`) } let emitted = 0 let skipped = 0 let guard = 0 let withOrtsteil = 0 let hamletPlaces = 0 let commaFree = 0 const N = pool.length const rowIDs = new RenderedRowIDs() while (emitted < count && guard++ < count * 6) { const drawn = pool[Math.floor(random() * N)]! // OA doesn't provide these two registers. // Each is drawn independently, so every combination occurs. // One is an Ortsteil borrowed from the tuple's own locality, the other a line with no commas. const localOrtsteile = ortsteile.get(drawn.locality.toLowerCase()) const hamlet = isOrtsteilStreet(drawn.street, localOrtsteile) const borrowed = localOrtsteile && random() < ortsteilFraction ? localOrtsteile[Math.floor(random() * localOrtsteile.length)] : null // A tuple whose street is itself an Ortsteil borrows no second Ortsteil. // The draws above still run, so every other row of a seeded run renders as it did. const ortsteil = hamlet ? null : borrowed const base: LocaleBaseTuple = ortsteil ? { ...drawn, dependent_locality: ortsteil } : drawn const separator = random() < commaFreeFraction ? " " : ", " const withRegion = regionRandom() < regionFraction const rendered = renderGermanRow(base, { random, separator, withRegion }) if (!rendered) { skipped++ continue } const synth = hamlet ? { ...rendered, components: ortsteilStreetComponents(rendered.components) } : rendered // --golden: emit per-locale-f1 eval rows ({raw, components}) instead of aligned BIO. if (opts.golden) { write(stringifyJSON({ raw: synth.raw, components: synth.components, country: "DE", order: "native" })) emitted++ continue } // The record is the tuple, and the text tells its renderings apart (#2765). // A hamlet keeps the tuple's id whichever tag its rendering gives it. const sourceID = rowIDs.claim( stableSourceID(source, { street: rendered.components.street, house_number: rendered.components.house_number, locality: rendered.components.locality, postcode: rendered.components.postcode, }), synth.raw ) if (!sourceID) { skipped++ continue } const canonical = { raw: synth.raw, components: synth.components, country: "DE", locale: synth.locale, source, source_id: sourceID, license: `OpenAddresses DE (Berlin/Saxony) tuples, rendered native-order — see ingest SOURCES`, } const aligned = alignRow(canonical as Parameters[0]) if (aligned.kind !== "labeled" || !aligned.row) { skipped++ continue } write( stringifyJSON({ ...aligned.row, synth_method: "german", synth_order: "native", synth_separator: separator === " " ? "space" : "comma", synth_base_id: null, }) ) emitted++ if (ortsteil) { withOrtsteil++ } if (synth.components.dependent_locality && !ortsteil) { hamletPlaces++ } if (separator === " ") { commaFree++ } } console.error( ` emitted ${emitted}: ${withOrtsteil} with an Ortsteil, ${hamletPlaces} with a streetless hamlet, ${commaFree} comma-free` ) return { emitted, skipped } }, }