@mailwoman/corpus 11.5.0 → 12.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/address-source-register.json +545 -11
- package/data/builds/v0.8.22-wofrank-overlay/OVERLAY_PLAN.json +51 -0
- package/data/builds/v0.8.24-everyplace/inputs.json +35 -0
- package/data/license-decisions.json +440 -9
- package/data/licenses/PROVENANCE.md +27 -18
- package/data/licenses/at-bev-adressregister-cc-by-4.0.md +25 -0
- package/data/licenses/br-ibge-cnefe-open-data.md +21 -0
- package/data/licenses/ca-qc-mrnf-cc-by-4.0.md +29 -0
- package/data/licenses/ca-statcan-open-licence.md +41 -0
- package/data/licenses/ca-yukon-ogl-2.0.md +19 -0
- package/data/licenses/dk-dmikg-cc-by-4.0.md +43 -0
- package/data/licenses/jp-mlit-isj-pdl-1.0.md +35 -0
- package/data/source-additions.json +90 -0
- package/data/source-resolutions.json +3 -2
- package/data/training-configs/v8.17.0-stage1-gazetteer-v0822-s42.yaml +557 -0
- package/data/training-configs/v8.17.0-stage2-corpus-v0822-s42.yaml +1008 -0
- package/data/training-configs/v8.18.0-gazetteer-then-mixture-v0822-s42.yaml +1225 -0
- package/data/training-configs/v8.20.0-wofrank-v0822-s42.yaml +863 -0
- package/data/training-configs/v8.21.0-outcomes-v0822-s42.yaml +873 -0
- package/data/training-configs/v8.22.0-stage1-everyplace-v0824-s42.yaml +374 -0
- package/data/training-configs/v8.22.0-stage2-corpus-v0824-s42.yaml +808 -0
- package/data/training-configs/v8.22.1-stage1-everyplace-v0824-s42.yaml +376 -0
- package/data/training-configs/v8.22.1-stage2-corpus-v0824-s42.yaml +793 -0
- package/data/training-configs/v9.0.0-bytestem-v090-s42.yaml +665 -0
- package/data/training-configs/v9.1.0-bytestem-global-v091-s42.yaml +710 -0
- package/data/training-configs/v9.2.0-bytestem-global-v092-s42.yaml +714 -0
- package/data/training-manifests/v0.8.22-wofrank-overlay.json +9000 -0
- package/data/training-manifests/v0.8.24-everyplace-overlay.json +9000 -0
- package/data/training-manifests/v0.9.0-compact.effective.json +2556 -0
- package/data/training-manifests/v0.9.0-compact.json +9000 -0
- package/data/training-manifests/v0.9.1-compact.json +9660 -0
- package/data/training-manifests/v0.9.2-compact.effective.json +2670 -0
- package/data/training-manifests/v0.9.2-compact.json +9660 -0
- package/lib/adapters/geonames/features/adapter.ts +29 -11
- package/lib/adapters/overture/adapter.ts +26 -6
- package/lib/adapters/street/line.ts +6 -5
- package/lib/adapters/street/unit.ts +7 -0
- package/lib/adapters/wof/admin/json/adapter.ts +38 -3
- package/lib/adapters/wof/json-rows.ts +84 -5
- package/lib/adapters/wof/sample.ts +42 -6
- package/lib/au/adapters/gnaf/source.ts +12 -0
- package/lib/build/code-hash.ts +1 -1
- package/lib/cjk/foreign-places.ts +1 -1
- package/lib/fr/adapters/ban/adapter.ts +57 -8
- package/lib/fr/recipes/admin-split.ts +14 -2
- package/lib/fr/recipes/lieudit.ts +1 -1
- package/lib/fr/recipes/order.ts +14 -5
- package/lib/international/recipes/locale.ts +1 -1
- package/lib/kr/adapters/localdata/permit-rows.ts +1 -1
- package/lib/parquet/schema.ts +7 -0
- package/lib/recipes/po/box/cedex/recipe.ts +1 -1
- package/lib/recipes/po/box/cedex/vocabulary.ts +4 -4
- package/lib/recipes/trailing-region.ts +147 -17
- package/lib/synthesizers/po-box.ts +51 -12
- package/lib/test-kit/corpus-recipe.ts +3 -0
- package/lib/tools/anthropic/batches.ts +221 -0
- package/lib/tools/anthropic/labeling.ts +263 -0
- package/lib/tools/compact-v9.ts +890 -0
- package/lib/tools/fetch/wikidata/vital-places/entities.ts +20 -2
- package/lib/tools/fetch/wikidata/vital-places/qrank.ts +5 -4
- package/lib/tools/fragment-assay.run.ts +2 -1
- package/lib/tools/name-roles/name-roles.run.ts +296 -0
- package/lib/tools/name-roles/prompt.ts +253 -0
- package/lib/tools/overlay/deletions.ts +1 -1
- package/lib/tools/overlay/draw-weight.ts +275 -0
- package/lib/tools/place-twins/place-twins.run.ts +528 -0
- package/lib/tools/place-twins/prompt.ts +276 -0
- package/lib/tools/prominent-shapes/prominent-shapes.run.ts +420 -0
- package/lib/tools/prominent-shapes/prompt.ts +189 -0
- package/lib/tools/prominent-shapes/read-seeds.ts +286 -0
- package/lib/tools/prominent-shapes/seeds.ts +281 -0
- package/lib/tools/prominent-shapes/validate.ts +563 -0
- package/lib/tools/source-register/build.ts +1 -0
- package/lib/training/config/admission.ts +9 -2
- package/lib/training/config/schema.ts +68 -1
- package/lib/types.ts +23 -0
- package/lib/us/adapters/usgov/usgs-structures/adapter.ts +103 -6
- package/lib/utils/split.ts +1 -1
- package/out/adapters/geonames/features/adapter.d.ts +2 -2
- package/out/adapters/geonames/features/adapter.d.ts.map +1 -1
- package/out/adapters/geonames/features/adapter.js +25 -11
- package/out/adapters/geonames/features/adapter.js.map +1 -1
- package/out/adapters/overture/adapter.d.ts.map +1 -1
- package/out/adapters/overture/adapter.js +21 -5
- package/out/adapters/overture/adapter.js.map +1 -1
- package/out/adapters/street/line.d.ts +4 -4
- package/out/adapters/street/line.d.ts.map +1 -1
- package/out/adapters/street/line.js +5 -5
- package/out/adapters/street/line.js.map +1 -1
- package/out/adapters/street/unit.d.ts +4 -0
- package/out/adapters/street/unit.d.ts.map +1 -1
- package/out/adapters/street/unit.js +3 -0
- package/out/adapters/street/unit.js.map +1 -1
- package/out/adapters/wof/admin/json/adapter.d.ts +7 -0
- package/out/adapters/wof/admin/json/adapter.d.ts.map +1 -1
- package/out/adapters/wof/admin/json/adapter.js +28 -3
- package/out/adapters/wof/admin/json/adapter.js.map +1 -1
- package/out/adapters/wof/json-rows.d.ts +8 -0
- package/out/adapters/wof/json-rows.d.ts.map +1 -1
- package/out/adapters/wof/json-rows.js +56 -4
- package/out/adapters/wof/json-rows.js.map +1 -1
- package/out/adapters/wof/sample.d.ts +12 -0
- package/out/adapters/wof/sample.d.ts.map +1 -1
- package/out/adapters/wof/sample.js +37 -6
- package/out/adapters/wof/sample.js.map +1 -1
- package/out/au/adapters/gnaf/source.d.ts +9 -0
- package/out/au/adapters/gnaf/source.d.ts.map +1 -1
- package/out/au/adapters/gnaf/source.js +9 -0
- package/out/au/adapters/gnaf/source.js.map +1 -1
- package/out/build/code-hash.js +1 -1
- package/out/build/code-hash.js.map +1 -1
- package/out/cjk/foreign-places.js +1 -1
- package/out/cjk/foreign-places.js.map +1 -1
- package/out/fr/adapters/ban/adapter.d.ts.map +1 -1
- package/out/fr/adapters/ban/adapter.js +49 -7
- package/out/fr/adapters/ban/adapter.js.map +1 -1
- package/out/fr/recipes/admin-split.d.ts.map +1 -1
- package/out/fr/recipes/admin-split.js +15 -2
- package/out/fr/recipes/admin-split.js.map +1 -1
- package/out/fr/recipes/lieudit.js +1 -1
- package/out/fr/recipes/lieudit.js.map +1 -1
- package/out/fr/recipes/order.d.ts.map +1 -1
- package/out/fr/recipes/order.js +16 -5
- package/out/fr/recipes/order.js.map +1 -1
- package/out/international/recipes/locale.js +1 -1
- package/out/international/recipes/locale.js.map +1 -1
- package/out/kr/adapters/localdata/permit-rows.js +1 -1
- package/out/kr/adapters/localdata/permit-rows.js.map +1 -1
- package/out/parquet/schema.d.ts +6 -0
- package/out/parquet/schema.d.ts.map +1 -1
- package/out/parquet/schema.js +6 -0
- package/out/parquet/schema.js.map +1 -1
- package/out/recipes/po/box/cedex/recipe.js +1 -1
- package/out/recipes/po/box/cedex/recipe.js.map +1 -1
- package/out/recipes/po/box/cedex/vocabulary.d.ts +1 -1
- package/out/recipes/po/box/cedex/vocabulary.d.ts.map +1 -1
- package/out/recipes/po/box/cedex/vocabulary.js +4 -4
- package/out/recipes/po/box/cedex/vocabulary.js.map +1 -1
- package/out/recipes/trailing-region.d.ts.map +1 -1
- package/out/recipes/trailing-region.js +122 -17
- package/out/recipes/trailing-region.js.map +1 -1
- package/out/synthesizers/po-box.d.ts +7 -0
- package/out/synthesizers/po-box.d.ts.map +1 -1
- package/out/synthesizers/po-box.js +36 -12
- package/out/synthesizers/po-box.js.map +1 -1
- package/out/test-kit/corpus-recipe.d.ts +3 -0
- package/out/test-kit/corpus-recipe.d.ts.map +1 -1
- package/out/test-kit/corpus-recipe.js.map +1 -1
- package/out/tools/anthropic/batches.d.ts +117 -0
- package/out/tools/anthropic/batches.d.ts.map +1 -0
- package/out/tools/anthropic/batches.js +141 -0
- package/out/tools/anthropic/batches.js.map +1 -0
- package/out/tools/anthropic/labeling.d.ts +97 -0
- package/out/tools/anthropic/labeling.d.ts.map +1 -0
- package/out/tools/anthropic/labeling.js +146 -0
- package/out/tools/anthropic/labeling.js.map +1 -0
- package/out/tools/compact-v9.d.ts +124 -0
- package/out/tools/compact-v9.d.ts.map +1 -0
- package/out/tools/compact-v9.js +507 -0
- package/out/tools/compact-v9.js.map +1 -0
- package/out/tools/fetch/wikidata/vital-places/entities.d.ts +3 -0
- package/out/tools/fetch/wikidata/vital-places/entities.d.ts.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/entities.js +19 -1
- package/out/tools/fetch/wikidata/vital-places/entities.js.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/qrank.d.ts.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/qrank.js +4 -4
- package/out/tools/fetch/wikidata/vital-places/qrank.js.map +1 -1
- package/out/tools/fragment-assay.run.js +1 -1
- package/out/tools/fragment-assay.run.js.map +1 -1
- package/out/tools/name-roles/name-roles.run.d.ts +2 -0
- package/out/tools/name-roles/name-roles.run.d.ts.map +1 -0
- package/out/tools/name-roles/name-roles.run.js +230 -0
- package/out/tools/name-roles/name-roles.run.js.map +1 -0
- package/out/tools/name-roles/prompt.d.ts +166 -0
- package/out/tools/name-roles/prompt.d.ts.map +1 -0
- package/out/tools/name-roles/prompt.js +176 -0
- package/out/tools/name-roles/prompt.js.map +1 -0
- package/out/tools/overlay/deletions.js +1 -1
- package/out/tools/overlay/deletions.js.map +1 -1
- package/out/tools/overlay/draw-weight.d.ts +86 -0
- package/out/tools/overlay/draw-weight.d.ts.map +1 -0
- package/out/tools/overlay/draw-weight.js +131 -0
- package/out/tools/overlay/draw-weight.js.map +1 -0
- package/out/tools/place-twins/place-twins.run.d.ts +2 -0
- package/out/tools/place-twins/place-twins.run.d.ts.map +1 -0
- package/out/tools/place-twins/place-twins.run.js +385 -0
- package/out/tools/place-twins/place-twins.run.js.map +1 -0
- package/out/tools/place-twins/prompt.d.ts +169 -0
- package/out/tools/place-twins/prompt.d.ts.map +1 -0
- package/out/tools/place-twins/prompt.js +183 -0
- package/out/tools/place-twins/prompt.js.map +1 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.d.ts +2 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.d.ts.map +1 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.js +302 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.js.map +1 -0
- package/out/tools/prominent-shapes/prompt.d.ts +74 -0
- package/out/tools/prominent-shapes/prompt.d.ts.map +1 -0
- package/out/tools/prominent-shapes/prompt.js +156 -0
- package/out/tools/prominent-shapes/prompt.js.map +1 -0
- package/out/tools/prominent-shapes/read-seeds.d.ts +23 -0
- package/out/tools/prominent-shapes/read-seeds.d.ts.map +1 -0
- package/out/tools/prominent-shapes/read-seeds.js +219 -0
- package/out/tools/prominent-shapes/read-seeds.js.map +1 -0
- package/out/tools/prominent-shapes/seeds.d.ts +132 -0
- package/out/tools/prominent-shapes/seeds.d.ts.map +1 -0
- package/out/tools/prominent-shapes/seeds.js +178 -0
- package/out/tools/prominent-shapes/seeds.js.map +1 -0
- package/out/tools/prominent-shapes/validate.d.ts +152 -0
- package/out/tools/prominent-shapes/validate.d.ts.map +1 -0
- package/out/tools/prominent-shapes/validate.js +389 -0
- package/out/tools/prominent-shapes/validate.js.map +1 -0
- package/out/tools/source-register/build.d.ts.map +1 -1
- package/out/tools/source-register/build.js +1 -0
- package/out/tools/source-register/build.js.map +1 -1
- package/out/training/config/admission.d.ts +2 -1
- package/out/training/config/admission.d.ts.map +1 -1
- package/out/training/config/admission.js +9 -2
- package/out/training/config/admission.js.map +1 -1
- package/out/training/config/schema.d.ts +276 -1
- package/out/training/config/schema.d.ts.map +1 -1
- package/out/training/config/schema.js +64 -1
- package/out/training/config/schema.js.map +1 -1
- package/out/types.d.ts +21 -0
- package/out/types.d.ts.map +1 -1
- package/out/types.js +13 -0
- package/out/types.js.map +1 -1
- package/out/us/adapters/usgov/usgs-structures/adapter.d.ts.map +1 -1
- package/out/us/adapters/usgov/usgs-structures/adapter.js +78 -4
- package/out/us/adapters/usgov/usgs-structures/adapter.js.map +1 -1
- package/out/utils/split.js +1 -1
- package/out/utils/split.js.map +1 -1
- package/package.json +24 -24
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file Asks a language model whether a settlement the admin build added from Overture or GeoNames is a WOF
|
|
6
|
+
* record under another spelling or script.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* node packages/corpus/lib/tools/place-twins/place-twins.run.ts <mode> --out <dir> [--unmatched <jsonl>]
|
|
10
|
+
* [--take <items>] [--model <id>] [--effort <level>] [--chunk <items per request>] [--limit <requests>]
|
|
11
|
+
*
|
|
12
|
+
* `census` reads the admin build's unmatched-places file, finds each settlement's WOF records inside the
|
|
13
|
+
* match radius, and writes `items.jsonl` with one line per settlement that has at least one.
|
|
14
|
+
* `pilot`, `submit`, `status` and `collect` then work as `name-roles.run.ts` does, over the first `--take`
|
|
15
|
+
* items in the order `rankItems` gives them. `collect` writes `pairs.jsonl`.
|
|
16
|
+
*
|
|
17
|
+
* The output is a review file. An Overture pair belongs in `overture_wof_match`, a table of the Overture
|
|
18
|
+
* part, and a GeoNames pair in the WOF forks' concordances. This tool writes to neither.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
appendLocalTextFile,
|
|
23
|
+
writeLocalJSONFile,
|
|
24
|
+
writeLocalJSONLFile,
|
|
25
|
+
writeLocalTextFile,
|
|
26
|
+
} from "@mailwoman/core/fs/writers"
|
|
27
|
+
import { OVERTURE_ID_BASE } from "@mailwoman/core/resolver/synthetic-id-ranges"
|
|
28
|
+
import { parseArguments } from "@mailwoman/core/scripting/arguments"
|
|
29
|
+
import { stringifyJSON } from "@mailwoman/core/values/json"
|
|
30
|
+
import { ownNameSimilarity, romanizeNameKey } from "@mailwoman/resolver-wof-sqlite/candidate/own-name"
|
|
31
|
+
import { normalizeLocalityForKey } from "@mailwoman/resolver-wof-sqlite/labels/street/normalize"
|
|
32
|
+
import { wofDatabasePath } from "@mailwoman/resolver-wof-sqlite/paths"
|
|
33
|
+
import type { WOFDatabase } from "@mailwoman/resolver-wof-sqlite/schema"
|
|
34
|
+
import { haversine } from "@mailwoman/spatial/geometries/point/distance"
|
|
35
|
+
import type { DatabaseClient } from "@mailwoman/sqlite/client"
|
|
36
|
+
import { openBuiltClient } from "@mailwoman/sqlite/sealed"
|
|
37
|
+
import { PathBuilder, resolvePath } from "path-ts"
|
|
38
|
+
import { JSONSpliterator } from "spliterator"
|
|
39
|
+
|
|
40
|
+
import {
|
|
41
|
+
collectLabelingBatch,
|
|
42
|
+
pilotLabelingRequests,
|
|
43
|
+
readLabelingBatch,
|
|
44
|
+
submitLabelingBatch,
|
|
45
|
+
countEach,
|
|
46
|
+
toLabelingChunks,
|
|
47
|
+
} from "#tools/anthropic/labeling"
|
|
48
|
+
import {
|
|
49
|
+
NameComparison,
|
|
50
|
+
parsePlaceTwinResponse,
|
|
51
|
+
placeTwinRequestParams,
|
|
52
|
+
type AddedPlaceItem,
|
|
53
|
+
type TwinCandidate,
|
|
54
|
+
type TwinLabel,
|
|
55
|
+
} from "#tools/place-twins/prompt"
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The settlement tier of the admin build's matcher (`MATCH_TIERS.settlement` in
|
|
59
|
+
* `packages/gazetteer/tools/pipeline/admin/sources/wof-match.ts`): the placetypes a
|
|
60
|
+
* settlement may match across, and the farthest a matching WOF record may sit.
|
|
61
|
+
*/
|
|
62
|
+
const SETTLEMENT_PLACETYPES = ["locality", "localadmin", "borough"]
|
|
63
|
+
const MATCH_RADIUS_KM = 5
|
|
64
|
+
|
|
65
|
+
const GRID_DEGREES = 0.05
|
|
66
|
+
const KM_PER_DEGREE = 111.32
|
|
67
|
+
const MAX_CANDIDATES = 4
|
|
68
|
+
const MAX_CANDIDATE_NAMES = 8
|
|
69
|
+
const MAX_ADDED_NAMES = 6
|
|
70
|
+
const ID_QUERY_SIZE = 500
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* One line of the admin build's unmatched-places file, as `UnmatchedPlace` in the matcher writes it.
|
|
74
|
+
*/
|
|
75
|
+
interface UnmatchedLine {
|
|
76
|
+
id: number
|
|
77
|
+
source: "overture" | "geonames"
|
|
78
|
+
sourceID: string
|
|
79
|
+
name: string
|
|
80
|
+
placetype: string
|
|
81
|
+
country: string
|
|
82
|
+
latitude: number
|
|
83
|
+
longitude: number
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const { values, positionals } = parseArguments({
|
|
87
|
+
allowPositionals: true,
|
|
88
|
+
options: {
|
|
89
|
+
out: { type: "string" },
|
|
90
|
+
unmatched: { type: "string" },
|
|
91
|
+
take: { type: "string" },
|
|
92
|
+
skip: { type: "string" },
|
|
93
|
+
items: { type: "string" },
|
|
94
|
+
model: { type: "string", default: "claude-opus-5-5" },
|
|
95
|
+
effort: { type: "string", default: "medium" },
|
|
96
|
+
chunk: { type: "string", default: "15" },
|
|
97
|
+
limit: { type: "string" },
|
|
98
|
+
},
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
const mode = positionals[0]
|
|
102
|
+
|
|
103
|
+
if (!values.out) throw new Error("--out names the directory the items, batch record and pairs are written to")
|
|
104
|
+
|
|
105
|
+
const out = PathBuilder.from(resolvePath(values.out as string))
|
|
106
|
+
const settings = { model: values.model as string, effort: values.effort as string }
|
|
107
|
+
|
|
108
|
+
const parseLabels = (text: string, items: readonly AddedPlaceItem[]) =>
|
|
109
|
+
parsePlaceTwinResponse(
|
|
110
|
+
text,
|
|
111
|
+
items.map((item) => item.candidates.length)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Reads every name row of `ids`, grouped by id in the table's order.
|
|
116
|
+
*/
|
|
117
|
+
async function readNames(db: DatabaseClient<WOFDatabase>, ids: readonly number[]): Promise<Map<number, string[]>> {
|
|
118
|
+
const names = new Map<number, string[]>()
|
|
119
|
+
|
|
120
|
+
for (let start = 0; start < ids.length; start += ID_QUERY_SIZE) {
|
|
121
|
+
const rows = await db
|
|
122
|
+
.selectFrom("names")
|
|
123
|
+
.select(["id", "name", "privateuse"])
|
|
124
|
+
.where("id", "in", ids.slice(start, start + ID_QUERY_SIZE))
|
|
125
|
+
.execute()
|
|
126
|
+
|
|
127
|
+
// A preferred name leads, so the cap on names keeps it.
|
|
128
|
+
rows.sort((a, b) => Number(b.privateuse === "preferred") - Number(a.privateuse === "preferred"))
|
|
129
|
+
|
|
130
|
+
for (const row of rows) {
|
|
131
|
+
const held = names.get(row.id)
|
|
132
|
+
|
|
133
|
+
if (held) {
|
|
134
|
+
held.push(row.name)
|
|
135
|
+
} else {
|
|
136
|
+
names.set(row.id, [row.name])
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return names
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The primary name first, then the other distinct names up to `cap`.
|
|
146
|
+
*/
|
|
147
|
+
function leadNames(primary: string, others: readonly string[] | undefined, cap: number): string[] {
|
|
148
|
+
return [...new Set([primary, ...(others ?? [])])].slice(0, cap)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The name key with every character outside letters, digits and spaces replaced by a space.
|
|
153
|
+
*
|
|
154
|
+
* `romanizeNameKey` returns `null` for a key that holds a hyphen, an apostrophe or an ʻokina,
|
|
155
|
+
* so without this step `Ermengol-Serra` and `Al Miʻli` read as names in an uncovered script.
|
|
156
|
+
*/
|
|
157
|
+
function comparisonKey(name: string): string {
|
|
158
|
+
return normalizeLocalityForKey(name)
|
|
159
|
+
.replaceAll(/[^\p{L}\p{N}\s]/gu, " ")
|
|
160
|
+
.replaceAll(/\s+/g, " ")
|
|
161
|
+
.trim()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Compares every name of an added place with every name of its candidates.
|
|
166
|
+
*/
|
|
167
|
+
function compareNames(
|
|
168
|
+
added: readonly string[],
|
|
169
|
+
candidates: readonly TwinCandidate[]
|
|
170
|
+
): Pick<AddedPlaceItem, "comparison" | "similarity"> {
|
|
171
|
+
const addedKeys = added.map((name) => comparisonKey(name))
|
|
172
|
+
const addedRomanizes = addedKeys.map((key) => romanizeNameKey(key) != null)
|
|
173
|
+
let similarity: number | null = null
|
|
174
|
+
let crossScript = false
|
|
175
|
+
|
|
176
|
+
for (const candidate of candidates) {
|
|
177
|
+
for (const name of candidate.names) {
|
|
178
|
+
const key = comparisonKey(name)
|
|
179
|
+
const romanizes = romanizeNameKey(key) != null
|
|
180
|
+
|
|
181
|
+
for (const [index, addedKey] of addedKeys.entries()) {
|
|
182
|
+
if (romanizes !== addedRomanizes[index]) {
|
|
183
|
+
crossScript = true
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const score = ownNameSimilarity(addedKey, key)
|
|
187
|
+
|
|
188
|
+
if (score != null && (similarity == null || score > similarity)) {
|
|
189
|
+
similarity = score
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (similarity != null) return { comparison: NameComparison.Romanized, similarity: Number(similarity.toFixed(3)) }
|
|
196
|
+
|
|
197
|
+
return { comparison: crossScript ? NameComparison.CrossScript : NameComparison.Uncovered, similarity: null }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Builds the items of one country: each unmatched settlement with its WOF records inside the match radius.
|
|
202
|
+
*/
|
|
203
|
+
async function buildCountryItems(
|
|
204
|
+
db: DatabaseClient<WOFDatabase>,
|
|
205
|
+
country: string,
|
|
206
|
+
unmatched: readonly UnmatchedLine[]
|
|
207
|
+
): Promise<AddedPlaceItem[]> {
|
|
208
|
+
const records = await db
|
|
209
|
+
.selectFrom("spr")
|
|
210
|
+
.select(["id", "name", "placetype", "latitude", "longitude"])
|
|
211
|
+
.where("country", "=", country)
|
|
212
|
+
.where("placetype", "in", SETTLEMENT_PLACETYPES)
|
|
213
|
+
.where("is_current", "=", 1)
|
|
214
|
+
.where("id", "<", OVERTURE_ID_BASE)
|
|
215
|
+
.execute()
|
|
216
|
+
|
|
217
|
+
const grid = new Map<string, number[]>()
|
|
218
|
+
|
|
219
|
+
for (const [index, record] of records.entries()) {
|
|
220
|
+
const cell = `${Math.floor(record.latitude / GRID_DEGREES)}:${Math.floor(record.longitude / GRID_DEGREES)}`
|
|
221
|
+
const held = grid.get(cell)
|
|
222
|
+
|
|
223
|
+
if (held) {
|
|
224
|
+
held.push(index)
|
|
225
|
+
} else {
|
|
226
|
+
grid.set(cell, [index])
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const near: Array<{ place: UnmatchedLine; found: Array<{ index: number; km: number }> }> = []
|
|
231
|
+
|
|
232
|
+
for (const place of unmatched) {
|
|
233
|
+
const row = Math.floor(place.latitude / GRID_DEGREES)
|
|
234
|
+
const column = Math.floor(place.longitude / GRID_DEGREES)
|
|
235
|
+
const rowSpan = Math.ceil(MATCH_RADIUS_KM / (KM_PER_DEGREE * GRID_DEGREES))
|
|
236
|
+
|
|
237
|
+
// A degree of longitude shortens toward the poles, so the radius spans more columns there.
|
|
238
|
+
const kmPerLongitudeCell = KM_PER_DEGREE * GRID_DEGREES * Math.max(0.01, Math.cos((place.latitude * Math.PI) / 180))
|
|
239
|
+
const columnSpan = Math.min(200, Math.ceil(MATCH_RADIUS_KM / kmPerLongitudeCell))
|
|
240
|
+
const found: Array<{ index: number; km: number }> = []
|
|
241
|
+
|
|
242
|
+
for (let r = row - rowSpan; r <= row + rowSpan; r++) {
|
|
243
|
+
for (let c = column - columnSpan; c <= column + columnSpan; c++) {
|
|
244
|
+
for (const index of grid.get(`${r}:${c}`) ?? []) {
|
|
245
|
+
const record = records[index]!
|
|
246
|
+
const km = haversine(place.latitude, place.longitude, record.latitude, record.longitude, "km")
|
|
247
|
+
|
|
248
|
+
if (km <= MATCH_RADIUS_KM) {
|
|
249
|
+
found.push({ index, km })
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (!found.length) continue
|
|
256
|
+
|
|
257
|
+
found.sort((a, b) => a.km - b.km)
|
|
258
|
+
near.push({ place, found: found.slice(0, MAX_CANDIDATES) })
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const candidateNames = await readNames(db, [
|
|
262
|
+
...new Set(near.flatMap(({ found }) => found.map(({ index }) => records[index]!.id))),
|
|
263
|
+
])
|
|
264
|
+
|
|
265
|
+
const addedNames = await readNames(
|
|
266
|
+
db,
|
|
267
|
+
near.map(({ place }) => place.id)
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
return near.map(({ place, found }) => {
|
|
271
|
+
const names = leadNames(place.name, addedNames.get(place.id), MAX_ADDED_NAMES)
|
|
272
|
+
|
|
273
|
+
const candidates = found.map(({ index, km }) => {
|
|
274
|
+
const record = records[index]!
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
wofID: record.id,
|
|
278
|
+
names: leadNames(record.name ?? "", candidateNames.get(record.id), MAX_CANDIDATE_NAMES).filter(
|
|
279
|
+
(name) => name !== ""
|
|
280
|
+
),
|
|
281
|
+
placetype: record.placetype ?? "",
|
|
282
|
+
km: Number(km.toFixed(2)),
|
|
283
|
+
}
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
return {
|
|
287
|
+
id: place.id,
|
|
288
|
+
source: place.source,
|
|
289
|
+
sourceID: place.sourceID,
|
|
290
|
+
names,
|
|
291
|
+
placetype: place.placetype,
|
|
292
|
+
country: place.country,
|
|
293
|
+
latitude: place.latitude,
|
|
294
|
+
longitude: place.longitude,
|
|
295
|
+
candidates,
|
|
296
|
+
...compareNames(names, candidates),
|
|
297
|
+
}
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Orders the items a budget admits.
|
|
303
|
+
*
|
|
304
|
+
* Names in different scripts come first, because the romanizer cannot compare them and the model can.
|
|
305
|
+
* The romanized pairs below a similarity of 1 follow from the most alike down.
|
|
306
|
+
*
|
|
307
|
+
* A pair at exactly 1 has two names that romanize to one string, so code can pair
|
|
308
|
+
* it without the model, and it ranks after them.
|
|
309
|
+
* The names outside the romanizer's scripts come last.
|
|
310
|
+
*/
|
|
311
|
+
function rankItems(items: AddedPlaceItem[]): AddedPlaceItem[] {
|
|
312
|
+
const tier = (item: AddedPlaceItem) => {
|
|
313
|
+
if (item.comparison === NameComparison.CrossScript) return 0
|
|
314
|
+
|
|
315
|
+
if (item.comparison === NameComparison.Uncovered) return 3
|
|
316
|
+
|
|
317
|
+
return item.similarity === 1 ? 2 : 1
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return items.toSorted(
|
|
321
|
+
(a, b) =>
|
|
322
|
+
tier(a) - tier(b) ||
|
|
323
|
+
(b.similarity ?? 0) - (a.similarity ?? 0) ||
|
|
324
|
+
a.country.localeCompare(b.country) ||
|
|
325
|
+
a.id - b.id
|
|
326
|
+
)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function readRankedItems(): Promise<AddedPlaceItem[]> {
|
|
330
|
+
// `--items` reads another directory's census, so a second batch over the same census keeps its own batch record.
|
|
331
|
+
const itemsPath = values.items ? resolvePath(values.items as string) : out("items.jsonl")
|
|
332
|
+
const items = rankItems(await JSONSpliterator.fromAsync<AddedPlaceItem>(itemsPath).toArray())
|
|
333
|
+
|
|
334
|
+
const skip = Number(values.skip ?? 0)
|
|
335
|
+
|
|
336
|
+
return values.take ? items.slice(skip, skip + Number(values.take)) : items.slice(skip)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (mode === "census") {
|
|
340
|
+
if (!values.unmatched) throw new Error("--unmatched names the admin build's unmatched-places file")
|
|
341
|
+
|
|
342
|
+
const byCountry = new Map<string, UnmatchedLine[]>()
|
|
343
|
+
let read = 0
|
|
344
|
+
|
|
345
|
+
for await (const line of JSONSpliterator.fromAsync<UnmatchedLine>(resolvePath(values.unmatched as string))) {
|
|
346
|
+
read++
|
|
347
|
+
|
|
348
|
+
if (!SETTLEMENT_PLACETYPES.includes(line.placetype)) continue
|
|
349
|
+
|
|
350
|
+
const held = byCountry.get(line.country)
|
|
351
|
+
|
|
352
|
+
if (held) {
|
|
353
|
+
held.push(line)
|
|
354
|
+
} else {
|
|
355
|
+
byCountry.set(line.country, [line])
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
using db = await openBuiltClient<WOFDatabase>(wofDatabasePath("admin-global-priority.db"))
|
|
360
|
+
|
|
361
|
+
// The file belongs to one build.
|
|
362
|
+
// A line whose row the database lacks means the two came from different builds.
|
|
363
|
+
const probe = [...byCountry.values()].flat().slice(0, 500)
|
|
364
|
+
|
|
365
|
+
const present = await db
|
|
366
|
+
.selectFrom("spr")
|
|
367
|
+
.select("id")
|
|
368
|
+
.where(
|
|
369
|
+
"id",
|
|
370
|
+
"in",
|
|
371
|
+
probe.map((line) => line.id)
|
|
372
|
+
)
|
|
373
|
+
.execute()
|
|
374
|
+
|
|
375
|
+
if (present.length !== probe.length) {
|
|
376
|
+
throw new Error(
|
|
377
|
+
`${probe.length - present.length} of the first ${probe.length} unmatched places have no row in the admin database`
|
|
378
|
+
)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
await writeLocalTextFile("", out("items.jsonl"))
|
|
382
|
+
|
|
383
|
+
const comparisons: string[] = []
|
|
384
|
+
const sources: string[] = []
|
|
385
|
+
const similarities: number[] = []
|
|
386
|
+
let settlements = 0
|
|
387
|
+
|
|
388
|
+
for (const [country, lines] of [...byCountry].toSorted(([a], [b]) => a.localeCompare(b))) {
|
|
389
|
+
settlements += lines.length
|
|
390
|
+
|
|
391
|
+
const items = await buildCountryItems(db, country, lines)
|
|
392
|
+
|
|
393
|
+
if (!items.length) continue
|
|
394
|
+
|
|
395
|
+
await appendLocalTextFile(items.map((item) => `${stringifyJSON(item)}\n`).join(""), out("items.jsonl"))
|
|
396
|
+
|
|
397
|
+
for (const item of items) {
|
|
398
|
+
comparisons.push(item.comparison)
|
|
399
|
+
sources.push(item.source)
|
|
400
|
+
|
|
401
|
+
if (item.similarity != null) {
|
|
402
|
+
similarities.push(item.similarity)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const census = {
|
|
408
|
+
unmatchedPlaces: read,
|
|
409
|
+
unmatchedSettlements: settlements,
|
|
410
|
+
withAWOFRecordInRadius: comparisons.length,
|
|
411
|
+
radiusKm: MATCH_RADIUS_KM,
|
|
412
|
+
bySource: countEach(sources),
|
|
413
|
+
byComparison: countEach(comparisons),
|
|
414
|
+
romanizedSimilarity: countEach(similarities.map((value) => (Math.floor(value * 10) / 10).toFixed(1))),
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
await writeLocalJSONFile(census, out("census.json"))
|
|
418
|
+
|
|
419
|
+
console.log(stringifyJSON(census))
|
|
420
|
+
} else if (mode === "pilot") {
|
|
421
|
+
const chunks = toLabelingChunks(await readRankedItems(), Number(values.chunk), "place-twins")
|
|
422
|
+
|
|
423
|
+
const pilot = await pilotLabelingRequests(
|
|
424
|
+
chunks,
|
|
425
|
+
Number(values.limit ?? 3),
|
|
426
|
+
settings,
|
|
427
|
+
placeTwinRequestParams,
|
|
428
|
+
parseLabels
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
for (const { chunk, labels, usage } of pilot.requests) {
|
|
432
|
+
for (const [i, item] of chunk.items.entries()) {
|
|
433
|
+
const label = labels[i]!
|
|
434
|
+
const paired = label.match == null ? "-" : item.candidates[label.match]!.names.slice(0, 3).join(" / ")
|
|
435
|
+
const offered = item.candidates.map((candidate) => `${candidate.names[0]} ${candidate.km} km`).join("; ")
|
|
436
|
+
|
|
437
|
+
console.log(
|
|
438
|
+
`${label.reason}\t${label.confidence}\t${item.country} ${item.names.slice(0, 3).join(" / ")} => ${paired} | offered: ${offered} | ${item.comparison} ${item.similarity ?? ""}`
|
|
439
|
+
)
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
console.log(stringifyJSON(usage))
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
console.log(
|
|
446
|
+
stringifyJSON({
|
|
447
|
+
requests: chunks.length,
|
|
448
|
+
batchCostPerRequestUSD: Number(pilot.batchCostPerRequestUSD.toFixed(5)),
|
|
449
|
+
projectedBatchCostUSD: Number((pilot.batchCostPerRequestUSD * chunks.length).toFixed(2)),
|
|
450
|
+
})
|
|
451
|
+
)
|
|
452
|
+
} else if (mode === "submit") {
|
|
453
|
+
let chunks = toLabelingChunks(await readRankedItems(), Number(values.chunk), "place-twins")
|
|
454
|
+
|
|
455
|
+
if (values.limit) {
|
|
456
|
+
chunks = chunks.slice(0, Number(values.limit))
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
console.log(stringifyJSON(await submitLabelingBatch(out, chunks, settings, placeTwinRequestParams)))
|
|
460
|
+
} else if (mode === "status") {
|
|
461
|
+
const batch = await readLabelingBatch(out)
|
|
462
|
+
|
|
463
|
+
console.log(stringifyJSON({ id: batch.id, status: batch.processing_status, ...batch.request_counts }))
|
|
464
|
+
} else if (mode === "collect") {
|
|
465
|
+
const { record, labeled, failed, resultsByType, costUSD } = await collectLabelingBatch<AddedPlaceItem, TwinLabel>(
|
|
466
|
+
out,
|
|
467
|
+
parseLabels
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
const rows = labeled.map(({ item, label }) => {
|
|
471
|
+
const paired = label.match == null ? null : item.candidates[label.match]!
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
added_id: item.id,
|
|
475
|
+
source: item.source,
|
|
476
|
+
source_id: item.sourceID,
|
|
477
|
+
country: item.country,
|
|
478
|
+
placetype: item.placetype,
|
|
479
|
+
names: item.names,
|
|
480
|
+
wof_id: paired?.wofID ?? null,
|
|
481
|
+
wof_names: paired?.names ?? null,
|
|
482
|
+
km: paired?.km ?? null,
|
|
483
|
+
candidates: item.candidates.length,
|
|
484
|
+
comparison: item.comparison,
|
|
485
|
+
similarity: item.similarity,
|
|
486
|
+
reason: label.reason,
|
|
487
|
+
confidence: label.confidence,
|
|
488
|
+
model: record.model,
|
|
489
|
+
effort: record.effort,
|
|
490
|
+
batch_id: record.id,
|
|
491
|
+
}
|
|
492
|
+
})
|
|
493
|
+
|
|
494
|
+
await writeLocalJSONLFile(rows, out("pairs.jsonl"))
|
|
495
|
+
|
|
496
|
+
const paired = rows.filter((row) => row.wof_id != null)
|
|
497
|
+
|
|
498
|
+
const summary = {
|
|
499
|
+
batch: record.id,
|
|
500
|
+
model: record.model,
|
|
501
|
+
effort: record.effort,
|
|
502
|
+
requests: record.requests,
|
|
503
|
+
resultsByType,
|
|
504
|
+
items: record.items,
|
|
505
|
+
labeled: rows.length,
|
|
506
|
+
failedRequests: failed.length,
|
|
507
|
+
failedItems: failed.reduce((sum, chunk) => sum + chunk.items, 0),
|
|
508
|
+
paired: paired.length,
|
|
509
|
+
pairedBySource: countEach(paired.map((row) => row.source)),
|
|
510
|
+
pairedHighConfidence: paired.filter((row) => row.confidence === "high").length,
|
|
511
|
+
reasons: countEach(rows.map((row) => row.reason)),
|
|
512
|
+
confidences: countEach(rows.map((row) => row.confidence)),
|
|
513
|
+
reasonsByComparison: Object.fromEntries(
|
|
514
|
+
Object.values(NameComparison).map((comparison) => [
|
|
515
|
+
comparison,
|
|
516
|
+
countEach(rows.filter((row) => row.comparison === comparison).map((row) => row.reason)),
|
|
517
|
+
])
|
|
518
|
+
),
|
|
519
|
+
pairedCountries: Object.keys(countEach(paired.map((row) => row.country))).length,
|
|
520
|
+
costUSD,
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
await writeLocalJSONFile(summary, out("summary.json"))
|
|
524
|
+
|
|
525
|
+
console.log(stringifyJSON(summary))
|
|
526
|
+
} else {
|
|
527
|
+
throw new Error(`The mode is one of census, pilot, submit, status and collect, and this run named ${String(mode)}`)
|
|
528
|
+
}
|