// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Asks a language model whether a settlement the admin build added from Overture or GeoNames is a WOF * record under another spelling or script. * * Usage: * node packages/corpus/lib/tools/place-twins/place-twins.run.ts --out [--unmatched ] * [--take ] [--model ] [--effort ] [--chunk ] [--limit ] * * `census` reads the admin build's unmatched-places file, finds each settlement's WOF records inside the * match radius, and writes `items.jsonl` with one line per settlement that has at least one. * `pilot`, `submit`, `status` and `collect` then work as `name-roles.run.ts` does, over the first `--take` * items in the order `rankItems` gives them. `collect` writes `pairs.jsonl`. * * The output is a review file. An Overture pair belongs in `overture_wof_match`, a table of the Overture * part, and a GeoNames pair in the WOF forks' concordances. This tool writes to neither. */ import { appendLocalTextFile, writeLocalJSONFile, writeLocalJSONLFile, writeLocalTextFile, } from "@mailwoman/core/fs/writers" import { OVERTURE_ID_BASE } from "@mailwoman/core/resolver/synthetic-id-ranges" import { parseArguments } from "@mailwoman/core/scripting/arguments" import { stringifyJSON } from "@mailwoman/core/values/json" import { ownNameSimilarity, romanizeNameKey } from "@mailwoman/resolver-wof-sqlite/candidate/own-name" import { normalizeLocalityForKey } from "@mailwoman/resolver-wof-sqlite/labels/street/normalize" import { wofDatabasePath } from "@mailwoman/resolver-wof-sqlite/paths" import type { WOFDatabase } from "@mailwoman/resolver-wof-sqlite/schema" import { haversine } from "@mailwoman/spatial/geometries/point/distance" import type { DatabaseClient } from "@mailwoman/sqlite/client" import { openBuiltClient } from "@mailwoman/sqlite/sealed" import { PathBuilder, resolvePath } from "path-ts" import { JSONSpliterator } from "spliterator" import { collectLabelingBatch, pilotLabelingRequests, readLabelingBatch, submitLabelingBatch, countEach, toLabelingChunks, } from "#tools/anthropic/labeling" import { NameComparison, parsePlaceTwinResponse, placeTwinRequestParams, type AddedPlaceItem, type TwinCandidate, type TwinLabel, } from "#tools/place-twins/prompt" /** * The settlement tier of the admin build's matcher (`MATCH_TIERS.settlement` in * `packages/gazetteer/tools/pipeline/admin/sources/wof-match.ts`): the placetypes a * settlement may match across, and the farthest a matching WOF record may sit. */ const SETTLEMENT_PLACETYPES = ["locality", "localadmin", "borough"] const MATCH_RADIUS_KM = 5 const GRID_DEGREES = 0.05 const KM_PER_DEGREE = 111.32 const MAX_CANDIDATES = 4 const MAX_CANDIDATE_NAMES = 8 const MAX_ADDED_NAMES = 6 const ID_QUERY_SIZE = 500 /** * One line of the admin build's unmatched-places file, as `UnmatchedPlace` in the matcher writes it. */ interface UnmatchedLine { id: number source: "overture" | "geonames" sourceID: string name: string placetype: string country: string latitude: number longitude: number } const { values, positionals } = parseArguments({ allowPositionals: true, options: { out: { type: "string" }, unmatched: { type: "string" }, take: { type: "string" }, skip: { type: "string" }, items: { type: "string" }, model: { type: "string", default: "claude-opus-5-5" }, effort: { type: "string", default: "medium" }, chunk: { type: "string", default: "15" }, limit: { type: "string" }, }, }) const mode = positionals[0] if (!values.out) throw new Error("--out names the directory the items, batch record and pairs are written to") const out = PathBuilder.from(resolvePath(values.out as string)) const settings = { model: values.model as string, effort: values.effort as string } const parseLabels = (text: string, items: readonly AddedPlaceItem[]) => parsePlaceTwinResponse( text, items.map((item) => item.candidates.length) ) /** * Reads every name row of `ids`, grouped by id in the table's order. */ async function readNames(db: DatabaseClient, ids: readonly number[]): Promise> { const names = new Map() for (let start = 0; start < ids.length; start += ID_QUERY_SIZE) { const rows = await db .selectFrom("names") .select(["id", "name", "privateuse"]) .where("id", "in", ids.slice(start, start + ID_QUERY_SIZE)) .execute() // A preferred name leads, so the cap on names keeps it. rows.sort((a, b) => Number(b.privateuse === "preferred") - Number(a.privateuse === "preferred")) for (const row of rows) { const held = names.get(row.id) if (held) { held.push(row.name) } else { names.set(row.id, [row.name]) } } } return names } /** * The primary name first, then the other distinct names up to `cap`. */ function leadNames(primary: string, others: readonly string[] | undefined, cap: number): string[] { return [...new Set([primary, ...(others ?? [])])].slice(0, cap) } /** * The name key with every character outside letters, digits and spaces replaced by a space. * * `romanizeNameKey` returns `null` for a key that holds a hyphen, an apostrophe or an ʻokina, * so without this step `Ermengol-Serra` and `Al Miʻli` read as names in an uncovered script. */ function comparisonKey(name: string): string { return normalizeLocalityForKey(name) .replaceAll(/[^\p{L}\p{N}\s]/gu, " ") .replaceAll(/\s+/g, " ") .trim() } /** * Compares every name of an added place with every name of its candidates. */ function compareNames( added: readonly string[], candidates: readonly TwinCandidate[] ): Pick { const addedKeys = added.map((name) => comparisonKey(name)) const addedRomanizes = addedKeys.map((key) => romanizeNameKey(key) != null) let similarity: number | null = null let crossScript = false for (const candidate of candidates) { for (const name of candidate.names) { const key = comparisonKey(name) const romanizes = romanizeNameKey(key) != null for (const [index, addedKey] of addedKeys.entries()) { if (romanizes !== addedRomanizes[index]) { crossScript = true } const score = ownNameSimilarity(addedKey, key) if (score != null && (similarity == null || score > similarity)) { similarity = score } } } } if (similarity != null) return { comparison: NameComparison.Romanized, similarity: Number(similarity.toFixed(3)) } return { comparison: crossScript ? NameComparison.CrossScript : NameComparison.Uncovered, similarity: null } } /** * Builds the items of one country: each unmatched settlement with its WOF records inside the match radius. */ async function buildCountryItems( db: DatabaseClient, country: string, unmatched: readonly UnmatchedLine[] ): Promise { const records = await db .selectFrom("spr") .select(["id", "name", "placetype", "latitude", "longitude"]) .where("country", "=", country) .where("placetype", "in", SETTLEMENT_PLACETYPES) .where("is_current", "=", 1) .where("id", "<", OVERTURE_ID_BASE) .execute() const grid = new Map() for (const [index, record] of records.entries()) { const cell = `${Math.floor(record.latitude / GRID_DEGREES)}:${Math.floor(record.longitude / GRID_DEGREES)}` const held = grid.get(cell) if (held) { held.push(index) } else { grid.set(cell, [index]) } } const near: Array<{ place: UnmatchedLine; found: Array<{ index: number; km: number }> }> = [] for (const place of unmatched) { const row = Math.floor(place.latitude / GRID_DEGREES) const column = Math.floor(place.longitude / GRID_DEGREES) const rowSpan = Math.ceil(MATCH_RADIUS_KM / (KM_PER_DEGREE * GRID_DEGREES)) // A degree of longitude shortens toward the poles, so the radius spans more columns there. const kmPerLongitudeCell = KM_PER_DEGREE * GRID_DEGREES * Math.max(0.01, Math.cos((place.latitude * Math.PI) / 180)) const columnSpan = Math.min(200, Math.ceil(MATCH_RADIUS_KM / kmPerLongitudeCell)) const found: Array<{ index: number; km: number }> = [] for (let r = row - rowSpan; r <= row + rowSpan; r++) { for (let c = column - columnSpan; c <= column + columnSpan; c++) { for (const index of grid.get(`${r}:${c}`) ?? []) { const record = records[index]! const km = haversine(place.latitude, place.longitude, record.latitude, record.longitude, "km") if (km <= MATCH_RADIUS_KM) { found.push({ index, km }) } } } } if (!found.length) continue found.sort((a, b) => a.km - b.km) near.push({ place, found: found.slice(0, MAX_CANDIDATES) }) } const candidateNames = await readNames(db, [ ...new Set(near.flatMap(({ found }) => found.map(({ index }) => records[index]!.id))), ]) const addedNames = await readNames( db, near.map(({ place }) => place.id) ) return near.map(({ place, found }) => { const names = leadNames(place.name, addedNames.get(place.id), MAX_ADDED_NAMES) const candidates = found.map(({ index, km }) => { const record = records[index]! return { wofID: record.id, names: leadNames(record.name ?? "", candidateNames.get(record.id), MAX_CANDIDATE_NAMES).filter( (name) => name !== "" ), placetype: record.placetype ?? "", km: Number(km.toFixed(2)), } }) return { id: place.id, source: place.source, sourceID: place.sourceID, names, placetype: place.placetype, country: place.country, latitude: place.latitude, longitude: place.longitude, candidates, ...compareNames(names, candidates), } }) } /** * Orders the items a budget admits. * * Names in different scripts come first, because the romanizer cannot compare them and the model can. * The romanized pairs below a similarity of 1 follow from the most alike down. * * A pair at exactly 1 has two names that romanize to one string, so code can pair * it without the model, and it ranks after them. * The names outside the romanizer's scripts come last. */ function rankItems(items: AddedPlaceItem[]): AddedPlaceItem[] { const tier = (item: AddedPlaceItem) => { if (item.comparison === NameComparison.CrossScript) return 0 if (item.comparison === NameComparison.Uncovered) return 3 return item.similarity === 1 ? 2 : 1 } return items.toSorted( (a, b) => tier(a) - tier(b) || (b.similarity ?? 0) - (a.similarity ?? 0) || a.country.localeCompare(b.country) || a.id - b.id ) } async function readRankedItems(): Promise { // `--items` reads another directory's census, so a second batch over the same census keeps its own batch record. const itemsPath = values.items ? resolvePath(values.items as string) : out("items.jsonl") const items = rankItems(await JSONSpliterator.fromAsync(itemsPath).toArray()) const skip = Number(values.skip ?? 0) return values.take ? items.slice(skip, skip + Number(values.take)) : items.slice(skip) } if (mode === "census") { if (!values.unmatched) throw new Error("--unmatched names the admin build's unmatched-places file") const byCountry = new Map() let read = 0 for await (const line of JSONSpliterator.fromAsync(resolvePath(values.unmatched as string))) { read++ if (!SETTLEMENT_PLACETYPES.includes(line.placetype)) continue const held = byCountry.get(line.country) if (held) { held.push(line) } else { byCountry.set(line.country, [line]) } } using db = await openBuiltClient(wofDatabasePath("admin-global-priority.db")) // The file belongs to one build. // A line whose row the database lacks means the two came from different builds. const probe = [...byCountry.values()].flat().slice(0, 500) const present = await db .selectFrom("spr") .select("id") .where( "id", "in", probe.map((line) => line.id) ) .execute() if (present.length !== probe.length) { throw new Error( `${probe.length - present.length} of the first ${probe.length} unmatched places have no row in the admin database` ) } await writeLocalTextFile("", out("items.jsonl")) const comparisons: string[] = [] const sources: string[] = [] const similarities: number[] = [] let settlements = 0 for (const [country, lines] of [...byCountry].toSorted(([a], [b]) => a.localeCompare(b))) { settlements += lines.length const items = await buildCountryItems(db, country, lines) if (!items.length) continue await appendLocalTextFile(items.map((item) => `${stringifyJSON(item)}\n`).join(""), out("items.jsonl")) for (const item of items) { comparisons.push(item.comparison) sources.push(item.source) if (item.similarity != null) { similarities.push(item.similarity) } } } const census = { unmatchedPlaces: read, unmatchedSettlements: settlements, withAWOFRecordInRadius: comparisons.length, radiusKm: MATCH_RADIUS_KM, bySource: countEach(sources), byComparison: countEach(comparisons), romanizedSimilarity: countEach(similarities.map((value) => (Math.floor(value * 10) / 10).toFixed(1))), } await writeLocalJSONFile(census, out("census.json")) console.log(stringifyJSON(census)) } else if (mode === "pilot") { const chunks = toLabelingChunks(await readRankedItems(), Number(values.chunk), "place-twins") const pilot = await pilotLabelingRequests( chunks, Number(values.limit ?? 3), settings, placeTwinRequestParams, parseLabels ) for (const { chunk, labels, usage } of pilot.requests) { for (const [i, item] of chunk.items.entries()) { const label = labels[i]! const paired = label.match == null ? "-" : item.candidates[label.match]!.names.slice(0, 3).join(" / ") const offered = item.candidates.map((candidate) => `${candidate.names[0]} ${candidate.km} km`).join("; ") console.log( `${label.reason}\t${label.confidence}\t${item.country} ${item.names.slice(0, 3).join(" / ")} => ${paired} | offered: ${offered} | ${item.comparison} ${item.similarity ?? ""}` ) } console.log(stringifyJSON(usage)) } console.log( stringifyJSON({ requests: chunks.length, batchCostPerRequestUSD: Number(pilot.batchCostPerRequestUSD.toFixed(5)), projectedBatchCostUSD: Number((pilot.batchCostPerRequestUSD * chunks.length).toFixed(2)), }) ) } else if (mode === "submit") { let chunks = toLabelingChunks(await readRankedItems(), Number(values.chunk), "place-twins") if (values.limit) { chunks = chunks.slice(0, Number(values.limit)) } console.log(stringifyJSON(await submitLabelingBatch(out, chunks, settings, placeTwinRequestParams))) } else if (mode === "status") { const batch = await readLabelingBatch(out) console.log(stringifyJSON({ id: batch.id, status: batch.processing_status, ...batch.request_counts })) } else if (mode === "collect") { const { record, labeled, failed, resultsByType, costUSD } = await collectLabelingBatch( out, parseLabels ) const rows = labeled.map(({ item, label }) => { const paired = label.match == null ? null : item.candidates[label.match]! return { added_id: item.id, source: item.source, source_id: item.sourceID, country: item.country, placetype: item.placetype, names: item.names, wof_id: paired?.wofID ?? null, wof_names: paired?.names ?? null, km: paired?.km ?? null, candidates: item.candidates.length, comparison: item.comparison, similarity: item.similarity, reason: label.reason, confidence: label.confidence, model: record.model, effort: record.effort, batch_id: record.id, } }) await writeLocalJSONLFile(rows, out("pairs.jsonl")) const paired = rows.filter((row) => row.wof_id != null) const summary = { batch: record.id, model: record.model, effort: record.effort, requests: record.requests, resultsByType, items: record.items, labeled: rows.length, failedRequests: failed.length, failedItems: failed.reduce((sum, chunk) => sum + chunk.items, 0), paired: paired.length, pairedBySource: countEach(paired.map((row) => row.source)), pairedHighConfidence: paired.filter((row) => row.confidence === "high").length, reasons: countEach(rows.map((row) => row.reason)), confidences: countEach(rows.map((row) => row.confidence)), reasonsByComparison: Object.fromEntries( Object.values(NameComparison).map((comparison) => [ comparison, countEach(rows.filter((row) => row.comparison === comparison).map((row) => row.reason)), ]) ), pairedCountries: Object.keys(countEach(paired.map((row) => row.country))).length, costUSD, } await writeLocalJSONFile(summary, out("summary.json")) console.log(stringifyJSON(summary)) } else { throw new Error(`The mode is one of census, pilot, submit, status and collect, and this run named ${String(mode)}`) }