// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Reads the seeds of the prominent places the #3156 census selected. * * The census's `places.parquet` supplies the selection, each place's name, parent locality, region, * region abbreviations and postal-pair reading. * The Who's On First admin database supplies the other-language surfaces: the `preferred` rows of * `names` in the country's official languages and English, for the place, for the parent locality and * region among its ancestors, and for its country. * The codex supplies the country's rendered forms. */ import { countryRenderForms, isTwoLetterCountryCode } from "@mailwoman/codex/country/country" import { officialLanguagesAlpha3 } from "@mailwoman/codex/country/region-languages" import { foldCaseWhitespace } from "@mailwoman/normalize/fold" import type { WOFDatabase } from "@mailwoman/resolver-wof-sqlite/schema" import { openBuiltClient } from "@mailwoman/sqlite/sealed" import { escapeSQLString, openDuckDB } from "#parquet/duckdb" import { parquetColumnNames } from "#parquet/readers" import type { PlaceBand } from "#recipes/prominent/places" import { chunked } from "#tools/fetch/wikidata/vital-places/progress" import { assembleSeed, type SeedSkip, type ShapeSeed, type SurfaceDraft } from "#tools/prominent-shapes/seeds" /** * The census columns a seed is read from. */ const CENSUS_COLUMNS = [ "spr_id", "country", "band", "name", "rank", "by_rank", "capital", "parent_locality", "region", "region_abbrs", "postal_pair", ] as const /** * The ids one SQLite query lists. */ const ID_CHUNK = 500 /** * One selected place as the census records it. */ interface CensusPlace { spr_id: number country: string band: PlaceBand name: string rank: number | null capital: boolean parent_locality: string | null region: string | null region_abbrs: string[] postal_pair: boolean } /** * The seeds read, and the places left without one by reason. */ export interface SeedReadResult { seeds: ShapeSeed[] selected: number skipped: Partial> } async function readCensusPlaces(placesParquet: string): Promise { const columns = new Set(await parquetColumnNames(placesParquet)) const missing = CENSUS_COLUMNS.filter((column) => !columns.has(column)) if (missing.length) { throw new Error( `${placesParquet} lacks the census columns ${missing.join(", ")}; a seed cannot be read without them` ) } using db = await openDuckDB() const result = await db.runAndReadAll( `SELECT ${CENSUS_COLUMNS.join(", ")} FROM read_parquet('${escapeSQLString(placesParquet)}') ` + "WHERE by_rank OR capital ORDER BY country, band, rank NULLS LAST, spr_id" ) return (result.getRowObjectsJson() as Array>).map((row) => ({ spr_id: Number(row["spr_id"]), country: String(row["country"]), band: String(row["band"]) as PlaceBand, name: String(row["name"]), rank: row["rank"] == null ? null : Number(row["rank"]), capital: row["capital"] === true, parent_locality: typeof row["parent_locality"] === "string" ? row["parent_locality"] : null, region: typeof row["region"] === "string" ? row["region"] : null, region_abbrs: Array.isArray(row["region_abbrs"]) ? row["region_abbrs"].map(String) : [], postal_pair: row["postal_pair"] === true, })) } /** * The languages a country's surfaces are read in: its official languages, then English. */ function surfaceLanguages(country: string): string[] { return [...new Set([...officialLanguagesAlpha3(country), "eng"])] } /** * The shortest Latin-script country surface a form writes. * * A shorter one collides with region abbreviations, as `packages/corpus/AGENTS.md` records. * `日本` is two characters of another script and stays. */ const LATIN_COUNTRY_SURFACE_MIN_LENGTH = 3 /** * Whether a country surface is written: neither a two-letter code nor a Latin surface under the floor. */ function isWritableCountrySurface(text: string): boolean { const shortLatin = /^[\p{Script=Latin}.\s]*$/u.test(text) && text.trim().length < LATIN_COUNTRY_SURFACE_MIN_LENGTH return !isTwoLetterCountryCode(text) && !shortLatin } /** * Reads the seed of every prominent place in `placesParquet`. * * A parent locality or region takes its other-language surfaces from the ancestor * whose WOF name is the census's name for it. * Without such an ancestor its only surface is the census's name. * * @throws When the census file lacks a column a seed is read from. */ export async function readShapeSeeds(options: { placesParquet: string; wofDatabase: string }): Promise { const places = await readCensusPlaces(options.placesParquet) using wof = await openBuiltClient(options.wofDatabase) // The parent locality and region records among each place's ancestors, matched by the census's name. const parentID = new Map() const regionID = new Map() const byID = new Map(places.map((place) => [place.spr_id, place])) for (const ids of chunked([...byID.keys()], ID_CHUNK)) { const ancestors = await wof .selectFrom("ancestors") .innerJoin("spr", "spr.id", "ancestors.ancestor_id") .select(["ancestors.id", "ancestors.ancestor_id", "ancestors.ancestor_placetype", "spr.name"]) .where("ancestors.id", "in", ids) .where("ancestors.ancestor_placetype", "in", ["locality", "localadmin", "region"]) .execute() for (const ancestor of ancestors) { const place = byID.get(ancestor.id)! const fold = foldCaseWhitespace(ancestor.name ?? "") const isRegion = ancestor.ancestor_placetype === "region" const expected = isRegion ? place.region : place.parent_locality const target = isRegion ? regionID : parentID if (ancestor.ancestor_id !== place.spr_id && expected != null && fold === foldCaseWhitespace(expected)) { target.set(place.spr_id, Math.min(target.get(place.spr_id) ?? Infinity, ancestor.ancestor_id)) } } } // Each country's own record: a country before a dependency, the lowest id first. const countries = [...new Set(places.map((place) => place.country))] const countryRecord = new Map() const countryRows = await wof .selectFrom("spr") .select(["id", "name", "placetype", "country"]) .where("placetype", "in", ["country", "dependency"]) .where("country", "in", countries) .where("is_current", "!=", 0) .where("is_deprecated", "=", 0) .orderBy("placetype") .orderBy("id") .execute() for (const row of countryRows) { // `XX` is WOF's code for a place of no recorded country, so a record filed under // it belongs to no country's row. country-branch: `XX` is WOF's placeholder for an // unrecorded country, a sentinel of the source and no country's rule. if (row.country && row.country !== "XX" && row.name && !countryRecord.has(row.country)) { countryRecord.set(row.country, { id: row.id, name: row.name }) } } // The preferred names of every record a seed reads, in the languages its country writes. const languages = new Set(countries.flatMap(surfaceLanguages)) const namedIDs = new Set([...byID.keys(), ...parentID.values(), ...regionID.values()]) for (const record of countryRecord.values()) { namedIDs.add(record.id) } const namesByID = new Map>() for (const ids of chunked([...namedIDs], ID_CHUNK)) { const rows = await wof .selectFrom("names") .select(["id", "name", "language"]) .where("id", "in", ids) .where("privateuse", "=", "preferred") .where("language", "in", [...languages]) .orderBy("id") .orderBy("language") .orderBy("name") .execute() for (const row of rows) { if (!row.language) continue const list = namesByID.get(row.id) ?? [] list.push({ name: row.name, language: row.language }) namesByID.set(row.id, list) } } const nameDrafts = (id: number | null | undefined, country: string): SurfaceDraft[] => { if (id == null) return [] const wanted = surfaceLanguages(country) return (namesByID.get(id) ?? []) .filter((row) => wanted.includes(row.language)) .toSorted((a, b) => wanted.indexOf(a.language) - wanted.indexOf(b.language)) .map((row) => ({ text: row.name, language: row.language, origin: `wof:names:${id}:${row.language}:preferred` })) } const censusDraft = (text: string | null, column: string, id: number): SurfaceDraft[] => text == null ? [] : [{ text, language: null, origin: `census:${column}:${id}` }] const seeds: ShapeSeed[] = [] const skipped: Partial> = {} for (const place of places) { const country = countryRecord.get(place.country) const seed = assembleSeed({ wof_id: place.spr_id, country: place.country, band: place.band, rank: place.rank, capital: place.capital, postal_pair: place.postal_pair, names: [...censusDraft(place.name, "name", place.spr_id), ...nameDrafts(place.spr_id, place.country)], parents: [ ...censusDraft(place.parent_locality, "parent_locality", place.spr_id), ...nameDrafts(parentID.get(place.spr_id), place.country), ], regions: [ ...censusDraft(place.region, "region", place.spr_id), ...nameDrafts(regionID.get(place.spr_id), place.country), ], region_abbreviations: place.region_abbrs.map((text) => ({ text, language: null, origin: `census:region_abbrs:${place.spr_id}`, })), countries: [ ...countryRenderForms(place.country).map((text) => ({ text, language: null, origin: `codex:countryRenderForms:${place.country}`, })), ...(country ? [{ text: country.name, language: null, origin: `wof:spr:${country.id}:name` }] : []), ...nameDrafts(country?.id, place.country), ].filter((draft) => isWritableCountrySurface(draft.text)), }) if (typeof seed === "string") { skipped[seed] = (skipped[seed] ?? 0) + 1 } else { seeds.push(seed) } } return { seeds, selected: places.length, skipped } }