@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
@@ -14,6 +14,8 @@ import type { SeededRandom } from "@mailwoman/core/math/random"
14
14
 
15
15
  import { type CJKRecord, labelTokensByFirstSpan, RowRenderer, verifyRecord } from "#cjk/builder"
16
16
  import { intToKanji } from "#cjk/text"
17
+ import type { JPSourceRow } from "#jp/corpus/sources"
18
+ import { splitJPStreet } from "#jp/text"
17
19
 
18
20
  /**
19
21
  * The label set the Japanese corpus is tagged against.
@@ -26,6 +28,17 @@ export const JP_LABEL_SET_NAME = "stage3-jp"
26
28
  */
27
29
  export const JP_CORPUS_SOURCE = "overture-jp"
28
30
 
31
+ /**
32
+ * Register label for bare Japanese chō (`district`) rows emitted so `日本`-initial district
33
+ * names (`日本橋本石町`, `日本橋本町`, `日本橋室町`) aren't misread as `country: 日本` (#2931).
34
+ */
35
+ const JP_BARE_DISTRICT_REGISTER = "bare_district"
36
+
37
+ /**
38
+ * Prefix shared by the Japanese country name (`日本`) and `日本橋`-family chō names (#2931).
39
+ */
40
+ const JP_COUNTRY_PREFIX = "日本"
41
+
29
42
  const COMPACT = /^[0-9]+(?:-[0-9]+)*$/u
30
43
 
31
44
  /**
@@ -185,3 +198,77 @@ export function chooseJPRegister(rng: SeededRandom, options: readonly string[]):
185
198
  export function verifyJPRecord(record: CJKRecord, tagSet: ReadonlySet<string>): void {
186
199
  verifyRecord(record, tagSet, { labelSetName: JP_LABEL_SET_NAME })
187
200
  }
201
+
202
+ /**
203
+ * Renders one bare Japanese chō name (`日本橋本石町`) labeled as a single `district` span (#2931).
204
+ */
205
+ function bareJPDistrictRow(district: string): CJKRecord {
206
+ const renderer = new RowRenderer()
207
+
208
+ renderer.put("district", district)
209
+
210
+ return {
211
+ raw: renderer.raw,
212
+ ...labelTokensByFirstSpan(renderer.raw, renderer.starts, renderer.ends, renderer.tags),
213
+ span_starts: renderer.starts,
214
+ span_ends: renderer.ends,
215
+ span_tags: renderer.tags,
216
+ country: "JP",
217
+ source: JP_CORPUS_SOURCE,
218
+ register: JP_BARE_DISTRICT_REGISTER,
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Renders a chō-only Japanese admin chain (`東京都中央区日本橋本石町`) with no block or house number (#2931).
224
+ */
225
+ function choOnlyJPAdminRow(prefecture: string, municipality: string, district: string): CJKRecord {
226
+ const renderer = new RowRenderer()
227
+
228
+ renderer.put("prefecture", prefecture)
229
+ renderer.put("municipality", municipality)
230
+ renderer.put("district", district)
231
+
232
+ return {
233
+ raw: renderer.raw,
234
+ ...labelTokensByFirstSpan(renderer.raw, renderer.starts, renderer.ends, renderer.tags),
235
+ span_starts: renderer.starts,
236
+ span_ends: renderer.ends,
237
+ span_tags: renderer.tags,
238
+ country: "JP",
239
+ source: JP_CORPUS_SOURCE,
240
+ register: JP_BARE_DISTRICT_REGISTER,
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Collects deduplicated bare-district (`日本橋本石町`) and chō-only admin (`東京都中央区日本橋本石町`)
246
+ * rows from selected JP source rows for districts starting with `日本` (#2931).
247
+ *
248
+ * Consumes no RNG state, preserving exact draw parity for all standard registers.
249
+ */
250
+ export function collectBareJPDistrictRows(rows: readonly JPSourceRow[]): CJKRecord[] {
251
+ const seenBare = new Set<string>()
252
+ const seenAdmin = new Set<string>()
253
+ const records: CJKRecord[] = []
254
+
255
+ for (const [prefecture, municipality, street] of rows) {
256
+ const [district] = splitJPStreet(street)
257
+
258
+ if (!district.startsWith(JP_COUNTRY_PREFIX) || district === JP_COUNTRY_PREFIX) continue
259
+
260
+ if (!seenBare.has(district)) {
261
+ seenBare.add(district)
262
+ records.push(bareJPDistrictRow(district))
263
+ }
264
+
265
+ const adminKey = `${prefecture}\t${municipality}\t${district}`
266
+
267
+ if (!seenAdmin.has(adminKey)) {
268
+ seenAdmin.add(adminKey)
269
+ records.push(choOnlyJPAdminRow(prefecture, municipality, district))
270
+ }
271
+ }
272
+
273
+ return records
274
+ }
@@ -154,7 +154,7 @@ export const poBoxCedexRecipe: CorpusRecipe = {
154
154
  country = "NZ"
155
155
  locale = "en-NZ"
156
156
  } else if (kind === "po-box-us-military") {
157
- const military = synthesizeMilitaryPoBoxRow({ random })
157
+ const military = synthesizeMilitaryPoBoxRow({ random, varyCase: true })
158
158
  const { country: _country, ...components } = military.components
159
159
  rendered = { fmt: "po-box-military", raw: military.raw, components: components as Record<string, string> }
160
160
  country = "US"
@@ -51,15 +51,15 @@ export const AU_LEADERS_CURRENT = ["PO Box", "P.O. Box", "Post Office Box", "GPO
51
51
  /**
52
52
  * Recognized legacy Australian delivery-service leaders.
53
53
  */
54
- export const AU_LEADERS_LEGACY = ["RMB", "RSD", "CMB"]
54
+ export const AU_LEADERS_LEGACY = ["RMB", "RSD", "CMB", "Community Mail Bag"]
55
55
  /**
56
56
  * Common New Zealand delivery-service leaders.
57
57
  */
58
- export const NZ_LEADERS_COMMON = ["PO Box", "Private Bag"]
58
+ export const NZ_LEADERS_COMMON = ["PO Box", "Private Bag", "Private Box"]
59
59
  /**
60
- * Rare New Zealand delivery-service leader.
60
+ * Rare New Zealand delivery-service leaders.
61
61
  */
62
- export const NZ_LEADERS_RARE = ["CMB"]
62
+ export const NZ_LEADERS_RARE = ["CMB", "Response Bag", "Community Mail Box"]
63
63
 
64
64
  /**
65
65
  * Quebec first-letter choices from the Canadian FSA prior.
@@ -231,8 +231,37 @@ export interface ProminentPlaceRow {
231
231
  export const PROMINENT_PLACES_SOURCE = defaultRecipeSource("synth-prominent-places")
232
232
 
233
233
  /**
234
- * The distinct components one place is written with in one shape:
235
- * each second-segment form in each case form.
234
+ * Matches a Great Britain saint-prefixed possessive place name such as `St. Mary's`, `St.Ann's`,
235
+ * `St David's`, or `Saint Luke's`, capturing the possessive name after the saint prefix (#1754).
236
+ */
237
+ const GB_SAINT_POSSESSIVE = /^(?:St\.?|Saint)\s*([A-Z][^,]*'s)$/u
238
+
239
+ /**
240
+ * Written name forms for one place in one shape.
241
+ *
242
+ * Keeps the WOF primary name first.
243
+ * For GB saint-prefixed possessive places in two-part `parent` or `region` shapes
244
+ * (`St. Mary's, Oxford`, `St David's, Pembrokeshire`), also emits the periodless `St <X>'s` and
245
+ * spelled-out `Saint <X>'s` forms so both surfaces and their lowercase forms appear in training (#1754).
246
+ */
247
+ function placeNameForms(tuple: ProminentPlaceTuple, shape: QueryShape): readonly string[] {
248
+ // country-branch: #1754 targets Great Britain saint-prefixed possessive place names.
249
+ if (tuple.country !== "GB" || (shape !== "parent" && shape !== "region")) {
250
+ return [tuple.name]
251
+ }
252
+
253
+ const match = GB_SAINT_POSSESSIVE.exec(tuple.name)
254
+
255
+ if (!match) return [tuple.name]
256
+
257
+ const rest = match[1]!
258
+
259
+ return [...new Set([tuple.name, `St ${rest}`, `Saint ${rest}`])]
260
+ }
261
+
262
+ /**
263
+ * The distinct components one place is written with in one shape: each place-name form
264
+ * and second-segment form in each case form.
236
265
  *
237
266
  * A shape the label policy leaves unwritten, or one the place has no second segment for, has none.
238
267
  */
@@ -245,14 +274,18 @@ function prominentPlaceVariants(
245
274
 
246
275
  if (!tag || !second) return []
247
276
 
248
- return second.forms.flatMap((form) => {
249
- const rendered = renderHierarchy(
250
- second.tag ? { [tag]: tuple.name, [second.tag]: form } : { [tag]: tuple.name },
251
- tuple.country
252
- )
277
+ const names = placeNameForms(tuple, shape)
278
+
279
+ return names.flatMap((name) =>
280
+ second.forms.flatMap((form) => {
281
+ const rendered = renderHierarchy(
282
+ second.tag ? { [tag]: name, [second.tag]: form } : { [tag]: name },
283
+ tuple.country
284
+ )
253
285
 
254
- return rendered ? caseForms(rendered.components) : []
255
- })
286
+ return rendered ? caseForms(rendered.components) : []
287
+ })
288
+ )
256
289
  }
257
290
 
258
291
  /**
@@ -5,9 +5,21 @@
5
5
  * `trailing-region` — the `«locality», «region»[, «country»]` admin tail,
6
6
  * built from real `(locality, region)` WOF ancestor pairs.
7
7
  *
8
- * A tuple's `postcodePlacement` selects where the postcode sits: `leading`
9
- * (the default, so a tuples file written before the field existed is unchanged),
8
+ * A tuple's `postcodePlacement` selects where the postcode sits: `leading`,
10
9
  * `after_locality`, or `after_region`.
10
+ * When absent, placement is inferred from the country's codex layout and postcode format
11
+ * (defaulting to `leading` when unknown, so tuples files written before the field existed are unchanged).
12
+ *
13
+ * For `after_locality` tuples (for example `Barcelona 6001, Venezuela`
14
+ * and `Barcelona 6001, Anzoátegui, Venezuela`), the recipe emits rows both with
15
+ * and without a region, omits synthetic house numbers so the locality-postcode pair
16
+ * is never confused with a street-number tail, and adds anchor-varied contrast
17
+ * rows for non-US four-digit postcode countries (#1821).
18
+ *
19
+ * For `before_locality` countries (`PL`, `CZ`, `DE`, `FR`, `IT`, `ES`, and peers),
20
+ * one tuple in {@linkcode LOCALITY_FIRST_LEADING_MODULUS} (16.7%) renders in locality-first
21
+ * order (`Warszawa 00-002, Poland`, `Praha 100 00, Czechia`, and with-region counterparts)
22
+ * without a synthetic house number (#3646).
11
23
  *
12
24
  * A bare `«region»` form is deliberately absent: teaching it as `region` would fight
13
25
  * the locality/region ambiguity the dominance race arbitrates.
@@ -15,9 +27,16 @@
15
27
  * row begins with the locality and teaches the model that the first segment is the locality.
16
28
  */
17
29
 
30
+ import { formatAddress } from "@mailwoman/codex/address/format"
18
31
  import { lookupCanadianProvince } from "@mailwoman/codex/ca"
19
- import { lookupUSState } from "@mailwoman/codex/us"
32
+ import { ISO2_TO_NAME } from "@mailwoman/codex/country"
33
+ import { lookupUSState, US_STATE_BY_ABBREVIATION } from "@mailwoman/codex/us"
20
34
  import { mulberry32 as makeMulberry32 } from "@mailwoman/core/utils"
35
+ import {
36
+ hasPostcodeForm,
37
+ postcodePlacement as codexPostcodePlacement,
38
+ postcodeSyntaxCountries,
39
+ } from "@mailwoman/postcode/country-formats"
21
40
 
22
41
  import {
23
42
  alignAndWrite,
@@ -30,6 +49,54 @@ import {
30
49
  import { defaultRecipeSource } from "#recipes/sources"
31
50
  import { SurfaceOrigin } from "#types"
32
51
 
52
+ const US_CONTRAST_REGIONS: readonly string[] = Object.values(US_STATE_BY_ABBREVIATION)
53
+ // country-branch: #1821 anchor contrasts test the US country frame independently of the region anchor.
54
+ const US_COUNTRY_NAME = ISO2_TO_NAME.get("US") ?? "United States"
55
+
56
+ /**
57
+ * Deterministic cadence (1 in 6 = 16.7%) for rendering `before_locality` countries in
58
+ * locality-first `<locality> <postcode>[, <region>], <country>` order (#3646).
59
+ */
60
+ const LOCALITY_FIRST_LEADING_MODULUS = 6
61
+
62
+ /**
63
+ * Infers a country's postcode placement inside the admin tail from its codex
64
+ * address layout and libaddressinput postcode placement, defaulting to `leading`
65
+ * when the country is unknown or prints postcodes before the locality.
66
+ */
67
+ function inferPostcodePlacement(cc: string): PostcodePlacement {
68
+ const country = cc.trim().toUpperCase()
69
+
70
+ if (!country || codexPostcodePlacement(country) !== "after_locality") return "leading"
71
+
72
+ const probe = formatAddress({ locality: "__LOC__", region: "__REG__", postcode: "__PC__" }, country, {
73
+ singleLine: true,
74
+ })
75
+
76
+ if (probe) {
77
+ const regionAt = probe.indexOf("__REG__")
78
+ const postcodeAt = probe.indexOf("__PC__")
79
+
80
+ if (regionAt !== -1 && postcodeAt !== -1 && regionAt < postcodeAt) {
81
+ return "after_region"
82
+ }
83
+ }
84
+
85
+ return "after_locality"
86
+ }
87
+
88
+ /**
89
+ * Non-US countries whose postcode syntax accepts a four-digit numeric postcode,
90
+ * derived from `@mailwoman/postcode` rather than a static country list.
91
+ */
92
+ function nonUSFourDigitPostcodeCountries(): readonly string[] {
93
+ // country-branch: #1821 targets non-US four-digit postcode countries whose locality-postcode
94
+ // tails collapse to street + house_number outside the US country frame.
95
+ return postcodeSyntaxCountries().filter((cc) => cc !== "US" && hasPostcodeForm("6001", cc))
96
+ }
97
+
98
+ const FOUR_DIGIT_NON_US_COUNTRIES: ReadonlySet<string> = new Set(nonUSFourDigitPostcodeCountries())
99
+
33
100
  /**
34
101
  * The region code an address line in this country writes, or `null` where the region name is written out.
35
102
  *
@@ -78,28 +145,65 @@ export const trailingRegionRecipe: CorpusRecipe = {
78
145
  const region = String(t.region ?? "").trim()
79
146
  const country = String(t.country ?? "").trim()
80
147
  const dependentLocality = String(t.dependentLocality ?? "").trim()
148
+ const postcode = String(t.postcode ?? "").trim()
149
+
150
+ const cc = String(t.cc ?? "")
151
+ .trim()
152
+ .toUpperCase()
153
+
154
+ const placement = (t.postcodePlacement as PostcodePlacement | undefined) ?? inferPostcodePlacement(cc)
155
+
156
+ const allowRegionlessAfterLocality = placement === "after_locality" && postcode.length > 0 && country.length > 0
81
157
 
82
158
  // A pair whose region equals its locality provides no signal about the boundary this recipe teaches.
83
- if (!locality || !region || locality === region) {
159
+ // Region-less tuples are admitted only for `after_locality` postcode tails with a country
160
+ // (e.g. `Barcelona 6001, Venezuela`), where the postcode separates locality from country.
161
+ if (!locality || (region && locality === region) || (!region && !allowRegionlessAfterLocality)) {
84
162
  skipped++
85
163
 
86
164
  continue
87
165
  }
88
166
 
89
- const withCountry = read % 2 === 0 && country.length > 0
90
- const postcode = String(t.postcode ?? "").trim()
167
+ const withCountry = !region ? true : read % 2 === 0 && country.length > 0
168
+
169
+ // #3646: emit a deterministic 16.7% (1-in-6) locality-first variant for `before_locality`
170
+ // countries (`Warszawa 00-002, Poland`, `Praha 100 00, Czechia`), alternating
171
+ // regionless and with-region tails without synthetic house numbers.
172
+ const localityFirstVariant =
173
+ placement === "leading" &&
174
+ postcode.length > 0 &&
175
+ country.length > 0 &&
176
+ codexPostcodePlacement(cc) === "before_locality" &&
177
+ read % LOCALITY_FIRST_LEADING_MODULUS === 0
178
+
179
+ const effectivePlacement: PostcodePlacement = localityFirstVariant ? "after_locality" : placement
91
180
 
92
- // The house number is the second trigger: the postcode discards the region,
93
- // the house number then displaces the locality.
94
- const withHouseNumber = postcode.length > 0 && read % 4 === 1
181
+ // For `after_locality` rows with a region and country, alternate between
182
+ // `«locality» «postcode», «region», «country»` and `«locality» «postcode», «country»`.
183
+ // For locality-first variants of `before_locality` countries, alternate the same way
184
+ // across every second hit (`read % 12 === 6` regionless, `read % 12 === 0` with region).
185
+ const includeRegion =
186
+ Boolean(region) &&
187
+ !(allowRegionlessAfterLocality && withCountry && read % 4 === 0) &&
188
+ !(localityFirstVariant && read % (LOCALITY_FIRST_LEADING_MODULUS * 2) !== 0)
189
+
190
+ // The house number is the second trigger for `leading` / `after_region` rows:
191
+ // the postcode discards the region, and the house number then displaces the locality.
192
+ // `after_locality` rows (including locality-first variants) omit synthetic house numbers
193
+ // so `«locality» «postcode»` never co-occurs with a house number on a streetless tail.
194
+ const withHouseNumber = postcode.length > 0 && effectivePlacement !== "after_locality" && read % 4 === 1
95
195
  const houseNumber = withHouseNumber ? String((read % 97) + 1) : ""
96
196
 
97
- const components: Record<string, string> = { locality, region }
197
+ const components: Record<string, string> = { locality }
98
198
 
99
199
  if (dependentLocality && dependentLocality !== locality) {
100
200
  components["dependent_locality"] = dependentLocality
101
201
  }
102
202
 
203
+ if (includeRegion) {
204
+ components["region"] = region
205
+ }
206
+
103
207
  if (withCountry) {
104
208
  components["country"] = country
105
209
  }
@@ -112,27 +216,29 @@ export const trailingRegionRecipe: CorpusRecipe = {
112
216
  components["house_number"] = houseNumber
113
217
  }
114
218
 
115
- const placement = (t.postcodePlacement as PostcodePlacement | undefined) ?? "leading"
116
- const bareLocality = postcode && placement === "after_locality" ? `${locality} ${postcode}` : locality
219
+ const bareLocality = postcode && effectivePlacement === "after_locality" ? `${locality} ${postcode}` : locality
117
220
 
118
221
  const localitySegment = components["dependent_locality"] ? `${dependentLocality}, ${bareLocality}` : bareLocality
119
222
 
120
223
  // The code alternates with the region name rather than replacing it:
121
224
  // both forms are posted and the resolver matches on the name.
122
- const regionCode = read % 3 === 2 ? regionCodeSurface(String(t.cc ?? ""), region) : null
225
+ const regionCode = includeRegion && read % 3 === 2 ? regionCodeSurface(cc, region) : null
123
226
  const regionSurface = regionCode ?? region
124
227
 
125
- if (regionCode) {
228
+ if (includeRegion && regionCode) {
126
229
  components["region"] = regionCode
127
230
  }
128
231
 
129
- const regionSegment = postcode && placement === "after_region" ? `${regionSurface} ${postcode}` : regionSurface
232
+ const regionSegment =
233
+ postcode && effectivePlacement === "after_region" ? `${regionSurface} ${postcode}` : regionSurface
130
234
 
131
- const tail = withCountry
132
- ? `${localitySegment}, ${regionSegment}, ${country}`
133
- : `${localitySegment}, ${regionSegment}`
235
+ const tail = includeRegion
236
+ ? withCountry
237
+ ? `${localitySegment}, ${regionSegment}, ${country}`
238
+ : `${localitySegment}, ${regionSegment}`
239
+ : `${localitySegment}, ${country}`
134
240
 
135
- const leadingPostcode = postcode && placement === "leading" ? `${postcode} ` : ""
241
+ const leadingPostcode = postcode && effectivePlacement === "leading" ? `${postcode} ` : ""
136
242
  const head = withHouseNumber ? `${houseNumber}, ${leadingPostcode}` : leadingPostcode
137
243
  const raw = `${head}${tail}`
138
244
  // A distinct source for the structured rows: the sampler buckets by `source`,
@@ -143,7 +249,7 @@ export const trailingRegionRecipe: CorpusRecipe = {
143
249
  const canonical = {
144
250
  raw,
145
251
  components,
146
- country: String(t.cc ?? "").trim() || "und",
252
+ country: cc || "und",
147
253
  locale: String(t.locale ?? "und"),
148
254
  source: sourceLabel,
149
255
  source_id,
@@ -163,6 +269,60 @@ export const trailingRegionRecipe: CorpusRecipe = {
163
269
  } else {
164
270
  skipped++
165
271
  }
272
+
273
+ // #1821 anchor contrasts: US competence on `«locality» «postcode», «region», «country»`
274
+ // requires both a US region and `United States`.
275
+ // These contrast pairs vary each anchor independently so neither anchor by
276
+ // itself decides the locality-postcode boundary.
277
+ if (
278
+ placement === "after_locality" &&
279
+ includeRegion &&
280
+ withCountry &&
281
+ read % 8 === 2 &&
282
+ FOUR_DIGIT_NON_US_COUNTRIES.has(cc) &&
283
+ /^\d{4}$/u.test(postcode)
284
+ ) {
285
+ const usRegion = US_CONTRAST_REGIONS[read % US_CONTRAST_REGIONS.length]!
286
+
287
+ const contrastRows: Array<{ suffix: string; regionValue: string; countryValue: string }> = [
288
+ { suffix: "contrast-us-region", regionValue: usRegion, countryValue: country },
289
+ { suffix: "contrast-us-country", regionValue: regionSurface, countryValue: US_COUNTRY_NAME },
290
+ ]
291
+
292
+ for (const contrast of contrastRows) {
293
+ const contrastComponents: Record<string, string> = {
294
+ locality,
295
+ postcode,
296
+ region: contrast.regionValue,
297
+ country: contrast.countryValue,
298
+ }
299
+
300
+ if (components["dependent_locality"]) {
301
+ contrastComponents["dependent_locality"] = components["dependent_locality"]
302
+ }
303
+
304
+ const contrastCanonical = {
305
+ raw: `${localitySegment}, ${contrast.regionValue}, ${contrast.countryValue}`,
306
+ components: contrastComponents,
307
+ country: cc,
308
+ locale: String(t.locale ?? "und"),
309
+ source: sourceLabel,
310
+ source_id: recipeSourceID(sourceLabel, { ...contrastComponents, v: `${read}-${contrast.suffix}` }),
311
+ license: canonical.license,
312
+ }
313
+
314
+ if (
315
+ alignAndWrite(write, contrastCanonical, `trailing-region:${contrast.suffix}`, {
316
+ ...TRAILING_REGION_PROVENANCE,
317
+ baseSourceID: t.sourceID ?? null,
318
+ })
319
+ ) {
320
+ emitted++
321
+ } else {
322
+ skipped++
323
+ }
324
+ }
325
+ }
166
326
  }
167
327
 
168
328
  return { read, emitted, skipped }
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { ComponentDict } from "@mailwoman/codex/address/render"
10
10
  import { countryCodeForTable } from "@mailwoman/codex/country"
11
+ import { US_MILITARY_POST_OFFICE_CODES, US_MILITARY_UNIT_DESIGNATORS } from "@mailwoman/codex/us"
11
12
  import { sample } from "@mailwoman/core/math/random"
12
13
 
13
14
  import { formatCorpusRow } from "#surfaces/corpus-row"
@@ -69,11 +70,19 @@ export const PO_BOX_LOCALE_TEMPLATES: ReadonlyArray<LocaleTemplate> = [
69
70
  },
70
71
  {
71
72
  locale: "en-AU",
72
- leaders: ["PO Box", "P.O. Box", "Post Office Box", "GPO Box", "Locked Bag"],
73
+ leaders: ["PO Box", "P.O. Box", "Post Office Box", "GPO Box", "Locked Bag", "Private Bag", "Community Mail Bag"],
73
74
  },
74
75
  {
75
76
  locale: "en-NZ",
76
- leaders: ["PO Box", "P.O. Box", "Post Office Box", "Private Bag", "Private Box"],
77
+ leaders: [
78
+ "PO Box",
79
+ "P.O. Box",
80
+ "Post Office Box",
81
+ "Private Bag",
82
+ "Private Box",
83
+ "Response Bag",
84
+ "Community Mail Box",
85
+ ],
77
86
  },
78
87
  {
79
88
  locale: "fr-FR",
@@ -157,6 +166,13 @@ export interface PoBoxSynthesisOpts {
157
166
  * @defaultValue `0`
158
167
  */
159
168
  pmbRatio?: number
169
+ /**
170
+ * Vary casing of US military PO-box lines across title, uppercase (`UNIT 2050 BOX 4190`),
171
+ * and lowercase (`psc 802 box 74, apo ae 09499`).
172
+ *
173
+ * @defaultValue `false`
174
+ */
175
+ varyCase?: boolean
160
176
  }
161
177
 
162
178
  function defaultPickNumber(random: () => number): string {
@@ -237,13 +253,14 @@ export function synthesizePoBoxRow(
237
253
  }
238
254
  }
239
255
 
240
- const MIL_UNITS: ReadonlyArray<{ code: string; boxRequired: boolean }> = [
241
- { code: "PSC", boxRequired: true },
242
- { code: "CMR", boxRequired: true },
243
- { code: "Unit", boxRequired: false },
244
- ]
256
+ const MIL_UNITS: ReadonlyArray<{ code: string; boxRequired: boolean }> = US_MILITARY_UNIT_DESIGNATORS.map(
257
+ ({ code, requiresBox }) => ({
258
+ code: code === "UNIT" ? "Unit" : code,
259
+ boxRequired: requiresBox,
260
+ })
261
+ )
245
262
 
246
- const MIL_PO_CODES = ["APO", "FPO", "DPO"] as const
263
+ const MIL_PO_CODES: ReadonlyArray<string> = US_MILITARY_POST_OFFICE_CODES.map(({ code }) => code)
247
264
 
248
265
  // Each armed-forces region has its own ZIP range.
249
266
  const MIL_REGION_ZIP: ReadonlyArray<{ region: string; zip: (r: () => number) => string }> = [
@@ -263,11 +280,33 @@ export function synthesizeMilitaryPoBoxRow(opts: PoBoxSynthesisOpts = {}): Synth
263
280
  const random = opts.random ?? Math.random
264
281
  const unit = sample(MIL_UNITS, random)
265
282
  const unitID = String(1 + Math.floor(random() * 9999))
266
- const { region, zip } = sample(MIL_REGION_ZIP, random)
283
+ const { region: baseRegion, zip } = sample(MIL_REGION_ZIP, random)
267
284
  const zipStr = zip(random)
268
- const po = sample(MIL_PO_CODES, random)
269
- const hasBox = unit.boxRequired || random() < 0.5
270
- const unitLine = hasBox ? `${unit.code} ${unitID} Box ${1 + Math.floor(random() * 9999)}` : `${unit.code} ${unitID}`
285
+ const basePo = sample(MIL_PO_CODES, random)
286
+ const hasBox = unit.boxRequired || random() < 0.75
287
+ const rawBoxNumber = 1 + Math.floor(random() * 9999)
288
+
289
+ const boxNumber =
290
+ rawBoxNumber < 1000 && random() < 0.15 ? String(rawBoxNumber).padStart(4, "0") : String(rawBoxNumber)
291
+
292
+ const baseUnitLine = hasBox ? `${unit.code} ${unitID} Box ${boxNumber}` : `${unit.code} ${unitID}`
293
+
294
+ let unitLine = baseUnitLine
295
+ let po = basePo
296
+ let region = baseRegion
297
+
298
+ if (opts.varyCase) {
299
+ const caseDraw = random()
300
+
301
+ if (caseDraw < 0.2) {
302
+ unitLine = baseUnitLine.toUpperCase()
303
+ } else if (caseDraw < 0.35) {
304
+ unitLine = baseUnitLine.toLowerCase()
305
+ po = basePo.toLowerCase()
306
+ region = baseRegion.toLowerCase()
307
+ }
308
+ }
309
+
271
310
  const raw = `${unitLine}, ${po} ${region} ${zipStr}`
272
311
 
273
312
  return {
@@ -31,6 +31,9 @@ export interface RecipeRow {
31
31
  components?: Partial<Record<string, string>>
32
32
  labels?: string[]
33
33
  tokens?: string[]
34
+ span_tags?: string[]
35
+ span_starts?: number[]
36
+ span_ends?: number[]
34
37
  }
35
38
 
36
39
  /**