@mailwoman/registry 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/address-key.ts +42 -0
- package/geocode-handler.ts +35 -0
- package/geojson.ts +65 -0
- package/index.ts +23 -0
- package/ingest.ts +334 -0
- package/learned-scorer.ts +128 -0
- package/map-html.ts +318 -0
- package/models/crosssource-gbt-en-us.ts +34 -0
- package/models/dedup-gbt-en-us.ts +40 -0
- package/models/org-crosssource-gbt-en-us.ts +33 -0
- package/package.json +17 -9
- package/reconcile.ts +230 -0
- package/resolve.ts +463 -0
- package/tools/coverage-reconciliation.ts +229 -0
- package/tools/cross-dataset-correlation.ts +442 -0
- package/tools/cross-source-threshold-sweep.ts +446 -0
- package/tools/dedup-ceiling.ts +355 -0
- package/tools/eval-geocoder.ts +50 -0
- package/tools/geocoder-namesake-probe.ts +81 -0
- package/tools/geocoder-vs-provided-coords.ts +180 -0
- package/tools/gold-set-sample.ts +235 -0
- package/tools/index.ts +36 -0
- package/tools/learned-scorer-clustering-eval.ts +505 -0
- package/tools/learned-scorer-crossstate-eval.ts +414 -0
- package/tools/learned-scorer-eval.ts +589 -0
- package/tools/matcher-scale.ts +182 -0
- package/tools/nppes-dedup-benchmark.ts +1080 -0
- package/tools/train-cross-gbt.ts +410 -0
- package/tools/train-gbt.ts +363 -0
- package/tools/train-org-cross-gbt.ts +373 -0
- package/tools/txhhsc-to-oarow.ts +87 -0
- package/tools/viz/cross-dataset-map.ts +127 -0
- package/tools/viz/geocode-first-surface.ts +298 -0
- package/tools/viz/render-map.ts +64 -0
- package/tools/viz/render.ts +95 -0
- package/tools/viz/source-provenance-map.ts +135 -0
- package/tools/viz/yardstick-figure.ts +204 -0
- package/types.ts +71 -0
package/address-key.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The address-id consumer for the matcher (#259). Derives a stable {@link PostalAddressID} from a
|
|
7
|
+
* resolved {@link SourceRecord} and exposes it as a blocking key — the deterministic,
|
|
8
|
+
* exact-canonical-address complement to the fuzzy Fellegi-Sunter / GBT scoring. Two uses:
|
|
9
|
+
*
|
|
10
|
+
* - **As a pre-dedup / join key:** `GROUP BY postalAddressID(record)` collapses records that resolve
|
|
11
|
+
* to the same place AND share a canonical address with NO scoring at all — the cheap, certain
|
|
12
|
+
* slice of dedup before the matcher does the fuzzy rest.
|
|
13
|
+
* - **As a blocking key:** {@link addressIDBlockingKey} adds the address-id to the blocking union, so
|
|
14
|
+
* records sharing one are guaranteed to be compared.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createPostalAddressID, type PostalAddressID } from "@mailwoman/address-id"
|
|
18
|
+
import { type BlockingKey, exactKey } from "@mailwoman/match"
|
|
19
|
+
|
|
20
|
+
import type { SourceRecord } from "./types.ts"
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The stable address primary key for a record, or null when it isn't geocoded (no coordinate → no locality cell) or
|
|
24
|
+
* carries no raw address to hash. Uses the resolved coordinate + the raw address; the state prefix is plucked from the
|
|
25
|
+
* address when present.
|
|
26
|
+
*/
|
|
27
|
+
export function postalAddressID(record: SourceRecord): PostalAddressID | null {
|
|
28
|
+
const coordinate = record.address?.geocode?.coordinate
|
|
29
|
+
const address = record.address?.raw
|
|
30
|
+
|
|
31
|
+
if (!coordinate || !address) return null
|
|
32
|
+
|
|
33
|
+
return createPostalAddressID({ coordinate, address })
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A blocking key on the {@link postalAddressID} — records that resolve to the same place with the same canonical address
|
|
38
|
+
* block together. Add it to {@link defaultBlockingKeys}'s union when an exact address join should never be missed.
|
|
39
|
+
*/
|
|
40
|
+
export function addressIDBlockingKey(): BlockingKey<SourceRecord> {
|
|
41
|
+
return exactKey((record) => postalAddressID(record))
|
|
42
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The per-record geocode step, factored out of the worker so it unit-tests against a fake seam (no
|
|
7
|
+
* neural model / SQLite). `geocode-worker.ts` builds the real seam from config and wraps this.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { type ColumnMapping, type GeocodeAddress, pick } from "./ingest.ts"
|
|
11
|
+
import type { SourceRecord } from "./types.ts"
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Build the handler `geocodeStream` runs per normalized record: recompute the joined address string from `record.raw` +
|
|
15
|
+
* `mapping.address` (the worker can't receive the original closure), geocode it via `seam`, and attach the result.
|
|
16
|
+
* Records with no mapped address pass through untouched (no geocode call). The default separator matches
|
|
17
|
+
* {@link ingestRow}'s `addressSeparator`.
|
|
18
|
+
*/
|
|
19
|
+
export function makeGeocodeHandler(
|
|
20
|
+
seam: GeocodeAddress,
|
|
21
|
+
mapping: ColumnMapping,
|
|
22
|
+
addressSeparator = ", "
|
|
23
|
+
): (record: SourceRecord) => Promise<SourceRecord> {
|
|
24
|
+
return async (record) => {
|
|
25
|
+
if (!record.raw) return record
|
|
26
|
+
|
|
27
|
+
const addressValue = pick(record.raw, mapping.address, addressSeparator)
|
|
28
|
+
|
|
29
|
+
if (!addressValue) return record
|
|
30
|
+
|
|
31
|
+
const address = (await seam(addressValue)) ?? undefined
|
|
32
|
+
|
|
33
|
+
return { ...record, address }
|
|
34
|
+
}
|
|
35
|
+
}
|
package/geojson.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Export resolved entities as GeoJSON — the bridge to QGIS and any web map. Each entity becomes a
|
|
7
|
+
* Point at its resolved coordinate, carrying the properties an analyst needs: how many records
|
|
8
|
+
* merged into it, how tightly (cohesion), the canonical name/org/address, and the geocode tier
|
|
9
|
+
* (so rooftop-precise entities can be styled apart from admin-centroid guesses). Entities without
|
|
10
|
+
* a coordinate are omitted (a Point feature needs one).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { GeoFeature, GeoFeatureCollection, PointLiteral } from "@mailwoman/spatial"
|
|
14
|
+
|
|
15
|
+
import type { EntityGeoData, ResolvedEntity, SourceRecord } from "./types.ts"
|
|
16
|
+
|
|
17
|
+
/** Assemble a display name from a record's parsed person name, if any. */
|
|
18
|
+
function displayName(record: SourceRecord): string | null {
|
|
19
|
+
const name = record.name
|
|
20
|
+
|
|
21
|
+
if (!name) return null
|
|
22
|
+
const joined = [name.prefix, name.given, name.middle, name.familyParticle, name.family, name.suffix]
|
|
23
|
+
.filter(Boolean)
|
|
24
|
+
.join(" ")
|
|
25
|
+
.trim()
|
|
26
|
+
|
|
27
|
+
return joined || null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One entity → one GeoJSON Point feature. */
|
|
31
|
+
function toFeature(entity: ResolvedEntity): GeoFeature<PointLiteral, EntityGeoData> {
|
|
32
|
+
const rep = entity.representative
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
type: "Feature",
|
|
36
|
+
id: undefined, // Consider using entity.id here.
|
|
37
|
+
geometry: {
|
|
38
|
+
type: "Point",
|
|
39
|
+
coordinates: [entity.coordinate!.longitude, entity.coordinate!.latitude],
|
|
40
|
+
},
|
|
41
|
+
properties: {
|
|
42
|
+
entityID: entity.id,
|
|
43
|
+
recordCount: entity.records.length,
|
|
44
|
+
cohesion: entity.cohesion,
|
|
45
|
+
sourceIds: entity.records.map((r) => r.id),
|
|
46
|
+
// Distinct provenance labels the entity's records span — an entity with ≥2 is a cross-dataset link.
|
|
47
|
+
sources: [...new Set(entity.records.map((r) => r.source).filter((s): s is string => !!s))].sort(),
|
|
48
|
+
name: displayName(rep),
|
|
49
|
+
organization: rep.organization?.canonical ?? null,
|
|
50
|
+
address: rep.address?.formatted ?? null,
|
|
51
|
+
geocodeTier: rep.address?.geocode?.tier ?? null,
|
|
52
|
+
},
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Convert resolved entities into a GeoJSON `FeatureCollection` of points, ready for QGIS. Entities with no resolved
|
|
58
|
+
* coordinate are skipped.
|
|
59
|
+
*/
|
|
60
|
+
export function toGeoJSON(entities: readonly ResolvedEntity[]): GeoFeatureCollection<PointLiteral, EntityGeoData> {
|
|
61
|
+
return {
|
|
62
|
+
type: "FeatureCollection",
|
|
63
|
+
features: entities.filter((entity) => entity.coordinate).map(toFeature),
|
|
64
|
+
}
|
|
65
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* `@mailwoman/registry` — the geocode-first record-matching application.
|
|
7
|
+
*
|
|
8
|
+
* {@link resolveEntities} runs the whole matcher (block → score → cluster) over normalized
|
|
9
|
+
* contact/organization {@link SourceRecord}s and returns canonical {@link ResolvedEntity entities};
|
|
10
|
+
* {@link toGeoJSON} exports them for QGIS. This is the clinic-funding use case mailwoman was built
|
|
11
|
+
* for, finally standing on a calibrated, label-free matcher.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export * from "./address-key.ts"
|
|
15
|
+
export * from "./geojson.ts"
|
|
16
|
+
export * from "./ingest.ts"
|
|
17
|
+
export * from "./geocode-handler.ts"
|
|
18
|
+
export * from "./learned-scorer.ts"
|
|
19
|
+
export * from "./map-html.ts"
|
|
20
|
+
export * from "./models/dedup-gbt-en-us.ts"
|
|
21
|
+
export * from "./reconcile.ts"
|
|
22
|
+
export * from "./resolve.ts"
|
|
23
|
+
export * from "./types.ts"
|
package/ingest.ts
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Ingest — turn messy tabular data (CSV, SQLite, hand-keyed spreadsheets) into normalized
|
|
7
|
+
* {@link SourceRecord}s, the front of the cascade.
|
|
8
|
+
*
|
|
9
|
+
* Two concerns, kept separate:
|
|
10
|
+
*
|
|
11
|
+
* 1. **Column mapping + normalization** (this is pure): a {@link ColumnMapping} says which column(s)
|
|
12
|
+
* hold the name, organization, address, phone, email; each row is normalized with
|
|
13
|
+
* `@mailwoman/record` (parse the person name, canonicalize the org). This is deterministic
|
|
14
|
+
* and testable with no heavy runtime.
|
|
15
|
+
* 2. **Geocoding** (the heavy part) is an injected seam — a {@link GeocodeAddress} the caller provides.
|
|
16
|
+
* Ingest never imports the neural parser, the resolver, or the shards; it just calls the
|
|
17
|
+
* seam per address. {@link geocodeAddressVia} builds that seam from mailwoman's real parse +
|
|
18
|
+
* geocode primitives (which the CLI constructs with the model + data in hand), so the wiring
|
|
19
|
+
* is concrete and testable without pinning the heavy runtime into this package.
|
|
20
|
+
*
|
|
21
|
+
* LLM-assisted column mapping (infer the mapping from a header + samples) is a documented
|
|
22
|
+
* fast-follow; the mapping is an explicit input here.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import type { AddressGeocode, PostalAddress } from "@mailwoman/record"
|
|
26
|
+
import { canonicalizeOrganizationName, parsePersonName, toPostalAddress, withGeocode } from "@mailwoman/record"
|
|
27
|
+
import { parse as parseCSVSync } from "csv-parse/sync"
|
|
28
|
+
import { CSVSpliterator, Delimiters } from "spliterator"
|
|
29
|
+
|
|
30
|
+
import type { SourceRecord } from "./types.ts"
|
|
31
|
+
|
|
32
|
+
/** Resolve a raw address string into a {@link PostalAddress}. The seam to mailwoman's geocoder. */
|
|
33
|
+
export type GeocodeAddress = (raw: string) => Promise<PostalAddress | null> | PostalAddress | null
|
|
34
|
+
|
|
35
|
+
/** Column delimiter of a delimited source. */
|
|
36
|
+
export type Delimiter = "comma" | "tab"
|
|
37
|
+
|
|
38
|
+
/** Infer the delimiter from a path's extension (`.tsv` → tab, else comma). */
|
|
39
|
+
export function delimiterFor(path: string): Delimiter {
|
|
40
|
+
return /\.tsv$/i.test(path) ? "tab" : "comma"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Stream a delimited file's rows lazily as header-keyed objects — the same shape {@link parseCSV} returns, but
|
|
45
|
+
* **without loading the file into memory**. A multi-GB source (the NPPES registry is ~4.8 GB / 9.6M rows — too big for
|
|
46
|
+
* `readFileSync`, which throws `ERR_STRING_TOO_LONG`) streams line by line. Keys are the original header names
|
|
47
|
+
* (`normalizeKeys: false`) so a {@link ColumnMapping} written against the source's headers matches. Filter/sample the
|
|
48
|
+
* stream before {@link ingestRows} to keep only the rows you geocode.
|
|
49
|
+
*
|
|
50
|
+
* `CSVSpliterator` (spliterator ≥ 3.2.0) handles the whole job: empty fields are preserved (a 330-column NPPES row
|
|
51
|
+
* stays 330 columns), CRLF row terminators are normalized (RFC 4180 default), and `enableQuoteHandling` makes quoted
|
|
52
|
+
* fields — embedded delimiters, embedded newlines, doubled-quote escapes — parse correctly while leaving unquoted files
|
|
53
|
+
* untouched. (This replaced a manual `TextSpliterator` + `split` workaround written against the 3.1.0 column tokenizer,
|
|
54
|
+
* which dropped empty fields and mis-parsed quotes.) Missing trailing fields land as `""`, matching the header
|
|
55
|
+
* contract. For small in-memory parses {@link parseCSV} remains.
|
|
56
|
+
*/
|
|
57
|
+
export async function* streamRows(
|
|
58
|
+
source: string,
|
|
59
|
+
opts: { delimiter?: Delimiter } = {}
|
|
60
|
+
): AsyncGenerator<Record<string, string>> {
|
|
61
|
+
const columnDelimiter = (opts.delimiter ?? delimiterFor(source)) === "tab" ? Delimiters.Tab : Delimiters.Comma
|
|
62
|
+
|
|
63
|
+
yield* CSVSpliterator.fromAsync<Record<string, string>>(source, {
|
|
64
|
+
mode: "object",
|
|
65
|
+
columnDelimiter,
|
|
66
|
+
normalizeKeys: false,
|
|
67
|
+
enableQuoteHandling: true,
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Maps dataset columns to record fields. A field may draw from several columns (joined with spaces).
|
|
73
|
+
*/
|
|
74
|
+
export interface ColumnMapping {
|
|
75
|
+
/** Column holding a stable row id. Falls back to the row index. */
|
|
76
|
+
id?: string
|
|
77
|
+
/** A literal provenance label for every row (not a column). */
|
|
78
|
+
source?: string
|
|
79
|
+
name?: string | string[]
|
|
80
|
+
organization?: string | string[]
|
|
81
|
+
address?: string | string[]
|
|
82
|
+
phone?: string
|
|
83
|
+
email?: string
|
|
84
|
+
/**
|
|
85
|
+
* Extra secondary-identifier fields → the column(s) to draw each from (joined with spaces). Land on
|
|
86
|
+
* `SourceRecord.attributes` under the same key, for the matcher's `discriminators` (authorized-official name,
|
|
87
|
+
* taxonomy, license…).
|
|
88
|
+
*/
|
|
89
|
+
attributes?: Record<string, string | string[]>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Best-effort {@link ColumnMapping} inferred from a header row — the "point it at any CSV" convenience. Each column name
|
|
94
|
+
* is matched (case- and punctuation-insensitive, on whole tokens) to a field by keyword, in a precedence that resolves
|
|
95
|
+
* the common ambiguities: a dedicated id / phone / email column is claimed before the generic sweep, an org / facility
|
|
96
|
+
* column beats a person "name", and address columns (street / city / state / zip…) collect into one multi-column field.
|
|
97
|
+
* Imperfect on bespoke headers (an explicit mapping or the LLM-assisted inference #603 is the answer there), but it
|
|
98
|
+
* nails tidy and semi-tidy files with no hand-mapping. Unmatched columns are left out.
|
|
99
|
+
*/
|
|
100
|
+
export function inferMapping(header: readonly string[]): ColumnMapping {
|
|
101
|
+
// Pad to whole-token boundaries so "state" doesn't match inside "statement".
|
|
102
|
+
const tok = (h: string) =>
|
|
103
|
+
` ${h
|
|
104
|
+
.toLowerCase()
|
|
105
|
+
.replace(/[^a-z0-9]+/g, " ")
|
|
106
|
+
.trim()} `
|
|
107
|
+
const mapping: ColumnMapping = {}
|
|
108
|
+
const name: string[] = []
|
|
109
|
+
const address: string[] = []
|
|
110
|
+
|
|
111
|
+
for (const column of header) {
|
|
112
|
+
const h = tok(column)
|
|
113
|
+
const has = (...words: string[]): boolean => words.some((w) => h.includes(` ${w} `))
|
|
114
|
+
|
|
115
|
+
if (!mapping.email && has("email", "e mail")) {
|
|
116
|
+
mapping.email = column
|
|
117
|
+
} else if (!mapping.phone && has("phone", "telephone", "tel", "mobile", "cell")) {
|
|
118
|
+
mapping.phone = column
|
|
119
|
+
} else if (!mapping.id && has("id", "npi", "ein", "frn", "spin", "uuid", "guid", "key")) {
|
|
120
|
+
mapping.id = column
|
|
121
|
+
} else if (has("org", "organization", "organisation", "company", "business", "facility", "agency", "employer")) {
|
|
122
|
+
mapping.organization ??= column
|
|
123
|
+
} else if (
|
|
124
|
+
has(
|
|
125
|
+
"street",
|
|
126
|
+
"address",
|
|
127
|
+
"addr",
|
|
128
|
+
"city",
|
|
129
|
+
"town",
|
|
130
|
+
"state",
|
|
131
|
+
"province",
|
|
132
|
+
"zip",
|
|
133
|
+
"zipcode",
|
|
134
|
+
"postal",
|
|
135
|
+
"postcode",
|
|
136
|
+
"county"
|
|
137
|
+
)
|
|
138
|
+
) {
|
|
139
|
+
address.push(column)
|
|
140
|
+
} else if (has("name", "first", "last", "given", "family", "middle", "surname", "fullname", "contact")) {
|
|
141
|
+
name.push(column)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (name.length) {
|
|
146
|
+
mapping.name = name.length === 1 ? name[0]! : name
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (address.length) {
|
|
150
|
+
mapping.address = address
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return mapping
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Options for {@link ingestRows}. */
|
|
157
|
+
export interface IngestOptions {
|
|
158
|
+
/** The geocoding seam. Without it, records carry name/org but no resolved address. */
|
|
159
|
+
geocodeAddress?: GeocodeAddress
|
|
160
|
+
/**
|
|
161
|
+
* Separator for joining a multi-column ADDRESS mapping (name/org always join with a space). Default `" "`. Pass `",
|
|
162
|
+
* "` to give the parser delimited input (`"214 Main St, Austin, TX 78701"`) instead of a concatenated run (`"214 Main
|
|
163
|
+
* St Austin TX 78701"`) — the latter strips the parser's segmentation boundaries and is partly OOD (it also breaks
|
|
164
|
+
* all-caps case-normalization; #694). **Default `", "` (#694 flip, validated).** Comma-join is the correct shape for
|
|
165
|
+
* an address built from separate columns, and #700 measured it at +15% cross-dataset rooftop (579→667) with no
|
|
166
|
+
* comma-less crater. The dedup GBT was trained on the old space-joined coords, so this flip is paired with a GBT
|
|
167
|
+
* re-validation (#694). Pass `" "` to restore the legacy space-join for a byte-stable A/B.
|
|
168
|
+
*/
|
|
169
|
+
addressSeparator?: string
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Parse a CSV string (with a header row) into row objects keyed by column name. */
|
|
173
|
+
export function parseCSV(text: string): Record<string, string>[] {
|
|
174
|
+
return parseCSVSync(text, { columns: true, skip_empty_lines: true, trim: true, relax_column_count: true })
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Join the named column(s) of a row into a single trimmed string, or undefined if empty. */
|
|
178
|
+
export function pick(row: Record<string, string>, columns?: string | string[], separator = " "): string | undefined {
|
|
179
|
+
if (!columns) return undefined
|
|
180
|
+
const list = Array.isArray(columns) ? columns : [columns]
|
|
181
|
+
const value = list
|
|
182
|
+
.map((c) => row[c]?.trim())
|
|
183
|
+
.filter(Boolean)
|
|
184
|
+
.join(separator)
|
|
185
|
+
.trim()
|
|
186
|
+
|
|
187
|
+
return value || undefined
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Normalize one tabular row into a {@link SourceRecord} under a {@link ColumnMapping}: parse the person name,
|
|
192
|
+
* canonicalize the org, and (if `opts.geocodeAddress` is provided) geocode the joined address. `id` falls back to the
|
|
193
|
+
* caller-supplied row index. Pure aside from the optional geocode seam, so the deterministic normalization can run
|
|
194
|
+
* single-threaded (see {@link normalizeCSV}) while geocoding is offloaded (see `geocodeStream`).
|
|
195
|
+
*/
|
|
196
|
+
export async function ingestRow(
|
|
197
|
+
row: Record<string, string>,
|
|
198
|
+
mapping: ColumnMapping,
|
|
199
|
+
index: number,
|
|
200
|
+
opts: IngestOptions = {}
|
|
201
|
+
): Promise<SourceRecord> {
|
|
202
|
+
const id = (mapping.id ? row[mapping.id]?.trim() : "") || String(index)
|
|
203
|
+
const nameValue = pick(row, mapping.name)
|
|
204
|
+
const orgValue = pick(row, mapping.organization)
|
|
205
|
+
const addressValue = pick(row, mapping.address, opts.addressSeparator ?? ", ")
|
|
206
|
+
|
|
207
|
+
let attributes: Record<string, string> | undefined
|
|
208
|
+
|
|
209
|
+
if (mapping.attributes) {
|
|
210
|
+
for (const [key, columns] of Object.entries(mapping.attributes)) {
|
|
211
|
+
const value = pick(row, columns)
|
|
212
|
+
|
|
213
|
+
if (value) {
|
|
214
|
+
;(attributes ??= {})[key] = value
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return {
|
|
220
|
+
id,
|
|
221
|
+
source: mapping.source,
|
|
222
|
+
name: nameValue ? parsePersonName(nameValue) : undefined,
|
|
223
|
+
organization: orgValue ? canonicalizeOrganizationName(orgValue) : undefined,
|
|
224
|
+
phone: (mapping.phone && row[mapping.phone]?.trim()) || undefined,
|
|
225
|
+
email: (mapping.email && row[mapping.email]?.trim()?.toLowerCase()) || undefined,
|
|
226
|
+
address: addressValue && opts.geocodeAddress ? ((await opts.geocodeAddress(addressValue)) ?? undefined) : undefined,
|
|
227
|
+
attributes,
|
|
228
|
+
raw: row,
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Normalize tabular rows into {@link SourceRecord}s under a {@link ColumnMapping}. Accepts a sync OR async iterable, so
|
|
234
|
+
* {@link parseCSV} (in-memory) and {@link streamRows} (lazy, for huge files) both thread straight through.
|
|
235
|
+
*/
|
|
236
|
+
export async function ingestRows(
|
|
237
|
+
rows: Iterable<Record<string, string>> | AsyncIterable<Record<string, string>>,
|
|
238
|
+
mapping: ColumnMapping,
|
|
239
|
+
opts: IngestOptions = {}
|
|
240
|
+
): Promise<SourceRecord[]> {
|
|
241
|
+
const records: SourceRecord[] = []
|
|
242
|
+
let index = 0
|
|
243
|
+
|
|
244
|
+
for await (const row of rows) {
|
|
245
|
+
records.push(await ingestRow(row, mapping, index, opts))
|
|
246
|
+
index++
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return records
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Stream a delimited file as normalized {@link SourceRecord}s — `streamRows` + {@link ingestRow} with **no geocoding**.
|
|
254
|
+
* This is the single-threaded, "fast enough" ergonomic core: column mapping, name parsing, and org canonicalization for
|
|
255
|
+
* a multi-GB file, line by line. Geocode separately by piping the output through `geocodeStream` (the only heavy step
|
|
256
|
+
* worth threading); for a light file (e.g. one that already carries geo cells) just consume this and stop.
|
|
257
|
+
*/
|
|
258
|
+
export async function* normalizeCSV(
|
|
259
|
+
source: string,
|
|
260
|
+
opts: { mapping: ColumnMapping; delimiter?: Delimiter }
|
|
261
|
+
): AsyncGenerator<SourceRecord> {
|
|
262
|
+
let index = 0
|
|
263
|
+
|
|
264
|
+
for await (const row of streamRows(source, { delimiter: opts.delimiter })) {
|
|
265
|
+
yield await ingestRow(row, opts.mapping, index)
|
|
266
|
+
index++
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The subset of mailwoman's `GeocodeResult` the adapter consumes — kept structural so this package never imports the
|
|
272
|
+
* heavy geocoder, yet a real `GeocodeResult` maps straight in.
|
|
273
|
+
*/
|
|
274
|
+
export interface RawGeocode {
|
|
275
|
+
lat: number | null
|
|
276
|
+
lon: number | null
|
|
277
|
+
resolution_tier: AddressGeocode["tier"]
|
|
278
|
+
uncertainty_m: number | null
|
|
279
|
+
hierarchy?: AddressGeocode["hierarchy"]
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The component map {@link toPostalAddress} consumes (kept structural so this package never imports the geocoder). */
|
|
283
|
+
type GeocodeComponents = Parameters<typeof toPostalAddress>[0]
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Build a {@link GeocodeAddress} from mailwoman's real parse + geocode primitives (injected — the CLI constructs the
|
|
287
|
+
* neural parser, resolver, and shards and passes them in). Parse → components → {@link toPostalAddress} (which fills
|
|
288
|
+
* the canonical key + formatted form) → attach the resolved coordinate. When geocoding can't place the address, the
|
|
289
|
+
* parsed-but-unlocated address is still returned.
|
|
290
|
+
*
|
|
291
|
+
* Two shapes:
|
|
292
|
+
*
|
|
293
|
+
* - `{ parse, geocode }` — the original: two independent calls. mailwoman's `geocodeAddress` re-parses internally, so
|
|
294
|
+
* this parses the address twice (fine when the two callbacks don't share a parser).
|
|
295
|
+
* - `{ parseAndGeocode }` — parse the address ONCE and return both the components and the geocode. Use this when the
|
|
296
|
+
* parse is the expensive step you'd rather not pay for twice (e.g. share `parseForGeocode`'s tree between the
|
|
297
|
+
* PostalAddress and `geocodeAddress`'s `parsedTree`). ~1.3× over the two-call shape on a real geocode pipeline.
|
|
298
|
+
*/
|
|
299
|
+
export function geocodeAddressVia(
|
|
300
|
+
deps: { country?: string } & (
|
|
301
|
+
| {
|
|
302
|
+
parse: (raw: string) => Promise<GeocodeComponents> | GeocodeComponents
|
|
303
|
+
geocode: (raw: string) => Promise<RawGeocode | null> | RawGeocode | null
|
|
304
|
+
}
|
|
305
|
+
| { parseAndGeocode: (raw: string) => Promise<{ components: GeocodeComponents; geo: RawGeocode | null }> }
|
|
306
|
+
)
|
|
307
|
+
): GeocodeAddress {
|
|
308
|
+
return async (raw: string): Promise<PostalAddress | null> => {
|
|
309
|
+
let components: GeocodeComponents
|
|
310
|
+
let resolved: RawGeocode | null
|
|
311
|
+
|
|
312
|
+
if ("parseAndGeocode" in deps) {
|
|
313
|
+
const r = await deps.parseAndGeocode(raw)
|
|
314
|
+
components = r.components
|
|
315
|
+
resolved = r.geo
|
|
316
|
+
} else {
|
|
317
|
+
components = await deps.parse(raw)
|
|
318
|
+
resolved = await deps.geocode(raw)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const base = toPostalAddress(components, { country: deps.country, raw })
|
|
322
|
+
|
|
323
|
+
if (!resolved || resolved.lat === null || resolved.lon === null) return base
|
|
324
|
+
|
|
325
|
+
const geocode: AddressGeocode = {
|
|
326
|
+
coordinate: { latitude: resolved.lat, longitude: resolved.lon },
|
|
327
|
+
tier: resolved.resolution_tier,
|
|
328
|
+
uncertaintyMeters: resolved.uncertainty_m,
|
|
329
|
+
hierarchy: resolved.hierarchy,
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return withGeocode(base, geocode)
|
|
333
|
+
}
|
|
334
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The learned scorer (#603) — the production wiring for the gradient-boosted-tree model behind
|
|
7
|
+
* {@link ResolveConfig.scorer}. Two pieces:
|
|
8
|
+
*
|
|
9
|
+
* 1. {@link createMatchFeaturizer} — the ONE feature extractor for a candidate pair, used identically
|
|
10
|
+
* at train time (`registry/tools/train-gbt.ts`), eval time (the learned-scorer
|
|
11
|
+
* evals), and inference time (here). A pair → one-hot of each comparison's agreement level +
|
|
12
|
+
* the over-merge interaction terms (co-located × name/org disagreement) + address
|
|
13
|
+
* crowdedness.
|
|
14
|
+
* 2. {@link createGbtScorer} — wraps a trained {@link GBT} + the featurizer into the `(a, b) => number`
|
|
15
|
+
* the resolve pipeline's `scorer` hook expects (a logit, threshold-comparable with the
|
|
16
|
+
* Fellegi-Sunter weight it replaces).
|
|
17
|
+
*
|
|
18
|
+
* Both take the comparison set as INPUT (rather than importing {@link buildDefaultModel}) so this
|
|
19
|
+
* module has no dependency cycle with `resolve.ts`. The contract that keeps train ≡ inference:
|
|
20
|
+
* feed the comparisons from `buildDefaultModel({ collapseSpatial: true, addressFrequency })` —
|
|
21
|
+
* the model's structure (and thus the feature layout) is fixed by that config; only the frequency
|
|
22
|
+
* VALUES differ between the training corpus and the matched set, which is the point (the model
|
|
23
|
+
* generalizes, as the cross-state eval showed).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
agreementPattern,
|
|
28
|
+
type Comparison,
|
|
29
|
+
type GBT,
|
|
30
|
+
gbtScore,
|
|
31
|
+
nameSimilarity,
|
|
32
|
+
type TermFrequencyTable,
|
|
33
|
+
} from "@mailwoman/match"
|
|
34
|
+
|
|
35
|
+
import type { SourceRecord } from "./types.ts"
|
|
36
|
+
|
|
37
|
+
/** Inputs shared by the featurizer + the scorer factory. */
|
|
38
|
+
export interface LearnedFeatureConfig {
|
|
39
|
+
/**
|
|
40
|
+
* The comparison set the features are built over — MUST be `buildDefaultModel({ collapseSpatial: true,
|
|
41
|
+
* addressFrequency }).comparisons` so the feature layout matches the trained model. (`usePhone` / `discriminators`
|
|
42
|
+
* are NOT part of the learned feature model — the GBT replaces the FS weight wholesale and owns its own feature
|
|
43
|
+
* vector.)
|
|
44
|
+
*/
|
|
45
|
+
comparisons: Comparison<SourceRecord>[]
|
|
46
|
+
/**
|
|
47
|
+
* Address-frequency table for the crowdedness feature (a crowded shared address is weak identity).
|
|
48
|
+
*/
|
|
49
|
+
addressFrequency: TermFrequencyTable
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Build the per-pair feature extractor. The vector is: one-hot of each comparison's agreement level, then the two
|
|
54
|
+
* over-merge interaction terms (spatial-exact × name-disagree, spatial-exact × org-disagree — the "same place,
|
|
55
|
+
* different names" signature that drives co-located over-merges), then address crowdedness scaled into [0, 1].
|
|
56
|
+
* Deterministic and EM-independent, so it is identical across train / eval / inference.
|
|
57
|
+
*/
|
|
58
|
+
export function createMatchFeaturizer(config: LearnedFeatureConfig): (a: SourceRecord, b: SourceRecord) => number[] {
|
|
59
|
+
const { comparisons, addressFrequency } = config
|
|
60
|
+
const levelCounts = comparisons.map((c) => c.levels.length)
|
|
61
|
+
const index = Object.fromEntries(comparisons.map((c, i) => [c.name, i])) as Record<string, number | undefined>
|
|
62
|
+
const spatialI = index["spatial"]
|
|
63
|
+
const givenI = index["given"]
|
|
64
|
+
const familyI = index["family"]
|
|
65
|
+
const orgI = index["organization"]
|
|
66
|
+
const lastLevel = (i: number): number => levelCounts[i]! - 1
|
|
67
|
+
|
|
68
|
+
return (a, b) => {
|
|
69
|
+
const pat = agreementPattern(comparisons, a, b)
|
|
70
|
+
const f: number[] = []
|
|
71
|
+
|
|
72
|
+
for (let i = 0; i < pat.length; i++) {
|
|
73
|
+
const lvl = pat[i]!
|
|
74
|
+
|
|
75
|
+
for (let l = 0; l < levelCounts[i]!; l++) {
|
|
76
|
+
f.push(lvl === l ? 1 : 0)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// Interaction: co-located (spatial exact = level 0) AND names/org disagree (catch-all level).
|
|
80
|
+
const spatialExact = spatialI !== undefined && pat[spatialI] === 0 ? 1 : 0
|
|
81
|
+
const nameDisagree =
|
|
82
|
+
givenI !== undefined &&
|
|
83
|
+
familyI !== undefined &&
|
|
84
|
+
pat[givenI] === lastLevel(givenI) &&
|
|
85
|
+
pat[familyI] === lastLevel(familyI)
|
|
86
|
+
? 1
|
|
87
|
+
: 0
|
|
88
|
+
const orgDisagree = orgI !== undefined && pat[orgI] === lastLevel(orgI) ? 1 : 0
|
|
89
|
+
f.push(spatialExact * nameDisagree) // the over-merge signature: same place, names disagree
|
|
90
|
+
f.push(spatialExact * orgDisagree)
|
|
91
|
+
// Address crowdedness (how shared this address is) — high → "same address" is weak evidence.
|
|
92
|
+
const freq = a.address?.raw ? addressFrequency.frequency(a.address.raw) : 0
|
|
93
|
+
f.push(Math.min(1, freq * 1000))
|
|
94
|
+
// #625 roll-up signature (2026-07-06 adjudication): every genuine over-merge in the adjudicated
|
|
95
|
+
// packet was a MANAGEMENT-COMPANY roll-up — differently-branded operating entities at a shared
|
|
96
|
+
// corporate/billing address where the AUTHORIZED OFFICIAL also agrees (the operator signs
|
|
97
|
+
// everything). The official is NOT in the comparison set (discriminators are excluded from the
|
|
98
|
+
// learned feature model), so the GBT could never see — let alone learn — that officialAgree in
|
|
99
|
+
// the presence of orgDisagree is ANTI-identity evidence. These three appended features express
|
|
100
|
+
// it directly from `attributes.authorizedOfficial`; appended at the END so models trained
|
|
101
|
+
// without them (the cross-source GBT) keep scoring unchanged (trailing features are ignored).
|
|
102
|
+
const offA = a.attributes?.["authorizedOfficial"]?.trim()
|
|
103
|
+
const offB = b.attributes?.["authorizedOfficial"]?.trim()
|
|
104
|
+
const officialAgree = offA && offB && nameSimilarity(offA, offB) >= 0.93 ? 1 : 0
|
|
105
|
+
f.push(officialAgree)
|
|
106
|
+
f.push(officialAgree * orgDisagree) // the roll-up core: same signer, different brand
|
|
107
|
+
f.push(officialAgree * orgDisagree * spatialExact)
|
|
108
|
+
|
|
109
|
+
// …at the same place
|
|
110
|
+
|
|
111
|
+
// scale into a usable range
|
|
112
|
+
return f
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Wrap a trained {@link GBT} into the `(a, b) => number` link scorer for {@link ResolveConfig.scorer}. The returned
|
|
118
|
+
* weight is the model's logit — same threshold-comparable units as the Fellegi-Sunter weight it replaces, so the
|
|
119
|
+
* pipeline's clustering + threshold semantics are unchanged.
|
|
120
|
+
*/
|
|
121
|
+
export function createGbtScorer(
|
|
122
|
+
config: LearnedFeatureConfig & { model: GBT }
|
|
123
|
+
): (a: SourceRecord, b: SourceRecord) => number {
|
|
124
|
+
const featurize = createMatchFeaturizer(config)
|
|
125
|
+
const { model } = config
|
|
126
|
+
|
|
127
|
+
return (a, b) => gbtScore(model, featurize(a, b))
|
|
128
|
+
}
|