@mailwoman/core 7.2.0 → 7.3.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/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/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/api/APIClient.d.ts.map +1 -1
- package/out/api/APIClient.js +2 -2
- package/out/api/APIClient.js.map +1 -1
- package/out/pipeline/types.d.ts +13 -0
- package/out/pipeline/types.d.ts.map +1 -1
- package/out/pipeline/types.js.map +1 -1
- package/out/scripting/utils/index.d.ts.map +1 -1
- package/out/scripting/utils/index.js +3 -5
- package/out/scripting/utils/index.js.map +1 -1
- package/package.json +190 -107
- 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 +357 -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 +103 -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
- package/out/lifecycle/ServiceSymbol.d.ts +0 -57
- package/out/lifecycle/ServiceSymbol.d.ts.map +0 -1
- package/out/lifecycle/ServiceSymbol.js +0 -60
- package/out/lifecycle/ServiceSymbol.js.map +0 -1
- package/out/lifecycle/index.d.ts +0 -11
- package/out/lifecycle/index.d.ts.map +0 -1
- package/out/lifecycle/index.js +0 -11
- package/out/lifecycle/index.js.map +0 -1
- package/out/lifecycle/lru-cache.d.ts +0 -22
- package/out/lifecycle/lru-cache.d.ts.map +0 -1
- package/out/lifecycle/lru-cache.js +0 -31
- package/out/lifecycle/lru-cache.js.map +0 -1
- package/out/lifecycle/services.d.ts +0 -144
- package/out/lifecycle/services.d.ts.map +0 -1
- package/out/lifecycle/services.js +0 -191
- package/out/lifecycle/services.js.map +0 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Feature extraction for the #244 coarse-placer — a fastText-style hashed char-n-gram
|
|
7
|
+
* representation plus explicit Unicode-script presence tokens. Deterministic + pure (shared by
|
|
8
|
+
* training and the always-resident inference), zero deps. A string → a set of active feature
|
|
9
|
+
* indices in [0, FEATURE_DIM).
|
|
10
|
+
*
|
|
11
|
+
* Why these features: script is the dominant coarse-geography signal (CJK→East Asia,
|
|
12
|
+
* Cyrillic→Eastern Europe, Arabic→MENA), and char n-grams separate WITHIN a script (Hangul→KR vs
|
|
13
|
+
* kana→JP vs Han-only→CN, or Dutch "straat" vs French "rue" within Latin). A linear model over
|
|
14
|
+
* both is a few hundred KB and runs in microseconds — the "always-resident, places the planet
|
|
15
|
+
* coarsely" tier.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The trained classes: the well-represented corpus countries, the #743 Overture-sourced EU expansion, and `OTHER` — the
|
|
20
|
+
* explicit off-map class (milestone 2) trained on non-Latin/non-CJK scripts via outlier exposure, so the model learns
|
|
21
|
+
* the edge of its competence and routes "probably off my loaded map" instead of a confident mis-placement. Index order
|
|
22
|
+
* is the label id.
|
|
23
|
+
*
|
|
24
|
+
* The first 11 are the original v0.5.0-corpus countries. The next 16 (#743) are EU locales the placer previously
|
|
25
|
+
* couldn't emit — ambiguous names there (FI "Helsinki", PL "Rybnik") landed off-continent in the population-first
|
|
26
|
+
* candidate gazetteer because no country prior pinned them. They're trained from the Overture per-country addresses
|
|
27
|
+
* theme (`build-dataset.mjs`), and they're pulled OUT of the Latin off-map OTHER outlier set
|
|
28
|
+
* (`build-outlier-latin.mjs`) that used to teach PL/PT/CZ → OTHER. Widening the class set is the soft-prior lever; it
|
|
29
|
+
* never hard-filters, so a neighbour confusion (DK↔NO, EE↔LT↔LV) still keeps resolution in-region, off the global-pop
|
|
30
|
+
* attractors. Adding a class requires a retrain + a fresh artifact — the bundled meta.json carries its own `classes`,
|
|
31
|
+
* so this constant only drives training (`train.mjs`), not inference.
|
|
32
|
+
*/
|
|
33
|
+
export const COARSE_CLASSES = [
|
|
34
|
+
"US",
|
|
35
|
+
"FR",
|
|
36
|
+
"GB",
|
|
37
|
+
"CN",
|
|
38
|
+
"NL",
|
|
39
|
+
"IT",
|
|
40
|
+
"DE",
|
|
41
|
+
"JP",
|
|
42
|
+
"ES",
|
|
43
|
+
"KR",
|
|
44
|
+
"TW",
|
|
45
|
+
"AT",
|
|
46
|
+
"BE",
|
|
47
|
+
"CH",
|
|
48
|
+
"CZ",
|
|
49
|
+
"DK",
|
|
50
|
+
"EE",
|
|
51
|
+
"FI",
|
|
52
|
+
"HR",
|
|
53
|
+
"LT",
|
|
54
|
+
"LU",
|
|
55
|
+
"LV",
|
|
56
|
+
"NO",
|
|
57
|
+
"PL",
|
|
58
|
+
"PT",
|
|
59
|
+
"SI",
|
|
60
|
+
"SK",
|
|
61
|
+
// #244/#928 AU expansion (2026-07-06): AU was unrepresentable (not in-map) AND its 4-digit postcode
|
|
62
|
+
// is format-ambiguous, so no #928 format-prior lever applies — the placer is AU's only country
|
|
63
|
+
// signal. Trained from the v0.9.2 G-NAF corpus shard (150k real Australian addresses).
|
|
64
|
+
"AU",
|
|
65
|
+
"OTHER",
|
|
66
|
+
] as const
|
|
67
|
+
export type CoarseClass = (typeof COARSE_CLASSES)[number]
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Hashed-feature dimensionality (2^16). Keeps the weight matrix small (28×65536 ≈ 1.8 MB int8) while collisions stay
|
|
71
|
+
* tolerable for a linear bag-of-features model; the discriminative n-grams are few.
|
|
72
|
+
*/
|
|
73
|
+
export const FEATURE_DIM = 1 << 16
|
|
74
|
+
|
|
75
|
+
/** Coarse Unicode-script buckets — strong priors the n-grams refine. */
|
|
76
|
+
const SCRIPTS = [
|
|
77
|
+
"latin",
|
|
78
|
+
"cjk",
|
|
79
|
+
"cyrillic",
|
|
80
|
+
"arabic",
|
|
81
|
+
"greek",
|
|
82
|
+
"hebrew",
|
|
83
|
+
"devanagari",
|
|
84
|
+
"thai",
|
|
85
|
+
"digit",
|
|
86
|
+
"other",
|
|
87
|
+
] as const
|
|
88
|
+
type Script = (typeof SCRIPTS)[number]
|
|
89
|
+
|
|
90
|
+
function scriptOf(cp: number): Script {
|
|
91
|
+
if (cp >= 0x30 && cp <= 0x39) return "digit"
|
|
92
|
+
|
|
93
|
+
if ((cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a) || (cp >= 0xc0 && cp <= 0x24f)) return "latin"
|
|
94
|
+
|
|
95
|
+
if (
|
|
96
|
+
(cp >= 0x3040 && cp <= 0x30ff) ||
|
|
97
|
+
(cp >= 0x4e00 && cp <= 0x9fff) ||
|
|
98
|
+
(cp >= 0xac00 && cp <= 0xd7af) ||
|
|
99
|
+
(cp >= 0x3400 && cp <= 0x4dbf)
|
|
100
|
+
)
|
|
101
|
+
return "cjk"
|
|
102
|
+
|
|
103
|
+
if ((cp >= 0x400 && cp <= 0x52f) || (cp >= 0x2de0 && cp <= 0x2dff)) return "cyrillic"
|
|
104
|
+
|
|
105
|
+
if ((cp >= 0x600 && cp <= 0x6ff) || (cp >= 0x750 && cp <= 0x77f) || (cp >= 0xfb50 && cp <= 0xfeff)) return "arabic"
|
|
106
|
+
|
|
107
|
+
if (cp >= 0x370 && cp <= 0x3ff) return "greek"
|
|
108
|
+
|
|
109
|
+
if (cp >= 0x590 && cp <= 0x5ff) return "hebrew"
|
|
110
|
+
|
|
111
|
+
if (cp >= 0x900 && cp <= 0x97f) return "devanagari"
|
|
112
|
+
|
|
113
|
+
if (cp >= 0xe00 && cp <= 0xe7f) return "thai"
|
|
114
|
+
|
|
115
|
+
return "other"
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** FNV-1a → a feature bucket in [0, FEATURE_DIM). */
|
|
119
|
+
function bucket(s: string, salt: number): number {
|
|
120
|
+
let h = (2166136261 ^ salt) >>> 0
|
|
121
|
+
|
|
122
|
+
for (let i = 0; i < s.length; i++) {
|
|
123
|
+
h ^= s.charCodeAt(i)
|
|
124
|
+
h = Math.imul(h, 16777619)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return (h >>> 0) % FEATURE_DIM
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Featurize an address into a deduped list of active feature indices: char 3/4/5-grams over the lowercased,
|
|
132
|
+
* boundary-marked string + one presence token per Unicode script seen (+ the dominant script). Non-Latin characters are
|
|
133
|
+
* PRESERVED (lowercasing only touches cased scripts).
|
|
134
|
+
*/
|
|
135
|
+
export function featurize(text: string): number[] {
|
|
136
|
+
const norm = text.toLowerCase().replace(/\s+/g, " ").trim()
|
|
137
|
+
|
|
138
|
+
if (!norm) return []
|
|
139
|
+
const active = new Set<number>()
|
|
140
|
+
|
|
141
|
+
// Script presence + dominant script (counted on the original to preserve case-neutral codepoints).
|
|
142
|
+
const counts = new Map<Script, number>()
|
|
143
|
+
|
|
144
|
+
for (const ch of norm) {
|
|
145
|
+
const sc = scriptOf(ch.codePointAt(0)!)
|
|
146
|
+
counts.set(sc, (counts.get(sc) ?? 0) + 1)
|
|
147
|
+
}
|
|
148
|
+
let dominant: Script = "other"
|
|
149
|
+
let max = -1
|
|
150
|
+
|
|
151
|
+
for (const [sc, n] of counts) {
|
|
152
|
+
active.add(bucket(`__scr_${sc}`, 1))
|
|
153
|
+
|
|
154
|
+
if (sc !== "digit" && sc !== "other" && n > max) {
|
|
155
|
+
max = n
|
|
156
|
+
dominant = sc
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
active.add(bucket(`__dom_${dominant}`, 2))
|
|
160
|
+
|
|
161
|
+
// Char n-grams (3,4,5) over the boundary-marked string.
|
|
162
|
+
const marked = `^${norm}$`
|
|
163
|
+
|
|
164
|
+
for (const n of [3, 4, 5]) {
|
|
165
|
+
for (let i = 0; i + n <= marked.length; i++) {
|
|
166
|
+
active.add(bucket(marked.slice(i, i + n), n))
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return [...active]
|
|
171
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Assemble a balanced (address → country) dataset for the #244 coarse-placer from the v0.5.0
|
|
7
|
+
* corpus. STRATIFIED: a flat random sample is 94% US+FR, so we sample up to N rows PER country
|
|
8
|
+
* and union.
|
|
9
|
+
*
|
|
10
|
+
* Two gotchas this handles:
|
|
11
|
+
*
|
|
12
|
+
* - DuckDB `USING SAMPLE n ROWS` samples the TABLE, then WHERE filters the sample — so we
|
|
13
|
+
* filter-THEN-sample in a subquery to get a true per-country sample.
|
|
14
|
+
* - The corpus val/test shards only carry US/FR/DE, so we draw ALL splits from the rich `train`
|
|
15
|
+
* shards and do our OWN per-country 80/10/10 split (dedup on raw → no row crosses splits).
|
|
16
|
+
*
|
|
17
|
+
* Run: `mailwoman placer build-dataset [--per-country 50000]` Output:
|
|
18
|
+
* `<repo>/data/coarse-placer/{train,val,test}.jsonl` (rows: {raw, country})
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { mkdirSync, writeFileSync } from "node:fs"
|
|
22
|
+
import * as path from "node:path"
|
|
23
|
+
|
|
24
|
+
import { dataRootPath } from "../../utils/data-root.ts"
|
|
25
|
+
import { repoRootPath } from "../../utils/repo.ts"
|
|
26
|
+
import { hashFNV1a } from "./fnv-hash.ts"
|
|
27
|
+
|
|
28
|
+
interface DatasetRow {
|
|
29
|
+
raw: string
|
|
30
|
+
country: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Options for {@linkcode buildDataset}. */
|
|
34
|
+
export interface BuildDatasetOptions {
|
|
35
|
+
/** Rows sampled per country. Default 50000. */
|
|
36
|
+
perCountry?: number
|
|
37
|
+
/** Dataset output dir. Default `<repo>/data/coarse-placer`. */
|
|
38
|
+
data?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Result of {@linkcode buildDataset}. */
|
|
42
|
+
export interface BuildDatasetResult {
|
|
43
|
+
outDir: string
|
|
44
|
+
train: number
|
|
45
|
+
val: number
|
|
46
|
+
test: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const VAL_FRAC = 0.1
|
|
50
|
+
const TEST_FRAC = 0.1
|
|
51
|
+
|
|
52
|
+
const COUNTRIES = ["US", "FR", "GB", "CN", "NL", "IT", "DE", "JP", "ES", "KR", "TW"]
|
|
53
|
+
|
|
54
|
+
// #743: the EU expansion. The v0.5.0 corpus carries zero rows for these locales, so they're drawn
|
|
55
|
+
// from the Overture per-country addresses theme (the same source build-eu-eval-set.ts uses). They
|
|
56
|
+
// were previously OTHER outlier exposure (PL/PT/CZ) or simply unrepresentable; here they become
|
|
57
|
+
// first-class in-map countries so the soft country prior can pin them.
|
|
58
|
+
const NEW_EU = ["AT", "BE", "CH", "CZ", "DK", "EE", "FI", "HR", "LT", "LU", "LV", "NO", "PL", "PT", "SI", "SK"]
|
|
59
|
+
// #743 in-map dilution fix: DE/ES/IT/NL are already in COUNTRIES (corpus format), but the eu-eval
|
|
60
|
+
// sets + every NEW_EU country are Overture format. Without an Overture sample of their OWN, their
|
|
61
|
+
// Overture-format eval rows scatter to the Overture-trained neighbours (measured: only 63% of ES
|
|
62
|
+
// eval rows routed ES, ~26% leaked to CH/PT/HR/IT/FR/CZ). SUPPLEMENT their corpus rows with an
|
|
63
|
+
// Overture sample so each owns its own format shape; the format then stops being discriminative and
|
|
64
|
+
// the model falls back to the linguistic n-grams. GB excluded — its Overture parquet is empty.
|
|
65
|
+
const IN_MAP_EU = ["DE", "ES", "IT", "NL"]
|
|
66
|
+
|
|
67
|
+
// #743 EU expansion: draw the new in-map countries from the Overture per-country addresses theme.
|
|
68
|
+
// The raw fields are formatted into native address strings with FORMAT VARIETY (4 templates picked
|
|
69
|
+
// deterministically per row) so the model can't shortcut on a single template shape — it must use
|
|
70
|
+
// the actual street-type words + locality n-grams (Finnish "katu/tie", Polish "ul.", Norwegian
|
|
71
|
+
// "veien") that carry the country signal. Same 80/10/10 dedup split as the corpus path.
|
|
72
|
+
function formatEu(street: unknown, number: unknown, postcode: unknown, loc: string, t: number): string {
|
|
73
|
+
const s = String(street).trim()
|
|
74
|
+
const num = number != null && String(number).trim() !== "" ? ` ${String(number).trim()}` : ""
|
|
75
|
+
const pc = postcode != null && String(postcode).trim() !== "" ? String(postcode).trim() : ""
|
|
76
|
+
|
|
77
|
+
switch (t) {
|
|
78
|
+
case 1:
|
|
79
|
+
return `${s}${num} ${loc}` // no postcode, no comma
|
|
80
|
+
case 2:
|
|
81
|
+
return `${s}${num}, ${loc}${pc ? `, ${pc}` : ""}` // postcode trailing
|
|
82
|
+
case 3:
|
|
83
|
+
return `${s}, ${pc ? `${pc} ` : ""}${loc}` // no house number
|
|
84
|
+
default:
|
|
85
|
+
return `${s}${num}, ${pc ? `${pc} ` : ""}${loc}` // {street number, postcode locality}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Coarse-placer dataset builder — see the module doc. */
|
|
90
|
+
export async function buildDataset(
|
|
91
|
+
options: BuildDatasetOptions = {},
|
|
92
|
+
report?: (line: string) => void
|
|
93
|
+
): Promise<BuildDatasetResult> {
|
|
94
|
+
const PER = options.perCountry ?? 50000
|
|
95
|
+
const OUT_DIR = options.data || repoRootPath("data", "coarse-placer")
|
|
96
|
+
|
|
97
|
+
const TRAIN_GLOB = dataRootPath("corpus", "versioned", "v0.5.0", "corpus-v0.5.0", "train", "*.parquet")
|
|
98
|
+
// #244/#928 AU expansion: the v0.5.0 pin carries only ~5.9k AU rows; the v0.9.2 G-NAF shard carries
|
|
99
|
+
// 150k real Australian addresses. AU rides the SAME corpus sampling path as COUNTRIES, just from its
|
|
100
|
+
// own glob — the (country, glob) pairs below unify the two.
|
|
101
|
+
const AU_GLOB = dataRootPath(
|
|
102
|
+
"corpus",
|
|
103
|
+
"versioned",
|
|
104
|
+
"v0.9.2-multilocale-au",
|
|
105
|
+
"corpus-v0.9.2-multilocale-au",
|
|
106
|
+
"train",
|
|
107
|
+
"*.parquet"
|
|
108
|
+
)
|
|
109
|
+
const OVERTURE_DIR = dataRootPath("overture", "2026-06-17.0")
|
|
110
|
+
mkdirSync(OUT_DIR, { recursive: true })
|
|
111
|
+
|
|
112
|
+
// Heavy dep (devDependency — operator tooling), lazy-imported so loading the tools barrel stays cheap.
|
|
113
|
+
const { DuckDBInstance } = await import("@duckdb/node-api")
|
|
114
|
+
const duck = await (await DuckDBInstance.create()).connect()
|
|
115
|
+
await duck.run("SET memory_limit='4GB'; SET threads=4;")
|
|
116
|
+
|
|
117
|
+
const train: DatasetRow[] = [],
|
|
118
|
+
val: DatasetRow[] = [],
|
|
119
|
+
test: DatasetRow[] = []
|
|
120
|
+
|
|
121
|
+
const CORPUS_SOURCES: ReadonlyArray<[string, string]> = [
|
|
122
|
+
...COUNTRIES.map((c): [string, string] => [c, String(TRAIN_GLOB)]),
|
|
123
|
+
["AU", String(AU_GLOB)],
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
for (const [country, glob] of CORPUS_SOURCES) {
|
|
127
|
+
// filter-THEN-sample: the subquery restricts to the country, SAMPLE draws from that filtered set.
|
|
128
|
+
const q = `SELECT raw FROM (
|
|
129
|
+
SELECT raw FROM read_parquet('${glob}') WHERE country = '${country}' AND nullif(trim(raw), '') IS NOT NULL
|
|
130
|
+
) USING SAMPLE ${Math.ceil(PER * 1.3)} ROWS`
|
|
131
|
+
const res = await duck.runAndReadAll(q)
|
|
132
|
+
const seen = new Set<string>()
|
|
133
|
+
const rows: string[] = []
|
|
134
|
+
|
|
135
|
+
for (const r of res.getRowObjects()) {
|
|
136
|
+
if (rows.length >= PER) break
|
|
137
|
+
const raw = String(r.raw).trim()
|
|
138
|
+
|
|
139
|
+
if (!raw || seen.has(raw)) continue
|
|
140
|
+
seen.add(raw)
|
|
141
|
+
rows.push(raw)
|
|
142
|
+
}
|
|
143
|
+
const nVal = Math.floor(rows.length * VAL_FRAC)
|
|
144
|
+
const nTest = Math.floor(rows.length * TEST_FRAC)
|
|
145
|
+
const valRows = rows.slice(0, nVal)
|
|
146
|
+
const testRows = rows.slice(nVal, nVal + nTest)
|
|
147
|
+
const trainRows = rows.slice(nVal + nTest)
|
|
148
|
+
|
|
149
|
+
for (const raw of trainRows) {
|
|
150
|
+
train.push({ raw, country })
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
for (const raw of valRows) {
|
|
154
|
+
val.push({ raw, country })
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
for (const raw of testRows) {
|
|
158
|
+
test.push({ raw, country })
|
|
159
|
+
}
|
|
160
|
+
report?.(` ${country}: train ${trainRows.length} val ${valRows.length} test ${testRows.length}`)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
for (const country of [...NEW_EU, ...IN_MAP_EU]) {
|
|
164
|
+
const parquet = `${OVERTURE_DIR}/addresses-${country.toLowerCase()}.parquet`
|
|
165
|
+
const q = `SELECT street, number, postcode,
|
|
166
|
+
COALESCE(NULLIF(trim(postal_city), ''), address_levels[len(address_levels)].value) AS loc
|
|
167
|
+
FROM read_parquet('${parquet}')
|
|
168
|
+
WHERE street IS NOT NULL AND trim(street) <> ''
|
|
169
|
+
USING SAMPLE ${Math.ceil(PER * 1.4)} ROWS`
|
|
170
|
+
let res
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
res = await duck.runAndReadAll(q)
|
|
174
|
+
} catch (e) {
|
|
175
|
+
report?.(` ${country}: SKIPPED — ${(e as Error).message}`)
|
|
176
|
+
continue
|
|
177
|
+
}
|
|
178
|
+
const seen = new Set<string>()
|
|
179
|
+
const rows: string[] = []
|
|
180
|
+
|
|
181
|
+
for (const r of res.getRowObjects()) {
|
|
182
|
+
if (rows.length >= PER) break
|
|
183
|
+
const loc = r.loc == null ? "" : String(r.loc).trim()
|
|
184
|
+
|
|
185
|
+
if (!loc) continue
|
|
186
|
+
const raw = formatEu(r.street, r.number, r.postcode, loc, hashFNV1a(`${r.street}|${loc}`) % 4)
|
|
187
|
+
|
|
188
|
+
if (!raw || seen.has(raw)) continue
|
|
189
|
+
seen.add(raw)
|
|
190
|
+
rows.push(raw)
|
|
191
|
+
}
|
|
192
|
+
const nVal = Math.floor(rows.length * VAL_FRAC)
|
|
193
|
+
const nTest = Math.floor(rows.length * TEST_FRAC)
|
|
194
|
+
|
|
195
|
+
for (const raw of rows.slice(0, nVal)) {
|
|
196
|
+
val.push({ raw, country })
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
for (const raw of rows.slice(nVal, nVal + nTest)) {
|
|
200
|
+
test.push({ raw, country })
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
for (const raw of rows.slice(nVal + nTest)) {
|
|
204
|
+
train.push({ raw, country })
|
|
205
|
+
}
|
|
206
|
+
report?.(` ${country} (overture): train ${rows.length - nVal - nTest} val ${nVal} test ${nTest}`)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const splits: [string, DatasetRow[]][] = [
|
|
210
|
+
["train", train],
|
|
211
|
+
["val", val],
|
|
212
|
+
["test", test],
|
|
213
|
+
]
|
|
214
|
+
|
|
215
|
+
for (const [name, rows] of splits) {
|
|
216
|
+
rows.sort((a, b) => hashFNV1a(a.raw + a.country) - hashFNV1a(b.raw + b.country)) // deterministic class-interleave
|
|
217
|
+
const p = path.join(OUT_DIR, `${name}.jsonl`)
|
|
218
|
+
writeFileSync(p, rows.map((r) => JSON.stringify(r)).join("\n") + "\n")
|
|
219
|
+
report?.(`→ ${p} (${rows.length} rows)`)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return { outDir: OUT_DIR, train: train.length, val: val.length, test: test.length }
|
|
223
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Outlier-exposure data for the #244 coarse-placer's explicit "OTHER" (off-map) class — milestone
|
|
7
|
+
* 2. The closed-set model is confidently wrong on scripts it never saw (Cyrillic→DE@0.71). The
|
|
8
|
+
* fix is to TRAIN an "off my loaded map" class on those scripts. Source: the WOF `names` table,
|
|
9
|
+
* which carries native-script alternate names in dozens of languages
|
|
10
|
+
* (rus/ukr/ara/ell/heb/hin/tha/kat/hye/…) — i.e. exactly the off-map scripts we want the model to
|
|
11
|
+
* learn to abstain on. Balanced per-language for script diversity, filtered to a genuinely
|
|
12
|
+
* off-map dominant script (not Latin, not CJK — those are the in-map countries), then APPENDED to
|
|
13
|
+
* the train/val/test splits as `country: "OTHER"`.
|
|
14
|
+
*
|
|
15
|
+
* Run AFTER build-dataset. Run: `mailwoman placer build-dataset --outliers exposure [--per-lang
|
|
16
|
+
* 2500]`
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { appendFileSync } from "node:fs"
|
|
20
|
+
import * as path from "node:path"
|
|
21
|
+
import { DatabaseSync } from "node:sqlite"
|
|
22
|
+
|
|
23
|
+
import { dataRootPath } from "../../utils/data-root.ts"
|
|
24
|
+
import { repoRootPath } from "../../utils/repo.ts"
|
|
25
|
+
import { hashFNV1a } from "./fnv-hash.ts"
|
|
26
|
+
|
|
27
|
+
/** Options for {@linkcode buildOutlierExposure}. */
|
|
28
|
+
export interface BuildOutlierExposureOptions {
|
|
29
|
+
/** Names sampled per off-map language. Default 2500. */
|
|
30
|
+
perLang?: number
|
|
31
|
+
/** WOF admin SQLite path. Default `$MAILWOMAN_DATA_ROOT/wof/admin-global-priority.db`. */
|
|
32
|
+
wof?: string
|
|
33
|
+
/** Dataset dir the OTHER rows append to. Default `<repo>/data/coarse-placer`. */
|
|
34
|
+
data?: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Result of {@linkcode buildOutlierExposure}. */
|
|
38
|
+
export interface BuildOutlierExposureResult {
|
|
39
|
+
/** Total OTHER pool size (names + address-shaped variants). */
|
|
40
|
+
total: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Off-map languages whose `names` are written in a NON-Latin, NON-CJK script (CJK = the in-map CN/JP/KR/TW).
|
|
44
|
+
const OFF_MAP_LANGS = [
|
|
45
|
+
"rus",
|
|
46
|
+
"ukr",
|
|
47
|
+
"bel",
|
|
48
|
+
"bul",
|
|
49
|
+
"srp",
|
|
50
|
+
"mkd", // Cyrillic
|
|
51
|
+
"ell", // Greek
|
|
52
|
+
"ara",
|
|
53
|
+
"fas",
|
|
54
|
+
"urd",
|
|
55
|
+
"snd",
|
|
56
|
+
"pus", // Arabic-script
|
|
57
|
+
"heb",
|
|
58
|
+
"yid", // Hebrew
|
|
59
|
+
"hin",
|
|
60
|
+
"mar",
|
|
61
|
+
"nep",
|
|
62
|
+
"san", // Devanagari
|
|
63
|
+
"ben",
|
|
64
|
+
"tam",
|
|
65
|
+
"tel",
|
|
66
|
+
"kan",
|
|
67
|
+
"mal",
|
|
68
|
+
"sin", // Brahmic
|
|
69
|
+
"tha",
|
|
70
|
+
"lao",
|
|
71
|
+
"khm",
|
|
72
|
+
"mya", // SE-Asian
|
|
73
|
+
"kat",
|
|
74
|
+
"hye",
|
|
75
|
+
"amh", // Georgian / Armenian / Ethiopic
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
/** Dominant script must be off-map: has chars in a non-Latin, non-CJK, non-digit block. */
|
|
79
|
+
function isOffMapScript(s: string): boolean {
|
|
80
|
+
let off = 0
|
|
81
|
+
let total = 0
|
|
82
|
+
|
|
83
|
+
for (const ch of s) {
|
|
84
|
+
const cp = ch.codePointAt(0)!
|
|
85
|
+
|
|
86
|
+
if (cp <= 0x40 || (cp >= 0x5b && cp <= 0x60) || cp === 0x20) continue // punct/space/digits
|
|
87
|
+
total++
|
|
88
|
+
const latin = (cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a) || (cp >= 0xc0 && cp <= 0x24f)
|
|
89
|
+
const cjk =
|
|
90
|
+
(cp >= 0x3040 && cp <= 0x30ff) ||
|
|
91
|
+
(cp >= 0x4e00 && cp <= 0x9fff) ||
|
|
92
|
+
(cp >= 0xac00 && cp <= 0xd7af) ||
|
|
93
|
+
(cp >= 0x3400 && cp <= 0x4dbf)
|
|
94
|
+
|
|
95
|
+
if (!latin && !cjk && cp > 0x2ff) {
|
|
96
|
+
off++
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return total > 0 && off / total > 0.6
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Mimic a real off-map ADDRESS: a pure-script place name isn't what we see at inference (those carry
|
|
104
|
+
// Latin digits + structure, e.g. "ул. Тверская, д. 1"). For each name we also emit an address-shaped
|
|
105
|
+
// variant — name + a house number, deterministically — so the model learns "off-map script + digits =
|
|
106
|
+
// still OTHER" and doesn't get pulled to a country by the numeric/punctuation n-grams.
|
|
107
|
+
function addressVariant(name: string, h: number): string {
|
|
108
|
+
const n = (h % 4) + 1 // 1–4 digit house number
|
|
109
|
+
const num = String(h % Math.pow(10, n) || 7)
|
|
110
|
+
|
|
111
|
+
switch (h % 3) {
|
|
112
|
+
case 0:
|
|
113
|
+
return `${name} ${num}`
|
|
114
|
+
case 1:
|
|
115
|
+
return `${num} ${name}`
|
|
116
|
+
default:
|
|
117
|
+
return `${name}, ${num}`
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Coarse-placer non-Latin outlier-exposure builder — see the module doc. */
|
|
122
|
+
export async function buildOutlierExposure(
|
|
123
|
+
options: BuildOutlierExposureOptions = {},
|
|
124
|
+
report?: (line: string) => void
|
|
125
|
+
): Promise<BuildOutlierExposureResult> {
|
|
126
|
+
const PER = options.perLang ?? 2500
|
|
127
|
+
const wofPath = options.wof || dataRootPath("wof", "admin-global-priority.db")
|
|
128
|
+
const dataDir = options.data || repoRootPath("data", "coarse-placer")
|
|
129
|
+
|
|
130
|
+
const db = new DatabaseSync(wofPath, { readOnly: true })
|
|
131
|
+
const pool: string[] = []
|
|
132
|
+
const seen = new Set<string>()
|
|
133
|
+
|
|
134
|
+
for (const lang of OFF_MAP_LANGS) {
|
|
135
|
+
const rows = db
|
|
136
|
+
.prepare(`SELECT name FROM names WHERE language = ? AND length(name) >= 4 LIMIT ?`)
|
|
137
|
+
.all(lang, PER * 2)
|
|
138
|
+
let kept = 0
|
|
139
|
+
|
|
140
|
+
for (const r of rows) {
|
|
141
|
+
if (kept >= PER) break
|
|
142
|
+
const name = String(r.name).trim()
|
|
143
|
+
|
|
144
|
+
if (!name || seen.has(name) || !isOffMapScript(name)) continue
|
|
145
|
+
seen.add(name)
|
|
146
|
+
pool.push(name)
|
|
147
|
+
pool.push(addressVariant(name, hashFNV1a(name))) // address-shaped sibling
|
|
148
|
+
kept++
|
|
149
|
+
}
|
|
150
|
+
report?.(` ${lang}: ${kept}`)
|
|
151
|
+
}
|
|
152
|
+
db.close()
|
|
153
|
+
|
|
154
|
+
// Deterministic shuffle (FNV hash sort) + split 80/10/10, append as OTHER.
|
|
155
|
+
pool.sort((a, b) => hashFNV1a(a) - hashFNV1a(b))
|
|
156
|
+
const nVal = Math.floor(pool.length * 0.1)
|
|
157
|
+
const nTest = Math.floor(pool.length * 0.1)
|
|
158
|
+
const splits: Record<string, string[]> = {
|
|
159
|
+
val: pool.slice(0, nVal),
|
|
160
|
+
test: pool.slice(nVal, nVal + nTest),
|
|
161
|
+
train: pool.slice(nVal + nTest),
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
for (const [split, names] of Object.entries(splits)) {
|
|
165
|
+
const lines = names.map((raw) => JSON.stringify({ raw, country: "OTHER" })).join("\n") + "\n"
|
|
166
|
+
appendFileSync(path.join(dataDir, `${split}.jsonl`), lines)
|
|
167
|
+
report?.(`appended ${names.length} OTHER → ${split}.jsonl`)
|
|
168
|
+
}
|
|
169
|
+
report?.(`total OTHER pool: ${pool.length}`)
|
|
170
|
+
|
|
171
|
+
return { total: pool.length }
|
|
172
|
+
}
|