@mailwoman/corpus 11.5.0 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/builds/v0.8.22-wofrank-overlay/OVERLAY_PLAN.json +51 -0
- package/data/builds/v0.8.24-everyplace/inputs.json +35 -0
- package/data/training-configs/v8.17.0-stage1-gazetteer-v0822-s42.yaml +557 -0
- package/data/training-configs/v8.17.0-stage2-corpus-v0822-s42.yaml +1008 -0
- package/data/training-configs/v8.18.0-gazetteer-then-mixture-v0822-s42.yaml +1225 -0
- package/data/training-configs/v8.20.0-wofrank-v0822-s42.yaml +863 -0
- package/data/training-configs/v8.21.0-outcomes-v0822-s42.yaml +873 -0
- package/data/training-configs/v8.22.0-stage1-everyplace-v0824-s42.yaml +374 -0
- package/data/training-configs/v8.22.0-stage2-corpus-v0824-s42.yaml +808 -0
- package/data/training-configs/v8.22.1-stage1-everyplace-v0824-s42.yaml +376 -0
- package/data/training-configs/v8.22.1-stage2-corpus-v0824-s42.yaml +793 -0
- package/data/training-configs/v9.0.0-bytestem-v090-s42.yaml +665 -0
- package/data/training-manifests/v0.8.22-wofrank-overlay.json +9000 -0
- package/data/training-manifests/v0.8.24-everyplace-overlay.json +9000 -0
- package/data/training-manifests/v0.9.0-compact.effective.json +2556 -0
- package/data/training-manifests/v0.9.0-compact.json +9000 -0
- package/lib/adapters/wof/admin/json/adapter.ts +38 -3
- package/lib/adapters/wof/json-rows.ts +84 -5
- package/lib/adapters/wof/sample.ts +42 -6
- package/lib/build/code-hash.ts +1 -1
- package/lib/cjk/foreign-places.ts +1 -1
- package/lib/kr/adapters/localdata/permit-rows.ts +1 -1
- package/lib/parquet/schema.ts +7 -0
- package/lib/tools/anthropic/batches.ts +221 -0
- package/lib/tools/anthropic/labeling.ts +263 -0
- package/lib/tools/compact-v9.ts +872 -0
- package/lib/tools/fetch/wikidata/vital-places/entities.ts +20 -2
- package/lib/tools/fetch/wikidata/vital-places/qrank.ts +5 -4
- package/lib/tools/fragment-assay.run.ts +2 -1
- package/lib/tools/name-roles/name-roles.run.ts +296 -0
- package/lib/tools/name-roles/prompt.ts +253 -0
- package/lib/tools/overlay/deletions.ts +1 -1
- package/lib/tools/overlay/draw-weight.ts +275 -0
- package/lib/tools/place-twins/place-twins.run.ts +528 -0
- package/lib/tools/place-twins/prompt.ts +276 -0
- package/lib/tools/prominent-shapes/prominent-shapes.run.ts +420 -0
- package/lib/tools/prominent-shapes/prompt.ts +189 -0
- package/lib/tools/prominent-shapes/read-seeds.ts +286 -0
- package/lib/tools/prominent-shapes/seeds.ts +281 -0
- package/lib/tools/prominent-shapes/validate.ts +563 -0
- package/lib/training/config/admission.ts +9 -2
- package/lib/training/config/schema.ts +68 -1
- package/lib/types.ts +23 -0
- package/lib/utils/split.ts +1 -1
- package/out/adapters/wof/admin/json/adapter.d.ts +7 -0
- package/out/adapters/wof/admin/json/adapter.d.ts.map +1 -1
- package/out/adapters/wof/admin/json/adapter.js +28 -3
- package/out/adapters/wof/admin/json/adapter.js.map +1 -1
- package/out/adapters/wof/json-rows.d.ts +8 -0
- package/out/adapters/wof/json-rows.d.ts.map +1 -1
- package/out/adapters/wof/json-rows.js +56 -4
- package/out/adapters/wof/json-rows.js.map +1 -1
- package/out/adapters/wof/sample.d.ts +12 -0
- package/out/adapters/wof/sample.d.ts.map +1 -1
- package/out/adapters/wof/sample.js +37 -6
- package/out/adapters/wof/sample.js.map +1 -1
- package/out/build/code-hash.js +1 -1
- package/out/build/code-hash.js.map +1 -1
- package/out/cjk/foreign-places.js +1 -1
- package/out/cjk/foreign-places.js.map +1 -1
- package/out/kr/adapters/localdata/permit-rows.js +1 -1
- package/out/kr/adapters/localdata/permit-rows.js.map +1 -1
- package/out/parquet/schema.d.ts +6 -0
- package/out/parquet/schema.d.ts.map +1 -1
- package/out/parquet/schema.js +6 -0
- package/out/parquet/schema.js.map +1 -1
- package/out/tools/anthropic/batches.d.ts +117 -0
- package/out/tools/anthropic/batches.d.ts.map +1 -0
- package/out/tools/anthropic/batches.js +141 -0
- package/out/tools/anthropic/batches.js.map +1 -0
- package/out/tools/anthropic/labeling.d.ts +97 -0
- package/out/tools/anthropic/labeling.d.ts.map +1 -0
- package/out/tools/anthropic/labeling.js +146 -0
- package/out/tools/anthropic/labeling.js.map +1 -0
- package/out/tools/compact-v9.d.ts +117 -0
- package/out/tools/compact-v9.d.ts.map +1 -0
- package/out/tools/compact-v9.js +494 -0
- package/out/tools/compact-v9.js.map +1 -0
- package/out/tools/fetch/wikidata/vital-places/entities.d.ts +3 -0
- package/out/tools/fetch/wikidata/vital-places/entities.d.ts.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/entities.js +19 -1
- package/out/tools/fetch/wikidata/vital-places/entities.js.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/qrank.d.ts.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/qrank.js +4 -4
- package/out/tools/fetch/wikidata/vital-places/qrank.js.map +1 -1
- package/out/tools/fragment-assay.run.js +1 -1
- package/out/tools/fragment-assay.run.js.map +1 -1
- package/out/tools/name-roles/name-roles.run.d.ts +2 -0
- package/out/tools/name-roles/name-roles.run.d.ts.map +1 -0
- package/out/tools/name-roles/name-roles.run.js +230 -0
- package/out/tools/name-roles/name-roles.run.js.map +1 -0
- package/out/tools/name-roles/prompt.d.ts +166 -0
- package/out/tools/name-roles/prompt.d.ts.map +1 -0
- package/out/tools/name-roles/prompt.js +176 -0
- package/out/tools/name-roles/prompt.js.map +1 -0
- package/out/tools/overlay/deletions.js +1 -1
- package/out/tools/overlay/deletions.js.map +1 -1
- package/out/tools/overlay/draw-weight.d.ts +86 -0
- package/out/tools/overlay/draw-weight.d.ts.map +1 -0
- package/out/tools/overlay/draw-weight.js +131 -0
- package/out/tools/overlay/draw-weight.js.map +1 -0
- package/out/tools/place-twins/place-twins.run.d.ts +2 -0
- package/out/tools/place-twins/place-twins.run.d.ts.map +1 -0
- package/out/tools/place-twins/place-twins.run.js +385 -0
- package/out/tools/place-twins/place-twins.run.js.map +1 -0
- package/out/tools/place-twins/prompt.d.ts +169 -0
- package/out/tools/place-twins/prompt.d.ts.map +1 -0
- package/out/tools/place-twins/prompt.js +183 -0
- package/out/tools/place-twins/prompt.js.map +1 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.d.ts +2 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.d.ts.map +1 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.js +302 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.js.map +1 -0
- package/out/tools/prominent-shapes/prompt.d.ts +74 -0
- package/out/tools/prominent-shapes/prompt.d.ts.map +1 -0
- package/out/tools/prominent-shapes/prompt.js +156 -0
- package/out/tools/prominent-shapes/prompt.js.map +1 -0
- package/out/tools/prominent-shapes/read-seeds.d.ts +23 -0
- package/out/tools/prominent-shapes/read-seeds.d.ts.map +1 -0
- package/out/tools/prominent-shapes/read-seeds.js +219 -0
- package/out/tools/prominent-shapes/read-seeds.js.map +1 -0
- package/out/tools/prominent-shapes/seeds.d.ts +132 -0
- package/out/tools/prominent-shapes/seeds.d.ts.map +1 -0
- package/out/tools/prominent-shapes/seeds.js +178 -0
- package/out/tools/prominent-shapes/seeds.js.map +1 -0
- package/out/tools/prominent-shapes/validate.d.ts +152 -0
- package/out/tools/prominent-shapes/validate.d.ts.map +1 -0
- package/out/tools/prominent-shapes/validate.js +389 -0
- package/out/tools/prominent-shapes/validate.js.map +1 -0
- package/out/training/config/admission.d.ts +2 -1
- package/out/training/config/admission.d.ts.map +1 -1
- package/out/training/config/admission.js +9 -2
- package/out/training/config/admission.js.map +1 -1
- package/out/training/config/schema.d.ts +276 -1
- package/out/training/config/schema.d.ts.map +1 -1
- package/out/training/config/schema.js +64 -1
- package/out/training/config/schema.js.map +1 -1
- package/out/types.d.ts +21 -0
- package/out/types.d.ts.map +1 -1
- package/out/types.js +13 -0
- package/out/types.js.map +1 -1
- package/out/utils/split.js +1 -1
- package/out/utils/split.js.map +1 -1
- package/package.json +24 -24
|
@@ -123,8 +123,26 @@ const WIKIDATA_API_RETRY_BASE_DELAY_MS = 5000
|
|
|
123
123
|
|
|
124
124
|
/**
|
|
125
125
|
* The languages whose labels and aliases are kept when a caller passes none.
|
|
126
|
-
|
|
127
|
-
|
|
126
|
+
*
|
|
127
|
+
* Covers every language declared in `SUPPORT_PROMISES` (`en`, `fr`, `es`, `de`, `it`,
|
|
128
|
+
* `nl`, `pl`, `pt`, `sv`, `ja`) alongside `ru`, `zh`, `ar`, and `he`.
|
|
129
|
+
*/
|
|
130
|
+
export const DEFAULT_LANGUAGES: readonly string[] = [
|
|
131
|
+
"en",
|
|
132
|
+
"fr",
|
|
133
|
+
"es",
|
|
134
|
+
"de",
|
|
135
|
+
"it",
|
|
136
|
+
"pt",
|
|
137
|
+
"ru",
|
|
138
|
+
"ja",
|
|
139
|
+
"zh",
|
|
140
|
+
"ar",
|
|
141
|
+
"he",
|
|
142
|
+
"nl",
|
|
143
|
+
"pl",
|
|
144
|
+
"sv",
|
|
145
|
+
]
|
|
128
146
|
|
|
129
147
|
/**
|
|
130
148
|
* The item for Earth, the globe a kept coordinate must sit on.
|
|
@@ -119,16 +119,17 @@ export async function readQRankDatapackage(client: Pick<APIClient, "fetch">): Pr
|
|
|
119
119
|
const hash = typeof resource?.hash === "string" ? resource.hash : null
|
|
120
120
|
const license = body.licenses?.[0]?.name
|
|
121
121
|
|
|
122
|
-
if (typeof body.version !== "string") throw new
|
|
122
|
+
if (typeof body.version !== "string") throw new TypeError(`${QRANK_DATAPACKAGE_URL}: version is not a string`)
|
|
123
123
|
|
|
124
|
-
if (typeof resource?.path !== "string")
|
|
124
|
+
if (typeof resource?.path !== "string")
|
|
125
|
+
throw new TypeError(`${QRANK_DATAPACKAGE_URL}: resources[0].path is not a string`)
|
|
125
126
|
|
|
126
127
|
if (typeof resource.bytes !== "number")
|
|
127
|
-
throw new
|
|
128
|
+
throw new TypeError(`${QRANK_DATAPACKAGE_URL}: resources[0].bytes is not a number`)
|
|
128
129
|
|
|
129
130
|
if (!hash?.startsWith("sha256:")) throw new Error(`${QRANK_DATAPACKAGE_URL}: resources[0].hash is not a sha256`)
|
|
130
131
|
|
|
131
|
-
if (typeof license !== "string") throw new
|
|
132
|
+
if (typeof license !== "string") throw new TypeError(`${QRANK_DATAPACKAGE_URL}: licenses[0].name is not a string`)
|
|
132
133
|
|
|
133
134
|
return {
|
|
134
135
|
version: body.version,
|
|
@@ -43,7 +43,8 @@ const command = "fragment-assay"
|
|
|
43
43
|
const outParquet = requiredArgument(command, "--out-parquet", values["out-parquet"])
|
|
44
44
|
const cap = Number(values["per-locale-cap"])
|
|
45
45
|
|
|
46
|
-
if (!Number.isSafeInteger(cap))
|
|
46
|
+
if (!Number.isSafeInteger(cap))
|
|
47
|
+
throw new TypeError(`--per-locale-cap must be an integer, got ${values["per-locale-cap"]}`)
|
|
47
48
|
|
|
48
49
|
const admission = await openSourceRightsAdmission({
|
|
49
50
|
context: "fragment-assay build",
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file Labels the role of every variant name on a US locality in the WOF admin database with a language model.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* node packages/corpus/lib/tools/name-roles/name-roles.run.ts <mode> --out <dir> [--model <id>] [--effort <level>]
|
|
9
|
+
* [--chunk <items per request>] [--limit <requests>]
|
|
10
|
+
*
|
|
11
|
+
* `pilot` sends `--limit` requests (default 3) one at a time at the standard price and prints their labels and token use.
|
|
12
|
+
* `submit` writes `chunks.jsonl` and creates one batch, recording it in `batch.json`.
|
|
13
|
+
* `status` prints the batch's state.
|
|
14
|
+
* `collect` reads the finished batch and writes `labels.jsonl`, `failed-chunks.jsonl` and `summary.json`.
|
|
15
|
+
*
|
|
16
|
+
* The output is a review file. No build reads it, and a label reaches the gazetteer only through a later, separate change.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { writeLocalJSONFile, writeLocalJSONLFile } from "@mailwoman/core/fs/writers"
|
|
20
|
+
import { parseArguments } from "@mailwoman/core/scripting/arguments"
|
|
21
|
+
import { stringifyJSON } from "@mailwoman/core/values/json"
|
|
22
|
+
import { normalizeLocalityForKey } from "@mailwoman/resolver-wof-sqlite/labels/street/normalize"
|
|
23
|
+
import { wofDatabasePath } from "@mailwoman/resolver-wof-sqlite/paths"
|
|
24
|
+
import type { WOFDatabase } from "@mailwoman/resolver-wof-sqlite/schema"
|
|
25
|
+
import { haversine } from "@mailwoman/spatial/geometries/point/distance"
|
|
26
|
+
import { openBuiltClient } from "@mailwoman/sqlite/sealed"
|
|
27
|
+
import { PathBuilder, resolvePath } from "path-ts"
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
collectLabelingBatch,
|
|
31
|
+
pilotLabelingRequests,
|
|
32
|
+
readLabelingBatch,
|
|
33
|
+
submitLabelingBatch,
|
|
34
|
+
countEach,
|
|
35
|
+
toLabelingChunks,
|
|
36
|
+
} from "#tools/anthropic/labeling"
|
|
37
|
+
import {
|
|
38
|
+
nameRoleRequestParams,
|
|
39
|
+
parseNameRoleResponse,
|
|
40
|
+
type VariantNameItem,
|
|
41
|
+
type VariantNameLabel,
|
|
42
|
+
} from "#tools/name-roles/prompt"
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The distance within which the prompt tells the model to read a locality holding the
|
|
46
|
+
* variant as its primary name as evidence of a separate community.
|
|
47
|
+
*
|
|
48
|
+
* The summary counts roles inside it, so a reader can see how the labels follow that instruction.
|
|
49
|
+
*/
|
|
50
|
+
const NEAR_COLLISION_KM = 15
|
|
51
|
+
|
|
52
|
+
const { values, positionals } = parseArguments({
|
|
53
|
+
allowPositionals: true,
|
|
54
|
+
options: {
|
|
55
|
+
out: { type: "string" },
|
|
56
|
+
model: { type: "string", default: "claude-opus-5-5" },
|
|
57
|
+
effort: { type: "string", default: "medium" },
|
|
58
|
+
chunk: { type: "string", default: "20" },
|
|
59
|
+
limit: { type: "string" },
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const mode = positionals[0]
|
|
64
|
+
|
|
65
|
+
if (!values.out) throw new Error("--out names the directory the chunks, batch record and labels are written to")
|
|
66
|
+
|
|
67
|
+
const out = PathBuilder.from(resolvePath(values.out as string))
|
|
68
|
+
const settings = { model: values.model as string, effort: values.effort as string }
|
|
69
|
+
const parseLabels = (text: string, items: readonly VariantNameItem[]) => parseNameRoleResponse(text, items.length)
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Reads every variant name on a current US locality with the evidence one request shows beside it.
|
|
73
|
+
*/
|
|
74
|
+
async function readVariantItems(): Promise<VariantNameItem[]> {
|
|
75
|
+
using db = await openBuiltClient<WOFDatabase>(wofDatabasePath("admin-global-priority.db"))
|
|
76
|
+
|
|
77
|
+
const localities = await db
|
|
78
|
+
.selectFrom("spr")
|
|
79
|
+
.select(["id", "name", "latitude", "longitude"])
|
|
80
|
+
.where("country", "=", "US")
|
|
81
|
+
.where("placetype", "=", "locality")
|
|
82
|
+
.where("is_current", "!=", 0)
|
|
83
|
+
.where("is_deprecated", "=", 0)
|
|
84
|
+
.execute()
|
|
85
|
+
|
|
86
|
+
const byID = new Map(localities.map((row) => [row.id, row]))
|
|
87
|
+
const byKey = new Map<string, number[]>()
|
|
88
|
+
|
|
89
|
+
for (const row of localities) {
|
|
90
|
+
if (!row.name) continue
|
|
91
|
+
|
|
92
|
+
const key = normalizeLocalityForKey(row.name)
|
|
93
|
+
const holders = byKey.get(key)
|
|
94
|
+
|
|
95
|
+
if (holders) {
|
|
96
|
+
holders.push(row.id)
|
|
97
|
+
} else {
|
|
98
|
+
byKey.set(key, [row.id])
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const ancestorRows = await db
|
|
103
|
+
.selectFrom("ancestors as a")
|
|
104
|
+
.innerJoin("spr as l", "l.id", "a.id")
|
|
105
|
+
.innerJoin("spr as p", "p.id", "a.ancestor_id")
|
|
106
|
+
.select(["a.id as id", "a.ancestor_placetype as placetype", "p.name as name"])
|
|
107
|
+
.where("l.country", "=", "US")
|
|
108
|
+
.where("l.placetype", "=", "locality")
|
|
109
|
+
.where("a.ancestor_placetype", "in", ["county", "region"])
|
|
110
|
+
.execute()
|
|
111
|
+
|
|
112
|
+
const county = new Map<number, string>()
|
|
113
|
+
const region = new Map<number, string>()
|
|
114
|
+
|
|
115
|
+
for (const row of ancestorRows) {
|
|
116
|
+
if (!row.name) continue
|
|
117
|
+
|
|
118
|
+
if (row.placetype === "county") {
|
|
119
|
+
county.set(row.id, row.name)
|
|
120
|
+
} else {
|
|
121
|
+
region.set(row.id, row.name)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const variants = await db
|
|
126
|
+
.selectFrom("names")
|
|
127
|
+
.select(["id", "name", "language"])
|
|
128
|
+
.where("privateuse", "=", "variant")
|
|
129
|
+
.where("language", "in", ["und", "eng"])
|
|
130
|
+
.where("country", "=", "US")
|
|
131
|
+
.where("placetype", "=", "locality")
|
|
132
|
+
.orderBy("id")
|
|
133
|
+
.orderBy("name")
|
|
134
|
+
.execute()
|
|
135
|
+
|
|
136
|
+
const siblings = new Map<number, string[]>()
|
|
137
|
+
|
|
138
|
+
for (const row of variants) {
|
|
139
|
+
if (!byID.has(row.id)) continue
|
|
140
|
+
|
|
141
|
+
const names = siblings.get(row.id)
|
|
142
|
+
|
|
143
|
+
if (names) {
|
|
144
|
+
names.push(row.name)
|
|
145
|
+
} else {
|
|
146
|
+
siblings.set(row.id, [row.name])
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const items: VariantNameItem[] = []
|
|
151
|
+
const seen = new Set<string>()
|
|
152
|
+
|
|
153
|
+
for (const row of variants) {
|
|
154
|
+
const holder = byID.get(row.id)
|
|
155
|
+
|
|
156
|
+
if (!holder?.name) continue
|
|
157
|
+
|
|
158
|
+
// The `und` and `eng` rows of one place repeat a name, and one label covers both.
|
|
159
|
+
const dedupe = `${row.id}\u0000${row.name}`
|
|
160
|
+
|
|
161
|
+
if (seen.has(dedupe)) continue
|
|
162
|
+
|
|
163
|
+
seen.add(dedupe)
|
|
164
|
+
|
|
165
|
+
const others = (byKey.get(normalizeLocalityForKey(row.name)) ?? []).filter((id) => id !== row.id)
|
|
166
|
+
let nearest: VariantNameItem["nearest"] = null
|
|
167
|
+
|
|
168
|
+
for (const id of others) {
|
|
169
|
+
const other = byID.get(id)!
|
|
170
|
+
const km = haversine(holder.latitude, holder.longitude, other.latitude, other.longitude, "km")
|
|
171
|
+
|
|
172
|
+
if (!nearest || km < nearest.km) {
|
|
173
|
+
nearest = { wofID: id, name: other.name!, county: county.get(id) ?? null, region: region.get(id) ?? null, km }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
items.push({
|
|
178
|
+
wofID: row.id,
|
|
179
|
+
name: row.name,
|
|
180
|
+
// The query keeps only the `und` and `eng` rows, so the column is never null here.
|
|
181
|
+
language: row.language as string,
|
|
182
|
+
holder: holder.name,
|
|
183
|
+
county: county.get(row.id) ?? null,
|
|
184
|
+
region: region.get(row.id) ?? null,
|
|
185
|
+
latitude: holder.latitude,
|
|
186
|
+
longitude: holder.longitude,
|
|
187
|
+
siblings: [...new Set(siblings.get(row.id))].filter((name) => name !== row.name),
|
|
188
|
+
collisions: others.length,
|
|
189
|
+
nearest,
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// One request then holds the places of one state, so its items share their geography.
|
|
194
|
+
items.sort(
|
|
195
|
+
(a, b) => (a.region ?? "").localeCompare(b.region ?? "") || a.wofID - b.wofID || a.name.localeCompare(b.name)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
return items
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (mode === "pilot") {
|
|
202
|
+
const chunks = toLabelingChunks(await readVariantItems(), Number(values.chunk), "name-roles")
|
|
203
|
+
|
|
204
|
+
const pilot = await pilotLabelingRequests(
|
|
205
|
+
chunks,
|
|
206
|
+
Number(values.limit ?? 3),
|
|
207
|
+
settings,
|
|
208
|
+
nameRoleRequestParams,
|
|
209
|
+
parseLabels
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
for (const { chunk, labels, usage } of pilot.requests) {
|
|
213
|
+
for (const [i, item] of chunk.items.entries()) {
|
|
214
|
+
const near = item.nearest
|
|
215
|
+
? `${item.nearest.name}, ${item.nearest.region} ${Math.round(item.nearest.km)} km`
|
|
216
|
+
: "none"
|
|
217
|
+
|
|
218
|
+
const label = labels[i]!
|
|
219
|
+
|
|
220
|
+
console.log(
|
|
221
|
+
`${label.role}\t${label.basis}\t${label.confidence}\t${item.name} | on ${item.holder}, ${item.county}, ${item.region} | collisions ${item.collisions}, nearest ${near}`
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
console.log(stringifyJSON(usage))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
console.log(
|
|
229
|
+
stringifyJSON({
|
|
230
|
+
requests: chunks.length,
|
|
231
|
+
batchCostPerRequestUSD: Number(pilot.batchCostPerRequestUSD.toFixed(5)),
|
|
232
|
+
projectedBatchCostUSD: Number((pilot.batchCostPerRequestUSD * chunks.length).toFixed(2)),
|
|
233
|
+
})
|
|
234
|
+
)
|
|
235
|
+
} else if (mode === "submit") {
|
|
236
|
+
let chunks = toLabelingChunks(await readVariantItems(), Number(values.chunk), "name-roles")
|
|
237
|
+
|
|
238
|
+
if (values.limit) {
|
|
239
|
+
chunks = chunks.slice(0, Number(values.limit))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
console.log(stringifyJSON(await submitLabelingBatch(out, chunks, settings, nameRoleRequestParams)))
|
|
243
|
+
} else if (mode === "status") {
|
|
244
|
+
const batch = await readLabelingBatch(out)
|
|
245
|
+
|
|
246
|
+
console.log(stringifyJSON({ id: batch.id, status: batch.processing_status, ...batch.request_counts }))
|
|
247
|
+
} else if (mode === "collect") {
|
|
248
|
+
const { record, labeled, failed, resultsByType, costUSD } = await collectLabelingBatch<
|
|
249
|
+
VariantNameItem,
|
|
250
|
+
VariantNameLabel
|
|
251
|
+
>(out, parseLabels)
|
|
252
|
+
|
|
253
|
+
const rows = labeled.map(({ item, label }) => ({
|
|
254
|
+
wof_id: item.wofID,
|
|
255
|
+
name: item.name,
|
|
256
|
+
language: item.language,
|
|
257
|
+
holder: item.holder,
|
|
258
|
+
county: item.county,
|
|
259
|
+
region: item.region,
|
|
260
|
+
collisions: item.collisions,
|
|
261
|
+
nearest_wof_id: item.nearest?.wofID ?? null,
|
|
262
|
+
nearest_km: item.nearest ? Number(item.nearest.km.toFixed(1)) : null,
|
|
263
|
+
...label,
|
|
264
|
+
model: record.model,
|
|
265
|
+
effort: record.effort,
|
|
266
|
+
batch_id: record.id,
|
|
267
|
+
}))
|
|
268
|
+
|
|
269
|
+
await writeLocalJSONLFile(rows, out("labels.jsonl"))
|
|
270
|
+
|
|
271
|
+
const summary = {
|
|
272
|
+
batch: record.id,
|
|
273
|
+
model: record.model,
|
|
274
|
+
effort: record.effort,
|
|
275
|
+
requests: record.requests,
|
|
276
|
+
resultsByType,
|
|
277
|
+
items: record.items,
|
|
278
|
+
labeled: rows.length,
|
|
279
|
+
failedRequests: failed.length,
|
|
280
|
+
failedItems: failed.reduce((sum, chunk) => sum + chunk.items, 0),
|
|
281
|
+
roles: countEach(rows.map((row) => row.role)),
|
|
282
|
+
bases: countEach(rows.map((row) => row.basis)),
|
|
283
|
+
confidences: countEach(rows.map((row) => row.confidence)),
|
|
284
|
+
rolesAmongCollisions: countEach(rows.filter((row) => row.collisions > 0).map((row) => row.role)),
|
|
285
|
+
rolesWithANearCollision: countEach(
|
|
286
|
+
rows.filter((row) => row.nearest_km != null && row.nearest_km <= NEAR_COLLISION_KM).map((row) => row.role)
|
|
287
|
+
),
|
|
288
|
+
costUSD,
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
await writeLocalJSONFile(summary, out("summary.json"))
|
|
292
|
+
|
|
293
|
+
console.log(stringifyJSON(summary))
|
|
294
|
+
} else {
|
|
295
|
+
throw new Error(`The mode is one of pilot, submit, status and collect, and this run named ${String(mode)}`)
|
|
296
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file The request and response shapes of the variant-name role labeling: what one variant name on a
|
|
6
|
+
* Who's On First locality is, as a language model reads it from the place, its county and the other
|
|
7
|
+
* localities that hold the same name as their primary one.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { stringifyJSON, tryParsingJSON } from "@mailwoman/core/values/json"
|
|
11
|
+
|
|
12
|
+
import type { MessageBatchRequest } from "#tools/anthropic/batches"
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What a variant name is in relation to the place that holds it.
|
|
16
|
+
*/
|
|
17
|
+
export const VariantNameRole = {
|
|
18
|
+
/**
|
|
19
|
+
* A respelling of the place's own primary name, such as `Cross Roads` on `Crossroads`.
|
|
20
|
+
*/
|
|
21
|
+
Spelling: "same_place_spelling",
|
|
22
|
+
/**
|
|
23
|
+
* An earlier name of the same settlement.
|
|
24
|
+
*/
|
|
25
|
+
Former: "same_place_former",
|
|
26
|
+
/**
|
|
27
|
+
* Another name in present use for the same settlement.
|
|
28
|
+
*/
|
|
29
|
+
Alternate: "same_place_alternate",
|
|
30
|
+
/**
|
|
31
|
+
* The name of a separate community, standing or absorbed, near the holder.
|
|
32
|
+
*/
|
|
33
|
+
OtherPlace: "other_place",
|
|
34
|
+
/**
|
|
35
|
+
* The name of a post office, station, landing, mine or other feature that isn't a settlement.
|
|
36
|
+
*/
|
|
37
|
+
Feature: "feature",
|
|
38
|
+
/**
|
|
39
|
+
* The evidence supplied and the model's recall decide no role.
|
|
40
|
+
*/
|
|
41
|
+
Unknown: "unknown",
|
|
42
|
+
} as const
|
|
43
|
+
|
|
44
|
+
export type VariantNameRole = (typeof VariantNameRole)[keyof typeof VariantNameRole]
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* What a label rests on.
|
|
48
|
+
*/
|
|
49
|
+
export const LabelBasis = {
|
|
50
|
+
/**
|
|
51
|
+
* The model recalls this specific place's naming history.
|
|
52
|
+
*/
|
|
53
|
+
Known: "known",
|
|
54
|
+
/**
|
|
55
|
+
* The supplied collision and distance decide it.
|
|
56
|
+
*/
|
|
57
|
+
Context: "context",
|
|
58
|
+
/**
|
|
59
|
+
* Only the shape of the two strings decides it.
|
|
60
|
+
*/
|
|
61
|
+
Form: "form",
|
|
62
|
+
} as const
|
|
63
|
+
|
|
64
|
+
export type LabelBasis = (typeof LabelBasis)[keyof typeof LabelBasis]
|
|
65
|
+
|
|
66
|
+
const CONFIDENCES = ["high", "medium", "low"] as const
|
|
67
|
+
|
|
68
|
+
export type LabelConfidence = (typeof CONFIDENCES)[number]
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One variant name with the evidence the model reads beside it.
|
|
72
|
+
*/
|
|
73
|
+
export interface VariantNameItem {
|
|
74
|
+
/**
|
|
75
|
+
* The holder's WOF id.
|
|
76
|
+
*/
|
|
77
|
+
wofID: number
|
|
78
|
+
/**
|
|
79
|
+
* The variant name as the `names` table writes it.
|
|
80
|
+
*/
|
|
81
|
+
name: string
|
|
82
|
+
/**
|
|
83
|
+
* The `names.language` of the row, `und` for a GNIS variant.
|
|
84
|
+
*/
|
|
85
|
+
language: string
|
|
86
|
+
/**
|
|
87
|
+
* The holder's primary name.
|
|
88
|
+
*/
|
|
89
|
+
holder: string
|
|
90
|
+
county: string | null
|
|
91
|
+
region: string | null
|
|
92
|
+
latitude: number
|
|
93
|
+
longitude: number
|
|
94
|
+
/**
|
|
95
|
+
* The holder's other variant names.
|
|
96
|
+
*/
|
|
97
|
+
siblings: string[]
|
|
98
|
+
/**
|
|
99
|
+
* The count of other US localities whose primary name has this name's key.
|
|
100
|
+
*/
|
|
101
|
+
collisions: number
|
|
102
|
+
/**
|
|
103
|
+
* The nearest of those localities, or `null` when the count is zero.
|
|
104
|
+
*/
|
|
105
|
+
nearest: { wofID: number; name: string; county: string | null; region: string | null; km: number } | null
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A label states the role the model assigned to one item, what the role rests on,
|
|
110
|
+
* and the model's confidence.
|
|
111
|
+
*/
|
|
112
|
+
export interface VariantNameLabel {
|
|
113
|
+
role: VariantNameRole
|
|
114
|
+
basis: LabelBasis
|
|
115
|
+
confidence: LabelConfidence
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The system prompt of every name-role request states the six roles, the three bases,
|
|
120
|
+
* and the rule that a locality holding the variant as its primary name within about
|
|
121
|
+
* 15 kilometers is evidence of a separate community.
|
|
122
|
+
*/
|
|
123
|
+
export const NAME_ROLE_SYSTEM_PROMPT = `You label variant names of United States populated places for a gazetteer.
|
|
124
|
+
|
|
125
|
+
Each item is one variant name that the USGS Geographic Names Information System or Who's On First records on a locality. A geocoder returns the locality when a user types the variant, so the gazetteer needs to know what the variant is. Some variants are earlier or alternate names of the same settlement. Others are the names of separate communities that a record absorbed, and many of those are also the primary name of a different locality elsewhere.
|
|
126
|
+
|
|
127
|
+
For each item you receive: the variant name, the locality that holds it with its county, state and coordinates, the locality's other variant names, the number of other US localities whose primary name is this variant, and the nearest of those with its distance in kilometers.
|
|
128
|
+
|
|
129
|
+
Assign one role:
|
|
130
|
+
- same_place_spelling: a respelling, spacing, punctuation or abbreviation difference of the holder's own primary name.
|
|
131
|
+
- same_place_former: an earlier name of the same settlement.
|
|
132
|
+
- same_place_alternate: another name in present use for the same settlement.
|
|
133
|
+
- other_place: the name of a separate community, standing today or absorbed, including a neighboring settlement that the nearest collision identifies.
|
|
134
|
+
- feature: the name of a post office, railroad station, landing, mine, camp or other feature that was never the settlement's name.
|
|
135
|
+
- unknown: neither your knowledge of the place nor the supplied evidence decides.
|
|
136
|
+
|
|
137
|
+
State the basis: "known" when you recall this specific place's naming history, "context" when the supplied collision and distance decide it, "form" when only the two strings decide it. State your confidence as high, medium or low. A nearby locality with the variant as its primary name, within about 15 kilometers, is strong evidence for other_place. A collision hundreds of kilometers away is a coincidence of common names and decides no role. Prefer unknown at low confidence over a guess.
|
|
138
|
+
|
|
139
|
+
Return one label per item, with the item's index.`
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The structured-output schema of one response: a label per item, addressed
|
|
143
|
+
* by the item's index in the request.
|
|
144
|
+
*/
|
|
145
|
+
export const NAME_ROLE_RESPONSE_SCHEMA = {
|
|
146
|
+
type: "object",
|
|
147
|
+
additionalProperties: false,
|
|
148
|
+
required: ["labels"],
|
|
149
|
+
properties: {
|
|
150
|
+
labels: {
|
|
151
|
+
type: "array",
|
|
152
|
+
items: {
|
|
153
|
+
type: "object",
|
|
154
|
+
additionalProperties: false,
|
|
155
|
+
required: ["i", "role", "basis", "confidence"],
|
|
156
|
+
properties: {
|
|
157
|
+
i: { type: "integer" },
|
|
158
|
+
role: { type: "string", enum: Object.values(VariantNameRole) },
|
|
159
|
+
basis: { type: "string", enum: Object.values(LabelBasis) },
|
|
160
|
+
confidence: { type: "string", enum: [...CONFIDENCES] },
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
} as const
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Renders the items of one request as the user message the model reads.
|
|
169
|
+
*/
|
|
170
|
+
export function renderNameRoleItems(items: readonly VariantNameItem[]): string {
|
|
171
|
+
const rows = items.map((item, i) => ({
|
|
172
|
+
i,
|
|
173
|
+
variant: item.name,
|
|
174
|
+
holder: item.holder,
|
|
175
|
+
county: item.county,
|
|
176
|
+
state: item.region,
|
|
177
|
+
lat: Number(item.latitude.toFixed(3)),
|
|
178
|
+
lon: Number(item.longitude.toFixed(3)),
|
|
179
|
+
other_variants: item.siblings,
|
|
180
|
+
localities_with_this_primary_name: item.collisions,
|
|
181
|
+
nearest: item.nearest
|
|
182
|
+
? {
|
|
183
|
+
name: item.nearest.name,
|
|
184
|
+
county: item.nearest.county,
|
|
185
|
+
state: item.nearest.region,
|
|
186
|
+
km: Math.round(item.nearest.km),
|
|
187
|
+
}
|
|
188
|
+
: null,
|
|
189
|
+
}))
|
|
190
|
+
|
|
191
|
+
return rows.map((row) => stringifyJSON(row)).join("\n")
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Builds the Messages parameters of one request.
|
|
196
|
+
*/
|
|
197
|
+
export function nameRoleRequestParams(
|
|
198
|
+
items: readonly VariantNameItem[],
|
|
199
|
+
options: { model: string; effort: string }
|
|
200
|
+
): MessageBatchRequest["params"] {
|
|
201
|
+
return {
|
|
202
|
+
model: options.model,
|
|
203
|
+
max_tokens: 8000,
|
|
204
|
+
system: NAME_ROLE_SYSTEM_PROMPT,
|
|
205
|
+
output_config: { effort: options.effort, format: { type: "json_schema", schema: NAME_ROLE_RESPONSE_SCHEMA } },
|
|
206
|
+
messages: [{ role: "user", content: renderNameRoleItems(items) }],
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const ROLES: ReadonlySet<string> = new Set(Object.values(VariantNameRole))
|
|
211
|
+
const BASES: ReadonlySet<string> = new Set(Object.values(LabelBasis))
|
|
212
|
+
const CONFIDENCE_SET: ReadonlySet<string> = new Set(CONFIDENCES)
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Parses one response into a label per item index.
|
|
216
|
+
*
|
|
217
|
+
* @throws When the text fails to parse as the schema's object, an index is outside
|
|
218
|
+
* the request or repeated, a value is outside its enumeration, or the response
|
|
219
|
+
* labels a different number of items than the request held.
|
|
220
|
+
*/
|
|
221
|
+
export function parseNameRoleResponse(text: string, itemCount: number): VariantNameLabel[] {
|
|
222
|
+
const parsed = tryParsingJSON(text) as { labels?: unknown } | null
|
|
223
|
+
|
|
224
|
+
if (!parsed || !Array.isArray(parsed.labels)) throw new Error("The response holds no `labels` array")
|
|
225
|
+
|
|
226
|
+
const labels: Array<VariantNameLabel | null> = Array.from({ length: itemCount }, () => null)
|
|
227
|
+
|
|
228
|
+
for (const entry of parsed.labels as Array<Record<string, unknown>>) {
|
|
229
|
+
const { i, role, basis, confidence } = entry
|
|
230
|
+
|
|
231
|
+
if (typeof i !== "number" || !Number.isInteger(i) || i < 0 || i >= itemCount) {
|
|
232
|
+
throw new Error(`The response labels index ${String(i)}, and the request held ${itemCount} items`)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (labels[i]) throw new Error(`The response labels index ${i} twice`)
|
|
236
|
+
|
|
237
|
+
if (typeof role !== "string" || !ROLES.has(role)) throw new Error(`Index ${i} has the role ${String(role)}`)
|
|
238
|
+
|
|
239
|
+
if (typeof basis !== "string" || !BASES.has(basis)) throw new Error(`Index ${i} has the basis ${String(basis)}`)
|
|
240
|
+
|
|
241
|
+
if (typeof confidence !== "string" || !CONFIDENCE_SET.has(confidence)) {
|
|
242
|
+
throw new Error(`Index ${i} has the confidence ${String(confidence)}`)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
labels[i] = { role: role as VariantNameRole, basis: basis as LabelBasis, confidence: confidence as LabelConfidence }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const missing = labels.findIndex((label) => label == null)
|
|
249
|
+
|
|
250
|
+
if (missing !== -1) throw new Error(`The response leaves index ${missing} of ${itemCount} unlabeled`)
|
|
251
|
+
|
|
252
|
+
return labels as VariantNameLabel[]
|
|
253
|
+
}
|
|
@@ -202,7 +202,7 @@ export async function matchedSourceIDs(
|
|
|
202
202
|
export async function readDeletionRequests(path: string): Promise<DeletionRequest[]> {
|
|
203
203
|
const requests = await readLocalJSONFile<unknown>(path)
|
|
204
204
|
|
|
205
|
-
if (!Array.isArray(requests)) throw new
|
|
205
|
+
if (!Array.isArray(requests)) throw new TypeError(`${path} holds no array of deletion requests`)
|
|
206
206
|
|
|
207
207
|
return requests as DeletionRequest[]
|
|
208
208
|
}
|