@mailwoman/corpus 7.2.0 → 7.2.1
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/package.json +59 -27
- package/src/adapter.ts +153 -0
- package/src/adapters/ban/adapter.ts +189 -0
- package/src/adapters/ban/street-decompose.ts +98 -0
- package/src/adapters/fcc-bdc/adapter.ts +188 -0
- package/src/adapters/geonames/adapter.ts +185 -0
- package/src/adapters/geonames-postal/adapter.ts +111 -0
- package/src/adapters/gnaf/adapter.ts +139 -0
- package/src/adapters/gnaf/assemble.ts +200 -0
- package/src/adapters/index.ts +135 -0
- package/src/adapters/openaddresses/adapter.ts +237 -0
- package/src/adapters/overture/adapter.ts +149 -0
- package/src/adapters/state-hi-schools/adapter.ts +171 -0
- package/src/adapters/state-ia-contractors/adapter.ts +148 -0
- package/src/adapters/state-ny-notaries/adapter.ts +169 -0
- package/src/adapters/state-tx-notaries/adapter.ts +160 -0
- package/src/adapters/synth-po-box/adapter.ts +197 -0
- package/src/adapters/tiger/adapter.ts +232 -0
- package/src/adapters/tiger/street-decompose.ts +120 -0
- package/src/adapters/usgov-hrsa-fqhc/adapter.ts +189 -0
- package/src/adapters/usgov-imls-pls/adapter.ts +152 -0
- package/src/adapters/usgov-irs-bmf/adapter.ts +155 -0
- package/src/adapters/usgov-nad/adapter.ts +338 -0
- package/src/adapters/usgov-nppes/adapter.ts +169 -0
- package/src/adapters/usgov-samhsa-treatment-locator/adapter.ts +211 -0
- package/src/adapters/wof-admin-jp/adapter.ts +176 -0
- package/src/adapters/wof-admin-json/adapter.ts +280 -0
- package/src/adapters/wof-postalcode-json/adapter.ts +209 -0
- package/src/align.ts +317 -0
- package/src/build.ts +348 -0
- package/src/codex/us-fips-state.ts +109 -0
- package/src/format.ts +14 -0
- package/src/golden.ts +147 -0
- package/src/index.ts +28 -0
- package/src/license.ts +48 -0
- package/src/parquet-wrapper/index.ts +9 -0
- package/src/parquet-wrapper/reader.ts +67 -0
- package/src/parquet-wrapper/schema.ts +80 -0
- package/src/parquet-wrapper/writer.ts +102 -0
- package/src/parquet.ts +360 -0
- package/src/runner.ts +283 -0
- package/src/shard-recipes/anchor-absorption.ts +86 -0
- package/src/shard-recipes/boundary-stress.ts +87 -0
- package/src/shard-recipes/country-balanced.ts +471 -0
- package/src/shard-recipes/cz-pcfirst-preposition.ts +83 -0
- package/src/shard-recipes/fr-admin-split.ts +212 -0
- package/src/shard-recipes/fr-bare-street.ts +85 -0
- package/src/shard-recipes/fr-fragment.ts +304 -0
- package/src/shard-recipes/fr-order.ts +283 -0
- package/src/shard-recipes/german.ts +206 -0
- package/src/shard-recipes/house-venue.ts +78 -0
- package/src/shard-recipes/index.ts +76 -0
- package/src/shard-recipes/intersection.ts +617 -0
- package/src/shard-recipes/locale.ts +415 -0
- package/src/shard-recipes/nl-postcode.ts +105 -0
- package/src/shard-recipes/no-fragment.ts +206 -0
- package/src/shard-recipes/no-street-led.ts +130 -0
- package/src/shard-recipes/no-street.ts +78 -0
- package/src/shard-recipes/po-box-cedex.ts +853 -0
- package/src/shard-recipes/po-box.ts +111 -0
- package/src/shard-recipes/scaffold.ts +187 -0
- package/src/shard-recipes/si-bare-village.ts +88 -0
- package/src/shard-recipes/street-affix.ts +549 -0
- package/src/shard-recipes/street-bare.ts +90 -0
- package/src/shard-recipes/street.ts +74 -0
- package/src/shard-recipes/unit.ts +315 -0
- package/src/split.ts +251 -0
- package/src/synthesize-anchor-absorption.ts +263 -0
- package/src/synthesize-boundary-stress.ts +504 -0
- package/src/synthesize-german.ts +227 -0
- package/src/synthesize-house-venue.ts +192 -0
- package/src/synthesize-intersection.ts +205 -0
- package/src/synthesize-no-street.ts +341 -0
- package/src/synthesize-po-box.ts +307 -0
- package/src/synthesize-street.ts +264 -0
- package/src/synthesize.ts +872 -0
- package/src/tokenize.ts +68 -0
- package/src/tools/align-shard.ts +67 -0
- package/src/tools/audit.ts +352 -0
- package/src/tools/corpus-stats.ts +183 -0
- package/src/tools/fetch/ban.ts +288 -0
- package/src/tools/fetch/download.ts +119 -0
- package/src/tools/fetch/hrsa.ts +65 -0
- package/src/tools/fetch/imls-pls.ts +162 -0
- package/src/tools/fetch/index.ts +121 -0
- package/src/tools/fetch/nad.ts +304 -0
- package/src/tools/fetch/nppes.ts +177 -0
- package/src/tools/fetch/openaddresses.ts +380 -0
- package/src/tools/fetch/state-hi-schools.ts +217 -0
- package/src/tools/fetch/state-sources.ts +142 -0
- package/src/tools/fetch/tiger-full.ts +318 -0
- package/src/tools/golden-expand.ts +524 -0
- package/src/tools/golden-promote.ts +304 -0
- package/src/tools/index.ts +24 -0
- package/src/tools/ingest-csv.ts +420 -0
- package/src/tools/jsonl-to-parquet.ts +200 -0
- package/src/tools/lint-shard-vocab.ts +357 -0
- package/src/tools/lint-shard.ts +502 -0
- package/src/tools/overlay-manifest.ts +141 -0
- package/src/tools/shard-kryptonite.ts +131 -0
- package/src/tools/shard-translit.ts +244 -0
- package/src/types.ts +213 -0
- package/src/wof-json.ts +236 -0
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Generate golden-set candidate entries by LLM-driven surface-form synthesis from a verified-label
|
|
7
|
+
* seed pulled out of the corpus's labeled test split.
|
|
8
|
+
*
|
|
9
|
+
* ## Why this approach
|
|
10
|
+
*
|
|
11
|
+
* The Phase 2 golden set has 74 entries; session-notes.md called for ≥500/locale. Manual curation
|
|
12
|
+
* doesn't scale. Pure-LLM generation (invent raw + labels from scratch) is too noisy — labels
|
|
13
|
+
* would be unverified.
|
|
14
|
+
*
|
|
15
|
+
* This module takes the middle path:
|
|
16
|
+
*
|
|
17
|
+
* 1. **Seeds come from corpus-v0.2.0 test shard** — already through the alignment pipeline, so labels
|
|
18
|
+
* are pipeline-verified.
|
|
19
|
+
* 2. **LLM only varies the surface form** — case, abbreviations, reordering, dropped components. The
|
|
20
|
+
* component VALUES (locality string, postcode digits, etc.) are preserved verbatim.
|
|
21
|
+
* 3. **Programmatic validator drops hallucinations** — every component value must appear as a
|
|
22
|
+
* substring (case-insensitive, whitespace-normalized) of the variant's raw. Failures dropped
|
|
23
|
+
* silently; cost is wasted tokens, never bad-labeled golden entries.
|
|
24
|
+
*
|
|
25
|
+
* ## Usage
|
|
26
|
+
*
|
|
27
|
+
* ```sh
|
|
28
|
+
* DEEPSEEK_API_KEY=sk-... \
|
|
29
|
+
* mailwoman corpus golden expand \
|
|
30
|
+
* --count 1000 \
|
|
31
|
+
* --variants 5 \
|
|
32
|
+
* --output data/eval/golden/candidates/expand-$(date +%Y%m%d-%H%M%S).jsonl
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* ## Env
|
|
36
|
+
*
|
|
37
|
+
* - `DEEPSEEK_API_KEY` — required for provider `deepseek`
|
|
38
|
+
* - `ANTHROPIC_API_KEY` — required for provider `anthropic`
|
|
39
|
+
*
|
|
40
|
+
* ## What this module does NOT do
|
|
41
|
+
*
|
|
42
|
+
* - Does not commit anything or modify the versioned golden dir. Candidates land in
|
|
43
|
+
* `data/eval/golden/candidates/` for operator review (skim, prune, then run
|
|
44
|
+
* `mailwoman corpus golden promote`).
|
|
45
|
+
* - Does not score the LLM's quality — that's an eyeball job after pilot lands.
|
|
46
|
+
* - Does not retry hallucinated candidates. Cost of wasted tokens is trivial (~$0.0006/each).
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
import { mkdir } from "node:fs/promises"
|
|
50
|
+
import { dirname } from "node:path"
|
|
51
|
+
|
|
52
|
+
import { ParquetReader } from "@dsnp/parquetjs"
|
|
53
|
+
import { $private } from "@mailwoman/core/env"
|
|
54
|
+
import { dataRootPath, writeJSONL } from "@mailwoman/core/utils"
|
|
55
|
+
|
|
56
|
+
// ── Types ─────────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
interface CorpusRow {
|
|
59
|
+
raw: string
|
|
60
|
+
tokens: string[]
|
|
61
|
+
labels: string[]
|
|
62
|
+
country: string
|
|
63
|
+
source: string
|
|
64
|
+
source_id: string
|
|
65
|
+
license: string
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface Seed {
|
|
69
|
+
raw: string
|
|
70
|
+
components: Record<string, string>
|
|
71
|
+
country: string
|
|
72
|
+
source: string
|
|
73
|
+
source_id: string
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface Candidate {
|
|
77
|
+
raw: string
|
|
78
|
+
dropped?: string[]
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface GoldenCandidate {
|
|
82
|
+
raw: string
|
|
83
|
+
components: Record<string, string>
|
|
84
|
+
country: string
|
|
85
|
+
source: string
|
|
86
|
+
seed_source_id: string
|
|
87
|
+
seed_source_adapter: string
|
|
88
|
+
dropped_components: string[]
|
|
89
|
+
provenance: { provider: string; model: string }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface ExpandGoldenOptions {
|
|
93
|
+
/** Corpus test shard path(s), comma-separated. Default: the v0.2.0 test shard under the data root. */
|
|
94
|
+
corpus?: string
|
|
95
|
+
/** Total seeds to process. Default `100` (pilot). */
|
|
96
|
+
count?: number
|
|
97
|
+
/** Variants requested per seed. Default `5`. */
|
|
98
|
+
variants?: number
|
|
99
|
+
/** JSONL output path. Default `data/eval/golden/candidates/expand-<ts>.jsonl`. */
|
|
100
|
+
output?: string
|
|
101
|
+
/** LLM provider. Default `deepseek`. */
|
|
102
|
+
provider?: "deepseek" | "anthropic"
|
|
103
|
+
/** Model id. Default depends on provider. */
|
|
104
|
+
model?: string
|
|
105
|
+
/** Parallel LLM calls. Default `4`. */
|
|
106
|
+
concurrency?: number
|
|
107
|
+
/** Comma-separated source allow-list. */
|
|
108
|
+
includeSources?: string
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface ExpandGoldenSummary {
|
|
112
|
+
seedsProcessed: number
|
|
113
|
+
kept: number
|
|
114
|
+
dropped: number
|
|
115
|
+
errored: number
|
|
116
|
+
outputPath: string
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ── Seed loading ──────────────────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Decode BIO labels + tokens into a verified components map. Mirrors the Python `decode_components` in
|
|
123
|
+
* mailwoman_train/eval.py — first-occurrence-wins per tag, contiguous B-X/I-X runs concatenated with a single space
|
|
124
|
+
* (the canonical separator used by corpus alignment).
|
|
125
|
+
*/
|
|
126
|
+
function decodeComponents(tokens: string[], labels: string[]): Record<string, string> {
|
|
127
|
+
const out: Record<string, string> = {}
|
|
128
|
+
let currentTag: string | null = null
|
|
129
|
+
let currentTokens: string[] = []
|
|
130
|
+
const flush = () => {
|
|
131
|
+
if (currentTag && currentTokens.length > 0 && !(currentTag in out)) {
|
|
132
|
+
out[currentTag] = currentTokens.join(" ").trim()
|
|
133
|
+
}
|
|
134
|
+
currentTag = null
|
|
135
|
+
currentTokens = []
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
for (let i = 0; i < labels.length; i++) {
|
|
139
|
+
const label = labels[i]!
|
|
140
|
+
const tok = tokens[i] ?? ""
|
|
141
|
+
|
|
142
|
+
if (label === "O") {
|
|
143
|
+
flush()
|
|
144
|
+
continue
|
|
145
|
+
}
|
|
146
|
+
const [prefix, tag] = label.split("-", 2)
|
|
147
|
+
|
|
148
|
+
if (prefix === "B" || currentTag !== tag) {
|
|
149
|
+
flush()
|
|
150
|
+
currentTag = tag!
|
|
151
|
+
currentTokens = [tok]
|
|
152
|
+
} else {
|
|
153
|
+
currentTokens.push(tok)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
flush()
|
|
157
|
+
|
|
158
|
+
return out
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function loadSeeds(
|
|
162
|
+
corpusPath: string,
|
|
163
|
+
count: number,
|
|
164
|
+
includeSources: Set<string> | null,
|
|
165
|
+
report?: (line: string) => void
|
|
166
|
+
): Promise<Seed[]> {
|
|
167
|
+
const paths = corpusPath
|
|
168
|
+
.split(",")
|
|
169
|
+
.map((p) => p.trim())
|
|
170
|
+
.filter(Boolean)
|
|
171
|
+
report?.(`reading seeds from ${paths.length} shard(s) (target: ${count}, stratified)`)
|
|
172
|
+
|
|
173
|
+
if (includeSources) {
|
|
174
|
+
report?.(` include-sources filter: ${Array.from(includeSources).join(", ")}`)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Stratified sampling: read all rows from all shards, group by source. Bounded by per-source
|
|
178
|
+
// reservoir: keep at most max(2*count, 5000) rows per source so we don't blow memory on train
|
|
179
|
+
// shards (1M rows × many shards). Sampling later is uniform within each pool.
|
|
180
|
+
const bySource = new Map<string, Seed[]>()
|
|
181
|
+
const PER_SOURCE_CAP = Math.max(2 * count, 5000)
|
|
182
|
+
let scanned = 0
|
|
183
|
+
let skippedThinComponents = 0
|
|
184
|
+
|
|
185
|
+
for (const path of paths) {
|
|
186
|
+
const reader = await ParquetReader.openFile(path)
|
|
187
|
+
const cursor = reader.getCursor()
|
|
188
|
+
|
|
189
|
+
while (true) {
|
|
190
|
+
const row = (await cursor.next()) as CorpusRow | null
|
|
191
|
+
|
|
192
|
+
if (!row) break
|
|
193
|
+
scanned++
|
|
194
|
+
|
|
195
|
+
// Source allow-list (--include-sources) — applied early to skip parsing rows we won't use
|
|
196
|
+
if (includeSources && !includeSources.has(row.source)) continue
|
|
197
|
+
const components = decodeComponents(row.tokens ?? [], row.labels ?? [])
|
|
198
|
+
|
|
199
|
+
// Skip rows with too few components — single-name wof-admin entries don't make useful seeds
|
|
200
|
+
if (Object.keys(components).length < 2) {
|
|
201
|
+
skippedThinComponents++
|
|
202
|
+
continue
|
|
203
|
+
}
|
|
204
|
+
const seed: Seed = {
|
|
205
|
+
raw: row.raw,
|
|
206
|
+
components,
|
|
207
|
+
country: row.country,
|
|
208
|
+
source: row.source,
|
|
209
|
+
source_id: row.source_id,
|
|
210
|
+
}
|
|
211
|
+
let bucket = bySource.get(row.source)
|
|
212
|
+
|
|
213
|
+
if (!bucket) {
|
|
214
|
+
bucket = []
|
|
215
|
+
bySource.set(row.source, bucket)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (bucket.length < PER_SOURCE_CAP) {
|
|
219
|
+
bucket.push(seed)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
await reader.close()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
report?.(
|
|
226
|
+
` scanned ${scanned} rows across ${paths.length} shard(s); thin-components dropped: ${skippedThinComponents}`
|
|
227
|
+
)
|
|
228
|
+
report?.(` per-source pool sizes:`)
|
|
229
|
+
|
|
230
|
+
for (const [src, pool] of bySource) {
|
|
231
|
+
report?.(` ${src}: ${pool.length}`)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Round-robin sample. Each source gives floor(count / nSources) seeds; rounding goes
|
|
235
|
+
// to sources in alphabetical order. If a pool is smaller than its target, take all of it.
|
|
236
|
+
const sources = Array.from(bySource.keys()).sort()
|
|
237
|
+
const perSource = Math.floor(count / sources.length)
|
|
238
|
+
const remainder = count - perSource * sources.length
|
|
239
|
+
const picked: Seed[] = []
|
|
240
|
+
|
|
241
|
+
for (let i = 0; i < sources.length; i++) {
|
|
242
|
+
const src = sources[i]!
|
|
243
|
+
const pool = bySource.get(src)!
|
|
244
|
+
const target = perSource + (i < remainder ? 1 : 0)
|
|
245
|
+
|
|
246
|
+
// Random subsample without replacement — deterministic via shuffle then slice
|
|
247
|
+
for (let j = pool.length - 1; j > 0; j--) {
|
|
248
|
+
const k = Math.floor(Math.random() * (j + 1))
|
|
249
|
+
;[pool[j], pool[k]] = [pool[k]!, pool[j]!]
|
|
250
|
+
}
|
|
251
|
+
const take = Math.min(target, pool.length)
|
|
252
|
+
picked.push(...pool.slice(0, take))
|
|
253
|
+
|
|
254
|
+
if (take < target) {
|
|
255
|
+
report?.(` ⚠ ${src}: requested ${target}, pool had ${pool.length}`)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
report?.(` → loaded ${picked.length} seeds across ${sources.length} sources`)
|
|
259
|
+
|
|
260
|
+
return picked
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ── LLM providers ─────────────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
interface LlmProvider {
|
|
266
|
+
name: string
|
|
267
|
+
model: string
|
|
268
|
+
generateVariants(seed: Seed, n: number): Promise<Candidate[]>
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const SYSTEM_PROMPT = `You are a postal-address surface-form generator. Given a structured address, produce realistic variants a human might type into a geocoder.
|
|
272
|
+
|
|
273
|
+
CONSTRAINT — you MUST preserve every kept component value verbatim in the output. You may:
|
|
274
|
+
- vary case (UPPER, lower, Title Case)
|
|
275
|
+
- abbreviate (Saint → St, Avenue → Ave, Boulevard → Blvd, North → N, etc.)
|
|
276
|
+
- vary punctuation (commas, dashes, spaces, line breaks)
|
|
277
|
+
- reorder components (postcode-first, country-first, address-only)
|
|
278
|
+
- drop OPTIONAL components — list them in "dropped"
|
|
279
|
+
|
|
280
|
+
OPTIONAL components (allowed to drop): country, postcode, dependent_locality, subregion, cedex.
|
|
281
|
+
REQUIRED components (must keep, even if input has them): locality, region (when present),
|
|
282
|
+
street, house_number, venue (when present).
|
|
283
|
+
|
|
284
|
+
ALWAYS keep AT LEAST 2 components in the final raw text. Single-component variants like
|
|
285
|
+
"VT" or "Paris" are USELESS as eval entries — do not produce them.
|
|
286
|
+
|
|
287
|
+
You MUST NOT:
|
|
288
|
+
- introduce typos (validator drops these silently — wasted tokens)
|
|
289
|
+
- invent new component values
|
|
290
|
+
- produce text longer than 500 characters
|
|
291
|
+
- output a degenerate single-token answer
|
|
292
|
+
|
|
293
|
+
OUTPUT a JSON array of N objects, each shaped {"raw": "...", "dropped": ["..."]}.`
|
|
294
|
+
|
|
295
|
+
function buildUserPrompt(seed: Seed, n: number): string {
|
|
296
|
+
return `INPUT:
|
|
297
|
+
${JSON.stringify({ raw: seed.raw, components: seed.components, country: seed.country }, null, 2)}
|
|
298
|
+
|
|
299
|
+
N: ${n}`
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function makeDeepseekProvider(model: string): LlmProvider {
|
|
303
|
+
const apiKey = $private.DEEPSEEK_API_KEY
|
|
304
|
+
|
|
305
|
+
if (!apiKey) throw new Error("DEEPSEEK_API_KEY env var is required for provider deepseek")
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
name: "deepseek",
|
|
309
|
+
model,
|
|
310
|
+
async generateVariants(seed, n) {
|
|
311
|
+
const res = await fetch("https://api.deepseek.com/chat/completions", {
|
|
312
|
+
method: "POST",
|
|
313
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
314
|
+
body: JSON.stringify({
|
|
315
|
+
model,
|
|
316
|
+
messages: [
|
|
317
|
+
{ role: "system", content: SYSTEM_PROMPT },
|
|
318
|
+
{ role: "user", content: buildUserPrompt(seed, n) },
|
|
319
|
+
],
|
|
320
|
+
response_format: { type: "json_object" },
|
|
321
|
+
max_tokens: 800,
|
|
322
|
+
temperature: 0.7,
|
|
323
|
+
}),
|
|
324
|
+
signal: AbortSignal.timeout(60_000),
|
|
325
|
+
})
|
|
326
|
+
|
|
327
|
+
if (!res.ok) throw new Error(`DeepSeek HTTP ${res.status}: ${await res.text()}`)
|
|
328
|
+
const data = (await res.json()) as { choices?: Array<{ message: { content: string } }> }
|
|
329
|
+
const content = data.choices?.[0]?.message.content ?? "{}"
|
|
330
|
+
|
|
331
|
+
return parseCandidates(content)
|
|
332
|
+
},
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function makeAnthropicProvider(model: string): LlmProvider {
|
|
337
|
+
const apiKey = $private.ANTHROPIC_API_KEY
|
|
338
|
+
|
|
339
|
+
if (!apiKey) throw new Error("ANTHROPIC_API_KEY env var is required for provider anthropic")
|
|
340
|
+
|
|
341
|
+
return {
|
|
342
|
+
name: "anthropic",
|
|
343
|
+
model,
|
|
344
|
+
async generateVariants(seed, n) {
|
|
345
|
+
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
346
|
+
method: "POST",
|
|
347
|
+
headers: {
|
|
348
|
+
"x-api-key": apiKey,
|
|
349
|
+
"anthropic-version": "2023-06-01",
|
|
350
|
+
"Content-Type": "application/json",
|
|
351
|
+
},
|
|
352
|
+
body: JSON.stringify({
|
|
353
|
+
model,
|
|
354
|
+
max_tokens: 800,
|
|
355
|
+
system: SYSTEM_PROMPT,
|
|
356
|
+
messages: [{ role: "user", content: buildUserPrompt(seed, n) }],
|
|
357
|
+
}),
|
|
358
|
+
signal: AbortSignal.timeout(60_000),
|
|
359
|
+
})
|
|
360
|
+
|
|
361
|
+
if (!res.ok) throw new Error(`Anthropic HTTP ${res.status}: ${await res.text()}`)
|
|
362
|
+
const data = (await res.json()) as { content?: Array<{ type: string; text: string }> }
|
|
363
|
+
const text = data.content?.find((c) => c.type === "text")?.text ?? "[]"
|
|
364
|
+
|
|
365
|
+
return parseCandidates(text)
|
|
366
|
+
},
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function parseCandidates(text: string): Candidate[] {
|
|
371
|
+
// Strip markdown fences the model sometimes wraps around JSON
|
|
372
|
+
const cleaned = text.replace(/^```(?:json)?\n?|\n?```$/g, "").trim()
|
|
373
|
+
|
|
374
|
+
try {
|
|
375
|
+
const parsed = JSON.parse(cleaned) as unknown
|
|
376
|
+
|
|
377
|
+
if (Array.isArray(parsed)) return parsed as Candidate[]
|
|
378
|
+
|
|
379
|
+
// Some providers wrap in {"variants": [...]} or {"candidates": [...]}
|
|
380
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
381
|
+
for (const key of ["variants", "candidates", "results"]) {
|
|
382
|
+
const v = (parsed as Record<string, unknown>)[key]
|
|
383
|
+
|
|
384
|
+
if (Array.isArray(v)) return v as Candidate[]
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
} catch {
|
|
388
|
+
// fall through
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
return []
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// ── Validator ─────────────────────────────────────────────────────────────
|
|
395
|
+
|
|
396
|
+
function normalize(s: string): string {
|
|
397
|
+
return s.toLowerCase().replace(/\s+/g, " ").trim()
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// Components that are NEVER allowed to be dropped — keeps degenerate single-token candidates out.
|
|
401
|
+
const REQUIRED_COMPONENT_TAGS = new Set(["locality", "region", "street", "house_number", "venue"])
|
|
402
|
+
|
|
403
|
+
function validate(seed: Seed, candidate: Candidate): boolean {
|
|
404
|
+
if (!candidate.raw || typeof candidate.raw !== "string") return false
|
|
405
|
+
|
|
406
|
+
if (candidate.raw.length > 500) return false
|
|
407
|
+
|
|
408
|
+
if (/```|<\/?\w+>|^\s*\{/.test(candidate.raw)) return false
|
|
409
|
+
const normRaw = normalize(candidate.raw)
|
|
410
|
+
const dropped = new Set(candidate.dropped ?? [])
|
|
411
|
+
|
|
412
|
+
// LLM cannot drop required components present in the seed.
|
|
413
|
+
for (const tag of dropped) {
|
|
414
|
+
if (REQUIRED_COMPONENT_TAGS.has(tag) && seed.components[tag]) return false
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Every kept component value must appear verbatim (post-normalization) in the candidate raw.
|
|
418
|
+
let keptCount = 0
|
|
419
|
+
|
|
420
|
+
for (const [tag, value] of Object.entries(seed.components)) {
|
|
421
|
+
if (dropped.has(tag)) continue
|
|
422
|
+
|
|
423
|
+
if (!value) continue
|
|
424
|
+
|
|
425
|
+
if (!normRaw.includes(normalize(value))) return false
|
|
426
|
+
keptCount++
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Reject degenerate single-component candidates ("VT", "Paris" alone).
|
|
430
|
+
if (keptCount < 2) return false
|
|
431
|
+
|
|
432
|
+
return true
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// ── Main pipeline ─────────────────────────────────────────────────────────
|
|
436
|
+
|
|
437
|
+
export async function expandGolden(
|
|
438
|
+
options: ExpandGoldenOptions = {},
|
|
439
|
+
report?: (line: string) => void
|
|
440
|
+
): Promise<ExpandGoldenSummary> {
|
|
441
|
+
const corpusPath =
|
|
442
|
+
options.corpus ?? dataRootPath("corpus", "versioned", "v0.2.0", "corpus-v0.2.0", "test", "part-0000.parquet")
|
|
443
|
+
const count = options.count ?? 100
|
|
444
|
+
const variants = options.variants ?? 5
|
|
445
|
+
const providerName = options.provider ?? "deepseek"
|
|
446
|
+
const model = options.model ?? (providerName === "anthropic" ? "claude-haiku-4-5-20251001" : "deepseek-chat")
|
|
447
|
+
const concurrencyLimit = options.concurrency ?? 4
|
|
448
|
+
const includeSources = options.includeSources ? new Set(options.includeSources.split(",").map((s) => s.trim())) : null
|
|
449
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)
|
|
450
|
+
const outputPath = options.output ?? `data/eval/golden/candidates/expand-${ts}.jsonl`
|
|
451
|
+
|
|
452
|
+
const provider = providerName === "anthropic" ? makeAnthropicProvider(model) : makeDeepseekProvider(model)
|
|
453
|
+
report?.(`provider: ${provider.name} model: ${provider.model}`)
|
|
454
|
+
|
|
455
|
+
const seeds = await loadSeeds(corpusPath, count, includeSources, report)
|
|
456
|
+
|
|
457
|
+
if (seeds.length === 0) {
|
|
458
|
+
throw new Error("no seeds loaded — corpus path or filter is wrong")
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
await mkdir(dirname(outputPath), { recursive: true })
|
|
462
|
+
const outRows: GoldenCandidate[] = []
|
|
463
|
+
let kept = 0
|
|
464
|
+
let dropped = 0
|
|
465
|
+
let errored = 0
|
|
466
|
+
|
|
467
|
+
// Bounded-concurrency worker pool
|
|
468
|
+
let cursor = 0
|
|
469
|
+
const workers = Array.from({ length: Math.min(concurrencyLimit, seeds.length) }, async () => {
|
|
470
|
+
while (true) {
|
|
471
|
+
const i = cursor++
|
|
472
|
+
|
|
473
|
+
if (i >= seeds.length) return
|
|
474
|
+
const seed = seeds[i]!
|
|
475
|
+
|
|
476
|
+
try {
|
|
477
|
+
const candidates = await provider.generateVariants(seed, variants)
|
|
478
|
+
|
|
479
|
+
for (const cand of candidates) {
|
|
480
|
+
if (validate(seed, cand)) {
|
|
481
|
+
const goldenCandidate: GoldenCandidate = {
|
|
482
|
+
raw: cand.raw,
|
|
483
|
+
components: { ...seed.components },
|
|
484
|
+
country: seed.country,
|
|
485
|
+
source: `expand-golden:${provider.name}`,
|
|
486
|
+
seed_source_id: seed.source_id,
|
|
487
|
+
seed_source_adapter: seed.source,
|
|
488
|
+
dropped_components: cand.dropped ?? [],
|
|
489
|
+
provenance: { provider: provider.name, model: provider.model },
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// Remove dropped components from the components map
|
|
493
|
+
for (const tag of goldenCandidate.dropped_components) {
|
|
494
|
+
delete goldenCandidate.components[tag]
|
|
495
|
+
}
|
|
496
|
+
outRows.push(goldenCandidate)
|
|
497
|
+
kept++
|
|
498
|
+
} else {
|
|
499
|
+
dropped++
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
} catch (err) {
|
|
503
|
+
errored++
|
|
504
|
+
report?.(` ✗ seed ${seed.source_id}: ${(err as Error).message}`)
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if ((i + 1) % 10 === 0) {
|
|
508
|
+
report?.(` progress: ${i + 1}/${seeds.length} kept=${kept} dropped=${dropped} errored=${errored}`)
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
})
|
|
512
|
+
await Promise.all(workers)
|
|
513
|
+
|
|
514
|
+
writeJSONL(outputPath, outRows)
|
|
515
|
+
report?.(`=== summary ===`)
|
|
516
|
+
report?.(`seeds processed: ${seeds.length}`)
|
|
517
|
+
report?.(`candidates kept: ${kept}`)
|
|
518
|
+
report?.(`candidates dropped (validator): ${dropped}`)
|
|
519
|
+
report?.(`seeds with errors: ${errored}`)
|
|
520
|
+
report?.(`yield: ${seeds.length > 0 ? ((kept / (seeds.length * variants)) * 100).toFixed(1) : "0"}%`)
|
|
521
|
+
report?.(`output: ${outputPath}`)
|
|
522
|
+
|
|
523
|
+
return { seedsProcessed: seeds.length, kept, dropped, errored, outputPath }
|
|
524
|
+
}
|