@mailwoman/corpus 12.0.0 → 12.2.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.
Files changed (140) hide show
  1. package/data/address-source-register.json +545 -11
  2. package/data/holdout/evaluation-groups.v0.9.3.json +224169 -0
  3. package/data/license-decisions.json +440 -9
  4. package/data/licenses/PROVENANCE.md +27 -18
  5. package/data/licenses/at-bev-adressregister-cc-by-4.0.md +25 -0
  6. package/data/licenses/br-ibge-cnefe-open-data.md +21 -0
  7. package/data/licenses/ca-qc-mrnf-cc-by-4.0.md +29 -0
  8. package/data/licenses/ca-statcan-open-licence.md +41 -0
  9. package/data/licenses/ca-yukon-ogl-2.0.md +19 -0
  10. package/data/licenses/dk-dmikg-cc-by-4.0.md +43 -0
  11. package/data/licenses/jp-mlit-isj-pdl-1.0.md +35 -0
  12. package/data/source-additions.json +90 -0
  13. package/data/source-resolutions.json +3 -2
  14. package/data/training-configs/v9.1.0-bytestem-global-v091-s42.yaml +710 -0
  15. package/data/training-configs/v9.2.0-bytestem-global-v092-s42.yaml +714 -0
  16. package/data/training-configs/v9.3.0-bytestem-global-v093-s42.yaml +746 -0
  17. package/data/training-manifests/v0.9.1-compact.json +9660 -0
  18. package/data/training-manifests/v0.9.2-compact.effective.json +2670 -0
  19. package/data/training-manifests/v0.9.2-compact.json +9660 -0
  20. package/data/training-manifests/v0.9.3-compact.effective.json +2660 -0
  21. package/data/training-manifests/v0.9.3-compact.json +9648 -0
  22. package/lib/adapters/geonames/features/adapter.ts +163 -20
  23. package/lib/adapters/overture/adapter.ts +26 -6
  24. package/lib/adapters/street/line.ts +6 -5
  25. package/lib/adapters/street/unit.ts +7 -0
  26. package/lib/adapters/wof/admin/json/dual-role.ts +46 -21
  27. package/lib/au/adapters/gnaf/source.ts +12 -0
  28. package/lib/build/schema-invariants.ts +447 -0
  29. package/lib/fr/adapters/ban/adapter.ts +57 -8
  30. package/lib/fr/recipes/admin-split.ts +14 -2
  31. package/lib/fr/recipes/lieudit.ts +1 -1
  32. package/lib/fr/recipes/order.ts +14 -5
  33. package/lib/international/recipes/locale.ts +1 -1
  34. package/lib/jp/corpus/assemble.ts +20 -1
  35. package/lib/jp/corpus/rows.ts +87 -0
  36. package/lib/recipes/po/box/cedex/recipe.ts +1 -1
  37. package/lib/recipes/po/box/cedex/vocabulary.ts +4 -4
  38. package/lib/recipes/prominent/places.ts +42 -9
  39. package/lib/recipes/trailing-region.ts +180 -20
  40. package/lib/synthesizers/po-box.ts +51 -12
  41. package/lib/test-kit/corpus-recipe.ts +3 -0
  42. package/lib/tools/compact-v9.ts +22 -4
  43. package/lib/tools/fetch/wikidata/vital-places/classify.ts +23 -7
  44. package/lib/tools/fetch/wikidata/vital-places/render.ts +57 -7
  45. package/lib/tools/source-register/build.ts +1 -0
  46. package/lib/training/config/schema.ts +3 -0
  47. package/lib/us/adapters/usgov/usgs-structures/adapter.ts +103 -6
  48. package/lib/us/street-unit.ts +14 -1
  49. package/out/adapters/geonames/features/adapter.d.ts +2 -2
  50. package/out/adapters/geonames/features/adapter.d.ts.map +1 -1
  51. package/out/adapters/geonames/features/adapter.js +114 -20
  52. package/out/adapters/geonames/features/adapter.js.map +1 -1
  53. package/out/adapters/overture/adapter.d.ts.map +1 -1
  54. package/out/adapters/overture/adapter.js +21 -5
  55. package/out/adapters/overture/adapter.js.map +1 -1
  56. package/out/adapters/street/line.d.ts +4 -4
  57. package/out/adapters/street/line.d.ts.map +1 -1
  58. package/out/adapters/street/line.js +5 -5
  59. package/out/adapters/street/line.js.map +1 -1
  60. package/out/adapters/street/unit.d.ts +4 -0
  61. package/out/adapters/street/unit.d.ts.map +1 -1
  62. package/out/adapters/street/unit.js +3 -0
  63. package/out/adapters/street/unit.js.map +1 -1
  64. package/out/adapters/wof/admin/json/dual-role.d.ts +8 -3
  65. package/out/adapters/wof/admin/json/dual-role.d.ts.map +1 -1
  66. package/out/adapters/wof/admin/json/dual-role.js +40 -19
  67. package/out/adapters/wof/admin/json/dual-role.js.map +1 -1
  68. package/out/au/adapters/gnaf/source.d.ts +9 -0
  69. package/out/au/adapters/gnaf/source.d.ts.map +1 -1
  70. package/out/au/adapters/gnaf/source.js +9 -0
  71. package/out/au/adapters/gnaf/source.js.map +1 -1
  72. package/out/build/schema-invariants.d.ts +101 -0
  73. package/out/build/schema-invariants.d.ts.map +1 -0
  74. package/out/build/schema-invariants.js +302 -0
  75. package/out/build/schema-invariants.js.map +1 -0
  76. package/out/fr/adapters/ban/adapter.d.ts.map +1 -1
  77. package/out/fr/adapters/ban/adapter.js +49 -7
  78. package/out/fr/adapters/ban/adapter.js.map +1 -1
  79. package/out/fr/recipes/admin-split.d.ts.map +1 -1
  80. package/out/fr/recipes/admin-split.js +15 -2
  81. package/out/fr/recipes/admin-split.js.map +1 -1
  82. package/out/fr/recipes/lieudit.js +1 -1
  83. package/out/fr/recipes/lieudit.js.map +1 -1
  84. package/out/fr/recipes/order.d.ts.map +1 -1
  85. package/out/fr/recipes/order.js +16 -5
  86. package/out/fr/recipes/order.js.map +1 -1
  87. package/out/international/recipes/locale.js +1 -1
  88. package/out/international/recipes/locale.js.map +1 -1
  89. package/out/jp/corpus/assemble.d.ts.map +1 -1
  90. package/out/jp/corpus/assemble.js +14 -2
  91. package/out/jp/corpus/assemble.js.map +1 -1
  92. package/out/jp/corpus/rows.d.ts +8 -0
  93. package/out/jp/corpus/rows.d.ts.map +1 -1
  94. package/out/jp/corpus/rows.js +72 -0
  95. package/out/jp/corpus/rows.js.map +1 -1
  96. package/out/recipes/po/box/cedex/recipe.js +1 -1
  97. package/out/recipes/po/box/cedex/recipe.js.map +1 -1
  98. package/out/recipes/po/box/cedex/vocabulary.d.ts +1 -1
  99. package/out/recipes/po/box/cedex/vocabulary.d.ts.map +1 -1
  100. package/out/recipes/po/box/cedex/vocabulary.js +4 -4
  101. package/out/recipes/po/box/cedex/vocabulary.js.map +1 -1
  102. package/out/recipes/prominent/places.d.ts.map +1 -1
  103. package/out/recipes/prominent/places.js +30 -5
  104. package/out/recipes/prominent/places.js.map +1 -1
  105. package/out/recipes/trailing-region.d.ts.map +1 -1
  106. package/out/recipes/trailing-region.js +148 -20
  107. package/out/recipes/trailing-region.js.map +1 -1
  108. package/out/synthesizers/po-box.d.ts +7 -0
  109. package/out/synthesizers/po-box.d.ts.map +1 -1
  110. package/out/synthesizers/po-box.js +36 -12
  111. package/out/synthesizers/po-box.js.map +1 -1
  112. package/out/test-kit/corpus-recipe.d.ts +3 -0
  113. package/out/test-kit/corpus-recipe.d.ts.map +1 -1
  114. package/out/test-kit/corpus-recipe.js.map +1 -1
  115. package/out/tools/compact-v9.d.ts +8 -1
  116. package/out/tools/compact-v9.d.ts.map +1 -1
  117. package/out/tools/compact-v9.js +17 -4
  118. package/out/tools/compact-v9.js.map +1 -1
  119. package/out/tools/fetch/wikidata/vital-places/classify.d.ts +12 -2
  120. package/out/tools/fetch/wikidata/vital-places/classify.d.ts.map +1 -1
  121. package/out/tools/fetch/wikidata/vital-places/classify.js +19 -7
  122. package/out/tools/fetch/wikidata/vital-places/classify.js.map +1 -1
  123. package/out/tools/fetch/wikidata/vital-places/render.d.ts +9 -5
  124. package/out/tools/fetch/wikidata/vital-places/render.d.ts.map +1 -1
  125. package/out/tools/fetch/wikidata/vital-places/render.js +44 -7
  126. package/out/tools/fetch/wikidata/vital-places/render.js.map +1 -1
  127. package/out/tools/source-register/build.d.ts.map +1 -1
  128. package/out/tools/source-register/build.js +1 -0
  129. package/out/tools/source-register/build.js.map +1 -1
  130. package/out/training/config/schema.d.ts +21 -0
  131. package/out/training/config/schema.d.ts.map +1 -1
  132. package/out/training/config/schema.js +3 -0
  133. package/out/training/config/schema.js.map +1 -1
  134. package/out/us/adapters/usgov/usgs-structures/adapter.d.ts.map +1 -1
  135. package/out/us/adapters/usgov/usgs-structures/adapter.js +78 -4
  136. package/out/us/adapters/usgov/usgs-structures/adapter.js.map +1 -1
  137. package/out/us/street-unit.d.ts.map +1 -1
  138. package/out/us/street-unit.js +11 -1
  139. package/out/us/street-unit.js.map +1 -1
  140. package/package.json +19 -19
@@ -37,6 +37,11 @@ export const DEFAULT_SKELETON_CAP = 6
37
37
 
38
38
  /**
39
39
  * Default Tier-2 dense register sources subject to cross-source deduplication and skeleton capping.
40
+ *
41
+ * The multi-country European `overture` source stays in Tier 1 rather than here:
42
+ * its rows span 16 countries at roughly 100k to 150k rows each.
43
+ * Skeleton-capping it dropped 700,104 of 1,825,956 rows in `v0.9.0-compact`,
44
+ * including ES and IT single-letter unit rows and CZ/SI addresses.
40
45
  */
41
46
  export const DEFAULT_TIER2_SOURCES = [
42
47
  "usgov-nad",
@@ -57,7 +62,6 @@ export const DEFAULT_TIER2_SOURCES = [
57
62
  "state-ia-contractors",
58
63
  "state-ny-notaries",
59
64
  "state-tx-notaries",
60
- "overture",
61
65
  "overture-latam",
62
66
  "gleif-lei",
63
67
  ] as const
@@ -104,6 +108,8 @@ export interface CompactCorpusV9Options {
104
108
  * `intersection_a`, `venue`, `building_name`, `building_number`).
105
109
  *
106
110
  * A `null` value keeps rare patterns uncapped.
111
+ * Bare single-letter `unit` rows (one token matching a single letter, such as ES
112
+ * `CALLE LA CRUZ A, 45` or IT `VIA NAPOLI A 5`) stay uncapped even when `rareSkeletonCap` is set.
107
113
  *
108
114
  * @default null
109
115
  */
@@ -239,6 +245,7 @@ interface PreparedFile {
239
245
  tier: 1 | 2
240
246
  hasAugmentation: boolean
241
247
  hasSpanTags: boolean
248
+ hasTokens: boolean
242
249
  splitAttribute: SplitAttributeFile | null
243
250
  }
244
251
 
@@ -328,6 +335,7 @@ async function prepareInputFiles(
328
335
  tier,
329
336
  hasAugmentation: columns.has("augmentation"),
330
337
  hasSpanTags: columns.has("span_tags"),
338
+ hasTokens: columns.has("tokens"),
331
339
  splitAttribute,
332
340
  })
333
341
  }
@@ -377,6 +385,7 @@ async function buildTier2KeepTable(
377
385
  "dedup_key VARCHAR, " +
378
386
  "skeleton_key VARCHAR, " +
379
387
  "is_rare BOOLEAN, " +
388
+ "is_single_letter_unit BOOLEAN, " +
380
389
  "tie_hash VARCHAR)"
381
390
  )
382
391
 
@@ -412,6 +421,14 @@ async function buildTier2KeepTable(
412
421
  `OR list_has_any(p.span_tags, ${rareTagsSQL}))`
413
422
  : `list_has_any(list_transform(p.labels, lambda x: regexp_replace(x, '^[BI]-', '')), ${rareTagsSQL})`
414
423
 
424
+ const unitTokensExpr = `list_filter(list_zip(p.tokens, p.labels), lambda x: x[2] IN ('B-unit', 'I-unit'))`
425
+
426
+ const singleLetterUnitExpr = file.hasTokens
427
+ ? `(CASE WHEN len(${unitTokensExpr}) = 1 ` +
428
+ `THEN regexp_matches(${unitTokensExpr}[1][1], '^\\p{L}$') ` +
429
+ `ELSE FALSE END)`
430
+ : "FALSE"
431
+
415
432
  await db.run(
416
433
  `INSERT INTO tier2_candidates ` +
417
434
  `SELECT ${file.index}, p.file_row_number, '${escapeSQLString(file.source)}', p.source_id, ` +
@@ -419,6 +436,7 @@ async function buildTier2KeepTable(
419
436
  `sha256(coalesce(p.country, '') || chr(0) || array_to_string(p.labels, ',') || chr(0) || ` +
420
437
  `regexp_replace(lower(p.raw), '[0-9]+', '#', 'g')), ` +
421
438
  `${rareExpr}, ` +
439
+ `${singleLetterUnitExpr}, ` +
422
440
  `md5(coalesce(p.source_id, '') || ':' || p.raw) ` +
423
441
  `FROM ${scan} p WHERE (${trainPredicate}) AND (${augPredicate})`
424
442
  )
@@ -426,7 +444,7 @@ async function buildTier2KeepTable(
426
444
 
427
445
  await db.run(
428
446
  "CREATE TEMP TABLE tier2_deduped AS " +
429
- "SELECT file_idx, file_row_number, source, source_id, skeleton_key, is_rare, tie_hash, " +
447
+ "SELECT file_idx, file_row_number, source, source_id, skeleton_key, is_rare, is_single_letter_unit, tie_hash, " +
430
448
  "row_number() OVER (PARTITION BY dedup_key ORDER BY source, source_id, file_idx, file_row_number) AS dedup_rn " +
431
449
  "FROM tier2_candidates"
432
450
  )
@@ -443,7 +461,7 @@ async function buildTier2KeepTable(
443
461
 
444
462
  await db.run(
445
463
  "CREATE TEMP TABLE tier2_ranked AS " +
446
- "SELECT file_idx, file_row_number, source, is_rare, " +
464
+ "SELECT file_idx, file_row_number, source, is_rare, is_single_letter_unit, " +
447
465
  "row_number() OVER (PARTITION BY skeleton_key ORDER BY tie_hash, source, source_id, file_idx, file_row_number) AS skel_rn " +
448
466
  "FROM tier2_deduped WHERE dedup_rn = 1"
449
467
  )
@@ -453,7 +471,7 @@ async function buildTier2KeepTable(
453
471
  const keepPredicate =
454
472
  rareSkeletonCap == null
455
473
  ? `(is_rare OR skel_rn <= ${skeletonCap})`
456
- : `((is_rare AND skel_rn <= ${rareSkeletonCap}) OR (NOT is_rare AND skel_rn <= ${skeletonCap}))`
474
+ : `(is_single_letter_unit OR (is_rare AND skel_rn <= ${rareSkeletonCap}) OR (NOT is_rare AND skel_rn <= ${skeletonCap}))`
457
475
 
458
476
  const skelDrops = await db.runAndReadAll(
459
477
  `SELECT source, count(*) AS dropped FROM tier2_ranked WHERE NOT ${keepPredicate} GROUP BY source`
@@ -22,10 +22,19 @@ import type { SPARQLResults, WikidataClient } from "#tools/fetch/wikidata/subven
22
22
  import { chunked, entityQID, formatElapsed, type ProgressReporter } from "#tools/fetch/wikidata/vital-places/progress"
23
23
 
24
24
  /**
25
- * A class under one of these roots makes its instances places: geographic location,
26
- * geographical feature and architectural structure.
25
+ * A class under one of these roots makes its instances places.
26
+ *
27
+ * Covers geographic location, geographical feature, architectural structure,
28
+ * `Q473972` (national parks), and archaeological site.
29
+ */
30
+ export const PLACE_ROOTS: readonly string[] = ["Q2221906", "Q618123", "Q811979", "Q473972", "Q839954"]
31
+
32
+ /**
33
+ * Direct `P31` classes for located physical features and public monuments whose Wikidata
34
+ * class tree doesn't walk up to {@linkcode PLACE_ROOTS}: oceanic trench (`Q21285941`),
35
+ * sculpture (`Q860861`), and statue (`Q179700`).
27
36
  */
28
- export const PLACE_ROOTS: readonly string[] = ["Q2221906", "Q618123", "Q811979"]
37
+ export const DIRECT_PLACE_CLASSES: readonly string[] = ["Q21285941", "Q860861", "Q179700"]
29
38
 
30
39
  /**
31
40
  * A class under one of these roots excludes its instances: occurrence
@@ -61,9 +70,11 @@ export const ROAD_ROOTS: readonly string[] = ["Q34442", "Q79007"]
61
70
 
62
71
  /**
63
72
  * Every root the descent query asks about: the inventory's and the render's.
73
+ *
74
+ * Keeps the v3 root order stable so cached `class-roots.v3.json` entries match without re-querying.
64
75
  */
65
76
  export const DESCENT_ROOTS: readonly string[] = [
66
- ...new Set([...PLACE_ROOTS, ...EXCLUDED_ROOTS, ...SETTLEMENT_ROOTS, ...SITE_ROOTS, ...ROAD_ROOTS]),
77
+ ...new Set(["Q2221906", "Q618123", "Q811979", ...EXCLUDED_ROOTS, ...SETTLEMENT_ROOTS, ...SITE_ROOTS, ...ROAD_ROOTS]),
67
78
  ]
68
79
 
69
80
  /**
@@ -170,9 +181,14 @@ export function placeVerdict(classes: readonly string[], roots: Readonly<ClassRo
170
181
 
171
182
  if (classRoots.some(excludesInstances)) return PLACE_VERDICTS.excluded
172
183
 
173
- return classRoots.some((rootsOfClass) => PLACE_ROOTS.some((root) => rootsOfClass.includes(root)))
174
- ? PLACE_VERDICTS.place
175
- : PLACE_VERDICTS.unclassified
184
+ if (
185
+ classes.some((cls) => DIRECT_PLACE_CLASSES.includes(cls)) ||
186
+ classRoots.some((rootsOfClass) => PLACE_ROOTS.some((root) => rootsOfClass.includes(root)))
187
+ ) {
188
+ return PLACE_VERDICTS.place
189
+ }
190
+
191
+ return PLACE_VERDICTS.unclassified
176
192
  }
177
193
 
178
194
  /**
@@ -65,16 +65,41 @@ export const VITAL_PLACE_RENDERINGS = {
65
65
 
66
66
  export type VitalPlaceRendering = (typeof VITAL_PLACE_RENDERINGS)[keyof typeof VITAL_PLACE_RENDERINGS]
67
67
 
68
+ /**
69
+ * Wikidata root for sovereign countries (`Q6256`).
70
+ *
71
+ * A country stays a settlement even when it also holds a biosphere-reserve or park class.
72
+ */
73
+ const COUNTRY_ROOT = "Q6256"
74
+
75
+ /**
76
+ * Wikidata root for national parks and nature reserves (`Q473972`).
77
+ */
78
+ const RESERVE_ROOT = "Q473972"
79
+
80
+ /**
81
+ * Direct `P31` classes for national parks and canyons/gorges that render as venues.
82
+ *
83
+ * Includes national park (`Q46169`), US national park (`Q34918903`), IUCN category
84
+ * II national park (`Q179049`), and canyon/gorge (`Q150784`).
85
+ * These stay venues even with an administrative class and a small staff population.
86
+ */
87
+ const NATURAL_PARK_AND_GORGE_CLASSES: ReadonlySet<string> = new Set(["Q46169", "Q34918903", "Q179049", "Q150784"])
88
+
68
89
  /**
69
90
  * Whether a place renders as venues.
70
91
  *
71
- * A place under a settlement root is left to Who's On First unless a class is also
72
- * under a site root and the place states no population.
73
- * Wikidata's class tree puts observation tower, national park and ancient city
74
- * under settlement or administrative roots.
92
+ * A place under a settlement root is left to Who's On First unless it is a non-country
93
+ * national park, canyon/gorge, or `Q473972` reserve without a pure settlement class.
94
+ * A site without positive population also stays a venue.
95
+ *
96
+ * Wikidata puts observation tower, national park, and ancient city under admin roots.
97
+ * The site exception keeps Eiffel Tower, Machu Picchu, and Northeast Greenland National Park as venues.
75
98
  *
76
- * The site exception keeps the Eiffel Tower and Machu Picchu as venues.
77
99
  * A capital whose old town is a World Heritage site states a population and stays a locality.
100
+ *
101
+ * A place under a road root renders as a road only when it holds no non-road site class.
102
+ * Charles Bridge stays a venue while streets such as Calle de Alcalá stay roads.
78
103
  */
79
104
  export function vitalPlaceRendering(
80
105
  place: Pick<VitalPlace, "classes" | "population" | "countryCodes">,
@@ -83,10 +108,35 @@ export function vitalPlaceRendering(
83
108
  const placeRoots = new Set(place.classes.flatMap((cls) => roots[cls] ?? []))
84
109
  const settlement = SETTLEMENT_ROOTS.some((root) => placeRoots.has(root))
85
110
  const site = SITE_ROOTS.some((root) => placeRoots.has(root))
111
+ const isCountry = placeRoots.has(COUNTRY_ROOT)
112
+ const hasPopulation = place.population != null && place.population > 0
113
+
114
+ const isNaturalParkOrGorge = !isCountry && place.classes.some((cls) => NATURAL_PARK_AND_GORGE_CLASSES.has(cls))
115
+
116
+ const hasPureSettlementClass = place.classes.some((cls) => {
117
+ const classRoots = roots[cls] ?? []
118
+
119
+ return (
120
+ SETTLEMENT_ROOTS.some((root) => classRoots.includes(root)) &&
121
+ !SITE_ROOTS.some((root) => classRoots.includes(root))
122
+ )
123
+ })
124
+
125
+ const isReserveOnly = !isCountry && placeRoots.has(RESERVE_ROOT) && !hasPureSettlementClass
126
+
127
+ if (isCountry || (settlement && !isNaturalParkOrGorge && !isReserveOnly && (!site || hasPopulation))) {
128
+ return VITAL_PLACE_RENDERINGS.settlement
129
+ }
130
+
131
+ const hasRoad = ROAD_ROOTS.some((root) => placeRoots.has(root))
132
+
133
+ const hasNonRoadSite = place.classes.some((cls) => {
134
+ const classRoots = roots[cls] ?? []
86
135
 
87
- if (settlement && (!site || place.population != null)) return VITAL_PLACE_RENDERINGS.settlement
136
+ return SITE_ROOTS.some((root) => classRoots.includes(root)) && !ROAD_ROOTS.some((root) => classRoots.includes(root))
137
+ })
88
138
 
89
- if (ROAD_ROOTS.some((root) => placeRoots.has(root))) return VITAL_PLACE_RENDERINGS.road
139
+ if (hasRoad && !hasNonRoadSite) return VITAL_PLACE_RENDERINGS.road
90
140
 
91
141
  if (!vitalPlaceCountry(place)) return VITAL_PLACE_RENDERINGS.noCountry
92
142
 
@@ -95,6 +95,7 @@ const RESEARCH_PASS_BY_ORIGIN: Readonly<Record<string, ResearchPass>> = {
95
95
  "2026-11-21_rights_review": ResearchPass.RightsReview,
96
96
  "2026-11-22_rights_review": ResearchPass.RightsReview,
97
97
  "2026-11-23_rights_review": ResearchPass.RightsReview,
98
+ "2026-12-02_rights_review": ResearchPass.RightsReview,
98
99
  "2026-10-03_decoder_exposure": ResearchPass.DecoderExposureSurvey,
99
100
  "2026-10-17_corpus_input_mapping": ResearchPass.CorpusInputMapping,
100
101
  }
@@ -226,6 +226,7 @@ export const DATA_SECTION = {
226
226
  augment_postcode_move_prob: float(0),
227
227
  augment_grouping_prob: float(0),
228
228
  code_unit_features: bool(false),
229
+ route_features: bool(false),
229
230
  augment_exclude_sources: strList(),
230
231
  anchor_lookup_path: optionalStr(),
231
232
  gazetteer_lexicon_path: optionalStr(),
@@ -321,6 +322,8 @@ export const MODEL_SECTION = {
321
322
  locality_surface_feature_dim: int(2n),
322
323
  use_code_unit_anchor: bool(false),
323
324
  code_unit_feature_dim: int(5n),
325
+ use_route_anchor: bool(false),
326
+ route_feature_dim: int(2n),
324
327
  use_char_embed: bool(false),
325
328
  char_embed_dim: int(64n),
326
329
  char_kernel_sizes: intList([3n, 4n, 5n]),
@@ -27,13 +27,14 @@
27
27
  */
28
28
 
29
29
  import { formatAddressRow } from "@mailwoman/codex/address/format"
30
+ import { escapeRegExp } from "@mailwoman/core/strings/regexp"
30
31
  import { JSONSpliterator } from "spliterator"
31
32
 
32
- import { createUnitSplitter, type UnitSplitter } from "#adapters/street/unit"
33
+ import { createUnitSplitter, type UnitSplitter, type UnitVocabulary } from "#adapters/street/unit"
33
34
  import { SourceRegister } from "#registers"
34
35
  import { streetIndexOpener } from "#street-index/reader"
35
36
  import { AddressRole, type AdapterOptions, type CanonicalRow, type CorpusAdapter, SurfaceOrigin } from "#types"
36
- import { lookupStateAbbreviation } from "#us/fips-state"
37
+ import { lookupStateAbbreviation, type USStateInfo } from "#us/fips-state"
37
38
  import { splitUSStreetLine } from "#us/street-unit"
38
39
  import { usgsStructureLayer } from "#us/structures/usgs/layers"
39
40
 
@@ -103,6 +104,90 @@ export interface USGSStructureFeature {
103
104
  properties: USGSStructureProperties
104
105
  }
105
106
 
107
+ /**
108
+ * Strips stray commas and any repeated state or ZIP Code tail from a USGS `city` value
109
+ * (such as `Matawan, NJ 07747`, `Boynton Beach, Florida 33435`, or `Grand Rapids, MI`).
110
+ */
111
+ function cleanUSCity(city: string, state: USStateInfo, zipcode: string): string {
112
+ const stripped = city
113
+ .trim()
114
+ .replaceAll(/^,+\s*|\s*,+$/gu, "")
115
+ .trim()
116
+
117
+ if (!stripped) return ""
118
+
119
+ const statePattern = `(?:${escapeRegExp(state.abbreviation)}|${escapeRegExp(state.name)})`
120
+ const stateTail = new RegExp(`,\\s*${statePattern}(?:\\s*,?\\s*\\d{5}(?:-\\d{4})?)?$`, "iu")
121
+ let cleaned = stripped.replace(stateTail, "").trim()
122
+
123
+ // Catch publisher typos in the state name (such as `Raiford, Florda 32083`)
124
+ // when the trailing five-digit ZIP Code matches the row's own postcode.
125
+ const zip5 = zipcode.slice(0, 5)
126
+
127
+ if (cleaned === stripped && /^\d{5}$/u.test(zip5)) {
128
+ const zipTail = new RegExp(`,\\s*[A-Za-z]+(?:\\s+[A-Za-z]+)?\\s*,?\\s*${escapeRegExp(zip5)}(?:-\\d{4})?$`, "iu")
129
+
130
+ cleaned = stripped.replace(zipTail, "").trim()
131
+ }
132
+
133
+ return cleaned.replaceAll(/\s*,+$/gu, "").trim()
134
+ }
135
+
136
+ /**
137
+ * Strips a trailing repeated locality from a USGS street name when it follows a comma
138
+ * (`Calle Lina R Corretger, Ciales`) or a complete US street suffix or route number
139
+ * (`Walnut Street Big Stone City`, `US Highway 70 East Otway`).
140
+ *
141
+ * Leaves street names that share words with the locality untouched: `Camino Del Mar`,
142
+ * `Stanton Terrace Southeast`, `Avenida de Mesilla`, and `US Highway 101 North of Ilwaco`.
143
+ */
144
+ function stripRepeatedLocality(
145
+ street: string,
146
+ locality: string,
147
+ rawCity: string,
148
+ vocabulary: UnitVocabulary | null
149
+ ): string {
150
+ const trimmedRawCity = rawCity.trim()
151
+
152
+ if (trimmedRawCity && trimmedRawCity.toLowerCase() !== locality.toLowerCase()) {
153
+ const rawTail = new RegExp(`,\\s*${escapeRegExp(trimmedRawCity)}$`, "iu")
154
+ const withoutRawCity = street.replace(rawTail, "").trim()
155
+
156
+ if (withoutRawCity && withoutRawCity !== street) return withoutRawCity
157
+ }
158
+
159
+ if (vocabulary?.directionals.has(locality.toLowerCase())) return street
160
+
161
+ const tailMatch = new RegExp(`(,\\s*|\\s+)${escapeRegExp(locality)}$`, "iu").exec(street)
162
+
163
+ if (!tailMatch) return street
164
+
165
+ const prefix = street.slice(0, tailMatch.index).trim()
166
+
167
+ if (!prefix) return street
168
+
169
+ if (tailMatch[1]!.includes(",")) return prefix
170
+
171
+ if (!vocabulary) return street
172
+
173
+ const words = prefix
174
+ .split(/\s+/u)
175
+ .map((word) => word.replaceAll(/[.,]+$/gu, "").toLowerCase())
176
+ .filter((word) => word.length > 0)
177
+
178
+ // Require at least two words before the repeated locality so prefix-led names like
179
+ // `Camino Del Mar` are never reduced to a bare street-type word (`Camino`).
180
+ if (words.length < 2) return street
181
+
182
+ if (words.length > 2 && vocabulary.directionals.has(words.at(-1)!) && !vocabulary.streetTypes.has(words.at(-1)!)) {
183
+ words.pop()
184
+ }
185
+
186
+ const last = words.at(-1)!
187
+
188
+ return vocabulary.streetTypes.has(last) || /\d/u.test(last) ? prefix : street
189
+ }
190
+
106
191
  /**
107
192
  * A structure's address as labeled components, or `null` when it lacks a street address,
108
193
  * city, recognized state or ZIP Code.
@@ -115,13 +200,25 @@ export function usgsStructureAddress(
115
200
  units: UnitSplitter
116
201
  ): CanonicalRow["components"] | null {
117
202
  const { address, city, state: stateCode, zipcode } = properties
118
- const place = { ...(city ? { locality: city } : {}), ...(zipcode ? { postcode: zipcode } : {}) }
119
- const line = address ? splitUSStreetLine(address, units, place) : null
120
203
  const state = lookupStateAbbreviation(stateCode)
121
204
 
122
- if (!line || !city || !state || !zipcode) return null
205
+ if (!address || !city || !state || !zipcode) return null
206
+
207
+ const cleanedCity = cleanUSCity(city, state, zipcode)
208
+
209
+ if (!cleanedCity) return null
210
+
211
+ const place = { locality: cleanedCity, postcode: zipcode }
212
+ const line = splitUSStreetLine(address, units, place)
213
+
214
+ if (!line) return null
215
+
216
+ const cleanedLine =
217
+ "street" in line && !line.unit
218
+ ? { ...line, street: stripRepeatedLocality(line.street, cleanedCity, city, units.vocabulary("US")) }
219
+ : line
123
220
 
124
- return { ...line, locality: city, region: state.abbreviation, postcode: zipcode }
221
+ return { ...cleanedLine, locality: cleanedCity, region: state.abbreviation, postcode: zipcode }
125
222
  }
126
223
 
127
224
  /**
@@ -69,9 +69,22 @@ export function splitUSStreetLine(
69
69
  const box = usPOBoxLine(line)
70
70
 
71
71
  if (box) return box
72
- const split = splitStreetLine(line)
72
+ let split = splitStreetLine(line)
73
73
 
74
74
  if (!split) return null
75
+
76
+ // A hyphenated single-letter suffix (`101 - B Street`) belongs to the street
77
+ // when the remainder is only a bare street-type word (`Street`, `Ave`, `Road`)
78
+ // rather than a complete street name (#3506).
79
+ if (split.house_number) {
80
+ const letterSuffix = /^(.+?)\s*-\s*([A-Za-z])$/u.exec(split.house_number)
81
+ const streetWord = split.street.replace(/[.,]$/u, "").toLowerCase()
82
+
83
+ if (letterSuffix && !/\s/u.test(split.street) && units.vocabulary("US")?.streetTypes.has(streetWord)) {
84
+ split = { house_number: letterSuffix[1]!, street: `${letterSuffix[2]!} ${split.street}` }
85
+ }
86
+ }
87
+
75
88
  const trailing = units.split(split.street, { ...place, country: "US" })
76
89
 
77
90
  return {
@@ -4,8 +4,8 @@ import { type CorpusAdapter } from "#types";
4
4
  */
5
5
  export declare const GEONAMES_FEATURES_ADAPTER_ID = "geonames-features";
6
6
  /**
7
- * The GeoNames feature classes this adapter reads: undersea (`U`), water (`H`),
8
- * terrain (`T`), parks and areas (`L`) and vegetation (`V`).
7
+ * The GeoNames feature classes this adapter reads unconditionally: undersea (`U`), water (`H`),
8
+ * terrain (`T`), parks and areas (`L`, which includes ports `PRT`) and vegetation (`V`).
9
9
  */
10
10
  export declare const GEONAMES_FEATURE_CLASSES: ReadonlySet<string>;
11
11
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../../lib/adapters/geonames/features/adapter.ts"],"names":[],"mappings":"AAgCA,OAAO,EAAuD,KAAK,aAAa,EAAiB,MAAM,QAAQ,CAAA;AAE/G;;GAEG;AACH,eAAO,MAAM,4BAA4B,sBAAsB,CAAA;AAE/D;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,WAAW,CAAC,MAAM,CAAsC,CAAA;AAE/F;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,KAAK,CAAA;AAE5C;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,sCAAsC,IAAI,CAAA;AAkDvD;;GAEG;AACH,wBAAgB,6BAA6B,IAAI,aAAa,CAmF7D;AAED;;GAEG;AACH,eAAO,MAAM,uBAAuB,eAAkC,CAAA"}
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../../lib/adapters/geonames/features/adapter.ts"],"names":[],"mappings":"AAwCA,OAAO,EAAuD,KAAK,aAAa,EAAiB,MAAM,QAAQ,CAAA;AAE/G;;GAEG;AACH,eAAO,MAAM,4BAA4B,sBAAsB,CAAA;AAE/D;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,WAAW,CAAC,MAAM,CAAsC,CAAA;AAmB/F;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,KAAK,CAAA;AAE5C;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,sCAAsC,IAAI,CAAA;AAoKvD;;GAEG;AACH,wBAAgB,6BAA6B,IAAI,aAAa,CAuF7D;AAED;;GAEG;AACH,eAAO,MAAM,uBAAuB,eAAkC,CAAA"}
@@ -1,15 +1,15 @@
1
1
  // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
  /**
4
- * @file Reads GeoNames physical features (seas and undersea terrain, water, landforms, parks and vegetation) from a
5
- * country dump and emits rows that label each feature's name as `venue`.
4
+ * @file Reads GeoNames physical features (seas and undersea terrain, water, landforms, parks and vegetation)
5
+ * and class `S` transit stations from a country dump and emits rows that label each feature's name as `venue`.
6
6
  *
7
- * A search for `Mariana Trench` or `Lake Tahoe, California` asks for a place that has a name and no address.
8
- * The corpus held no such rows before this source (#2897), so the parser had never read a bare physical-feature
9
- * name. Each feature renders bare and with its region where GeoNames records one, and one feature in
7
+ * A search for `Mariana Trench`, `Lake Tahoe, California`, or `Heathrow Airport` asks for a place that has a name
8
+ * and no address. The corpus held no such rows before this source (#2897), so the parser had never read a bare
9
+ * physical-feature name. Each feature renders bare and with its region where GeoNames records one, and one feature in
10
10
  * {@linkcode GEONAMES_FEATURES_WITH_COUNTRY_DIVISOR} also renders with its own country.
11
11
  *
12
- * The dump holds 5,076,239 such features in 16,318 (country, feature code) cells on 2026-11-02, and 991,667 of them
12
+ * The dump holds 5,076,239 physical features in 16,318 (country, feature code) cells on 2026-11-02, and 991,667 of them
13
13
  * are streams (feature code `STM`). A cell keeps at most {@linkcode GEONAMES_FEATURES_PER_CELL} features, chosen by the lowest hash of their
14
14
  * geonameid, so every feature code of every country is represented and no one class dominates.
15
15
  */
@@ -21,6 +21,7 @@ import { compareByScalarValue } from "@mailwoman/core/strings/compare";
21
21
  import { PathBuilder } from "path-ts";
22
22
  import { Globerator } from "spliterator/node/fs";
23
23
  import { GEONAMES_DEFAULT_LICENSE, GEONAMES_MAIN_COLUMNS as COL, loadAdmin1, loadCountries, } from "#adapters/geonames/adapter";
24
+ import { DualRoleBasis, dualRoleKey, dualRoleRowRule, readCapitalSeats, } from "#adapters/wof/admin/json/dual-role";
24
25
  import { SourceRegister } from "#registers";
25
26
  import { AddressRole, SurfaceOrigin } from "#types";
26
27
  /**
@@ -28,10 +29,23 @@ import { AddressRole, SurfaceOrigin } from "#types";
28
29
  */
29
30
  export const GEONAMES_FEATURES_ADAPTER_ID = "geonames-features";
30
31
  /**
31
- * The GeoNames feature classes this adapter reads: undersea (`U`), water (`H`),
32
- * terrain (`T`), parks and areas (`L`) and vegetation (`V`).
32
+ * The GeoNames feature classes this adapter reads unconditionally: undersea (`U`), water (`H`),
33
+ * terrain (`T`), parks and areas (`L`, which includes ports `PRT`) and vegetation (`V`).
33
34
  */
34
35
  export const GEONAMES_FEATURE_CLASSES = new Set(["U", "H", "T", "L", "V"]);
36
+ /**
37
+ * The GeoNames transit feature codes this adapter admits from class `S` (spots/buildings/facilities):
38
+ * airports (`AIRP`), rail stations (`RSTN`), metro stations (`MTRO`), bus stations (`BUSTN`),
39
+ * ports (`PRT`, also present under class `L`), and ferries (`FY`).
40
+ *
41
+ * `packages/mailwoman/tools/training/outcomes/masks.ts` routes these codes to the `transit`
42
+ * outcome reading using `geonames_transit_codes` in `packages/trainer/data/outcome_readings.json`.
43
+ */
44
+ const GEONAMES_TRANSIT_FEATURE_CODES = new Set(["AIRP", "RSTN", "MTRO", "BUSTN", "PRT", "FY"]);
45
+ function isSelectedGeonamesFeature(featureClass, featureCode) {
46
+ return (GEONAMES_FEATURE_CLASSES.has(featureClass) ||
47
+ (featureClass === "S" && GEONAMES_TRANSIT_FEATURE_CODES.has(featureCode)));
48
+ }
35
49
  /**
36
50
  * The most features one (country, feature code) cell contributes.
37
51
  *
@@ -54,21 +68,63 @@ export const GEONAMES_FEATURES_PER_CELL = 25;
54
68
  */
55
69
  export const GEONAMES_FEATURES_WITH_COUNTRY_DIVISOR = 4;
56
70
  /**
57
- * The geonameids each cell keeps: its {@linkcode GEONAMES_FEATURES_PER_CELL} lowest hashes.
71
+ * Historical, abandoned, or destroyed populated-place feature codes skipped
72
+ * when detecting dual-role regions.
73
+ */
74
+ const NON_CURRENT_PPL = new Set(["PPLH", "PPLQ", "PPLW", "PPLCH"]);
75
+ /**
76
+ * GeoNames feature codes for national capitals and admin-1 seats.
58
77
  */
59
- async function keptFeatureIDs(input, country) {
78
+ const ADMIN1_SEAT_CODES = new Set(["PPLC", "PPLA"]);
79
+ /**
80
+ * Scans one GeoNames dump in a single pass to collect:
81
+ * 1. The {@linkcode GEONAMES_FEATURES_PER_CELL} lowest-hashed feature geonameids
82
+ * per `(country, featureCode)` cell.
83
+ * 2. The dual-role admin-1 pairs where a current populated place in `(cc, admin1)`
84
+ * shares the folded name of that admin-1 unit and is either a capital/admin-1 seat
85
+ * or the unit's most populous locality.
86
+ * When a country has no populated-place rows in the dump (as in features-only fixtures),
87
+ * the committed capitals reference decides seats.
88
+ */
89
+ async function scanDump(input, country, admin1, seats) {
60
90
  const cells = new Map();
91
+ const countriesWithPPL = new Set();
92
+ const largestByAdmin1 = new Map();
93
+ const candidates = [];
61
94
  for await (const rec of readUnquotedTSV(input)) {
62
95
  const cls = rec[COL.featureClass] ?? "";
63
- if (!GEONAMES_FEATURE_CLASSES.has(cls))
64
- continue;
96
+ const code = (rec[COL.featureCode] ?? "").trim();
65
97
  const cc = (rec[COL.country] ?? "").trim();
66
98
  if (!cc || (country && cc !== country))
67
99
  continue;
68
100
  const geonameid = (rec[COL.geonameid] ?? "").trim();
69
- if (!geonameid || !(rec[COL.name] ?? "").trim())
101
+ const name = (rec[COL.name] ?? "").trim();
102
+ if (!geonameid || !name)
103
+ continue;
104
+ if (cls === "P" && !NON_CURRENT_PPL.has(code)) {
105
+ countriesWithPPL.add(cc);
106
+ const admin1Code = (rec[COL.admin1] ?? "").trim();
107
+ const admin1Key = `${cc}.${admin1Code}`;
108
+ const regionName = admin1.get(admin1Key);
109
+ if (regionName) {
110
+ const id = Number.parseInt(geonameid, 10) || 0;
111
+ const population = Number.parseInt(rec[COL.population] ?? "0", 10) || 0;
112
+ const prev = largestByAdmin1.get(admin1Key);
113
+ if (population > 0 &&
114
+ (!prev || population > prev.population || (population === prev.population && id < prev.id))) {
115
+ largestByAdmin1.set(admin1Key, { id, population });
116
+ }
117
+ const regionFolded = dualRoleKey(regionName);
118
+ const asciiName = (rec[COL.asciiname] ?? "").trim();
119
+ if (dualRoleKey(name) === regionFolded || (asciiName && dualRoleKey(asciiName) === regionFolded)) {
120
+ const isSeat = ADMIN1_SEAT_CODES.has(code) || seats.has(`${cc}|${regionFolded}`);
121
+ candidates.push({ admin1Key, cc, regionName, localityID: id, isSeat });
122
+ }
123
+ }
124
+ }
125
+ if (!isSelectedGeonamesFeature(cls, code))
70
126
  continue;
71
- const key = `${cc}\t${rec[COL.featureCode] ?? ""}`;
127
+ const key = `${cc}\t${code}`;
72
128
  const kept = cells.get(key) ?? [];
73
129
  const hash = hashFNV1a(geonameid);
74
130
  if (kept.length < GEONAMES_FEATURES_PER_CELL) {
@@ -86,7 +142,42 @@ async function keptFeatureIDs(input, country) {
86
142
  }
87
143
  }
88
144
  }
89
- return new Set([...cells.values()].flatMap((kept) => kept.map((feature) => feature.geonameid)));
145
+ const pairsByRegion = new Map();
146
+ for (const candidate of candidates) {
147
+ const basis = candidate.isSeat
148
+ ? DualRoleBasis.seat
149
+ : largestByAdmin1.get(candidate.admin1Key)?.id === candidate.localityID
150
+ ? DualRoleBasis.largest
151
+ : null;
152
+ if (basis && !pairsByRegion.has(candidate.admin1Key)) {
153
+ pairsByRegion.set(candidate.admin1Key, {
154
+ regionID: 0,
155
+ localityID: candidate.localityID,
156
+ country: candidate.cc,
157
+ name: candidate.regionName,
158
+ basis,
159
+ });
160
+ }
161
+ }
162
+ // Fallback for features-only dumps that omit populated-place rows: check admin1 names against the capitals reference.
163
+ for (const [admin1Key, regionName] of admin1) {
164
+ const cc = admin1Key.split(".")[0] ?? "";
165
+ if (!cc || (country && cc !== country) || countriesWithPPL.has(cc) || pairsByRegion.has(admin1Key))
166
+ continue;
167
+ if (seats.has(`${cc}|${dualRoleKey(regionName)}`)) {
168
+ pairsByRegion.set(admin1Key, {
169
+ regionID: 0,
170
+ localityID: 0,
171
+ country: cc,
172
+ name: regionName,
173
+ basis: DualRoleBasis.seat,
174
+ });
175
+ }
176
+ }
177
+ return {
178
+ kept: new Set([...cells.values()].flatMap((kept) => kept.map((feature) => feature.geonameid))),
179
+ dualRolePairs: [...pairsByRegion.values()],
180
+ };
90
181
  }
91
182
  /**
92
183
  * Creates the GeoNames physical-feature adapter.
@@ -99,7 +190,7 @@ export function createGeonamesFeaturesAdapter() {
99
190
  addressRole: AddressRole.Other,
100
191
  register: SourceRegister.GeoNames,
101
192
  surface: SurfaceOrigin.Rendered,
102
- description: "GeoNames physical features (CC-BY-4.0): seas, undersea terrain, water bodies, landforms, parks and forests, labeled as venue.",
193
+ description: "GeoNames physical and transit features (CC-BY-4.0): seas, undersea terrain, water bodies, landforms, parks, forests, and transit hubs (airports, rail/metro/bus stations, ports, ferries), labeled as venue.",
103
194
  async *rows(opts) {
104
195
  // The input is one dump (`allCountries.txt`) or a directory of country dumps (`US.txt`, `MP.txt`).
105
196
  const input = PathBuilder.from(opts.inputPath);
@@ -112,14 +203,14 @@ export function createGeonamesFeaturesAdapter() {
112
203
  .toSorted(compareByScalarValue)
113
204
  .map((name) => input(name))
114
205
  : [input];
115
- const admin1 = await loadAdmin1(dir);
116
- const countries = await loadCountries(dir);
206
+ const [admin1, countries, seats] = await Promise.all([loadAdmin1(dir), loadCountries(dir), readCapitalSeats()]);
117
207
  let emitted = 0;
118
208
  for (const dump of dumps) {
119
209
  yield* rowsOf(dump);
120
210
  }
121
211
  async function* rowsOf(dump) {
122
- const kept = await keptFeatureIDs(dump, opts.country);
212
+ const { kept, dualRolePairs } = await scanDump(dump, opts.country, admin1, seats);
213
+ const dualRole = dualRoleRowRule(GEONAMES_FEATURES_ADAPTER_ID, dualRolePairs);
123
214
  for await (const rec of readUnquotedTSV(dump)) {
124
215
  if (opts.signal?.aborted)
125
216
  break;
@@ -147,7 +238,7 @@ export function createGeonamesFeaturesAdapter() {
147
238
  const aligned = componentsPresentIn(variant.comp, variant.raw);
148
239
  if (!aligned.venue)
149
240
  continue;
150
- yield {
241
+ const row = {
151
242
  raw: variant.raw,
152
243
  components: aligned,
153
244
  country: cc,
@@ -155,6 +246,9 @@ export function createGeonamesFeaturesAdapter() {
155
246
  source_id: `${GEONAMES_FEATURES_ADAPTER_ID}-${geonameid}-${variant.slot}`,
156
247
  license: GEONAMES_DEFAULT_LICENSE,
157
248
  };
249
+ if (dualRole.drops(row))
250
+ continue;
251
+ yield row;
158
252
  emitted++;
159
253
  }
160
254
  }