// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Labels the role of every variant name on a US locality in the WOF admin database with a language model. * * Usage: * node packages/corpus/lib/tools/name-roles/name-roles.run.ts --out [--model ] [--effort ] * [--chunk ] [--limit ] * * `pilot` sends `--limit` requests (default 3) one at a time at the standard price and prints their labels and token use. * `submit` writes `chunks.jsonl` and creates one batch, recording it in `batch.json`. * `status` prints the batch's state. * `collect` reads the finished batch and writes `labels.jsonl`, `failed-chunks.jsonl` and `summary.json`. * * The output is a review file. No build reads it, and a label reaches the gazetteer only through a later, separate change. */ import { writeLocalJSONFile, writeLocalJSONLFile } from "@mailwoman/core/fs/writers" import { parseArguments } from "@mailwoman/core/scripting/arguments" import { stringifyJSON } from "@mailwoman/core/values/json" 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 { openBuiltClient } from "@mailwoman/sqlite/sealed" import { PathBuilder, resolvePath } from "path-ts" import { collectLabelingBatch, pilotLabelingRequests, readLabelingBatch, submitLabelingBatch, countEach, toLabelingChunks, } from "#tools/anthropic/labeling" import { nameRoleRequestParams, parseNameRoleResponse, type VariantNameItem, type VariantNameLabel, } from "#tools/name-roles/prompt" /** * The distance within which the prompt tells the model to read a locality holding the * variant as its primary name as evidence of a separate community. * * The summary counts roles inside it, so a reader can see how the labels follow that instruction. */ const NEAR_COLLISION_KM = 15 const { values, positionals } = parseArguments({ allowPositionals: true, options: { out: { type: "string" }, model: { type: "string", default: "claude-opus-5-5" }, effort: { type: "string", default: "medium" }, chunk: { type: "string", default: "20" }, limit: { type: "string" }, }, }) const mode = positionals[0] if (!values.out) throw new Error("--out names the directory the chunks, batch record and labels 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 VariantNameItem[]) => parseNameRoleResponse(text, items.length) /** * Reads every variant name on a current US locality with the evidence one request shows beside it. */ async function readVariantItems(): Promise { using db = await openBuiltClient(wofDatabasePath("admin-global-priority.db")) const localities = await db .selectFrom("spr") .select(["id", "name", "latitude", "longitude"]) .where("country", "=", "US") .where("placetype", "=", "locality") .where("is_current", "!=", 0) .where("is_deprecated", "=", 0) .execute() const byID = new Map(localities.map((row) => [row.id, row])) const byKey = new Map() for (const row of localities) { if (!row.name) continue const key = normalizeLocalityForKey(row.name) const holders = byKey.get(key) if (holders) { holders.push(row.id) } else { byKey.set(key, [row.id]) } } const ancestorRows = await db .selectFrom("ancestors as a") .innerJoin("spr as l", "l.id", "a.id") .innerJoin("spr as p", "p.id", "a.ancestor_id") .select(["a.id as id", "a.ancestor_placetype as placetype", "p.name as name"]) .where("l.country", "=", "US") .where("l.placetype", "=", "locality") .where("a.ancestor_placetype", "in", ["county", "region"]) .execute() const county = new Map() const region = new Map() for (const row of ancestorRows) { if (!row.name) continue if (row.placetype === "county") { county.set(row.id, row.name) } else { region.set(row.id, row.name) } } const variants = await db .selectFrom("names") .select(["id", "name", "language"]) .where("privateuse", "=", "variant") .where("language", "in", ["und", "eng"]) .where("country", "=", "US") .where("placetype", "=", "locality") .orderBy("id") .orderBy("name") .execute() const siblings = new Map() for (const row of variants) { if (!byID.has(row.id)) continue const names = siblings.get(row.id) if (names) { names.push(row.name) } else { siblings.set(row.id, [row.name]) } } const items: VariantNameItem[] = [] const seen = new Set() for (const row of variants) { const holder = byID.get(row.id) if (!holder?.name) continue // The `und` and `eng` rows of one place repeat a name, and one label covers both. const dedupe = `${row.id}\u0000${row.name}` if (seen.has(dedupe)) continue seen.add(dedupe) const others = (byKey.get(normalizeLocalityForKey(row.name)) ?? []).filter((id) => id !== row.id) let nearest: VariantNameItem["nearest"] = null for (const id of others) { const other = byID.get(id)! const km = haversine(holder.latitude, holder.longitude, other.latitude, other.longitude, "km") if (!nearest || km < nearest.km) { nearest = { wofID: id, name: other.name!, county: county.get(id) ?? null, region: region.get(id) ?? null, km } } } items.push({ wofID: row.id, name: row.name, // The query keeps only the `und` and `eng` rows, so the column is never null here. language: row.language as string, holder: holder.name, county: county.get(row.id) ?? null, region: region.get(row.id) ?? null, latitude: holder.latitude, longitude: holder.longitude, siblings: [...new Set(siblings.get(row.id))].filter((name) => name !== row.name), collisions: others.length, nearest, }) } // One request then holds the places of one state, so its items share their geography. items.sort( (a, b) => (a.region ?? "").localeCompare(b.region ?? "") || a.wofID - b.wofID || a.name.localeCompare(b.name) ) return items } if (mode === "pilot") { const chunks = toLabelingChunks(await readVariantItems(), Number(values.chunk), "name-roles") const pilot = await pilotLabelingRequests( chunks, Number(values.limit ?? 3), settings, nameRoleRequestParams, parseLabels ) for (const { chunk, labels, usage } of pilot.requests) { for (const [i, item] of chunk.items.entries()) { const near = item.nearest ? `${item.nearest.name}, ${item.nearest.region} ${Math.round(item.nearest.km)} km` : "none" const label = labels[i]! console.log( `${label.role}\t${label.basis}\t${label.confidence}\t${item.name} | on ${item.holder}, ${item.county}, ${item.region} | collisions ${item.collisions}, nearest ${near}` ) } 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 readVariantItems(), Number(values.chunk), "name-roles") if (values.limit) { chunks = chunks.slice(0, Number(values.limit)) } console.log(stringifyJSON(await submitLabelingBatch(out, chunks, settings, nameRoleRequestParams))) } 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< VariantNameItem, VariantNameLabel >(out, parseLabels) const rows = labeled.map(({ item, label }) => ({ wof_id: item.wofID, name: item.name, language: item.language, holder: item.holder, county: item.county, region: item.region, collisions: item.collisions, nearest_wof_id: item.nearest?.wofID ?? null, nearest_km: item.nearest ? Number(item.nearest.km.toFixed(1)) : null, ...label, model: record.model, effort: record.effort, batch_id: record.id, })) await writeLocalJSONLFile(rows, out("labels.jsonl")) 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), roles: countEach(rows.map((row) => row.role)), bases: countEach(rows.map((row) => row.basis)), confidences: countEach(rows.map((row) => row.confidence)), rolesAmongCollisions: countEach(rows.filter((row) => row.collisions > 0).map((row) => row.role)), rolesWithANearCollision: countEach( rows.filter((row) => row.nearest_km != null && row.nearest_km <= NEAR_COLLISION_KM).map((row) => row.role) ), costUSD, } await writeLocalJSONFile(summary, out("summary.json")) console.log(stringifyJSON(summary)) } else { throw new Error(`The mode is one of pilot, submit, status and collect, and this run named ${String(mode)}`) }