// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Checks the query forms a language model wrote for a prominent place against the place's seed. * * A form is kept only when it cites surfaces the seed supplied, each cited surface is found in the * form's text under the case and whitespace fold, and the text outside those spans is separators. * A form that cites a slot letter in place of a numbered key is kept when one key of that slot passes. * The last rule is what refuses a name the seed didn't supply: an alias, an exonym or a typo * leaves letters outside every span. * A refused form is dropped and counted under its reason. */ import { tryParsingJSON } from "@mailwoman/core/values/json" import { type SeedSurface, type ShapeSeed, SurfaceSlot } from "#tools/prominent-shapes/seeds" /** * One form as the model returns it: the text and the keys of the surfaces it contains. */ export interface ReturnedForm { raw: string uses: string[] } /** * The forms the model returned for one place. */ export interface ReturnedPlace { id: string forms: ReturnedForm[] } /** * The reasons a returned form is dropped. */ export const FormDrop = { /** * The form cites a key the seed doesn't hold. */ UnknownSurface: "unknown_surface_key", /** * The form cites a bare slot letter, and no choice of that slot's keys passes every other rule. */ LetterUnresolved: "slot_letter_without_passing_key", /** * The form cites a bare slot letter, and more than one choice of that slot's keys passes every other rule. */ LetterAmbiguous: "slot_letter_with_several_passing_keys", /** * The cited slots are a combination the label policy doesn't write. */ SlotsNotAllowed: "slots_not_allowed", /** * A cited surface isn't in the text, so its span has no offsets. */ UnresolvableSpan: "unresolvable_span", /** * The text holds letters or digits outside every cited surface. */ UnsuppliedText: "text_outside_supplied_surfaces", /** * Two spans touch without a separator in a script that separates words. */ UnseparatedSpans: "unseparated_spans", /** * The form writes one surface in Latin script beside another in a different script. */ MixedScript: "mixed_script", /** * The text is empty or longer than a search-box query. */ Length: "raw_length", /** * The same text was already kept for this place. */ Duplicate: "duplicate_raw", } as const /** * One drop reason. */ export type FormDrop = (typeof FormDrop)[keyof typeof FormDrop] /** * One labeled span of a kept form. */ export interface CandidateSpan { tag: "locality" | "dependent_locality" | "region" | "country" /** * The span's text as the form writes it. */ value: string /** * UTF-16 offsets into `raw`, `end` exclusive. */ start: number end: number /** * The supplied surface the span writes, and the record it came from. */ surface: string origin: string } /** * A kept form before the run's model and batch are added to it. */ export interface ValidatedForm { wof_id: number country: string band: ShapeSeed["band"] shape: string raw: string spans: CandidateSpan[] /** * Whether the form cited a bare slot letter (`n`) rather than a key (`n2`), * and the letter was resolved to the one key of that slot the text passes with. */ keys_from_letters: boolean } /** * The longest text kept, in UTF-16 units. */ const MAX_RAW_LENGTH = 120 /** * The characters a form may hold outside its spans. */ const SEPARATORS = /^[\s,.;/()\-–·、,]*$/u /** * A character of a script written without spaces between words, where two spans may touch. */ const UNSPACED_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u /** * A text folded for comparison, with each folded unit's offsets in the source. */ interface OffsetFold { text: string starts: number[] ends: number[] } /** * Folds case and whitespace as `foldCaseWhitespace` does, keeping where each folded unit came from. * * Each code point is lower-cased on its own, so a final sigma folds as a medial one does * and `ΠΑΦΟΣ` matches `Πάφος`'s letters where the context-sensitive mapping wouldn't. */ function foldWithOffsets(input: string): OffsetFold { const fold: OffsetFold = { text: "", starts: [], ends: [] } let offset = 0 // The source offsets of a whitespace run not yet written, or -1 outside one. let spaceStart = -1 let spaceEnd = -1 for (const char of input) { const start = offset offset += char.length if (/\s/u.test(char)) { if (fold.text !== "") { spaceStart = spaceStart < 0 ? start : spaceStart spaceEnd = offset } continue } if (spaceStart >= 0) { fold.text += " " fold.starts.push(spaceStart) fold.ends.push(spaceEnd) spaceStart = -1 } const lowered = char.toLowerCase().replaceAll("ς", "σ") fold.text += lowered // One offset pair per UTF-16 unit, so an index into the folded text reads its source offsets. fold.starts.push(...Array.from({ length: lowered.length }).fill(start)) fold.ends.push(...Array.from({ length: lowered.length }).fill(offset)) } return fold } /** * The tag a surface takes in a form of `seed`. */ function surfaceTag(seed: ShapeSeed, surface: SeedSurface): CandidateSpan["tag"] { switch (surface.slot) { case SurfaceSlot.Name: return seed.place_tag case SurfaceSlot.Parent: return seed.parent_tag ?? "locality" case SurfaceSlot.Region: case SurfaceSlot.RegionAbbreviation: return "region" case SurfaceSlot.Country: return "country" } } /** * The shape id of a set of cited slots: the second segments in a fixed order, * or `bare` for a form that cites only the name. */ export function shapeOfSlots(slots: ReadonlySet): string { const parts = [ slots.has(SurfaceSlot.Parent) ? "parent" : null, slots.has(SurfaceSlot.Region) ? "region" : null, slots.has(SurfaceSlot.RegionAbbreviation) ? "region_abbr" : null, slots.has(SurfaceSlot.Country) ? "country" : null, ].filter((part) => part != null) return parts.length ? parts.join("+") : "bare" } /** * Whether the label policy writes a form with these slots for `seed`: one name, at most one surface per * other slot, a region written once, and a parent beside every place the seed has a parent slot for. */ function slotsAllowed(seed: ShapeSeed, surfaces: readonly SeedSurface[]): boolean { const count = (slot: SurfaceSlot) => surfaces.filter((surface) => surface.slot === slot).length if (count(SurfaceSlot.Name) !== 1) return false if (Object.values(SurfaceSlot).some((slot) => count(slot) > 1)) return false if (count(SurfaceSlot.Region) + count(SurfaceSlot.RegionAbbreviation) > 1) return false // A postal pair's parent is its region, so an abbreviation replaces the parent rather than joining it. if (seed.parent_tag === "region") { return count(SurfaceSlot.Parent) + count(SurfaceSlot.RegionAbbreviation) === 1 } return seed.parent_tag === "locality" ? count(SurfaceSlot.Parent) === 1 : count(SurfaceSlot.Parent) === 0 } function isLatin(text: string): boolean { return /\p{Script=Latin}/u.test(text) } function hasOtherScript(text: string): boolean { return /[^\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/u.test(text) } /** * Every order of `items`, the given order first. */ function* orderings(items: readonly T[]): Generator { if (items.length <= 1) { yield [...items] return } for (let index = 0; index < items.length; index++) { for (const rest of orderings([...items.slice(0, index), ...items.slice(index + 1)])) { yield [items[index]!, ...rest] } } } /** * Finds each surface in `fold` from left to right in the order given, or `null` when one is absent. */ function locateInOrder( fold: OffsetFold, surfaces: readonly SeedSurface[] ): Array<{ surface: SeedSurface; start: number; end: number }> | null { const located: Array<{ surface: SeedSurface; start: number; end: number }> = [] let from = 0 for (const surface of surfaces) { const needle = foldWithOffsets(surface.text).text const at = needle === "" ? -1 : fold.text.indexOf(needle, from) if (at < 0) return null from = at + needle.length located.push({ surface, start: fold.starts[at]!, end: fold.ends[from - 1]! }) } return located } /** * Every choice of one item from each list, in the lists' order. * A list without an item leaves no choice. */ function* choices(lists: ReadonlyArray): Generator { const [head, ...rest] = lists if (!head) { yield [] return } for (const item of head) { for (const tail of choices(rest)) { yield [item, ...tail] } } } function isSurfaceSlot(key: string): key is SurfaceSlot { return (Object.values(SurfaceSlot) as string[]).includes(key) } /** * Checks one returned form against its seed. * * A bare slot letter cited as a key stands for a key of that slot. * Each choice of keys is checked under the rules a numbered citation passes. * * The form is kept only when exactly one choice passes, so a letter never decides * between two surfaces the text could both be. */ export function validateForm(seed: ShapeSeed, form: ReturnedForm): ValidatedForm | FormDrop { const raw = form.raw.trim() if (raw === "" || raw.length > MAX_RAW_LENGTH || /[\n\r\t]/u.test(raw)) return FormDrop.Length const byKey = new Map(seed.surfaces.map((surface) => [surface.key, surface])) const options: SeedSurface[][] = [] let fromLetters = false for (const key of form.uses) { const surface = byKey.get(key) if (surface) { options.push([surface]) } else if (isSurfaceSlot(key)) { fromLetters = true options.push(seed.surfaces.filter((candidate) => candidate.slot === key)) } else { return FormDrop.UnknownSurface } } if (!options.length) return FormDrop.UnknownSurface if (!fromLetters) return validateCitedSurfaces(seed, raw, options.flat(), false) let passing: ValidatedForm | null = null for (const surfaces of choices(options)) { const result = validateCitedSurfaces(seed, raw, surfaces, true) if (typeof result === "string") continue if (passing) return FormDrop.LetterAmbiguous passing = result } return passing ?? FormDrop.LetterUnresolved } /** * Checks a form's text against the surfaces it cites. * * The surfaces are located in the cited order first and then in every other order, * and the first order that leaves only separators outside the spans is kept. */ function validateCitedSurfaces( seed: ShapeSeed, raw: string, surfaces: readonly SeedSurface[], fromLetters: boolean ): ValidatedForm | FormDrop { if (!slotsAllowed(seed, surfaces)) return FormDrop.SlotsNotAllowed if ( surfaces.some((surface) => hasOtherScript(surface.text)) && surfaces.some((surface) => !hasOtherScript(surface.text) && isLatin(surface.text)) ) { return FormDrop.MixedScript } const fold = foldWithOffsets(raw) let failure: FormDrop = FormDrop.UnresolvableSpan for (const order of orderings(surfaces)) { const located = locateInOrder(fold, order) if (!located) continue const gaps = located.map((span, index) => raw.slice(index === 0 ? 0 : located[index - 1]!.end, span.start)) const tail = raw.slice(located.at(-1)!.end) if (gaps[0] !== "" || ![...gaps, tail].every((gap) => SEPARATORS.test(gap)) || !/^[).]?$/u.test(tail)) { failure = FormDrop.UnsuppliedText continue } const touching = gaps.some( (gap, index) => index > 0 && gap === "" && !(UNSPACED_SCRIPT.test(raw[located[index]!.start]!) || UNSPACED_SCRIPT.test(raw[located[index]!.start - 1]!)) ) if (touching) { failure = FormDrop.UnseparatedSpans continue } return { wof_id: seed.wof_id, country: seed.country, band: seed.band, shape: shapeOfSlots(new Set(surfaces.map((surface) => surface.slot))), raw, spans: located.map(({ surface, start, end }) => ({ tag: surfaceTag(seed, surface), value: raw.slice(start, end), start, end, surface: surface.text, origin: surface.origin, })), keys_from_letters: fromLetters, } } return failure } /** * The kept forms of one place and its drops by reason, with a repeated text kept once. */ export function validatePlaceForms( seed: ShapeSeed, forms: readonly ReturnedForm[] ): { kept: ValidatedForm[]; drops: Partial> } { const kept: ValidatedForm[] = [] const drops: Partial> = {} const seen = new Set() for (const form of forms) { const result = validateForm(seed, form) const drop = typeof result === "string" ? result : seen.has(result.raw) ? FormDrop.Duplicate : null if (drop || typeof result === "string") { drops[drop!] = (drops[drop!] ?? 0) + 1 continue } seen.add(result.raw) kept.push(result) } return { kept, drops } } /** * What one request's response held: the kept forms, the drops by reason, * the forms returned and the places answered. */ export interface ValidatedResponse { kept: ValidatedForm[] drops: Partial> returned: number answered: Set } /** * Validates the response text of one request against the request's seeds, * or returns `null` when the text isn't the schema's shape. */ export function validateResponse(text: string, seeds: readonly ShapeSeed[]): ValidatedResponse | null { const places = parseShapeResponse(text) if (!places) return null const byID = new Map(seeds.map((seed) => [String(seed.wof_id), seed])) const kept: ValidatedForm[] = [] const drops: Partial> = {} const answered = new Set() let returned = 0 for (const place of places) { const seed = byID.get(place.id) returned += place.forms.length if (!seed || answered.has(seed.wof_id)) { const reason = seed ? "repeated_place" : "place_not_in_request" drops[reason] = (drops[reason] ?? 0) + place.forms.length continue } answered.add(seed.wof_id) const result = validatePlaceForms(seed, place.forms) kept.push(...result.kept) for (const [reason, n] of Object.entries(result.drops)) { drops[reason] = (drops[reason] ?? 0) + n } } return { kept, drops, returned, answered } } /** * The reason every form of a response dropped under, or `null` when a form was kept, * the response held no form, or its forms dropped under more than one reason. * * One reason taking a whole response is a fault of the request or of the validator rather than of a form. */ export function wholeResponseDropReason(response: ValidatedResponse): string | null { const reasons = Object.entries(response.drops).filter(([, n]) => (n ?? 0) > 0) if (response.kept.length || response.returned === 0 || reasons.length !== 1) return null return reasons[0]![0] } /** * Parses a response's text into its places, or returns `null` when the text isn't the schema's shape. * * A place or form of another shape makes the whole response unreadable rather than a * shorter list, so a caller never counts a partly read response as a complete one. */ export function parseShapeResponse(text: string): ReturnedPlace[] | null { const parsed = tryParsingJSON(text) as { places?: unknown } | null if (!parsed || !Array.isArray(parsed.places)) return null const places: ReturnedPlace[] = [] for (const place of parsed.places as Array | null>) { if (typeof place?.id !== "string" || !Array.isArray(place.forms)) return null for (const form of place.forms as Array | null>) { const readable = typeof form?.raw === "string" && Array.isArray(form.uses) && form.uses.every((key) => typeof key === "string") if (!readable) return null } places.push({ id: place.id, forms: place.forms }) } return places }