// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The seed of one prominent place: the verified surfaces a query form may be written from (#3156). * * A seed lists every surface a form may contain, each under one slot and with the record it came from. * The language model that writes the forms chooses among these surfaces and supplies none of its own, * so a form's labels are the seed's. * * The slots follow the #3156 label policy (`prominentPlaceTag` in `#recipes/prominent/places`): * a locality is a `locality` in every form, a sub-locality is a `dependent_locality` beside its parent * locality, and a postal pair is a `locality` beside its parent's name as a `region`. */ import { foldCaseWhitespace } from "@mailwoman/normalize/fold" import type { PlaceBand } from "#recipes/prominent/places" /** * The slots a surface fills, by the letter its key starts with. */ export const SurfaceSlot = { /** * The place's own name. */ Name: "n", /** * The parent locality of a sub-locality. */ Parent: "p", /** * The region's name. */ Region: "r", /** * The region's abbreviation. */ RegionAbbreviation: "a", /** * The country. */ Country: "c", } as const /** * One slot. */ export type SurfaceSlot = (typeof SurfaceSlot)[keyof typeof SurfaceSlot] /** * One surface a form may contain. */ export interface SeedSurface { /** * The slot letter and a one-based index, the key the model cites: `n1`, `c3`. */ key: string slot: SurfaceSlot text: string /** * The ISO 639-3 language of a WOF `names` row, or `null` for a surface recorded without one. */ language: string | null /** * The record the surface was read from, such as `wof:names:85922583:eng:preferred`. */ origin: string } /** * A surface before it has a key. */ export type SurfaceDraft = Omit /** * One prominent place and the surfaces its forms are written from. */ export interface ShapeSeed { wof_id: number country: string band: PlaceBand /** * The place's rank within its country and band, or `null` for a capital the rank left out. */ rank: number | null capital: boolean /** * The tag of the place's own span. */ place_tag: "locality" | "dependent_locality" /** * The tag of a parent span, or `null` when the seed has no parent slot. */ parent_tag: "locality" | "region" | null surfaces: SeedSurface[] } /** * The reasons a prominent place gets no seed. */ export const SeedSkip = { /** * A sub-locality without a parent locality: the label policy writes it only beside one. */ NoParent: "sublocality_without_parent", /** * A sub-locality whose name equals its parent's, so every query form reads the same for both. */ ParentNamesake: "sublocality_named_as_parent", /** * Every name of the place is refused as a typed surface, so no form could cite a name. */ NoName: "no_typed_name", } as const /** * One skip reason. */ export type SeedSkip = (typeof SeedSkip)[keyof typeof SeedSkip] /** * What one prominent place contributes to a seed, as read from the census and Who's On First. */ export interface SeedInput { wof_id: number country: string band: PlaceBand rank: number | null capital: boolean postal_pair: boolean names: readonly SurfaceDraft[] parents: readonly SurfaceDraft[] regions: readonly SurfaceDraft[] region_abbreviations: readonly SurfaceDraft[] countries: readonly SurfaceDraft[] } /** * A region abbreviation a form may write: one to three Latin letters or digits, the #3156 census's filter. */ function isWritableRegionAbbreviation(abbreviation: string): boolean { return /^[A-Za-z0-9]{1,3}$/u.test(abbreviation) } /** * Text that marks a name as an article title or a rendering artifact rather than a typed surface: * a parenthesized qualifier (`Vaticano (disambigua)`) or a bidirectional control character. */ const UNTYPED_SURFACE = /[()‎‏‪-‮]/u /** * The drafts with a typed, non-empty text, one per folded text, in the order given. */ function distinctDrafts(drafts: readonly SurfaceDraft[]): SurfaceDraft[] { const seen = new Set() const kept: SurfaceDraft[] = [] for (const draft of drafts) { const fold = foldCaseWhitespace(draft.text) if (fold === "" || seen.has(fold) || UNTYPED_SURFACE.test(draft.text)) continue seen.add(fold) kept.push({ ...draft, text: draft.text.trim() }) } return kept } function keyed(slot: SurfaceSlot, drafts: readonly SurfaceDraft[]): SeedSurface[] { return distinctDrafts(drafts).map((draft, index) => ({ key: `${slot}${index + 1}`, slot, ...draft })) } /** * Builds a place's seed, or returns the reason the label policy writes no form for it. * * A place whose every name is refused gets no seed in either band, because every form needs one name. * A locality has no parent slot. * * A postal pair writes its parent's name in the region slot, and keeps the region's * abbreviations only when the region is that same name (`Brooklyn, NY`). */ export function assembleSeed(input: SeedInput): ShapeSeed | SeedSkip { const names = keyed(SurfaceSlot.Name, input.names) if (!names.length) return SeedSkip.NoName const parents = distinctDrafts(input.parents) const base = { wof_id: input.wof_id, country: input.country, band: input.band, rank: input.rank, capital: input.capital, } const countries = keyed(SurfaceSlot.Country, input.countries) const abbreviations = input.region_abbreviations.filter((draft) => isWritableRegionAbbreviation(draft.text)) if (input.band === "locality") { return { ...base, place_tag: "locality", parent_tag: null, surfaces: [ ...names, ...keyed(SurfaceSlot.Region, input.regions), ...keyed(SurfaceSlot.RegionAbbreviation, abbreviations), ...countries, ], } } if (!parents.length) return SeedSkip.NoParent const nameFolds = new Set(names.map((name) => foldCaseWhitespace(name.text))) if (parents.some((parent) => nameFolds.has(foldCaseWhitespace(parent.text)))) return SeedSkip.ParentNamesake if (input.postal_pair) { const parentFolds = new Set(parents.map((parent) => foldCaseWhitespace(parent.text))) const regionIsParent = input.regions.some((region) => parentFolds.has(foldCaseWhitespace(region.text))) return { ...base, place_tag: "locality", parent_tag: "region", surfaces: [ ...names, ...keyed(SurfaceSlot.Parent, parents), ...(regionIsParent ? keyed(SurfaceSlot.RegionAbbreviation, abbreviations) : []), ...countries, ], } } return { ...base, place_tag: "dependent_locality", parent_tag: "locality", surfaces: [ ...names, ...keyed(SurfaceSlot.Parent, parents), ...keyed(SurfaceSlot.Region, input.regions), ...keyed(SurfaceSlot.RegionAbbreviation, abbreviations), ...countries, ], } } /** * Keeps each country and band's highest-ranked `limit` seeds, and every capital. */ export function limitSeedsPerBand(seeds: readonly ShapeSeed[], limit: number): ShapeSeed[] { return [...Map.groupBy(seeds, (seed) => `${seed.country}\u0000${seed.band}`).values()].flatMap((group) => group .toSorted((a, b) => (a.rank ?? Infinity) - (b.rank ?? Infinity)) .filter((seed, index) => index < limit || seed.capital) ) } /** * Groups seeds into requests of at most `size` places, each of one country, * so a request lists its country's surfaces once. */ export function chunkSeedsByCountry(seeds: readonly ShapeSeed[], size: number): ShapeSeed[][] { const chunks: ShapeSeed[][] = [] const byCountry = Map.groupBy(seeds, (seed) => seed.country) for (const country of [...byCountry.keys()].toSorted()) { const group = byCountry.get(country)! for (let start = 0; start < group.length; start += size) { chunks.push(group.slice(start, start + size)) } } return chunks }