@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,141 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+ /**
4
+ * @file A client for Anthropic's Message Batches endpoint. The corpus labeling tools submit their requests through it.
5
+ *
6
+ * A batch is asynchronous: `createMessageBatch` returns an id, `readMessageBatch` reports its state,
7
+ * and `readMessageBatchResults` returns one line per request once the state is `ended`.
8
+ * Result lines arrive in any order, so a caller joins them to its requests by `custom_id`.
9
+ */
10
+ import { APIClient, pluckResponseData } from "@mailwoman/core/api";
11
+ import { tryParsingJSON } from "@mailwoman/core/values/json";
12
+ import { TextSpliterator } from "spliterator";
13
+ import { $private } from "#env";
14
+ const BATCHES_URL = "https://api.anthropic.com/v1/messages/batches";
15
+ /**
16
+ * The most requests one batch accepts.
17
+ */
18
+ export const MAX_BATCH_REQUESTS = 100_000;
19
+ /**
20
+ * Creates the client every batch call shares.
21
+ *
22
+ * @throws When `ANTHROPIC_API_KEY` is unset.
23
+ */
24
+ export function createAnthropicClient() {
25
+ const apiKey = $private.ANTHROPIC_API_KEY;
26
+ if (!apiKey)
27
+ throw new Error("ANTHROPIC_API_KEY is required to call Anthropic");
28
+ return new APIClient({
29
+ displayName: "anthropic",
30
+ retry: true,
31
+ axios: {
32
+ headers: { "x-api-key": apiKey, "anthropic-version": "2023-06-01", "Content-Type": "application/json" },
33
+ },
34
+ });
35
+ }
36
+ /**
37
+ * Sends one Messages request outside a batch, at the standard price,
38
+ * and returns it in a batch result's shape.
39
+ *
40
+ * A labeling tool sends one of these before a batch to confirm the API accepts its
41
+ * parameters and to measure the tokens one request uses.
42
+ */
43
+ export async function createMessage(client, request) {
44
+ const message = (await client
45
+ .fetch({
46
+ url: "https://api.anthropic.com/v1/messages",
47
+ method: "post",
48
+ timeout: 600_000,
49
+ data: request.params,
50
+ cache: false,
51
+ })
52
+ .then(pluckResponseData));
53
+ return { custom_id: request.custom_id, result: { type: "succeeded", message } };
54
+ }
55
+ /**
56
+ * Submits `requests` as one batch and returns its initial state.
57
+ *
58
+ * @throws When `requests` is empty or exceeds `MAX_BATCH_REQUESTS`.
59
+ */
60
+ export async function createMessageBatch(client, requests) {
61
+ if (!requests.length || requests.length > MAX_BATCH_REQUESTS) {
62
+ throw new Error(`A batch takes 1 to ${MAX_BATCH_REQUESTS} requests, and this one has ${requests.length}`);
63
+ }
64
+ return client
65
+ .fetch({ url: BATCHES_URL, method: "post", timeout: 600_000, data: { requests }, cache: false })
66
+ .then(pluckResponseData);
67
+ }
68
+ /**
69
+ * Reads the current state of the batch `id`.
70
+ */
71
+ export async function readMessageBatch(client, id) {
72
+ return client
73
+ .fetch({ url: `${BATCHES_URL}/${id}`, timeout: 60_000, cache: false })
74
+ .then(pluckResponseData);
75
+ }
76
+ /**
77
+ * Reads every result line of the finished batch `id`.
78
+ *
79
+ * @throws When the batch is still in progress, or when a line of the result file fails to parse.
80
+ */
81
+ export async function readMessageBatchResults(client, id) {
82
+ const batch = await readMessageBatch(client, id);
83
+ if (batch.processing_status !== "ended") {
84
+ throw new Error(`Batch ${id} is ${batch.processing_status}; its results exist only once it has ended`);
85
+ }
86
+ const { data } = await client.fetch({
87
+ url: `${BATCHES_URL}/${id}/results`,
88
+ timeout: 600_000,
89
+ responseType: "text",
90
+ transformResponse: (body) => body,
91
+ cache: false,
92
+ });
93
+ return parseMessageBatchResults(String(data), `Batch ${id}`);
94
+ }
95
+ /**
96
+ * Parses the JSONL body of a batch's results, as the API returns it or as a run saved it.
97
+ *
98
+ * @param source Where the body came from, as an error states it.
99
+ * @throws When a line fails to parse or lacks a request id or outcome, or when the body holds no result.
100
+ */
101
+ export function parseMessageBatchResults(body, source) {
102
+ const results = [];
103
+ for (const line of TextSpliterator.from(body)) {
104
+ if (line.trim() === "")
105
+ continue;
106
+ const parsed = tryParsingJSON(line);
107
+ if (parsed?.custom_id == null || parsed.result?.type == null) {
108
+ throw new Error(`${source} holds a result line that is not a batch result: ${line.slice(0, 200)}`);
109
+ }
110
+ results.push(parsed);
111
+ }
112
+ if (!results.length)
113
+ throw new Error(`${source} holds no batch result`);
114
+ return results;
115
+ }
116
+ /**
117
+ * Returns the text of a succeeded result, or `null` for any other outcome
118
+ * or a response that stopped at `max_tokens`.
119
+ */
120
+ export function resultText(result) {
121
+ const message = result.result.message;
122
+ if (result.result.type !== "succeeded" || !message || message.stop_reason !== "end_turn")
123
+ return null;
124
+ return message.content.find((block) => block.type === "text")?.text ?? null;
125
+ }
126
+ /**
127
+ * Sums the dollars the succeeded results cost at `price`.
128
+ */
129
+ export function batchCostUSD(results, price) {
130
+ let input = 0;
131
+ let output = 0;
132
+ for (const { result } of results) {
133
+ const usage = result.message?.usage;
134
+ if (!usage)
135
+ continue;
136
+ input += usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
137
+ output += usage.output_tokens;
138
+ }
139
+ return (input * price.input + output * price.output) / 1_000_000;
140
+ }
141
+ //# sourceMappingURL=batches.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batches.js","sourceRoot":"","sources":["../../../lib/tools/anthropic/batches.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,kEAAkE;AAElE;;;;;;GAMG;AAEH,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7C,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAA;AAE/B,MAAM,WAAW,GAAG,+CAA+C,CAAA;AAEnE;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAO,CAAA;AAwDzC;;;;GAIG;AACH,MAAM,UAAU,qBAAqB;IACpC,MAAM,MAAM,GAAG,QAAQ,CAAC,iBAAiB,CAAA;IAEzC,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAA;IAE/E,OAAO,IAAI,SAAS,CAAC;QACpB,WAAW,EAAE,WAAW;QACxB,KAAK,EAAE,IAAI;QACX,KAAK,EAAE;YACN,OAAO,EAAE,EAAE,WAAW,EAAE,MAAM,EAAE,mBAAmB,EAAE,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE;SACvG;KACD,CAAC,CAAA;AACH,CAAC;AA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";
2
+ import { type MessageBatch, type MessageBatchRequest, type MessageUsage, type TokenPrice } from "#tools/anthropic/batches";
3
+ /**
4
+ * Returns the batch price of `model`.
5
+ *
6
+ * @throws When no price is recorded for it, so a cost is never reported from a guessed rate.
7
+ */
8
+ export declare function batchPrice(model: string): TokenPrice;
9
+ /**
10
+ * The items one request labels.
11
+ */
12
+ export interface LabelingChunk<Item> {
13
+ custom_id: string;
14
+ items: Item[];
15
+ }
16
+ /**
17
+ * What `submitLabelingBatch` records, so a later `status` or `collect` reads
18
+ * the settings the batch ran under.
19
+ */
20
+ export interface LabelingBatchRecord {
21
+ id: string;
22
+ model: string;
23
+ effort: string;
24
+ requests: number;
25
+ items: number;
26
+ }
27
+ /**
28
+ * The model and effort a tool's requests run under.
29
+ */
30
+ export interface LabelingSettings {
31
+ model: string;
32
+ effort: string;
33
+ }
34
+ type ToParams<Item> = (items: readonly Item[], settings: LabelingSettings) => MessageBatchRequest["params"];
35
+ /**
36
+ * Parses one response into a label per item of its request, in item order,
37
+ * and throws on a response it refuses.
38
+ */
39
+ type ParseLabels<Item, Label> = (text: string, items: readonly Item[]) => Label[];
40
+ /**
41
+ * Splits `items` into requests of `size`, with ids `<prefix>-<n>`.
42
+ */
43
+ export declare function toLabelingChunks<Item>(items: readonly Item[], size: number, prefix: string): LabelingChunk<Item>[];
44
+ /**
45
+ * Sends `count` evenly spaced chunks one at a time at the standard price.
46
+ *
47
+ * @returns Each chunk with its labels and token use, and the batch cost per request those requests imply.
48
+ * @throws When a response stops at `max_tokens` or the parser refuses it,
49
+ * since a batch of the same requests would fail the same way.
50
+ */
51
+ export declare function pilotLabelingRequests<Item, Label>(chunks: ReadonlyArray<LabelingChunk<Item>>, count: number, settings: LabelingSettings, toParams: ToParams<Item>, parse: ParseLabels<Item, Label>): Promise<{
52
+ requests: Array<{
53
+ chunk: LabelingChunk<Item>;
54
+ labels: Label[];
55
+ usage: MessageUsage;
56
+ }>;
57
+ batchCostPerRequestUSD: number;
58
+ }>;
59
+ /**
60
+ * Writes `chunks.jsonl`, creates one batch of the chunks, and records it in `batch.json`.
61
+ */
62
+ export declare function submitLabelingBatch<Item>(out: PathBuilder, chunks: ReadonlyArray<LabelingChunk<Item>>, settings: LabelingSettings, toParams: ToParams<Item>): Promise<LabelingBatchRecord>;
63
+ /**
64
+ * Reads the state of the batch `batch.json` records.
65
+ */
66
+ export declare function readLabelingBatch(out: PathBuilder): Promise<MessageBatch>;
67
+ /**
68
+ * A request whose items received no label, and why.
69
+ */
70
+ export interface FailedChunk {
71
+ custom_id: string;
72
+ reason: string;
73
+ items: number;
74
+ }
75
+ /**
76
+ * Joins the finished batch to its chunks and writes `failed-chunks.jsonl`.
77
+ *
78
+ * @returns Every labeled item beside its label, the failed requests, the result
79
+ * count per outcome type, and the dollars the batch cost.
80
+ * @throws When the batch is still in progress.
81
+ */
82
+ export declare function collectLabelingBatch<Item, Label>(out: PathBuilder, parse: ParseLabels<Item, Label>): Promise<{
83
+ record: LabelingBatchRecord;
84
+ labeled: Array<{
85
+ item: Item;
86
+ label: Label;
87
+ }>;
88
+ failed: FailedChunk[];
89
+ resultsByType: Record<string, number>;
90
+ costUSD: number;
91
+ }>;
92
+ /**
93
+ * Counts each distinct value.
94
+ */
95
+ export declare function countEach(values: Iterable<string>): Record<string, number>;
96
+ export {};
97
+ //# sourceMappingURL=labeling.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"labeling.d.ts","sourceRoot":"","sources":["../../../lib/tools/anthropic/labeling.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAG1C,OAAO,EAQN,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAExB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,MAAM,0BAA0B,CAAA;AAWjC;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAMpD;AAED;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,IA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identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+ /**
4
+ * @file The submit, status and collect steps every batch labeling tool shares.
5
+ *
6
+ * A labeling tool splits its items into chunks, one request each, and the model returns one label per item.
7
+ * `submitLabelingBatch` writes `chunks.jsonl` and `batch.json` to the tool's output directory,
8
+ * and `collectLabelingBatch` joins the finished batch back to those chunks by `custom_id`.
9
+ * A request that failed, stopped at `max_tokens`, or returned labels the tool's parser refuses is listed as failed
10
+ * with its reason, and its items receive no label.
11
+ */
12
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers";
13
+ import { writeLocalJSONFile, writeLocalJSONLFile } from "@mailwoman/core/fs/writers";
14
+ import { JSONSpliterator } from "spliterator";
15
+ import { batchCostUSD, createAnthropicClient, createMessage, createMessageBatch, readMessageBatch, readMessageBatchResults, resultText, } from "#tools/anthropic/batches";
16
+ /**
17
+ * Dollars per million tokens on the batch endpoint, at half the standard price.
18
+ */
19
+ const BATCH_PRICES = {
20
+ "claude-opus-5-5": { input: 2, output: 10 },
21
+ "claude-sonnet-5-5": { input: 1, output: 5 },
22
+ "claude-haiku-5-5": { input: 0.05, output: 0.25 },
23
+ };
24
+ /**
25
+ * Returns the batch price of `model`.
26
+ *
27
+ * @throws When no price is recorded for it, so a cost is never reported from a guessed rate.
28
+ */
29
+ export function batchPrice(model) {
30
+ const price = BATCH_PRICES[model];
31
+ if (!price)
32
+ throw new Error(`No batch price is recorded for ${model}; add it to BATCH_PRICES`);
33
+ return price;
34
+ }
35
+ /**
36
+ * Splits `items` into requests of `size`, with ids `<prefix>-<n>`.
37
+ */
38
+ export function toLabelingChunks(items, size, prefix) {
39
+ if (!Number.isInteger(size) || size < 1)
40
+ throw new Error(`A chunk holds a whole number of items, and --chunk was ${size}`);
41
+ const chunks = [];
42
+ for (let start = 0; start < items.length; start += size) {
43
+ chunks.push({ custom_id: `${prefix}-${chunks.length}`, items: items.slice(start, start + size) });
44
+ }
45
+ return chunks;
46
+ }
47
+ /**
48
+ * Sends `count` evenly spaced chunks one at a time at the standard price.
49
+ *
50
+ * @returns Each chunk with its labels and token use, and the batch cost per request those requests imply.
51
+ * @throws When a response stops at `max_tokens` or the parser refuses it,
52
+ * since a batch of the same requests would fail the same way.
53
+ */
54
+ export async function pilotLabelingRequests(chunks, count, settings, toParams, parse) {
55
+ const client = createAnthropicClient();
56
+ const stride = Math.max(1, Math.floor(chunks.length / count));
57
+ const requests = [];
58
+ const results = [];
59
+ for (let n = 0; n < count && n * stride < chunks.length; n++) {
60
+ const chunk = chunks[n * stride];
61
+ const result = await createMessage(client, { custom_id: chunk.custom_id, params: toParams(chunk.items, settings) });
62
+ const text = resultText(result);
63
+ if (text == null)
64
+ throw new Error(`${chunk.custom_id} stopped at ${result.result.message?.stop_reason ?? "no message"}`);
65
+ requests.push({ chunk, labels: parse(text, chunk.items), usage: result.result.message.usage });
66
+ results.push(result);
67
+ }
68
+ return { requests, batchCostPerRequestUSD: batchCostUSD(results, batchPrice(settings.model)) / results.length };
69
+ }
70
+ /**
71
+ * Writes `chunks.jsonl`, creates one batch of the chunks, and records it in `batch.json`.
72
+ */
73
+ export async function submitLabelingBatch(out, chunks, settings, toParams) {
74
+ batchPrice(settings.model);
75
+ await writeLocalJSONLFile(chunks, out("chunks.jsonl"));
76
+ const batch = await createMessageBatch(createAnthropicClient(), chunks.map((chunk) => ({ custom_id: chunk.custom_id, params: toParams(chunk.items, settings) })));
77
+ const record = {
78
+ id: batch.id,
79
+ ...settings,
80
+ requests: chunks.length,
81
+ items: chunks.reduce((sum, chunk) => sum + chunk.items.length, 0),
82
+ };
83
+ await writeLocalJSONFile(record, out("batch.json"));
84
+ return record;
85
+ }
86
+ /**
87
+ * Reads the state of the batch `batch.json` records.
88
+ */
89
+ export async function readLabelingBatch(out) {
90
+ const { id } = await readLocalJSONFile(out("batch.json"));
91
+ return readMessageBatch(createAnthropicClient(), id);
92
+ }
93
+ /**
94
+ * Joins the finished batch to its chunks and writes `failed-chunks.jsonl`.
95
+ *
96
+ * @returns Every labeled item beside its label, the failed requests, the result
97
+ * count per outcome type, and the dollars the batch cost.
98
+ * @throws When the batch is still in progress.
99
+ */
100
+ export async function collectLabelingBatch(out, parse) {
101
+ const record = await readLocalJSONFile(out("batch.json"));
102
+ const chunks = await JSONSpliterator.fromAsync(out("chunks.jsonl")).toArray();
103
+ const results = await readMessageBatchResults(createAnthropicClient(), record.id);
104
+ const byCustomID = new Map(results.map((result) => [result.custom_id, result]));
105
+ const labeled = [];
106
+ const failed = [];
107
+ for (const chunk of chunks) {
108
+ const result = byCustomID.get(chunk.custom_id);
109
+ const text = result ? resultText(result) : null;
110
+ if (!result || text == null) {
111
+ const reason = result
112
+ ? `${result.result.type}:${result.result.message?.stop_reason ?? "no message"}`
113
+ : "no result line";
114
+ failed.push({ custom_id: chunk.custom_id, reason, items: chunk.items.length });
115
+ continue;
116
+ }
117
+ try {
118
+ const labels = parse(text, chunk.items);
119
+ for (const [i, item] of chunk.items.entries()) {
120
+ labeled.push({ item, label: labels[i] });
121
+ }
122
+ }
123
+ catch (error) {
124
+ failed.push({ custom_id: chunk.custom_id, reason: error.message, items: chunk.items.length });
125
+ }
126
+ }
127
+ await writeLocalJSONLFile(failed, out("failed-chunks.jsonl"));
128
+ return {
129
+ record,
130
+ labeled,
131
+ failed,
132
+ resultsByType: countEach(results.map((result) => result.result.type)),
133
+ costUSD: Number(batchCostUSD(results, batchPrice(record.model)).toFixed(2)),
134
+ };
135
+ }
136
+ /**
137
+ * Counts each distinct value.
138
+ */
139
+ export function countEach(values) {
140
+ const counts = {};
141
+ for (const value of values) {
142
+ counts[value] = (counts[value] ?? 0) + 1;
143
+ }
144
+ return counts;
145
+ }
146
+ //# sourceMappingURL=labeling.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"labeling.js","sourceRoot":"","sources":["../../../lib/tools/anthropic/labeling.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,kEAAkE;AAElE;;;;;;;;GAQG;AAEH,OAAO,EAAE,iBAAiB,EAA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A;IAEzC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC5B,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA;IACzC,CAAC;IAED,OAAO,MAAM,CAAA;AACd,CAAC"}
@@ -0,0 +1,124 @@
1
+ import { type PathBuilderLike } from "path-ts";
2
+ import { type DuckDBLimits } from "#parquet/duckdb";
3
+ /**
4
+ * Default maximum number of Tier-2 train rows kept per digit-masked skeleton bucket.
5
+ */
6
+ export declare const DEFAULT_SKELETON_CAP = 6;
7
+ /**
8
+ * Default Tier-2 dense register sources subject to cross-source deduplication and skeleton capping.
9
+ *
10
+ * The multi-country European `overture` source stays in Tier 1 rather than here:
11
+ * its rows span 16 countries at roughly 100k to 150k rows each.
12
+ * Skeleton-capping it dropped 700,104 of 1,825,956 rows in `v0.9.0-compact`,
13
+ * including ES and IT single-letter unit rows and CZ/SI addresses.
14
+ */
15
+ export declare const DEFAULT_TIER2_SOURCES: readonly ["usgov-nad", "ban", "ban-gp", "ban-gf", "ban-mq", "ban-re", "ban-yt", "ban-bl", "ban-mf", "ban-pm", "ban-wf", "ban-pf", "usgov-nppes", "tiger", "usgov-usgs-structures", "state-ia-contractors", "state-ny-notaries", "state-tx-notaries", "overture-latam", "gleif-lei"];
16
+ /**
17
+ * Options for {@linkcode compactCorpusV9}.
18
+ */
19
+ export interface CompactCorpusV9Options {
20
+ /**
21
+ * Input corpus directory holding `MANIFEST.json`, or direct path to `MANIFEST.json`.
22
+ */
23
+ inPath: PathBuilderLike;
24
+ /**
25
+ * Output directory for compacted Parquet files, `MANIFEST.json`, and `COMPACTION_REPORT.json`.
26
+ */
27
+ outDir: PathBuilderLike;
28
+ /**
29
+ * Output `corpus_version` recorded in `MANIFEST.json`.
30
+ *
31
+ * Defaults to `<input version>-v9-compact`.
32
+ */
33
+ version?: string;
34
+ /**
35
+ * Maximum Tier-2 train rows kept per `(country, labels, digit-masked raw)` skeleton bucket.
36
+ *
37
+ * @default 6
38
+ */
39
+ skeletonCap?: number;
40
+ /**
41
+ * Optional cap for rare Tier-2 pattern rows (`unit`, `po_box`, `cedex`,
42
+ * `intersection_a`, `venue`, `building_name`, `building_number`).
43
+ *
44
+ * A `null` value keeps rare patterns uncapped.
45
+ * Bare single-letter `unit` rows (one token matching a single letter, such as ES
46
+ * `CALLE LA CRUZ A, 45` or IT `VIA NAPOLI A 5`) stay uncapped even when `rareSkeletonCap` is set.
47
+ *
48
+ * @default null
49
+ */
50
+ rareSkeletonCap?: number | null;
51
+ /**
52
+ * Sources treated as Tier-2 dense registers.
53
+ *
54
+ * Every other source is treated as Tier 1.
55
+ *
56
+ * @default {@linkcode DEFAULT_TIER2_SOURCES}
57
+ */
58
+ tier2Sources?: readonly string[];
59
+ /**
60
+ * Optional path prefix written into `MANIFEST.json` entries.
61
+ *
62
+ * Defaults to the local `outDir` path.
63
+ */
64
+ modalRoot?: string;
65
+ /**
66
+ * Optional DuckDB memory/thread/spill settings.
67
+ */
68
+ limits?: DuckDBLimits;
69
+ }
70
+ /**
71
+ * Per-source row counts across compaction stages.
72
+ */
73
+ export interface CompactSourceStats {
74
+ source: string;
75
+ tier: 1 | 2;
76
+ inputTrainRows: number;
77
+ inputValRows: number;
78
+ inputTestRows: number;
79
+ keptTrainRows: number;
80
+ keptValRows: number;
81
+ keptTestRows: number;
82
+ droppedAugmentationRows: number;
83
+ droppedDedupRows: number;
84
+ droppedSkeletonCapRows: number;
85
+ }
86
+ /**
87
+ * Summary report written to `COMPACTION_REPORT.json` beside the compacted `MANIFEST.json`.
88
+ */
89
+ export interface CompactionReport {
90
+ compacted_at: string;
91
+ input_manifest: string;
92
+ corpus_version: string;
93
+ skeleton_cap: number;
94
+ rare_skeleton_cap: number | null;
95
+ tier2_sources: string[];
96
+ totals: {
97
+ input_rows: number;
98
+ kept_rows: number;
99
+ input_train_rows: number;
100
+ kept_train_rows: number;
101
+ input_val_rows: number;
102
+ kept_val_rows: number;
103
+ input_test_rows: number;
104
+ kept_test_rows: number;
105
+ dropped_augmentation_rows: number;
106
+ dropped_dedup_rows: number;
107
+ dropped_skeleton_cap_rows: number;
108
+ };
109
+ sources: CompactSourceStats[];
110
+ }
111
+ /**
112
+ * Result of {@linkcode compactCorpusV9}.
113
+ */
114
+ export interface CompactCorpusV9Result {
115
+ manifestPath: string;
116
+ reportPath: string;
117
+ report: CompactionReport;
118
+ }
119
+ /**
120
+ * Compacts a corpus manifest into a two-tier base-row v9 corpus while preserving all `val`
121
+ * and `test` rows and split-attribute holdout boundaries untouched.
122
+ */
123
+ export declare function compactCorpusV9(options: CompactCorpusV9Options): Promise<CompactCorpusV9Result>;
124
+ //# sourceMappingURL=compact-v9.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compact-v9.d.ts","sourceRoot":"","sources":["../../lib/tools/compact-v9.ts"],"names":[],"mappings":"AAwBA,OAAO,EAA4B,KAAK,eAAe,EAAE,MAAM,SAAS,CAAA;AAExE,OAAO,EAAsD,KAAK,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAMvG;;GAEG;AACH,eAAO,MAAM,oBAAoB,IAAI,CAAA;AAErC;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,YACjC,WAAW,EACX,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,aAAa,EACb,OAAO,EACP,uBAAuB,EACvB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,WAAW,CACF,CAAA;AAeV;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACtC;;OAEG;IACH,MAAM,EAAE,eAAe,CAAA;IACvB;;OAEG;IACH,MAAM,EAAE,eAAe,CAAA;IACvB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;OAIG;IACH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