// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Reads address context and derives street-side negatives for the sub-venue recipe. */ import { currentSourcePath } from "@mailwoman/core/data-root" import { mulberry32 as makeMulberry32 } from "@mailwoman/core/utils" import { stringifyJSON } from "@mailwoman/core/values/json" import type { PathBuilderLike } from "path-ts" import { readTuples as readLocaleTuples, type LocalePart } from "#international/recipes/locale" import { readTuples as readRecipeTuples } from "#recipes/scaffold" import type { LocaleBaseTuple } from "#surfaces/locale" // #region Address context /** * DE + ES address context. * * Both read through {@link readLocaleTuples}, the `locale` recipe's own streaming + reservoir reader, * so the CSV handling (quoted fields, crlf, city-noise cleaning, the DE per-part region fallback) * has exactly one implementation. * * The DE parts read the extracted `de/berlin.csv` and `de/sn/statewide.csv`. * They're the `europe.zip` members the recipe read before that archive left the data root, * with the md5s `9903d438…` and `623b099b…` that the note "a file's mtime isn't * its data's vintage" in `corpus/agents.md` records. * * A missing part throws in {@link readLocaleTuples}, so the DE leg cannot emit zero rows silently. */ const CONTEXT_PARTS: Readonly> = { DE: [ { path: currentSourcePath("openaddresses", "extracted", "de", "berlin.csv"), region: "Berlin" }, { path: currentSourcePath("openaddresses", "extracted", "de", "sn", "statewide.csv"), region: "Sachsen" }, ], ES: [{ path: currentSourcePath("openaddresses", "extracted", "es", "countrywide.csv") }], } /** * The `source` value a Great Britain house-venue tuple must include. * * The v3 tuples took their GB rows from HM Land Registry Price Paid Data. * Royal Mail and Ordnance Survey license its address fields for non-commercial use only (#2635). * Those GB rows have no `source` value. */ export const GB_CONTEXT_TUPLE_SOURCE = "gb-os-open" /** * Load the address skeletons every leg renders onto: GB / US / FR from the * house-venue tuples (`#recipes/house-venue-tuples`). * * Its GB rows come from the `gb-os-open` adapter's OS OpenData rows. * DE and ES streamed out of OpenAddresses. * * @throws When a GB tuple lacks {@linkcode GB_CONTEXT_TUPLE_SOURCE}, so a tuples file * built from Price Paid Data is refused rather than rendered. */ export async function loadContextTuples( tuplesPath: PathBuilderLike, seed: number ): Promise> { const byCountry = new Map() for await (const tuple of readRecipeTuples(tuplesPath)) { const country = String(tuple.country ?? "") // country-branch: GB is the one country whose earlier tuples came from a refused source (#2635). // The tuples file records provenance for GB rows only, so the check reads GB rows only. if (country === "GB" && tuple.source !== GB_CONTEXT_TUPLE_SOURCE) { throw new Error( `${tuplesPath.toString()} holds a GB tuple from source ${stringifyJSON(tuple.source ?? null)}; ` + `GB address skeletons must come from ${GB_CONTEXT_TUPLE_SOURCE}. Rebuild the tuples with ` + "`node packages/corpus/lib/tools/house-venue-tuples.run.ts`." ) } if (!country || !tuple.locality || !tuple.street) continue const mapped: LocaleBaseTuple = { house_number: String(tuple.houseNumber ?? tuple.house_number ?? ""), street: String(tuple.street), locality: String(tuple.locality), region: String(tuple.region ?? ""), postcode: String(tuple.postcode ?? ""), } const list = byCountry.get(country) if (list) { list.push(mapped) } else { byCountry.set(country, [mapped]) } } for (const [country, parts] of Object.entries(CONTEXT_PARTS)) { if (byCountry.has(country)) continue const pooled: LocaleBaseTuple[] = [] for (const [index, part] of parts.entries()) { // A dedicated stream prng, seeded per part, so the input sample is reproducible // without perturbing the emit loop's draws (the `locale` recipe's rule, kept). const streamRandom = makeMulberry32(seed + index) for (const tuple of await readLocaleTuples(part, streamRandom)) { pooled.push(tuple) } } byCountry.set(country, pooled) } return byCountry } /** * The street-side confound classes, mined from the leg's own address tuples. * * Real streets rather than invented ones. * The 176,519-row context pool includes 195 GB `hall` streets and 114 GB `gate` streets. * * It includes 134 distinct GB `-gate` tokens and a two-figure ` ` * population in both GB and US. * Each item comes from a real address where someone lives. * Each example comes from a real address tuple. */ export interface StreetNegatives { designator: LocaleBaseTuple[] modifierDesignator: LocaleBaseTuple[] gateSuffix: LocaleBaseTuple[] } /** * Shortest token that can take a `-gate` street suffix and still be a name rather than the bare word: * `gate` itself is four characters, so the class starts at five (`Highgate`, `Moorgate`, `Stonegate`). */ const MIN_GATE_SUFFIX_TOKEN_LENGTH = 5 export function buildStreetNegatives( context: readonly LocaleBaseTuple[], designatorPhrases: readonly string[], modifiers: readonly string[], country: string ): StreetNegatives { const designatorSet = new Set(designatorPhrases) const modifierSet = new Set(modifiers) const designator: LocaleBaseTuple[] = [] const modifierDesignator: LocaleBaseTuple[] = [] const gateSuffix: LocaleBaseTuple[] = [] for (const tuple of context) { const tokens = tuple.street.toLowerCase().match(/[\p{L}]+/gu) ?? [] let isDesignator = false let isPair = false for (const [index, token] of tokens.entries()) { if (designatorSet.has(token)) { isDesignator = true } if (index + 1 < tokens.length && modifierSet.has(token) && designatorSet.has(tokens[index + 1]!)) { isPair = true } // country-branch: `-gate` is a street-name suffix in British English only. // The street-morphology FST per locale would replace it. if (country === "GB" && token.length >= MIN_GATE_SUFFIX_TOKEN_LENGTH && token.endsWith("gate")) { gateSuffix.push(tuple) } } if (isPair) { modifierDesignator.push(tuple) } else if (isDesignator) { designator.push(tuple) } } return { designator, modifierDesignator, gateSuffix } } // #endregion