@mailwoman/core 7.1.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/api/APIClient.ts +175 -0
- package/api/headless.ts +23 -0
- package/api/index.ts +11 -0
- package/api/responses.ts +135 -0
- package/coarse-placer/coarse-placer.ts +300 -0
- package/coarse-placer/featurize.ts +171 -0
- package/coarse-placer/tools/build-dataset.ts +223 -0
- package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
- package/coarse-placer/tools/build-outlier-latin.ts +200 -0
- package/coarse-placer/tools/build-outlier-oa.ts +231 -0
- package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
- package/coarse-placer/tools/eval-openset.ts +519 -0
- package/coarse-placer/tools/eval-quant-compare.ts +151 -0
- package/coarse-placer/tools/eval.ts +187 -0
- package/coarse-placer/tools/fnv-hash.ts +24 -0
- package/coarse-placer/tools/index.ts +23 -0
- package/coarse-placer/tools/probe-frontier.ts +216 -0
- package/coarse-placer/tools/quantize.ts +116 -0
- package/coarse-placer/tools/train.ts +244 -0
- package/collections.ts +134 -0
- package/db/schema.ts +21 -0
- package/decoder/build-tree.ts +228 -0
- package/decoder/calibration.ts +101 -0
- package/decoder/containment.ts +87 -0
- package/decoder/index.ts +17 -0
- package/decoder/proposals-to-tree.ts +83 -0
- package/decoder/resolve-proposal-overlaps.ts +79 -0
- package/decoder/serialize-json.ts +70 -0
- package/decoder/serialize-tuples.ts +61 -0
- package/decoder/serialize-xml.ts +209 -0
- package/decoder/types.ts +159 -0
- package/decoder/unknown-spans.ts +103 -0
- package/decoder/validate-tree.ts +100 -0
- package/env/index.ts +42 -0
- package/env/load.ts +14 -0
- package/env/paths.ts +40 -0
- package/env/schema.ts +125 -0
- package/errors/index.ts +9 -0
- package/errors/schema.ts +155 -0
- package/fs/node.ts +38 -0
- package/identifiers.ts +58 -0
- package/index.ts +13 -0
- package/kysley/adapter.ts +29 -0
- package/kysley/client.ts +30 -0
- package/kysley/dialect-config.ts +30 -0
- package/kysley/dialect.ts +67 -0
- package/kysley/driver.ts +175 -0
- package/layers/index.ts +12 -0
- package/layers/manifest.ts +154 -0
- package/layers/schema.ts +105 -0
- package/lifecycle/ServiceSymbol.ts +95 -0
- package/lifecycle/index.ts +11 -0
- package/lifecycle/lru-cache.ts +44 -0
- package/lifecycle/services.ts +322 -0
- package/locale/index.ts +9 -0
- package/locale/locale.ts +49 -0
- package/locale/profiles/en-us.ts +69 -0
- package/locale/profiles/fr-fr.ts +75 -0
- package/locale/profiles/index.ts +9 -0
- package/locale/profiles/ja-jp.ts +33 -0
- package/locale/registry.ts +68 -0
- package/logging/index.ts +8 -0
- package/logging/shared.ts +145 -0
- package/logging/utils.ts +46 -0
- package/objects.ts +211 -0
- package/out/layers/index.d.ts +12 -0
- package/out/layers/index.d.ts.map +1 -0
- package/out/layers/index.js +12 -0
- package/out/layers/index.js.map +1 -0
- package/out/layers/manifest.d.ts +64 -0
- package/out/layers/manifest.d.ts.map +1 -0
- package/out/layers/manifest.js +102 -0
- package/out/layers/manifest.js.map +1 -0
- package/out/layers/schema.d.ts +72 -0
- package/out/layers/schema.d.ts.map +1 -0
- package/out/layers/schema.js +61 -0
- package/out/layers/schema.js.map +1 -0
- package/out/pipeline/index.d.ts +1 -1
- package/out/pipeline/index.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.js +27 -0
- package/out/pipeline/runtime-pipeline.js.map +1 -1
- package/out/pipeline/types.d.ts +74 -4
- package/out/pipeline/types.d.ts.map +1 -1
- package/out/pipeline/types.js.map +1 -1
- package/package.json +21 -21
- package/pipeline/index.ts +46 -0
- package/pipeline/reconcile-lookups.ts +108 -0
- package/pipeline/reconcile.ts +542 -0
- package/pipeline/runtime-pipeline.ts +732 -0
- package/pipeline/span-logit-aggregation.ts +151 -0
- package/pipeline/span-proposer.ts +587 -0
- package/pipeline/types.ts +348 -0
- package/policy/defaults.ts +35 -0
- package/policy/index.ts +10 -0
- package/policy/policy.ts +60 -0
- package/policy/proposal-collection.ts +64 -0
- package/policy/registry.ts +149 -0
- package/resolver/index.ts +29 -0
- package/resolver/types.ts +584 -0
- package/resources/LocaleIndex.ts +124 -0
- package/resources/ResourceMapCache.ts +126 -0
- package/resources/collections.ts +93 -0
- package/resources/debugging.ts +19 -0
- package/resources/git.ts +54 -0
- package/resources/index.ts +17 -0
- package/resources/languages/index.ts +49 -0
- package/resources/languages/types.gen.ts +1368 -0
- package/resources/libaddressinput.ts +105 -0
- package/resources/libpostal.ts +182 -0
- package/resources/locale.ts +23 -0
- package/resources/set.ts +179 -0
- package/resources/whosonfirst/DataSourceCache.ts +72 -0
- package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
- package/resources/whosonfirst/index.ts +10 -0
- package/resources/whosonfirst/loader.ts +157 -0
- package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
- package/resources/whosonfirst/placetypes/admin.ts +173 -0
- package/resources/whosonfirst/placetypes/definition.ts +135 -0
- package/resources/whosonfirst/placetypes/graph.ts +0 -0
- package/resources/whosonfirst/placetypes/index.ts +12 -0
- package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
- package/resources/whosonfirst/placetypes/tree.ts +46 -0
- package/routing/index.ts +208 -0
- package/scripting/index.ts +40 -0
- package/scripting/utils/index.ts +106 -0
- package/tokenization/Graph.ts +50 -0
- package/tokenization/Span.ts +297 -0
- package/tokenization/index.ts +9 -0
- package/tokenization/normalizer.ts +123 -0
- package/tools/download-libpostal-resources.ts +98 -0
- package/tools/download-ssl-address.ts +99 -0
- package/tools/generate-language-types.ts +194 -0
- package/tools/index.ts +13 -0
- package/types/Classification.ts +211 -0
- package/types/classifier.ts +133 -0
- package/types/component.ts +75 -0
- package/types/index.ts +10 -0
- package/types/mapping.ts +81 -0
- package/utils/data-root.ts +56 -0
- package/utils/hash.ts +27 -0
- package/utils/index.ts +14 -0
- package/utils/jsonl.ts +43 -0
- package/utils/python-json.ts +105 -0
- package/utils/python-random.ts +90 -0
- package/utils/repo.ts +118 -0
- package/utils/sealed-db.ts +85 -0
- package/utils/stats.ts +32 -0
- package/vitest.config.ts +53 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Latin-script off-map outlier exposure for the #244 coarse-placer (milestone 3). M2's OTHER class
|
|
7
|
+
* was trained on NON-Latin/non-CJK scripts (Cyrillic, Arabic, …) from WOF names, so off-map
|
|
8
|
+
* COUNTRIES written in Latin script (Poland, Brazil, Mexico, …) still mis-place to a trained
|
|
9
|
+
* Latin country (the "Latin-off-map residual"). The fix is REAL off-map addresses (not synthetic
|
|
10
|
+
* name variants — see #564: synthetic mass fits its own quirks): assemble address strings from
|
|
11
|
+
* the Overture per-country address parquet and append them as `country: "OTHER"`.
|
|
12
|
+
*
|
|
13
|
+
* Discipline: countries split into TRAIN (their rows feed train/val OTHER) and HELDOUT (rows go
|
|
14
|
+
* ONLY to the dedicated test file), so we can measure generalization to off-map countries the
|
|
15
|
+
* model never saw — not just memorization. The in-map test.jsonl is left UNTOUCHED so the
|
|
16
|
+
* before/after in-map regression check stays clean; the Latin metric lives in its own file.
|
|
17
|
+
*
|
|
18
|
+
* Run AFTER build-dataset + the exposure outliers (it appends). Re-runnable: it rewrites the
|
|
19
|
+
* dedicated test file and appends fresh OTHER rows (so don't run it twice onto the same splits
|
|
20
|
+
* without rebuilding train/val).
|
|
21
|
+
*
|
|
22
|
+
* Run: `mailwoman placer build-dataset --outliers latin [--per-country 6000] [--overture
|
|
23
|
+
* $MAILWOMAN_DATA_ROOT/overture/2026-05-20.0]`
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { appendFileSync, writeFileSync } from "node:fs"
|
|
27
|
+
import * as path from "node:path"
|
|
28
|
+
|
|
29
|
+
import { dataRootPath } from "../../utils/data-root.ts"
|
|
30
|
+
import { repoRootPath } from "../../utils/repo.ts"
|
|
31
|
+
import { hashFNV1a } from "./fnv-hash.ts"
|
|
32
|
+
|
|
33
|
+
interface LatinTestRow {
|
|
34
|
+
raw: string
|
|
35
|
+
country: string
|
|
36
|
+
group: string
|
|
37
|
+
srcCountry: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Options for {@linkcode buildOutlierLatin}. */
|
|
41
|
+
export interface BuildOutlierLatinOptions {
|
|
42
|
+
/** Rows sampled per off-map country. Default 6000. */
|
|
43
|
+
perCountry?: number
|
|
44
|
+
/** Overture release dir. Default `$MAILWOMAN_DATA_ROOT/overture/2026-05-20.0`. */
|
|
45
|
+
overture?: string
|
|
46
|
+
/** Dataset dir the OTHER rows append to. Default `<repo>/data/coarse-placer`. */
|
|
47
|
+
data?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Result of {@linkcode buildOutlierLatin}. */
|
|
51
|
+
export interface BuildOutlierLatinResult {
|
|
52
|
+
train: number
|
|
53
|
+
val: number
|
|
54
|
+
test: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Off-map (NOT among the trained countries) and Latin-script. TRAIN feeds the OTHER class; HELDOUT
|
|
58
|
+
// is test-only — the generalization probe (unseen off-map countries should still route OTHER).
|
|
59
|
+
// #743: PL/PT/CZ moved from OTHER to FIRST-CLASS in-map countries (they're now in COARSE_CLASSES),
|
|
60
|
+
// so they're removed here — keeping them would feed contradictory gold (the same address labelled
|
|
61
|
+
// both PL and OTHER). That leaves BR/MX as the Latin off-map TRAIN exposure and CA/LI as the
|
|
62
|
+
// heldout probe (the hard near-twins of in-map US/DE — an honest worst case). The in-map expansion
|
|
63
|
+
// itself shrinks the off-map Latin surface, and the bulk OTHER exposure is non-Latin (build-
|
|
64
|
+
// outlier-exposure.ts), so the thinner Latin train set is acceptable; watch OTHER-Latin recall in
|
|
65
|
+
// the openset eval.
|
|
66
|
+
const TRAIN_COUNTRIES = ["BR", "MX"]
|
|
67
|
+
const HELDOUT_COUNTRIES = ["CA", "LI"]
|
|
68
|
+
|
|
69
|
+
/** Address_levels arrives as a list (node-api) or its string repr; pull the value strings out. */
|
|
70
|
+
function levelValues(al: unknown): string[] {
|
|
71
|
+
if (Array.isArray(al)) return al.map((x) => (x && x.value ? String(x.value) : "")).filter(Boolean)
|
|
72
|
+
const s = String(al ?? "")
|
|
73
|
+
const out: string[] = []
|
|
74
|
+
|
|
75
|
+
for (const m of s.matchAll(/'value':\s*'([^']*)'/g)) {
|
|
76
|
+
out.push(m[1]!)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (!out.length) {
|
|
80
|
+
for (const m of s.matchAll(/"value":\s*"([^"]*)"/g)) {
|
|
81
|
+
out.push(m[1]!)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return out
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Assemble a plausible address string from an Overture address row. Deterministic variant by hash. */
|
|
89
|
+
function assemble(r: Record<string, unknown>): string | null {
|
|
90
|
+
const num = (r.number ?? "").toString().trim()
|
|
91
|
+
const street = (r.street ?? "").toString().trim()
|
|
92
|
+
const pc = (r.postcode ?? "").toString().trim()
|
|
93
|
+
const levels = levelValues(r.address_levels)
|
|
94
|
+
const locality = (r.postal_city ? String(r.postal_city) : "") || levels[levels.length - 1] || levels[0] || ""
|
|
95
|
+
|
|
96
|
+
if (!street && !locality) return null // nothing distinctive
|
|
97
|
+
const head = [num, street].filter(Boolean).join(" ")
|
|
98
|
+
const tail = [pc, locality].filter(Boolean).join(" ")
|
|
99
|
+
const h = hashFNV1a(`${num}|${street}|${pc}|${locality}`)
|
|
100
|
+
|
|
101
|
+
switch (h % 3) {
|
|
102
|
+
case 0:
|
|
103
|
+
return [head, tail].filter(Boolean).join(", ")
|
|
104
|
+
case 1:
|
|
105
|
+
return [head, locality, pc].filter(Boolean).join(", ").trim()
|
|
106
|
+
default:
|
|
107
|
+
return [head, [locality, pc].filter(Boolean).join(" ")].filter(Boolean).join(", ")
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Coarse-placer Overture Latin-off-map outlier builder — see the module doc. */
|
|
112
|
+
export async function buildOutlierLatin(
|
|
113
|
+
options: BuildOutlierLatinOptions = {},
|
|
114
|
+
report?: (line: string) => void
|
|
115
|
+
): Promise<BuildOutlierLatinResult> {
|
|
116
|
+
const PER = options.perCountry ?? 6000
|
|
117
|
+
const overtureDir = options.overture || dataRootPath("overture", "2026-05-20.0")
|
|
118
|
+
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
119
|
+
|
|
120
|
+
// Heavy dep (devDependency — operator tooling), lazy-imported so loading the tools barrel stays cheap.
|
|
121
|
+
const { DuckDBInstance } = await import("@duckdb/node-api")
|
|
122
|
+
const duck = await (await DuckDBInstance.create()).connect()
|
|
123
|
+
|
|
124
|
+
async function rowsFor(cc: string): Promise<string[]> {
|
|
125
|
+
const f = path.join(overtureDir, `addresses-${cc.toLowerCase()}.parquet`)
|
|
126
|
+
let res
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
res = await duck.runAndReadAll(
|
|
130
|
+
`SELECT number, street, postcode, postal_city, address_levels FROM read_parquet('${f}') LIMIT ${PER}`
|
|
131
|
+
)
|
|
132
|
+
} catch (e) {
|
|
133
|
+
report?.(` ${cc}: SKIP (${(e as Error).message.split("\n")[0]})`)
|
|
134
|
+
|
|
135
|
+
return []
|
|
136
|
+
}
|
|
137
|
+
const seen = new Set<string>()
|
|
138
|
+
const out: string[] = []
|
|
139
|
+
|
|
140
|
+
for (const r of res.getRowObjects()) {
|
|
141
|
+
const raw = assemble(r)
|
|
142
|
+
|
|
143
|
+
if (!raw || seen.has(raw) || raw.length < 6) continue
|
|
144
|
+
seen.add(raw)
|
|
145
|
+
out.push(raw)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return out
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const trainAppend: string[] = []
|
|
152
|
+
const valAppend: string[] = []
|
|
153
|
+
const testRows: LatinTestRow[] = []
|
|
154
|
+
|
|
155
|
+
// dedicated Latin off-map test: {raw, country:"OTHER", group, srcCountry}
|
|
156
|
+
|
|
157
|
+
for (const cc of TRAIN_COUNTRIES) {
|
|
158
|
+
const rows = (await rowsFor(cc)).sort((a, b) => hashFNV1a(a) - hashFNV1a(b))
|
|
159
|
+
const nVal = Math.floor(rows.length * 0.1)
|
|
160
|
+
const nTest = Math.floor(rows.length * 0.1)
|
|
161
|
+
const val = rows.slice(0, nVal)
|
|
162
|
+
const test = rows.slice(nVal, nVal + nTest)
|
|
163
|
+
const train = rows.slice(nVal + nTest)
|
|
164
|
+
|
|
165
|
+
for (const raw of train) {
|
|
166
|
+
trainAppend.push(raw)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
for (const raw of val) {
|
|
170
|
+
valAppend.push(raw)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
for (const raw of test) {
|
|
174
|
+
testRows.push({ raw, country: "OTHER", group: "indist", srcCountry: cc })
|
|
175
|
+
}
|
|
176
|
+
report?.(` TRAIN ${cc}: ${rows.length} (train ${train.length} / val ${val.length} / test ${test.length})`)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
for (const cc of HELDOUT_COUNTRIES) {
|
|
180
|
+
const rows = await rowsFor(cc)
|
|
181
|
+
|
|
182
|
+
for (const raw of rows) {
|
|
183
|
+
testRows.push({ raw, country: "OTHER", group: "heldout", srcCountry: cc })
|
|
184
|
+
}
|
|
185
|
+
report?.(` HELDOUT ${cc}: ${rows.length} (test-only)`)
|
|
186
|
+
}
|
|
187
|
+
;(duck as { disconnect?: () => void }).disconnect?.()
|
|
188
|
+
|
|
189
|
+
// Append OTHER rows to train/val; write the dedicated Latin off-map test file.
|
|
190
|
+
const wr = (rows: string[]): string => rows.map((raw) => JSON.stringify({ raw, country: "OTHER" })).join("\n") + "\n"
|
|
191
|
+
appendFileSync(path.join(dataDir, "train.jsonl"), wr(trainAppend))
|
|
192
|
+
appendFileSync(path.join(dataDir, "val.jsonl"), wr(valAppend))
|
|
193
|
+
writeFileSync(path.join(dataDir, "test-latin-offmap.jsonl"), testRows.map((r) => JSON.stringify(r)).join("\n") + "\n")
|
|
194
|
+
report?.(`\nappended OTHER → train +${trainAppend.length}, val +${valAppend.length}`)
|
|
195
|
+
report?.(
|
|
196
|
+
`wrote test-latin-offmap.jsonl: ${testRows.length} rows (indist ${testRows.filter((r) => r.group === "indist").length} / heldout ${testRows.filter((r) => r.group === "heldout").length})`
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
return { train: trainAppend.length, val: valAppend.length, test: testRows.length }
|
|
200
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* OpenAddresses Latin-off-map outlier exposure for the #244 coarse-placer (milestone 3, breadth).
|
|
7
|
+
* The successor to build-outlier-latin.ts (Overture): Overture's ALPHA addresses theme only
|
|
8
|
+
* carries real rows for ~7 off-map countries, so a model trained on them MEMORIZED rather than
|
|
9
|
+
* learned an "off-map" boundary (night-15 finding). OpenAddresses covers far more countries —
|
|
10
|
+
* this assembles address strings from OA's per-country CSVs and appends them as `country:
|
|
11
|
+
* "OTHER"`.
|
|
12
|
+
*
|
|
13
|
+
* Discipline (per the #244 scoping note + DeepSeek consult):
|
|
14
|
+
*
|
|
15
|
+
* - LEAVE-ONE-LANGUAGE-FAMILY-OUT, not random: whole families are held out (Nordic, Baltic, …) so a
|
|
16
|
+
* trained sibling's shared n-grams can't rescue the generalization metric. TRAIN families
|
|
17
|
+
* feed train/val/test(indist); HELDOUT families go ONLY to the dedicated test file.
|
|
18
|
+
* - Schema variance: read via DuckDB read_csv_auto(..., union_by_name) so differing per-source OA
|
|
19
|
+
* schemas align; assemble to the SAME format the in-map rows use (build-outlier-latin's
|
|
20
|
+
* assemble).
|
|
21
|
+
* - Dedup (per country) + per-country CAP (downsample): PL/CZ dwarf others, so cap so OTHER isn't
|
|
22
|
+
* "mostly Polish".
|
|
23
|
+
* - Country filter: only OFF-MAP countries (never the 11 in-map); the in-map test.jsonl is untouched.
|
|
24
|
+
*
|
|
25
|
+
* Run AFTER build-dataset + the exposure outliers (it APPENDS). Re-runnable: rewrites the
|
|
26
|
+
* dedicated test file and appends fresh OTHER rows — rebuild train/val before re-running.
|
|
27
|
+
*
|
|
28
|
+
* Run: `mailwoman placer build-dataset --outliers oa --oa-dir <extracted-OA-root> [--per-country
|
|
29
|
+
* 6000]`
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { appendFileSync, writeFileSync } from "node:fs"
|
|
33
|
+
import * as path from "node:path"
|
|
34
|
+
|
|
35
|
+
import { dataRootPath } from "../../utils/data-root.ts"
|
|
36
|
+
import { repoRootPath } from "../../utils/repo.ts"
|
|
37
|
+
import { hashFNV1a } from "./fnv-hash.ts"
|
|
38
|
+
|
|
39
|
+
interface OaTestRow {
|
|
40
|
+
raw: string
|
|
41
|
+
country: string
|
|
42
|
+
group: string
|
|
43
|
+
srcCountry: string
|
|
44
|
+
family: string
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Options for {@linkcode buildOutlierOA}. */
|
|
48
|
+
export interface BuildOutlierOAOptions {
|
|
49
|
+
/** Extracted OpenAddresses root. Default `$MAILWOMAN_DATA_ROOT/openaddresses/extracted`. */
|
|
50
|
+
oaDir?: string
|
|
51
|
+
/** Row cap per off-map country. Default 6000. */
|
|
52
|
+
perCountry?: number
|
|
53
|
+
/** Dataset dir the OTHER rows append to. Default `<repo>/data/coarse-placer`. */
|
|
54
|
+
data?: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Result of {@linkcode buildOutlierOA}. */
|
|
58
|
+
export interface BuildOutlierOAResult {
|
|
59
|
+
train: number
|
|
60
|
+
val: number
|
|
61
|
+
test: number
|
|
62
|
+
trainCountries: number
|
|
63
|
+
heldoutCountries: number
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The 11 IN-MAP countries the coarse-placer routes to — never appear in OTHER. (build-dataset.ts)
|
|
67
|
+
const IN_MAP = new Set(["US", "FR", "GB", "CN", "NL", "IT", "DE", "JP", "ES", "KR", "TW"])
|
|
68
|
+
|
|
69
|
+
// Language/region families for the leave-one-family-out split. Off-map countries OA's europe+asia zips
|
|
70
|
+
// plausibly carry; the actual TRAIN/HELDOUT set is intersected with what's on disk at runtime. HELDOUT
|
|
71
|
+
// families are the generalization probe (the model never sees a single row from them).
|
|
72
|
+
// Off-map families, intersected at runtime with what OA's europe+asia zips actually carry (verified
|
|
73
|
+
// on disk: ae at au be cz dk ee fi gr il is kw kz lt lu lv nc nz pl pt qa ro sa se sg si sk).
|
|
74
|
+
const FAMILIES: Record<string, string[]> = {
|
|
75
|
+
slavic_latin: ["PL", "CZ", "SK", "SI"],
|
|
76
|
+
romance_offmap: ["PT", "RO"],
|
|
77
|
+
germanic_offmap: ["AT", "BE", "LU"],
|
|
78
|
+
nordic: ["SE", "DK", "FI", "IS"],
|
|
79
|
+
hellenic: ["GR"],
|
|
80
|
+
central_asian: ["KZ"],
|
|
81
|
+
maritime_asia: ["SG"],
|
|
82
|
+
baltic: ["EE", "LV", "LT"],
|
|
83
|
+
oceania: ["AU", "NZ", "NC"],
|
|
84
|
+
middle_east: ["AE", "IL", "KW", "QA", "SA"],
|
|
85
|
+
}
|
|
86
|
+
// Leave-one-language-FAMILY-out probe (DeepSeek): hold out WHOLE families the model never sees a row
|
|
87
|
+
// from — Baltic (Latin, distinct), Oceania (English-Latin, distinct), Middle-East (romanized non-Latin).
|
|
88
|
+
const HELDOUT_FAMILIES = new Set(["baltic", "oceania", "middle_east"])
|
|
89
|
+
|
|
90
|
+
/** Assemble a plausible address string from an OA row — SAME shape variants as build-outlier-latin. */
|
|
91
|
+
function assemble(r: Record<string, unknown>): string | null {
|
|
92
|
+
const num = (r.number ?? "").toString().trim()
|
|
93
|
+
const street = (r.street ?? "").toString().trim()
|
|
94
|
+
const pc = (r.postcode ?? "").toString().trim()
|
|
95
|
+
const locality = (r.city ?? "").toString().trim()
|
|
96
|
+
|
|
97
|
+
if (!street && !locality) return null
|
|
98
|
+
|
|
99
|
+
// nothing distinctive
|
|
100
|
+
// Drop raw-coord-only / PO-box-ish noise (DeepSeek gotcha): need a real street or locality token.
|
|
101
|
+
if (!street && !/[a-z]/i.test(locality)) return null
|
|
102
|
+
const head = [num, street].filter(Boolean).join(" ")
|
|
103
|
+
const h = hashFNV1a(`${num}|${street}|${pc}|${locality}`)
|
|
104
|
+
|
|
105
|
+
switch (h % 3) {
|
|
106
|
+
case 0:
|
|
107
|
+
return [head, [pc, locality].filter(Boolean).join(" ")].filter(Boolean).join(", ")
|
|
108
|
+
case 1:
|
|
109
|
+
return [head, locality, pc].filter(Boolean).join(", ").trim()
|
|
110
|
+
default:
|
|
111
|
+
return [head, [locality, pc].filter(Boolean).join(" ")].filter(Boolean).join(", ")
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Coarse-placer OpenAddresses Latin-off-map outlier builder — see the module doc. */
|
|
116
|
+
export async function buildOutlierOA(
|
|
117
|
+
options: BuildOutlierOAOptions = {},
|
|
118
|
+
report?: (line: string) => void
|
|
119
|
+
): Promise<BuildOutlierOAResult> {
|
|
120
|
+
const oaDir = options.oaDir || dataRootPath("openaddresses", "extracted")
|
|
121
|
+
const PER = options.perCountry ?? 6000
|
|
122
|
+
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
123
|
+
|
|
124
|
+
// Heavy dep (devDependency — operator tooling), lazy-imported so loading the tools barrel stays cheap.
|
|
125
|
+
const { DuckDBInstance } = await import("@duckdb/node-api")
|
|
126
|
+
const duck = await (await DuckDBInstance.create()).connect()
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Read+assemble up to PER deduped rows for a country from its OA CSVs (glob under the per-country dir).
|
|
130
|
+
*/
|
|
131
|
+
async function rowsFor(cc: string): Promise<string[]> {
|
|
132
|
+
const lc = cc.toLowerCase()
|
|
133
|
+
// OA collected layout: `<cc>/[<region>/]<source>.csv` (country at root; `summary/` excluded by
|
|
134
|
+
// rooting the glob at <cc>). `**` matches zero-or-more dirs → handles both flat + region-nested.
|
|
135
|
+
const glob = path.join(oaDir, lc, "**", "*.csv")
|
|
136
|
+
let res
|
|
137
|
+
|
|
138
|
+
try {
|
|
139
|
+
res = await duck.runAndReadAll(
|
|
140
|
+
// union_by_name aligns the differing per-source schemas; LOWER the header access so NUMBER /
|
|
141
|
+
// number both resolve. Pull a generous superset, dedup+cap in JS.
|
|
142
|
+
`SELECT COLUMNS('(?i)^(number|street|city|postcode)$') FROM read_csv_auto('${glob}', union_by_name=true, ignore_errors=true, sample_size=-1) LIMIT ${PER * 8}`
|
|
143
|
+
)
|
|
144
|
+
} catch (e) {
|
|
145
|
+
report?.(` ${cc}: SKIP (${(e as Error).message.split("\n")[0]})`)
|
|
146
|
+
|
|
147
|
+
return []
|
|
148
|
+
}
|
|
149
|
+
const seen = new Set<string>()
|
|
150
|
+
const out: string[] = []
|
|
151
|
+
|
|
152
|
+
for (const r of res.getRowObjects()) {
|
|
153
|
+
// COLUMNS() preserves source-case keys; normalize to lowercase access.
|
|
154
|
+
const row: Record<string, unknown> = {}
|
|
155
|
+
|
|
156
|
+
for (const [k, v] of Object.entries(r)) {
|
|
157
|
+
row[k.toLowerCase()] = v
|
|
158
|
+
}
|
|
159
|
+
const raw = assemble(row)
|
|
160
|
+
|
|
161
|
+
if (!raw || raw.length < 6 || seen.has(raw)) continue
|
|
162
|
+
seen.add(raw)
|
|
163
|
+
out.push(raw)
|
|
164
|
+
|
|
165
|
+
if (out.length >= PER) break
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return out.sort((a, b) => hashFNV1a(a) - hashFNV1a(b))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const trainAppend: string[] = []
|
|
172
|
+
const valAppend: string[] = []
|
|
173
|
+
const testRows: OaTestRow[] = [] // {raw, country:"OTHER", group, srcCountry, family}
|
|
174
|
+
let trainCC = 0
|
|
175
|
+
let heldCC = 0
|
|
176
|
+
|
|
177
|
+
for (const [family, countries] of Object.entries(FAMILIES)) {
|
|
178
|
+
const heldout = HELDOUT_FAMILIES.has(family)
|
|
179
|
+
|
|
180
|
+
for (const cc of countries) {
|
|
181
|
+
if (IN_MAP.has(cc)) continue
|
|
182
|
+
const rows = await rowsFor(cc)
|
|
183
|
+
|
|
184
|
+
if (rows.length === 0) continue
|
|
185
|
+
|
|
186
|
+
if (heldout) {
|
|
187
|
+
for (const raw of rows) {
|
|
188
|
+
testRows.push({ raw, country: "OTHER", group: "heldout", srcCountry: cc, family })
|
|
189
|
+
}
|
|
190
|
+
heldCC++
|
|
191
|
+
report?.(` HELDOUT ${cc} (${family}): ${rows.length} (test-only)`)
|
|
192
|
+
} else {
|
|
193
|
+
const nVal = Math.floor(rows.length * 0.1)
|
|
194
|
+
const nTest = Math.floor(rows.length * 0.1)
|
|
195
|
+
|
|
196
|
+
for (const raw of rows.slice(0, nVal)) {
|
|
197
|
+
valAppend.push(raw)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
for (const raw of rows.slice(nVal, nVal + nTest)) {
|
|
201
|
+
testRows.push({ raw, country: "OTHER", group: "indist", srcCountry: cc, family })
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
for (const raw of rows.slice(nVal + nTest)) {
|
|
205
|
+
trainAppend.push(raw)
|
|
206
|
+
}
|
|
207
|
+
trainCC++
|
|
208
|
+
report?.(` TRAIN ${cc} (${family}): ${rows.length}`)
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
;(duck as { disconnect?: () => void }).disconnect?.()
|
|
213
|
+
|
|
214
|
+
const wr = (rows: string[]): string => rows.map((raw) => JSON.stringify({ raw, country: "OTHER" })).join("\n") + "\n"
|
|
215
|
+
appendFileSync(path.join(dataDir, "train.jsonl"), wr(trainAppend))
|
|
216
|
+
appendFileSync(path.join(dataDir, "val.jsonl"), wr(valAppend))
|
|
217
|
+
writeFileSync(path.join(dataDir, "test-latin-offmap.jsonl"), testRows.map((r) => JSON.stringify(r)).join("\n") + "\n")
|
|
218
|
+
report?.(`\nTRAIN countries: ${trainCC} · HELDOUT countries: ${heldCC}`)
|
|
219
|
+
report?.(`appended OTHER → train +${trainAppend.length}, val +${valAppend.length}`)
|
|
220
|
+
report?.(
|
|
221
|
+
`wrote test-latin-offmap.jsonl: ${testRows.length} (indist ${testRows.filter((r) => r.group === "indist").length} / heldout ${testRows.filter((r) => r.group === "heldout").length})`
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
train: trainAppend.length,
|
|
226
|
+
val: valAppend.length,
|
|
227
|
+
test: testRows.length,
|
|
228
|
+
trainCountries: trainCC,
|
|
229
|
+
heldoutCountries: heldCC,
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Measure the #244 coarse-placer's handling of the Latin-script off-map residual (milestone 3). A
|
|
7
|
+
* Latin off-map address is HANDLED when the model routes it to OTHER or abstains — anything else
|
|
8
|
+
* is a confident mis-placement onto a wrong (trained) country. Reports handled-rate overall, by
|
|
9
|
+
* group (indist = held-out rows of trained-OTHER countries; heldout = countries never trained),
|
|
10
|
+
* and by source country, plus where the misses land. Run baseline (current model) and the M3
|
|
11
|
+
* retrain through this to read the before/after.
|
|
12
|
+
*
|
|
13
|
+
* Run: `mailwoman placer eval latin-offmap --model <dir> [--abstain 0.5]`
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { readFileSync } from "node:fs"
|
|
17
|
+
import * as path from "node:path"
|
|
18
|
+
|
|
19
|
+
import { dataRootPath } from "../../utils/data-root.ts"
|
|
20
|
+
import { repoRootPath } from "../../utils/repo.ts"
|
|
21
|
+
import { formatPercent } from "../../utils/stats.ts"
|
|
22
|
+
import { CoarsePlacer, type CoarsePlacerMeta, type CoarsePrediction } from "../coarse-placer.ts"
|
|
23
|
+
|
|
24
|
+
interface OffMapRow {
|
|
25
|
+
raw: string
|
|
26
|
+
country: string
|
|
27
|
+
group: string
|
|
28
|
+
srcCountry: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Options for {@linkcode evalLatinOffmap}. */
|
|
32
|
+
export interface EvalLatinOffmapOptions {
|
|
33
|
+
/** Model artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
|
|
34
|
+
model?: string
|
|
35
|
+
/** Abstention threshold. Default 0.5. */
|
|
36
|
+
abstain?: number
|
|
37
|
+
/** Dataset dir (`test-latin-offmap.jsonl`). Default `<repo>/data/coarse-placer`. */
|
|
38
|
+
data?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Result of {@linkcode evalLatinOffmap}. */
|
|
42
|
+
export interface EvalLatinOffmapResult {
|
|
43
|
+
n: number
|
|
44
|
+
handled: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Coarse-placer Latin off-map handling eval — see the module doc. Emits the report to stdout. */
|
|
48
|
+
export async function evalLatinOffmap(options: EvalLatinOffmapOptions = {}): Promise<EvalLatinOffmapResult> {
|
|
49
|
+
const modelDir = options.model || dataRootPath("coarse-placer", "model")
|
|
50
|
+
const abstain = options.abstain ?? 0.5
|
|
51
|
+
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
52
|
+
|
|
53
|
+
const meta = JSON.parse(readFileSync(path.join(modelDir, "meta.json"), "utf8")) as CoarsePlacerMeta
|
|
54
|
+
const buf = readFileSync(path.join(modelDir, "weights.bin"))
|
|
55
|
+
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
|
|
56
|
+
let weights: Float32Array
|
|
57
|
+
|
|
58
|
+
if (meta.quantization === "int8-per-row") {
|
|
59
|
+
const int8 = new Int8Array(ab)
|
|
60
|
+
const C = meta.classes.length
|
|
61
|
+
const dim = meta.featureDim
|
|
62
|
+
const scales = meta.scales!
|
|
63
|
+
weights = new Float32Array(C * dim)
|
|
64
|
+
|
|
65
|
+
for (let c = 0; c < C; c++) {
|
|
66
|
+
const s = scales[c]!
|
|
67
|
+
const base = c * dim
|
|
68
|
+
|
|
69
|
+
for (let i = 0; i < dim; i++) {
|
|
70
|
+
weights[base + i] = int8[base + i]! * s
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
} else {
|
|
74
|
+
weights = new Float32Array(ab)
|
|
75
|
+
}
|
|
76
|
+
const placer = new CoarsePlacer({ ...meta, weights }, { abstainBelow: abstain })
|
|
77
|
+
|
|
78
|
+
const rows: OffMapRow[] = readFileSync(path.join(dataDir, "test-latin-offmap.jsonl"), "utf8")
|
|
79
|
+
.trim()
|
|
80
|
+
.split("\n")
|
|
81
|
+
.map((l) => JSON.parse(l) as OffMapRow)
|
|
82
|
+
|
|
83
|
+
const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
|
|
84
|
+
const by: Record<string, { n: number; ok: number }> = {} // key → {n, ok}
|
|
85
|
+
const missTo: Record<string, number> = {} // wrong country → count
|
|
86
|
+
const bump = (k: string): { n: number; ok: number } => (by[k] ??= { n: 0, ok: 0 })
|
|
87
|
+
let n = 0
|
|
88
|
+
let ok = 0
|
|
89
|
+
const samples: string[] = []
|
|
90
|
+
|
|
91
|
+
for (const r of rows) {
|
|
92
|
+
const p = placer.predict(r.raw)
|
|
93
|
+
const h = handled(p)
|
|
94
|
+
n++
|
|
95
|
+
|
|
96
|
+
if (h) {
|
|
97
|
+
ok++
|
|
98
|
+
}
|
|
99
|
+
bump(`group:${r.group}`).n++
|
|
100
|
+
bump(`cc:${r.srcCountry}`).n++
|
|
101
|
+
|
|
102
|
+
if (h) {
|
|
103
|
+
bump(`group:${r.group}`).ok++
|
|
104
|
+
bump(`cc:${r.srcCountry}`).ok++
|
|
105
|
+
} else {
|
|
106
|
+
missTo[p.country!] = (missTo[p.country!] ?? 0) + 1
|
|
107
|
+
|
|
108
|
+
if (samples.length < 8) {
|
|
109
|
+
samples.push(` ${r.srcCountry} → ${p.country} @${p.confidence.toFixed(2)} «${r.raw.slice(0, 38)}»`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
console.log(`Latin off-map handling — model ${path.basename(modelDir)} (abstain ${abstain}, n=${n})`)
|
|
114
|
+
console.log(` OVERALL handled (OTHER-or-abstain): ${ok}/${n} (${formatPercent(ok, n)}) ← want ≥90%`)
|
|
115
|
+
console.log(` by group:`)
|
|
116
|
+
|
|
117
|
+
for (const k of Object.keys(by)
|
|
118
|
+
.filter((k) => k.startsWith("group:"))
|
|
119
|
+
.sort()) {
|
|
120
|
+
console.log(` ${k.slice(6).padEnd(8)} ${formatPercent(by[k]!.ok, by[k]!.n)} (n=${by[k]!.n})`)
|
|
121
|
+
}
|
|
122
|
+
console.log(` by source country:`)
|
|
123
|
+
|
|
124
|
+
for (const k of Object.keys(by)
|
|
125
|
+
.filter((k) => k.startsWith("cc:"))
|
|
126
|
+
.sort()) {
|
|
127
|
+
console.log(` ${k.slice(3).padEnd(4)} ${formatPercent(by[k]!.ok, by[k]!.n)} (n=${by[k]!.n})`)
|
|
128
|
+
}
|
|
129
|
+
const misses = Object.entries(missTo).sort((a, b) => b[1] - a[1])
|
|
130
|
+
|
|
131
|
+
if (misses.length) {
|
|
132
|
+
console.log(` misses land on: ${misses.map(([c, m]) => `${c}:${m}`).join(", ")}`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (samples.length) {
|
|
136
|
+
console.log(` sample misplacements:\n${samples.join("\n")}`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return { n, handled: ok }
|
|
140
|
+
}
|