@mailwoman/corpus 12.1.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 (55) hide show
  1. package/data/holdout/evaluation-groups.v0.9.3.json +224169 -0
  2. package/data/training-configs/v9.3.0-bytestem-global-v093-s42.yaml +746 -0
  3. package/data/training-manifests/v0.9.3-compact.effective.json +2660 -0
  4. package/data/training-manifests/v0.9.3-compact.json +9648 -0
  5. package/lib/adapters/geonames/features/adapter.ts +135 -10
  6. package/lib/adapters/wof/admin/json/dual-role.ts +46 -21
  7. package/lib/build/schema-invariants.ts +447 -0
  8. package/lib/jp/corpus/assemble.ts +20 -1
  9. package/lib/jp/corpus/rows.ts +87 -0
  10. package/lib/recipes/prominent/places.ts +42 -9
  11. package/lib/recipes/trailing-region.ts +37 -7
  12. package/lib/tools/fetch/wikidata/vital-places/classify.ts +23 -7
  13. package/lib/tools/fetch/wikidata/vital-places/render.ts +57 -7
  14. package/lib/training/config/schema.ts +3 -0
  15. package/lib/us/street-unit.ts +14 -1
  16. package/out/adapters/geonames/features/adapter.d.ts.map +1 -1
  17. package/out/adapters/geonames/features/adapter.js +90 -10
  18. package/out/adapters/geonames/features/adapter.js.map +1 -1
  19. package/out/adapters/wof/admin/json/dual-role.d.ts +8 -3
  20. package/out/adapters/wof/admin/json/dual-role.d.ts.map +1 -1
  21. package/out/adapters/wof/admin/json/dual-role.js +40 -19
  22. package/out/adapters/wof/admin/json/dual-role.js.map +1 -1
  23. package/out/build/schema-invariants.d.ts +101 -0
  24. package/out/build/schema-invariants.d.ts.map +1 -0
  25. package/out/build/schema-invariants.js +302 -0
  26. package/out/build/schema-invariants.js.map +1 -0
  27. package/out/jp/corpus/assemble.d.ts.map +1 -1
  28. package/out/jp/corpus/assemble.js +14 -2
  29. package/out/jp/corpus/assemble.js.map +1 -1
  30. package/out/jp/corpus/rows.d.ts +8 -0
  31. package/out/jp/corpus/rows.d.ts.map +1 -1
  32. package/out/jp/corpus/rows.js +72 -0
  33. package/out/jp/corpus/rows.js.map +1 -1
  34. package/out/recipes/prominent/places.d.ts.map +1 -1
  35. package/out/recipes/prominent/places.js +30 -5
  36. package/out/recipes/prominent/places.js.map +1 -1
  37. package/out/recipes/trailing-region.d.ts.map +1 -1
  38. package/out/recipes/trailing-region.js +30 -7
  39. package/out/recipes/trailing-region.js.map +1 -1
  40. package/out/tools/fetch/wikidata/vital-places/classify.d.ts +12 -2
  41. package/out/tools/fetch/wikidata/vital-places/classify.d.ts.map +1 -1
  42. package/out/tools/fetch/wikidata/vital-places/classify.js +19 -7
  43. package/out/tools/fetch/wikidata/vital-places/classify.js.map +1 -1
  44. package/out/tools/fetch/wikidata/vital-places/render.d.ts +9 -5
  45. package/out/tools/fetch/wikidata/vital-places/render.d.ts.map +1 -1
  46. package/out/tools/fetch/wikidata/vital-places/render.js +44 -7
  47. package/out/tools/fetch/wikidata/vital-places/render.js.map +1 -1
  48. package/out/training/config/schema.d.ts +21 -0
  49. package/out/training/config/schema.d.ts.map +1 -1
  50. package/out/training/config/schema.js +3 -0
  51. package/out/training/config/schema.js.map +1 -1
  52. package/out/us/street-unit.d.ts.map +1 -1
  53. package/out/us/street-unit.js +11 -1
  54. package/out/us/street-unit.js.map +1 -1
  55. package/package.json +19 -19
@@ -0,0 +1,447 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file Pre-training corpus schema-invariant audit over a built or assembled parquet manifest.
6
+ *
7
+ * Catches stale adapter outputs before a training launch bills GPU hours.
8
+ * Each invariant scans the parquet files a manifest lists through DuckDB, reports exact per-source
9
+ * denominators and violation counts, and confirms concrete failing sample rows with UTF-16 span slicing.
10
+ *
11
+ * A missing manifest, an empty file list, a missing parquet file, or an unreadable parquet file throws
12
+ * rather than reporting zero violations.
13
+ */
14
+
15
+ import { thoroughfareClassOf } from "@mailwoman/codex/labels/street/thoroughfare-classes"
16
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
17
+ import { isFile } from "@mailwoman/core/fs/readers/stat"
18
+ import { foldNFKCWhitespace } from "@mailwoman/normalize/fold"
19
+ import { dirname, type PathBuilderLike, resolvePath } from "path-ts"
20
+
21
+ import { PARQUET_MANIFEST_FILE } from "#build/holdout-check"
22
+ import { type DuckDBLimits, escapeSQLString, openDuckDB } from "#parquet/duckdb"
23
+ import { componentAtIndexSQL } from "#parquet/span-sql"
24
+ import { baseManifestFiles, localManifestFilePath } from "#tools/overlay/manifest"
25
+
26
+ /**
27
+ * Route and thoroughfare words disallowed in a US `street_prefix` span.
28
+ * Supplements {@link thoroughfareClassOf} (locale `"us"`).
29
+ *
30
+ * Under USPS Publication 28 and `SCHEMA.mdx`, a US `street_prefix` holds only a pre-directional
31
+ * or positional pre-modifier (`N`, `SW`, `North`, `Upper`, `Old`).
32
+ * Numbered-route words and thoroughfare types belong inside `street` or `street_suffix`.
33
+ */
34
+ export const US_STREET_PREFIX_DISALLOWED_WORDS: ReadonlySet<string> = new Set([
35
+ "alternate",
36
+ "alt",
37
+ "bus",
38
+ "business",
39
+ "byp",
40
+ "bypass",
41
+ "calle",
42
+ "corte",
43
+ "county",
44
+ "dr",
45
+ "drive",
46
+ "farm",
47
+ "fm",
48
+ "interstate",
49
+ "loop",
50
+ "market",
51
+ "paseo",
52
+ "piazza",
53
+ "placita",
54
+ "plaza",
55
+ "ranch",
56
+ "rm",
57
+ "spur",
58
+ "sr",
59
+ "state",
60
+ "tpke",
61
+ "trace",
62
+ "trail",
63
+ "trl",
64
+ "turnpike",
65
+ "us",
66
+ "via",
67
+ "way",
68
+ ])
69
+
70
+ /**
71
+ * One concrete row violating a corpus schema invariant, with exact UTF-16 span substrings.
72
+ */
73
+ export interface SchemaInvariantSample {
74
+ source_id: string
75
+ source: string
76
+ raw: string
77
+ street_prefix: string
78
+ street: string | null
79
+ offending_token: string
80
+ }
81
+
82
+ /**
83
+ * Frequency of one offending `street_prefix` string inside a failing source.
84
+ */
85
+ export interface SchemaInvariantPrefixCount {
86
+ prefix: string
87
+ count: number
88
+ offending_token: string
89
+ }
90
+
91
+ /**
92
+ * Measured denominator, violation count, top offending values, and sample rows for one source.
93
+ */
94
+ export interface SchemaInvariantSourceReport {
95
+ us_rows: number
96
+ checked_rows: number
97
+ violation_rows: number
98
+ violation_rate: number
99
+ top_prefixes: SchemaInvariantPrefixCount[]
100
+ samples: SchemaInvariantSample[]
101
+ }
102
+
103
+ /**
104
+ * Outcome of one schema invariant across all scanned sources.
105
+ */
106
+ export interface SchemaInvariantResult {
107
+ id: "us_street_prefix_directional_only"
108
+ status: "pass" | "fail"
109
+ total_us_rows: number
110
+ total_checked_rows: number
111
+ violation_rows: number
112
+ violation_rate: number
113
+ by_source: Record<string, SchemaInvariantSourceReport>
114
+ }
115
+
116
+ /**
117
+ * Complete corpus schema-invariant audit report for one manifest.
118
+ */
119
+ export interface SchemaInvariantAuditReport {
120
+ corpus_dir: string
121
+ manifest_path: string
122
+ files_scanned: number
123
+ sources_filter: string[] | null
124
+ status: "pass" | "fail"
125
+ invariants: SchemaInvariantResult[]
126
+ }
127
+
128
+ /**
129
+ * Options for {@linkcode auditCorpusSchemaInvariants}.
130
+ */
131
+ export interface SchemaInvariantAuditOptions {
132
+ corpusDir: PathBuilderLike
133
+ manifestPath?: PathBuilderLike
134
+ /**
135
+ * Optional source filter.
136
+ *
137
+ * An empty collection throws rather than producing a vacuous pass.
138
+ */
139
+ sources?: readonly string[] | ReadonlySet<string> | null
140
+ sampleLimit?: number
141
+ topPrefixLimit?: number
142
+ limits?: DuckDBLimits
143
+ }
144
+
145
+ /**
146
+ * Returns the first thoroughfare or route token in a US `street_prefix` span, or `null`.
147
+ *
148
+ * Removes periods before tokenizing so `U.S.` folds to `us` and `N.` folds to `n`.
149
+ *
150
+ * @public
151
+ */
152
+ export function findDisallowedUSStreetPrefixToken(prefix: string): string | null {
153
+ const folded = foldNFKCWhitespace(prefix).replaceAll(".", "")
154
+
155
+ if (!folded) return null
156
+
157
+ const tokens = folded.split(/[^\p{L}\p{N}]+/u).filter((token) => token.length > 0)
158
+
159
+ for (const token of tokens) {
160
+ if (thoroughfareClassOf(token, "us") != null || US_STREET_PREFIX_DISALLOWED_WORDS.has(token)) {
161
+ return token
162
+ }
163
+ }
164
+
165
+ return null
166
+ }
167
+
168
+ function sqlQuoted(value: string): string {
169
+ return `'${escapeSQLString(value)}'`
170
+ }
171
+
172
+ function toStringArray(value: unknown): string[] {
173
+ if (Array.isArray(value)) return value.map((entry) => String(entry))
174
+
175
+ if (value && typeof value === "object" && "items" in value) {
176
+ const items = (value as { items?: unknown }).items
177
+
178
+ if (Array.isArray(items)) return items.map((entry) => String(entry))
179
+ }
180
+
181
+ return []
182
+ }
183
+
184
+ function toNumberArray(value: unknown): number[] {
185
+ if (Array.isArray(value)) return value.map((entry) => Number(entry))
186
+
187
+ if (value && typeof value === "object" && "items" in value) {
188
+ const items = (value as { items?: unknown }).items
189
+
190
+ if (Array.isArray(items)) return items.map((entry) => Number(entry))
191
+ }
192
+
193
+ return []
194
+ }
195
+
196
+ /**
197
+ * Maximum number of missing parquet paths printed inline in an audit refusal error.
198
+ */
199
+ const MAX_REPORTED_MISSING_PATHS = 5
200
+
201
+ function sliceSpanUTF16(raw: string, tags: string[], starts: number[], ends: number[], target: string): string | null {
202
+ const index = tags.indexOf(target)
203
+
204
+ if (index === -1) return null
205
+
206
+ const start = starts[index]
207
+ const end = ends[index]
208
+
209
+ if (typeof start !== "number" || typeof end !== "number") return null
210
+
211
+ return raw.slice(start, end)
212
+ }
213
+
214
+ /**
215
+ * Audits a corpus manifest's parquet files for adapter schema invariants before training.
216
+ *
217
+ * Currently enforces `us_street_prefix_directional_only`: every `US` row's `street_prefix` span
218
+ * must hold only directional or positional pre-modifiers, never thoroughfare types or route words.
219
+ * Non-US rows are excluded because Romance conventions place thoroughfare types
220
+ * (`Rue`, `Via`, `Calle`) in `street_prefix`.
221
+ *
222
+ * @throws When the manifest is missing or lists no files, when any listed parquet file
223
+ * is missing or unreadable, or when `sources` is explicitly empty.
224
+ */
225
+ export async function auditCorpusSchemaInvariants(
226
+ options: SchemaInvariantAuditOptions
227
+ ): Promise<SchemaInvariantAuditReport> {
228
+ const corpusDir = options.corpusDir.toString()
229
+ const manifestPath = (options.manifestPath ?? resolvePath(corpusDir, PARQUET_MANIFEST_FILE)).toString()
230
+ const sampleLimit = options.sampleLimit ?? 5
231
+ const topPrefixLimit = options.topPrefixLimit ?? 15
232
+
233
+ if (!(await isFile(manifestPath))) {
234
+ throw new Error(`Corpus schema-invariant audit requires manifest at ${manifestPath}, but the file is missing.`)
235
+ }
236
+
237
+ let sourcesFilter: string[] | null = null
238
+
239
+ if (options.sources != null) {
240
+ sourcesFilter = [...new Set(options.sources)].toSorted()
241
+
242
+ if (!sourcesFilter.length) {
243
+ throw new Error("Corpus schema-invariant audit received an empty sources filter.")
244
+ }
245
+ }
246
+
247
+ const manifest = await readLocalJSONFile<object>(manifestPath)
248
+ const entries = baseManifestFiles(manifest)
249
+
250
+ if (!entries.length) {
251
+ throw new Error(`Corpus manifest ${manifestPath} lists zero parquet files.`)
252
+ }
253
+
254
+ const manifestDir = dirname(manifestPath)
255
+ const parquetPaths: string[] = []
256
+ const missingPaths: string[] = []
257
+
258
+ for (const entry of entries) {
259
+ const resolved = resolvePath(manifestDir, localManifestFilePath(entry.path)).toString()
260
+
261
+ if (await isFile(resolved)) {
262
+ parquetPaths.push(resolved)
263
+ } else {
264
+ missingPaths.push(resolved)
265
+ }
266
+ }
267
+
268
+ if (missingPaths.length) {
269
+ const preview = missingPaths.slice(0, MAX_REPORTED_MISSING_PATHS).join(", ")
270
+
271
+ const extra =
272
+ missingPaths.length > MAX_REPORTED_MISSING_PATHS
273
+ ? ` (+${missingPaths.length - MAX_REPORTED_MISSING_PATHS} more)`
274
+ : ""
275
+
276
+ throw new Error(
277
+ `Corpus schema-invariant audit cannot read ${missingPaths.length} missing parquet file(s) from ${manifestPath}: ${preview}${extra}`
278
+ )
279
+ }
280
+
281
+ const fileListSQL = parquetPaths.map(sqlQuoted).join(", ")
282
+ const sourcePredicate = sourcesFilter ? ` AND source IN (${sourcesFilter.map(sqlQuoted).join(", ")})` : ""
283
+
284
+ using db = await openDuckDB(options.limits)
285
+
286
+ const denominatorResult = await db.runAndReadAll(
287
+ `SELECT source, ` +
288
+ `count(*)::BIGINT AS us_rows, ` +
289
+ `count(*) FILTER (WHERE list_contains(span_tags, 'street_prefix'))::BIGINT AS checked_rows ` +
290
+ `FROM read_parquet([${fileListSQL}], union_by_name=true) ` +
291
+ `WHERE country = 'US'${sourcePredicate} ` +
292
+ `GROUP BY source ORDER BY source`
293
+ )
294
+
295
+ const bySource = new Map<string, SchemaInvariantSourceReport>()
296
+ let totalUSRows = 0
297
+ let totalCheckedRows = 0
298
+
299
+ for (const row of denominatorResult.getRowObjects()) {
300
+ const source = String(row.source)
301
+ const usRows = Number(row.us_rows)
302
+ const checkedRows = Number(row.checked_rows)
303
+
304
+ totalUSRows += usRows
305
+ totalCheckedRows += checkedRows
306
+
307
+ bySource.set(source, {
308
+ us_rows: usRows,
309
+ checked_rows: checkedRows,
310
+ violation_rows: 0,
311
+ violation_rate: 0,
312
+ top_prefixes: [],
313
+ samples: [],
314
+ })
315
+ }
316
+
317
+ const prefixExpr = componentAtIndexSQL("idx", "raw")
318
+
319
+ const prefixResult = await db.runAndReadAll(
320
+ `WITH us_prefixed AS (` +
321
+ `SELECT source, raw, span_starts, span_ends, list_position(span_tags, 'street_prefix') AS idx ` +
322
+ `FROM read_parquet([${fileListSQL}], union_by_name=true) ` +
323
+ `WHERE country = 'US' AND list_contains(span_tags, 'street_prefix')${sourcePredicate}` +
324
+ `) ` +
325
+ `SELECT source, trim(${prefixExpr}) AS prefix, count(*)::BIGINT AS n ` +
326
+ `FROM us_prefixed GROUP BY source, prefix`
327
+ )
328
+
329
+ const offendingBySource = new Map<string, Map<string, { count: number; token: string }>>()
330
+ const rawOffendingPrefixesBySource = new Map<string, Set<string>>()
331
+
332
+ for (const row of prefixResult.getRowObjects()) {
333
+ const source = String(row.source)
334
+ const rawPrefix = String(row.prefix ?? "")
335
+ const count = Number(row.n)
336
+ const offendingToken = findDisallowedUSStreetPrefixToken(rawPrefix)
337
+
338
+ if (!offendingToken) continue
339
+
340
+ const foldedKey = foldNFKCWhitespace(rawPrefix)
341
+ let sourceMap = offendingBySource.get(source)
342
+
343
+ if (!sourceMap) {
344
+ sourceMap = new Map()
345
+ offendingBySource.set(source, sourceMap)
346
+ }
347
+
348
+ const prev = sourceMap.get(foldedKey)
349
+
350
+ sourceMap.set(foldedKey, { count: (prev?.count ?? 0) + count, token: offendingToken })
351
+
352
+ let rawSet = rawOffendingPrefixesBySource.get(source)
353
+
354
+ if (!rawSet) {
355
+ rawSet = new Set()
356
+ rawOffendingPrefixesBySource.set(source, rawSet)
357
+ }
358
+
359
+ rawSet.add(rawPrefix)
360
+ }
361
+
362
+ let totalViolations = 0
363
+
364
+ for (const [source, sourceMap] of offendingBySource) {
365
+ const entry = bySource.get(source)
366
+
367
+ if (!entry) continue
368
+
369
+ const sorted = [...sourceMap.entries()]
370
+ .map(([prefix, info]) => ({ prefix, count: info.count, offending_token: info.token }))
371
+ .toSorted((a, b) => b.count - a.count || a.prefix.localeCompare(b.prefix))
372
+
373
+ const violations = sorted.reduce((sum, item) => sum + item.count, 0)
374
+
375
+ entry.violation_rows = violations
376
+ entry.violation_rate = entry.checked_rows > 0 ? violations / entry.checked_rows : 0
377
+ entry.top_prefixes = sorted.slice(0, topPrefixLimit)
378
+ totalViolations += violations
379
+
380
+ if (sampleLimit > 0) {
381
+ const candidatePrefixes = [...(rawOffendingPrefixesBySource.get(source) ?? [])].slice(0, 64)
382
+
383
+ if (candidatePrefixes.length) {
384
+ const inList = candidatePrefixes.map(sqlQuoted).join(", ")
385
+ const fetchLimit = Math.max(sampleLimit * 3, 15)
386
+
387
+ const sampleResult = await db.runAndReadAll(
388
+ `WITH us_prefixed AS (` +
389
+ `SELECT source, source_id, raw, span_tags, span_starts, span_ends, ` +
390
+ `list_position(span_tags, 'street_prefix') AS idx ` +
391
+ `FROM read_parquet([${fileListSQL}], union_by_name=true) ` +
392
+ `WHERE country = 'US' AND source = ${sqlQuoted(source)} ` +
393
+ `AND list_contains(span_tags, 'street_prefix')` +
394
+ `) ` +
395
+ `SELECT source, source_id, raw, span_tags, span_starts, span_ends ` +
396
+ `FROM us_prefixed ` +
397
+ `WHERE trim(${prefixExpr}) IN (${inList}) ` +
398
+ `LIMIT ${fetchLimit}`
399
+ )
400
+
401
+ for (const row of sampleResult.getRowObjects()) {
402
+ if (entry.samples.length >= sampleLimit) break
403
+
404
+ const raw = String(row.raw ?? "")
405
+ const tags = toStringArray(row.span_tags)
406
+ const starts = toNumberArray(row.span_starts)
407
+ const ends = toNumberArray(row.span_ends)
408
+ const exactPrefix = sliceSpanUTF16(raw, tags, starts, ends, "street_prefix")
409
+
410
+ if (exactPrefix == null) continue
411
+
412
+ const confirmedToken = findDisallowedUSStreetPrefixToken(exactPrefix)
413
+
414
+ if (!confirmedToken) continue
415
+
416
+ entry.samples.push({
417
+ source_id: String(row.source_id ?? ""),
418
+ source: String(row.source ?? ""),
419
+ raw,
420
+ street_prefix: exactPrefix,
421
+ street: sliceSpanUTF16(raw, tags, starts, ends, "street"),
422
+ offending_token: confirmedToken,
423
+ })
424
+ }
425
+ }
426
+ }
427
+ }
428
+
429
+ const invariant: SchemaInvariantResult = {
430
+ id: "us_street_prefix_directional_only",
431
+ status: totalViolations === 0 ? "pass" : "fail",
432
+ total_us_rows: totalUSRows,
433
+ total_checked_rows: totalCheckedRows,
434
+ violation_rows: totalViolations,
435
+ violation_rate: totalCheckedRows > 0 ? totalViolations / totalCheckedRows : 0,
436
+ by_source: Object.fromEntries(bySource),
437
+ }
438
+
439
+ return {
440
+ corpus_dir: corpusDir,
441
+ manifest_path: manifestPath,
442
+ files_scanned: parquetPaths.length,
443
+ sources_filter: sourcesFilter,
444
+ status: invariant.status,
445
+ invariants: [invariant],
446
+ }
447
+ }
@@ -40,6 +40,7 @@ import { normalizeCJKText } from "#cjk/text"
40
40
  import {
41
41
  availableJPRegisters,
42
42
  chooseJPRegister,
43
+ collectBareJPDistrictRows,
43
44
  JP_CORPUS_SOURCE,
44
45
  JP_LABEL_SET_NAME,
45
46
  JP_REGISTER_WEIGHTS,
@@ -388,15 +389,33 @@ export async function buildJPCorpus(options: JPCorpusOptions): Promise<JPCorpusR
388
389
 
389
390
  const splits = new Map<string, CJKSplitReport>()
390
391
 
392
+ const bareTrainDistricts = collectBareJPDistrictRows(selection.train)
393
+
394
+ for (const record of bareTrainDistricts) {
395
+ verifyJPRecord(record, tagSet)
396
+ }
397
+
391
398
  for (const [split, sourceRows] of [
392
399
  ["train", selection.train],
393
400
  ["val", selection.val],
394
401
  ] as const) {
402
+ let emittedTrainRows = 0
403
+
395
404
  const report = await writeCJKSplit({
396
405
  directory: resolvePath(outDir, split),
397
406
  rows: sourceRows,
398
407
  rowsPerPart: options.rowsPerPart,
399
- encodePart: (rows) => encoder.encode(rows),
408
+ encodePart: (rows) => {
409
+ const encoded = encoder.encode(rows)
410
+
411
+ emittedTrainRows += rows.length
412
+
413
+ if (split === "train" && bareTrainDistricts.length && emittedTrainRows === sourceRows.length) {
414
+ return [...encoded, ...bareTrainDistricts]
415
+ }
416
+
417
+ return encoded
418
+ },
400
419
  partPrefix: "part",
401
420
  context: "JP corpus assembly",
402
421
  statsSample: { kind: CJKStatsSample.FirstOfEachPart, rows: options.statsSamplePerPart },
@@ -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
+ }
@@ -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
  /**