@mailwoman/corpus 11.5.0 → 12.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/data/address-source-register.json +545 -11
  2. package/data/builds/v0.8.22-wofrank-overlay/OVERLAY_PLAN.json +51 -0
  3. package/data/builds/v0.8.24-everyplace/inputs.json +35 -0
  4. package/data/license-decisions.json +440 -9
  5. package/data/licenses/PROVENANCE.md +27 -18
  6. package/data/licenses/at-bev-adressregister-cc-by-4.0.md +25 -0
  7. package/data/licenses/br-ibge-cnefe-open-data.md +21 -0
  8. package/data/licenses/ca-qc-mrnf-cc-by-4.0.md +29 -0
  9. package/data/licenses/ca-statcan-open-licence.md +41 -0
  10. package/data/licenses/ca-yukon-ogl-2.0.md +19 -0
  11. package/data/licenses/dk-dmikg-cc-by-4.0.md +43 -0
  12. package/data/licenses/jp-mlit-isj-pdl-1.0.md +35 -0
  13. package/data/source-additions.json +90 -0
  14. package/data/source-resolutions.json +3 -2
  15. package/data/training-configs/v8.17.0-stage1-gazetteer-v0822-s42.yaml +557 -0
  16. package/data/training-configs/v8.17.0-stage2-corpus-v0822-s42.yaml +1008 -0
  17. package/data/training-configs/v8.18.0-gazetteer-then-mixture-v0822-s42.yaml +1225 -0
  18. package/data/training-configs/v8.20.0-wofrank-v0822-s42.yaml +863 -0
  19. package/data/training-configs/v8.21.0-outcomes-v0822-s42.yaml +873 -0
  20. package/data/training-configs/v8.22.0-stage1-everyplace-v0824-s42.yaml +374 -0
  21. package/data/training-configs/v8.22.0-stage2-corpus-v0824-s42.yaml +808 -0
  22. package/data/training-configs/v8.22.1-stage1-everyplace-v0824-s42.yaml +376 -0
  23. package/data/training-configs/v8.22.1-stage2-corpus-v0824-s42.yaml +793 -0
  24. package/data/training-configs/v9.0.0-bytestem-v090-s42.yaml +665 -0
  25. package/data/training-configs/v9.1.0-bytestem-global-v091-s42.yaml +710 -0
  26. package/data/training-configs/v9.2.0-bytestem-global-v092-s42.yaml +714 -0
  27. package/data/training-manifests/v0.8.22-wofrank-overlay.json +9000 -0
  28. package/data/training-manifests/v0.8.24-everyplace-overlay.json +9000 -0
  29. package/data/training-manifests/v0.9.0-compact.effective.json +2556 -0
  30. package/data/training-manifests/v0.9.0-compact.json +9000 -0
  31. package/data/training-manifests/v0.9.1-compact.json +9660 -0
  32. package/data/training-manifests/v0.9.2-compact.effective.json +2670 -0
  33. package/data/training-manifests/v0.9.2-compact.json +9660 -0
  34. package/lib/adapters/geonames/features/adapter.ts +29 -11
  35. package/lib/adapters/overture/adapter.ts +26 -6
  36. package/lib/adapters/street/line.ts +6 -5
  37. package/lib/adapters/street/unit.ts +7 -0
  38. package/lib/adapters/wof/admin/json/adapter.ts +38 -3
  39. package/lib/adapters/wof/json-rows.ts +84 -5
  40. package/lib/adapters/wof/sample.ts +42 -6
  41. package/lib/au/adapters/gnaf/source.ts +12 -0
  42. package/lib/build/code-hash.ts +1 -1
  43. package/lib/cjk/foreign-places.ts +1 -1
  44. package/lib/fr/adapters/ban/adapter.ts +57 -8
  45. package/lib/fr/recipes/admin-split.ts +14 -2
  46. package/lib/fr/recipes/lieudit.ts +1 -1
  47. package/lib/fr/recipes/order.ts +14 -5
  48. package/lib/international/recipes/locale.ts +1 -1
  49. package/lib/kr/adapters/localdata/permit-rows.ts +1 -1
  50. package/lib/parquet/schema.ts +7 -0
  51. package/lib/recipes/po/box/cedex/recipe.ts +1 -1
  52. package/lib/recipes/po/box/cedex/vocabulary.ts +4 -4
  53. package/lib/recipes/trailing-region.ts +147 -17
  54. package/lib/synthesizers/po-box.ts +51 -12
  55. package/lib/test-kit/corpus-recipe.ts +3 -0
  56. package/lib/tools/anthropic/batches.ts +221 -0
  57. package/lib/tools/anthropic/labeling.ts +263 -0
  58. package/lib/tools/compact-v9.ts +890 -0
  59. package/lib/tools/fetch/wikidata/vital-places/entities.ts +20 -2
  60. package/lib/tools/fetch/wikidata/vital-places/qrank.ts +5 -4
  61. package/lib/tools/fragment-assay.run.ts +2 -1
  62. package/lib/tools/name-roles/name-roles.run.ts +296 -0
  63. package/lib/tools/name-roles/prompt.ts +253 -0
  64. package/lib/tools/overlay/deletions.ts +1 -1
  65. package/lib/tools/overlay/draw-weight.ts +275 -0
  66. package/lib/tools/place-twins/place-twins.run.ts +528 -0
  67. package/lib/tools/place-twins/prompt.ts +276 -0
  68. package/lib/tools/prominent-shapes/prominent-shapes.run.ts +420 -0
  69. package/lib/tools/prominent-shapes/prompt.ts +189 -0
  70. package/lib/tools/prominent-shapes/read-seeds.ts +286 -0
  71. package/lib/tools/prominent-shapes/seeds.ts +281 -0
  72. package/lib/tools/prominent-shapes/validate.ts +563 -0
  73. package/lib/tools/source-register/build.ts +1 -0
  74. package/lib/training/config/admission.ts +9 -2
  75. package/lib/training/config/schema.ts +68 -1
  76. package/lib/types.ts +23 -0
  77. package/lib/us/adapters/usgov/usgs-structures/adapter.ts +103 -6
  78. package/lib/utils/split.ts +1 -1
  79. package/out/adapters/geonames/features/adapter.d.ts +2 -2
  80. package/out/adapters/geonames/features/adapter.d.ts.map +1 -1
  81. package/out/adapters/geonames/features/adapter.js +25 -11
  82. package/out/adapters/geonames/features/adapter.js.map +1 -1
  83. package/out/adapters/overture/adapter.d.ts.map +1 -1
  84. package/out/adapters/overture/adapter.js +21 -5
  85. package/out/adapters/overture/adapter.js.map +1 -1
  86. package/out/adapters/street/line.d.ts +4 -4
  87. package/out/adapters/street/line.d.ts.map +1 -1
  88. package/out/adapters/street/line.js +5 -5
  89. package/out/adapters/street/line.js.map +1 -1
  90. package/out/adapters/street/unit.d.ts +4 -0
  91. package/out/adapters/street/unit.d.ts.map +1 -1
  92. package/out/adapters/street/unit.js +3 -0
  93. package/out/adapters/street/unit.js.map +1 -1
  94. package/out/adapters/wof/admin/json/adapter.d.ts +7 -0
  95. package/out/adapters/wof/admin/json/adapter.d.ts.map +1 -1
  96. package/out/adapters/wof/admin/json/adapter.js +28 -3
  97. package/out/adapters/wof/admin/json/adapter.js.map +1 -1
  98. package/out/adapters/wof/json-rows.d.ts +8 -0
  99. package/out/adapters/wof/json-rows.d.ts.map +1 -1
  100. package/out/adapters/wof/json-rows.js +56 -4
  101. package/out/adapters/wof/json-rows.js.map +1 -1
  102. package/out/adapters/wof/sample.d.ts +12 -0
  103. package/out/adapters/wof/sample.d.ts.map +1 -1
  104. package/out/adapters/wof/sample.js +37 -6
  105. package/out/adapters/wof/sample.js.map +1 -1
  106. package/out/au/adapters/gnaf/source.d.ts +9 -0
  107. package/out/au/adapters/gnaf/source.d.ts.map +1 -1
  108. package/out/au/adapters/gnaf/source.js +9 -0
  109. package/out/au/adapters/gnaf/source.js.map +1 -1
  110. package/out/build/code-hash.js +1 -1
  111. package/out/build/code-hash.js.map +1 -1
  112. package/out/cjk/foreign-places.js +1 -1
  113. package/out/cjk/foreign-places.js.map +1 -1
  114. package/out/fr/adapters/ban/adapter.d.ts.map +1 -1
  115. package/out/fr/adapters/ban/adapter.js +49 -7
  116. package/out/fr/adapters/ban/adapter.js.map +1 -1
  117. package/out/fr/recipes/admin-split.d.ts.map +1 -1
  118. package/out/fr/recipes/admin-split.js +15 -2
  119. package/out/fr/recipes/admin-split.js.map +1 -1
  120. package/out/fr/recipes/lieudit.js +1 -1
  121. package/out/fr/recipes/lieudit.js.map +1 -1
  122. package/out/fr/recipes/order.d.ts.map +1 -1
  123. package/out/fr/recipes/order.js +16 -5
  124. package/out/fr/recipes/order.js.map +1 -1
  125. package/out/international/recipes/locale.js +1 -1
  126. package/out/international/recipes/locale.js.map +1 -1
  127. package/out/kr/adapters/localdata/permit-rows.js +1 -1
  128. package/out/kr/adapters/localdata/permit-rows.js.map +1 -1
  129. package/out/parquet/schema.d.ts +6 -0
  130. package/out/parquet/schema.d.ts.map +1 -1
  131. package/out/parquet/schema.js +6 -0
  132. package/out/parquet/schema.js.map +1 -1
  133. package/out/recipes/po/box/cedex/recipe.js +1 -1
  134. package/out/recipes/po/box/cedex/recipe.js.map +1 -1
  135. package/out/recipes/po/box/cedex/vocabulary.d.ts +1 -1
  136. package/out/recipes/po/box/cedex/vocabulary.d.ts.map +1 -1
  137. package/out/recipes/po/box/cedex/vocabulary.js +4 -4
  138. package/out/recipes/po/box/cedex/vocabulary.js.map +1 -1
  139. package/out/recipes/trailing-region.d.ts.map +1 -1
  140. package/out/recipes/trailing-region.js +122 -17
  141. package/out/recipes/trailing-region.js.map +1 -1
  142. package/out/synthesizers/po-box.d.ts +7 -0
  143. package/out/synthesizers/po-box.d.ts.map +1 -1
  144. package/out/synthesizers/po-box.js +36 -12
  145. package/out/synthesizers/po-box.js.map +1 -1
  146. package/out/test-kit/corpus-recipe.d.ts +3 -0
  147. package/out/test-kit/corpus-recipe.d.ts.map +1 -1
  148. package/out/test-kit/corpus-recipe.js.map +1 -1
  149. package/out/tools/anthropic/batches.d.ts +117 -0
  150. package/out/tools/anthropic/batches.d.ts.map +1 -0
  151. package/out/tools/anthropic/batches.js +141 -0
  152. package/out/tools/anthropic/batches.js.map +1 -0
  153. package/out/tools/anthropic/labeling.d.ts +97 -0
  154. package/out/tools/anthropic/labeling.d.ts.map +1 -0
  155. package/out/tools/anthropic/labeling.js +146 -0
  156. package/out/tools/anthropic/labeling.js.map +1 -0
  157. package/out/tools/compact-v9.d.ts +124 -0
  158. package/out/tools/compact-v9.d.ts.map +1 -0
  159. package/out/tools/compact-v9.js +507 -0
  160. package/out/tools/compact-v9.js.map +1 -0
  161. package/out/tools/fetch/wikidata/vital-places/entities.d.ts +3 -0
  162. package/out/tools/fetch/wikidata/vital-places/entities.d.ts.map +1 -1
  163. package/out/tools/fetch/wikidata/vital-places/entities.js +19 -1
  164. package/out/tools/fetch/wikidata/vital-places/entities.js.map +1 -1
  165. package/out/tools/fetch/wikidata/vital-places/qrank.d.ts.map +1 -1
  166. package/out/tools/fetch/wikidata/vital-places/qrank.js +4 -4
  167. package/out/tools/fetch/wikidata/vital-places/qrank.js.map +1 -1
  168. package/out/tools/fragment-assay.run.js +1 -1
  169. package/out/tools/fragment-assay.run.js.map +1 -1
  170. package/out/tools/name-roles/name-roles.run.d.ts +2 -0
  171. package/out/tools/name-roles/name-roles.run.d.ts.map +1 -0
  172. package/out/tools/name-roles/name-roles.run.js +230 -0
  173. package/out/tools/name-roles/name-roles.run.js.map +1 -0
  174. package/out/tools/name-roles/prompt.d.ts +166 -0
  175. package/out/tools/name-roles/prompt.d.ts.map +1 -0
  176. package/out/tools/name-roles/prompt.js +176 -0
  177. package/out/tools/name-roles/prompt.js.map +1 -0
  178. package/out/tools/overlay/deletions.js +1 -1
  179. package/out/tools/overlay/deletions.js.map +1 -1
  180. package/out/tools/overlay/draw-weight.d.ts +86 -0
  181. package/out/tools/overlay/draw-weight.d.ts.map +1 -0
  182. package/out/tools/overlay/draw-weight.js +131 -0
  183. package/out/tools/overlay/draw-weight.js.map +1 -0
  184. package/out/tools/place-twins/place-twins.run.d.ts +2 -0
  185. package/out/tools/place-twins/place-twins.run.d.ts.map +1 -0
  186. package/out/tools/place-twins/place-twins.run.js +385 -0
  187. package/out/tools/place-twins/place-twins.run.js.map +1 -0
  188. package/out/tools/place-twins/prompt.d.ts +169 -0
  189. package/out/tools/place-twins/prompt.d.ts.map +1 -0
  190. package/out/tools/place-twins/prompt.js +183 -0
  191. package/out/tools/place-twins/prompt.js.map +1 -0
  192. package/out/tools/prominent-shapes/prominent-shapes.run.d.ts +2 -0
  193. package/out/tools/prominent-shapes/prominent-shapes.run.d.ts.map +1 -0
  194. package/out/tools/prominent-shapes/prominent-shapes.run.js +302 -0
  195. package/out/tools/prominent-shapes/prominent-shapes.run.js.map +1 -0
  196. package/out/tools/prominent-shapes/prompt.d.ts +74 -0
  197. package/out/tools/prominent-shapes/prompt.d.ts.map +1 -0
  198. package/out/tools/prominent-shapes/prompt.js +156 -0
  199. package/out/tools/prominent-shapes/prompt.js.map +1 -0
  200. package/out/tools/prominent-shapes/read-seeds.d.ts +23 -0
  201. package/out/tools/prominent-shapes/read-seeds.d.ts.map +1 -0
  202. package/out/tools/prominent-shapes/read-seeds.js +219 -0
  203. package/out/tools/prominent-shapes/read-seeds.js.map +1 -0
  204. package/out/tools/prominent-shapes/seeds.d.ts +132 -0
  205. package/out/tools/prominent-shapes/seeds.d.ts.map +1 -0
  206. package/out/tools/prominent-shapes/seeds.js +178 -0
  207. package/out/tools/prominent-shapes/seeds.js.map +1 -0
  208. package/out/tools/prominent-shapes/validate.d.ts +152 -0
  209. package/out/tools/prominent-shapes/validate.d.ts.map +1 -0
  210. package/out/tools/prominent-shapes/validate.js +389 -0
  211. package/out/tools/prominent-shapes/validate.js.map +1 -0
  212. package/out/tools/source-register/build.d.ts.map +1 -1
  213. package/out/tools/source-register/build.js +1 -0
  214. package/out/tools/source-register/build.js.map +1 -1
  215. package/out/training/config/admission.d.ts +2 -1
  216. package/out/training/config/admission.d.ts.map +1 -1
  217. package/out/training/config/admission.js +9 -2
  218. package/out/training/config/admission.js.map +1 -1
  219. package/out/training/config/schema.d.ts +276 -1
  220. package/out/training/config/schema.d.ts.map +1 -1
  221. package/out/training/config/schema.js +64 -1
  222. package/out/training/config/schema.js.map +1 -1
  223. package/out/types.d.ts +21 -0
  224. package/out/types.d.ts.map +1 -1
  225. package/out/types.js +13 -0
  226. package/out/types.js.map +1 -1
  227. package/out/us/adapters/usgov/usgs-structures/adapter.d.ts.map +1 -1
  228. package/out/us/adapters/usgov/usgs-structures/adapter.js +78 -4
  229. package/out/us/adapters/usgov/usgs-structures/adapter.js.map +1 -1
  230. package/out/utils/split.js +1 -1
  231. package/out/utils/split.js.map +1 -1
  232. package/package.json +24 -24
@@ -0,0 +1,189 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file The request that asks a language model for the query forms of a country's prominent places (#3156).
6
+ *
7
+ * One request lists about ten places of one country.
8
+ * Each place lists its surfaces under keys, and the model returns texts with the keys each contains.
9
+ * The model decides which surfaces people combine, in which order, case and punctuation.
10
+ * It supplies no name: `#tools/prominent-shapes/validate` drops a text holding anything but cited surfaces.
11
+ */
12
+
13
+ import { stringifyJSON } from "@mailwoman/core/values/json"
14
+
15
+ import type { MessageBatchRequest } from "#tools/anthropic/batches"
16
+ import { type SeedSurface, type ShapeSeed, SurfaceSlot } from "#tools/prominent-shapes/seeds"
17
+
18
+ /**
19
+ * The worked example of the instructions: a place's surface lines as a request renders them,
20
+ * and one form citing the second name and the second country by their numbered keys.
21
+ */
22
+ const SHAPE_KEY_EXAMPLE = {
23
+ surfaces: 'n1="Munich" n2="München"[deu] with country surfaces c1="Germany" c2="Deutschland"[deu],',
24
+ form: '{"raw": "München, Deutschland", "uses": ["n2", "c2"]}',
25
+ } as const
26
+
27
+ /**
28
+ * The instructions every request shares.
29
+ */
30
+ export const SHAPE_SYSTEM_PROMPT = [
31
+ "You write the short queries people type into a map or geocoder search box to find a well-known place.",
32
+ "",
33
+ "Each request names one country and lists places in it. Every place lists its surfaces, each under a key",
34
+ "made of a slot letter and a number, such as n1, n2 or c3. The letter is the surface's slot:",
35
+ "n = the place's own name, p = its parent city, r = its region (state, province, prefecture),",
36
+ "a = the region's abbreviation, c = the country. A bracket after a surface is its language code.",
37
+ "",
38
+ "For each place, write the queries a person would plausibly type, and for each give `raw` (the query text)",
39
+ "and `uses` (the keys of the surfaces it contains, in the order they appear in `raw`).",
40
+ "`uses` lists the numbered keys exactly as supplied, never the bare letter: for a place listing",
41
+ SHAPE_KEY_EXAMPLE.surfaces,
42
+ `the form ${SHAPE_KEY_EXAMPLE.form} is right, and "uses": ["n", "c"] is wrong.`,
43
+ "",
44
+ "Rules:",
45
+ "- `raw` contains only the cited surfaces and separators (spaces, commas, and the separators the country's",
46
+ " own writing uses). Add no other word: no street, postcode, 'city', 'near', article, preposition or suffix.",
47
+ "- Write each surface exactly as supplied, letter for letter, including its diacritics. You may change its",
48
+ " letter case only (lower, UPPER, Title). Never abbreviate, translate, transliterate, respell, shorten,",
49
+ " extend or misspell a surface, and never use a name that isn't in the list.",
50
+ "- Use exactly one n surface. Use at most one p, at most one of r or a, and at most one c.",
51
+ "- A place's line states which keys every form must contain; follow it.",
52
+ "- Keep one language per query: do not put a surface in one script beside a surface in another script.",
53
+ " Queries in the country's own language and script matter as much as English ones; use each supplied",
54
+ " language's surfaces together and in that language's customary order and punctuation (for example",
55
+ " larger-to-smaller without separators where that is how the language writes places).",
56
+ "- Vary the forms the way real typing varies: the name alone, name then region, name then region",
57
+ " abbreviation, name then country, with a comma, without a comma, all lower case, and sometimes upper case.",
58
+ " Prefer the combinations people type most. Skip a combination nobody would type.",
59
+ "- Do not repeat a `raw`. Return each place under the id given, and every place of the request.",
60
+ ].join("\n")
61
+
62
+ /**
63
+ * The structured-output schema of a response.
64
+ */
65
+ export const SHAPE_RESPONSE_SCHEMA = {
66
+ type: "object",
67
+ additionalProperties: false,
68
+ required: ["places"],
69
+ properties: {
70
+ places: {
71
+ type: "array",
72
+ items: {
73
+ type: "object",
74
+ additionalProperties: false,
75
+ required: ["id", "forms"],
76
+ properties: {
77
+ id: { type: "string" },
78
+ forms: {
79
+ type: "array",
80
+ items: {
81
+ type: "object",
82
+ additionalProperties: false,
83
+ required: ["raw", "uses"],
84
+ properties: {
85
+ raw: { type: "string" },
86
+ uses: { type: "array", items: { type: "string" } },
87
+ },
88
+ },
89
+ },
90
+ },
91
+ },
92
+ },
93
+ },
94
+ } as const
95
+
96
+ function renderSurfaces(surfaces: readonly SeedSurface[], slot: SurfaceSlot): string | null {
97
+ const listed = surfaces.filter((surface) => surface.slot === slot)
98
+
99
+ if (!listed.length) return null
100
+
101
+ return listed
102
+ .map((surface) => `${surface.key}=${stringifyJSON(surface.text)}${surface.language ? `[${surface.language}]` : ""}`)
103
+ .join(" ")
104
+ }
105
+
106
+ /**
107
+ * The keys every form of `seed` must contain, in the words the request states them.
108
+ */
109
+ function requiredKeys(seed: ShapeSeed): string {
110
+ if (seed.parent_tag === "locality") return "every form contains one n and one p"
111
+
112
+ if (seed.parent_tag === "region") {
113
+ return seed.surfaces.some((surface) => surface.slot === SurfaceSlot.RegionAbbreviation)
114
+ ? "every form contains one n and either one p or one a"
115
+ : "every form contains one n and one p"
116
+ }
117
+
118
+ return "every form contains one n"
119
+ }
120
+
121
+ /**
122
+ * Renders the places of one request as the user message.
123
+ *
124
+ * Every seed is of one country, and that country's surfaces are listed once from the first seed.
125
+ *
126
+ * @throws When the seeds are empty or of more than one country.
127
+ */
128
+ export function renderShapeRequest(seeds: readonly ShapeSeed[], formsPerPlace: number): string {
129
+ const [first] = seeds
130
+
131
+ if (!first || seeds.some((seed) => seed.country !== first.country)) {
132
+ throw new Error("A request lists the places of exactly one country")
133
+ }
134
+
135
+ const lines = [
136
+ `Country ${first.country}. Country surfaces: ${renderSurfaces(first.surfaces, SurfaceSlot.Country) ?? "none; write no country"}`,
137
+ `Write about ${formsPerPlace} forms for each place, fewer when the place has few surfaces.`,
138
+ "",
139
+ ]
140
+
141
+ for (const seed of seeds) {
142
+ const kind = seed.band === "locality" ? "city or town" : "district of its parent city"
143
+
144
+ lines.push(`Place ${seed.wof_id} (${kind}; ${requiredKeys(seed)})`)
145
+
146
+ for (const slot of [SurfaceSlot.Name, SurfaceSlot.Parent, SurfaceSlot.Region, SurfaceSlot.RegionAbbreviation]) {
147
+ const rendered = renderSurfaces(seed.surfaces, slot)
148
+
149
+ if (rendered) {
150
+ lines.push(` ${rendered}`)
151
+ }
152
+ }
153
+ }
154
+
155
+ return lines.join("\n")
156
+ }
157
+
158
+ /**
159
+ * The settings of a run's requests.
160
+ */
161
+ export interface ShapeRequestOptions {
162
+ model: string
163
+ effort: string
164
+ formsPerPlace: number
165
+ maxTokens: number
166
+ }
167
+
168
+ /**
169
+ * Builds the Messages parameters of one request.
170
+ */
171
+ export function shapeRequestParams(
172
+ seeds: readonly ShapeSeed[],
173
+ options: ShapeRequestOptions
174
+ ): MessageBatchRequest["params"] {
175
+ return {
176
+ model: options.model,
177
+ max_tokens: options.maxTokens,
178
+ system: SHAPE_SYSTEM_PROMPT,
179
+ output_config: { effort: options.effort, format: { type: "json_schema", schema: SHAPE_RESPONSE_SCHEMA } },
180
+ messages: [{ role: "user", content: renderShapeRequest(seeds, options.formsPerPlace) }],
181
+ }
182
+ }
183
+
184
+ /**
185
+ * The batch id of the request at `index`.
186
+ */
187
+ export function shapeRequestID(index: number): string {
188
+ return `shapes-${String(index).padStart(5, "0")}`
189
+ }
@@ -0,0 +1,286 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file Reads the seeds of the prominent places the #3156 census selected.
6
+ *
7
+ * The census's `places.parquet` supplies the selection, each place's name, parent locality, region,
8
+ * region abbreviations and postal-pair reading.
9
+ * The Who's On First admin database supplies the other-language surfaces: the `preferred` rows of
10
+ * `names` in the country's official languages and English, for the place, for the parent locality and
11
+ * region among its ancestors, and for its country.
12
+ * The codex supplies the country's rendered forms.
13
+ */
14
+
15
+ import { countryRenderForms, isTwoLetterCountryCode } from "@mailwoman/codex/country/country"
16
+ import { officialLanguagesAlpha3 } from "@mailwoman/codex/country/region-languages"
17
+ import { foldCaseWhitespace } from "@mailwoman/normalize/fold"
18
+ import type { WOFDatabase } from "@mailwoman/resolver-wof-sqlite/schema"
19
+ import { openBuiltClient } from "@mailwoman/sqlite/sealed"
20
+
21
+ import { escapeSQLString, openDuckDB } from "#parquet/duckdb"
22
+ import { parquetColumnNames } from "#parquet/readers"
23
+ import type { PlaceBand } from "#recipes/prominent/places"
24
+ import { chunked } from "#tools/fetch/wikidata/vital-places/progress"
25
+ import { assembleSeed, type SeedSkip, type ShapeSeed, type SurfaceDraft } from "#tools/prominent-shapes/seeds"
26
+
27
+ /**
28
+ * The census columns a seed is read from.
29
+ */
30
+ const CENSUS_COLUMNS = [
31
+ "spr_id",
32
+ "country",
33
+ "band",
34
+ "name",
35
+ "rank",
36
+ "by_rank",
37
+ "capital",
38
+ "parent_locality",
39
+ "region",
40
+ "region_abbrs",
41
+ "postal_pair",
42
+ ] as const
43
+
44
+ /**
45
+ * The ids one SQLite query lists.
46
+ */
47
+ const ID_CHUNK = 500
48
+
49
+ /**
50
+ * One selected place as the census records it.
51
+ */
52
+ interface CensusPlace {
53
+ spr_id: number
54
+ country: string
55
+ band: PlaceBand
56
+ name: string
57
+ rank: number | null
58
+ capital: boolean
59
+ parent_locality: string | null
60
+ region: string | null
61
+ region_abbrs: string[]
62
+ postal_pair: boolean
63
+ }
64
+
65
+ /**
66
+ * The seeds read, and the places left without one by reason.
67
+ */
68
+ export interface SeedReadResult {
69
+ seeds: ShapeSeed[]
70
+ selected: number
71
+ skipped: Partial<Record<SeedSkip, number>>
72
+ }
73
+
74
+ async function readCensusPlaces(placesParquet: string): Promise<CensusPlace[]> {
75
+ const columns = new Set(await parquetColumnNames(placesParquet))
76
+ const missing = CENSUS_COLUMNS.filter((column) => !columns.has(column))
77
+
78
+ if (missing.length) {
79
+ throw new Error(
80
+ `${placesParquet} lacks the census columns ${missing.join(", ")}; a seed cannot be read without them`
81
+ )
82
+ }
83
+
84
+ using db = await openDuckDB()
85
+
86
+ const result = await db.runAndReadAll(
87
+ `SELECT ${CENSUS_COLUMNS.join(", ")} FROM read_parquet('${escapeSQLString(placesParquet)}') ` +
88
+ "WHERE by_rank OR capital ORDER BY country, band, rank NULLS LAST, spr_id"
89
+ )
90
+
91
+ return (result.getRowObjectsJson() as Array<Record<string, unknown>>).map((row) => ({
92
+ spr_id: Number(row["spr_id"]),
93
+ country: String(row["country"]),
94
+ band: String(row["band"]) as PlaceBand,
95
+ name: String(row["name"]),
96
+ rank: row["rank"] == null ? null : Number(row["rank"]),
97
+ capital: row["capital"] === true,
98
+ parent_locality: typeof row["parent_locality"] === "string" ? row["parent_locality"] : null,
99
+ region: typeof row["region"] === "string" ? row["region"] : null,
100
+ region_abbrs: Array.isArray(row["region_abbrs"]) ? row["region_abbrs"].map(String) : [],
101
+ postal_pair: row["postal_pair"] === true,
102
+ }))
103
+ }
104
+
105
+ /**
106
+ * The languages a country's surfaces are read in: its official languages, then English.
107
+ */
108
+ function surfaceLanguages(country: string): string[] {
109
+ return [...new Set([...officialLanguagesAlpha3(country), "eng"])]
110
+ }
111
+
112
+ /**
113
+ * The shortest Latin-script country surface a form writes.
114
+ *
115
+ * A shorter one collides with region abbreviations, as `packages/corpus/AGENTS.md` records.
116
+ * `日本` is two characters of another script and stays.
117
+ */
118
+ const LATIN_COUNTRY_SURFACE_MIN_LENGTH = 3
119
+
120
+ /**
121
+ * Whether a country surface is written: neither a two-letter code nor a Latin surface under the floor.
122
+ */
123
+ function isWritableCountrySurface(text: string): boolean {
124
+ const shortLatin = /^[\p{Script=Latin}.\s]*$/u.test(text) && text.trim().length < LATIN_COUNTRY_SURFACE_MIN_LENGTH
125
+
126
+ return !isTwoLetterCountryCode(text) && !shortLatin
127
+ }
128
+
129
+ /**
130
+ * Reads the seed of every prominent place in `placesParquet`.
131
+ *
132
+ * A parent locality or region takes its other-language surfaces from the ancestor
133
+ * whose WOF name is the census's name for it.
134
+ * Without such an ancestor its only surface is the census's name.
135
+ *
136
+ * @throws When the census file lacks a column a seed is read from.
137
+ */
138
+ export async function readShapeSeeds(options: { placesParquet: string; wofDatabase: string }): Promise<SeedReadResult> {
139
+ const places = await readCensusPlaces(options.placesParquet)
140
+
141
+ using wof = await openBuiltClient<WOFDatabase>(options.wofDatabase)
142
+
143
+ // The parent locality and region records among each place's ancestors, matched by the census's name.
144
+ const parentID = new Map<number, number>()
145
+ const regionID = new Map<number, number>()
146
+ const byID = new Map(places.map((place) => [place.spr_id, place]))
147
+
148
+ for (const ids of chunked([...byID.keys()], ID_CHUNK)) {
149
+ const ancestors = await wof
150
+ .selectFrom("ancestors")
151
+ .innerJoin("spr", "spr.id", "ancestors.ancestor_id")
152
+ .select(["ancestors.id", "ancestors.ancestor_id", "ancestors.ancestor_placetype", "spr.name"])
153
+ .where("ancestors.id", "in", ids)
154
+ .where("ancestors.ancestor_placetype", "in", ["locality", "localadmin", "region"])
155
+ .execute()
156
+
157
+ for (const ancestor of ancestors) {
158
+ const place = byID.get(ancestor.id)!
159
+ const fold = foldCaseWhitespace(ancestor.name ?? "")
160
+ const isRegion = ancestor.ancestor_placetype === "region"
161
+ const expected = isRegion ? place.region : place.parent_locality
162
+ const target = isRegion ? regionID : parentID
163
+
164
+ if (ancestor.ancestor_id !== place.spr_id && expected != null && fold === foldCaseWhitespace(expected)) {
165
+ target.set(place.spr_id, Math.min(target.get(place.spr_id) ?? Infinity, ancestor.ancestor_id))
166
+ }
167
+ }
168
+ }
169
+
170
+ // Each country's own record: a country before a dependency, the lowest id first.
171
+ const countries = [...new Set(places.map((place) => place.country))]
172
+ const countryRecord = new Map<string, { id: number; name: string }>()
173
+
174
+ const countryRows = await wof
175
+ .selectFrom("spr")
176
+ .select(["id", "name", "placetype", "country"])
177
+ .where("placetype", "in", ["country", "dependency"])
178
+ .where("country", "in", countries)
179
+ .where("is_current", "!=", 0)
180
+ .where("is_deprecated", "=", 0)
181
+ .orderBy("placetype")
182
+ .orderBy("id")
183
+ .execute()
184
+
185
+ for (const row of countryRows) {
186
+ // `XX` is WOF's code for a place of no recorded country, so a record filed under
187
+ // it belongs to no country's row. country-branch: `XX` is WOF's placeholder for an
188
+ // unrecorded country, a sentinel of the source and no country's rule.
189
+ if (row.country && row.country !== "XX" && row.name && !countryRecord.has(row.country)) {
190
+ countryRecord.set(row.country, { id: row.id, name: row.name })
191
+ }
192
+ }
193
+
194
+ // The preferred names of every record a seed reads, in the languages its country writes.
195
+ const languages = new Set(countries.flatMap(surfaceLanguages))
196
+ const namedIDs = new Set([...byID.keys(), ...parentID.values(), ...regionID.values()])
197
+
198
+ for (const record of countryRecord.values()) {
199
+ namedIDs.add(record.id)
200
+ }
201
+
202
+ const namesByID = new Map<number, Array<{ name: string; language: string }>>()
203
+
204
+ for (const ids of chunked([...namedIDs], ID_CHUNK)) {
205
+ const rows = await wof
206
+ .selectFrom("names")
207
+ .select(["id", "name", "language"])
208
+ .where("id", "in", ids)
209
+ .where("privateuse", "=", "preferred")
210
+ .where("language", "in", [...languages])
211
+ .orderBy("id")
212
+ .orderBy("language")
213
+ .orderBy("name")
214
+ .execute()
215
+
216
+ for (const row of rows) {
217
+ if (!row.language) continue
218
+
219
+ const list = namesByID.get(row.id) ?? []
220
+
221
+ list.push({ name: row.name, language: row.language })
222
+ namesByID.set(row.id, list)
223
+ }
224
+ }
225
+
226
+ const nameDrafts = (id: number | null | undefined, country: string): SurfaceDraft[] => {
227
+ if (id == null) return []
228
+
229
+ const wanted = surfaceLanguages(country)
230
+
231
+ return (namesByID.get(id) ?? [])
232
+ .filter((row) => wanted.includes(row.language))
233
+ .toSorted((a, b) => wanted.indexOf(a.language) - wanted.indexOf(b.language))
234
+ .map((row) => ({ text: row.name, language: row.language, origin: `wof:names:${id}:${row.language}:preferred` }))
235
+ }
236
+
237
+ const censusDraft = (text: string | null, column: string, id: number): SurfaceDraft[] =>
238
+ text == null ? [] : [{ text, language: null, origin: `census:${column}:${id}` }]
239
+
240
+ const seeds: ShapeSeed[] = []
241
+ const skipped: Partial<Record<SeedSkip, number>> = {}
242
+
243
+ for (const place of places) {
244
+ const country = countryRecord.get(place.country)
245
+
246
+ const seed = assembleSeed({
247
+ wof_id: place.spr_id,
248
+ country: place.country,
249
+ band: place.band,
250
+ rank: place.rank,
251
+ capital: place.capital,
252
+ postal_pair: place.postal_pair,
253
+ names: [...censusDraft(place.name, "name", place.spr_id), ...nameDrafts(place.spr_id, place.country)],
254
+ parents: [
255
+ ...censusDraft(place.parent_locality, "parent_locality", place.spr_id),
256
+ ...nameDrafts(parentID.get(place.spr_id), place.country),
257
+ ],
258
+ regions: [
259
+ ...censusDraft(place.region, "region", place.spr_id),
260
+ ...nameDrafts(regionID.get(place.spr_id), place.country),
261
+ ],
262
+ region_abbreviations: place.region_abbrs.map((text) => ({
263
+ text,
264
+ language: null,
265
+ origin: `census:region_abbrs:${place.spr_id}`,
266
+ })),
267
+ countries: [
268
+ ...countryRenderForms(place.country).map((text) => ({
269
+ text,
270
+ language: null,
271
+ origin: `codex:countryRenderForms:${place.country}`,
272
+ })),
273
+ ...(country ? [{ text: country.name, language: null, origin: `wof:spr:${country.id}:name` }] : []),
274
+ ...nameDrafts(country?.id, place.country),
275
+ ].filter((draft) => isWritableCountrySurface(draft.text)),
276
+ })
277
+
278
+ if (typeof seed === "string") {
279
+ skipped[seed] = (skipped[seed] ?? 0) + 1
280
+ } else {
281
+ seeds.push(seed)
282
+ }
283
+ }
284
+
285
+ return { seeds, selected: places.length, skipped }
286
+ }