tinyfix-tr 0.0.0-stage → 0.1.1

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +139 -2
  3. package/dist/pkg/src/context.d.ts +13 -0
  4. package/dist/pkg/src/context.js +80 -0
  5. package/dist/pkg/src/data.d.ts +53 -0
  6. package/dist/pkg/src/data.js +498 -0
  7. package/dist/pkg/src/engine.d.ts +39 -0
  8. package/dist/pkg/src/engine.js +357 -0
  9. package/dist/pkg/src/index.d.ts +30 -0
  10. package/dist/pkg/src/index.js +85 -0
  11. package/dist/pkg/src/protocol.d.ts +64 -0
  12. package/dist/pkg/src/protocol.js +1 -0
  13. package/dist/pkg/src/types.d.ts +184 -0
  14. package/dist/pkg/src/types.js +16 -0
  15. package/dist/pkg/src/worker.d.ts +11 -0
  16. package/dist/pkg/src/worker.js +111 -0
  17. package/dist/pkg/src/workerClient.d.ts +3 -0
  18. package/dist/pkg/src/workerClient.js +202 -0
  19. package/dist/src/context-vocab.d.ts +1 -0
  20. package/dist/src/context-vocab.js +2 -0
  21. package/dist/src/context.d.ts +92 -0
  22. package/dist/src/context.js +390 -0
  23. package/dist/src/corrector.d.ts +338 -0
  24. package/dist/src/corrector.js +2684 -0
  25. package/dist/src/known.d.ts +88 -0
  26. package/dist/src/known.js +286 -0
  27. package/dist/src/lexicon-binary.d.ts +85 -0
  28. package/dist/src/lexicon-binary.js +805 -0
  29. package/dist/src/lexicon.d.ts +24 -0
  30. package/dist/src/lexicon.js +79 -0
  31. package/dist/src/morphology/analyzer.d.ts +30 -0
  32. package/dist/src/morphology/analyzer.js +311 -0
  33. package/dist/src/morphology/binary.d.ts +22 -0
  34. package/dist/src/morphology/binary.js +372 -0
  35. package/dist/src/morphology/dictionary.d.ts +21 -0
  36. package/dist/src/morphology/dictionary.js +559 -0
  37. package/dist/src/morphology/fuzzy.d.ts +44 -0
  38. package/dist/src/morphology/fuzzy.js +599 -0
  39. package/dist/src/morphology/index.d.ts +40 -0
  40. package/dist/src/morphology/index.js +81 -0
  41. package/dist/src/morphology/morphotactics.d.ts +148 -0
  42. package/dist/src/morphology/morphotactics.js +1871 -0
  43. package/dist/src/morphology/phonetics.d.ts +71 -0
  44. package/dist/src/morphology/phonetics.js +309 -0
  45. package/dist/src/morphology/prior.d.ts +61 -0
  46. package/dist/src/morphology/prior.js +457 -0
  47. package/dist/src/morphology/types.d.ts +110 -0
  48. package/dist/src/morphology/types.js +32 -0
  49. package/dist/src/rules/proper-names.d.ts +145 -0
  50. package/dist/src/rules/proper-names.js +1217 -0
  51. package/dist/src/rules/turkish-rules.d.ts +126 -0
  52. package/dist/src/rules/turkish-rules.js +365 -0
  53. package/dist/src/sentence.d.ts +83 -0
  54. package/dist/src/sentence.js +2408 -0
  55. package/dist/src/turkish.d.ts +20 -0
  56. package/dist/src/turkish.js +94 -0
  57. package/package.json +60 -4
@@ -0,0 +1,390 @@
1
+ /**
2
+ * The context model: scores how well a candidate span fits between the text on its left and right.
3
+ *
4
+ * Supports:
5
+ * - v3 Subword Transformer ONNX (`subwords [n, T]`, `sub_segments [n, T]`, `features [n, 26]`)
6
+ * - v2 Char-Conv ONNX (`tokens [n, 144]`, `segments [n, 144]`, `features [n, 18]`)
7
+ * - v1 Char-Conv ONNX & fake test runners (`tokens [n, 144]`, `segments [n, 144]`)
8
+ *
9
+ * Character encoding, subword tokenization, sequence packing, and 26-dim feature layout here
10
+ * must match py/build_tokenizer.py, py/context_data.py, and py/context_arch.py exactly.
11
+ */
12
+ import { CONTEXT_VOCAB_TEXT } from "./context-vocab.js";
13
+ import { hasTurkishMarks, isAllUpper, isUpperInitial, LETTERS, lowerTr } from "./turkish.js";
14
+ export const LEFT = 80;
15
+ export const RIGHT = 40;
16
+ export const SPAN = 24;
17
+ export const SEQUENCE = LEFT + SPAN + RIGHT;
18
+ export const LEFT_SUB = 24;
19
+ export const SPAN_SUB = 8;
20
+ export const RIGHT_SUB = 20;
21
+ export const MAX_SUB_LEN = 64;
22
+ export const FEATURE_DIM = 26;
23
+ export const LEGACY_FEATURE_DIM = 18;
24
+ /** 0 is padding, 1 is any character not listed. */
25
+ export const ALPHABET = "abcçdefgğhıijklmnoöprsştuüvyzâîûqwxABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX0 .,;:!?'\"()-";
26
+ const CHAR_ID = new Map([...ALPHABET].map((char, index) => [char, index + 2]));
27
+ const POSS_MORPHEMES = new Set(["P1sg", "P2sg", "P3sg", "P1pl", "P2pl", "P3pl"]);
28
+ const FINITE_MORPHEMES = new Set(["Prog1", "Prog2", "Past", "Narr", "Fut", "Aor", "Opt", "Desr", "Neces", "Imp"]);
29
+ const FUNC_POS = new Set(["Pron", "Conj", "Postp", "Det"]);
30
+ const WORD_PREFIX = "▁";
31
+ const SUB_PAD_ID = 0;
32
+ const SUB_UNK_ID = 1;
33
+ const SUB_CLS_ID = 2;
34
+ const SUB_CAP_ID = 4;
35
+ const SUB_ALLCAP_ID = 5;
36
+ const SUB_NUM_ID = 6;
37
+ const SUB_TOKEN_RE = new RegExp(`[${LETTERS}]+|[0-9]+|[^\\s]`, "g");
38
+ let vocabCache = null;
39
+ function getSubwordVocab() {
40
+ if (vocabCache)
41
+ return vocabCache;
42
+ const lines = CONTEXT_VOCAB_TEXT.split("\n");
43
+ const idOf = new Map();
44
+ let maxLen = 1;
45
+ for (let i = 0; i < lines.length; i++) {
46
+ const tok = lines[i];
47
+ idOf.set(tok, i);
48
+ if (!(tok.startsWith("<") && tok.endsWith(">")) && tok.length > maxLen) {
49
+ maxLen = tok.length;
50
+ }
51
+ }
52
+ vocabCache = { idOf, maxLen };
53
+ return vocabCache;
54
+ }
55
+ function encodeSubwordPiece(low, wordStart, idOf, maxLen, out) {
56
+ const n = low.length;
57
+ let pos = 0;
58
+ while (pos < n) {
59
+ if (pos === 0 && wordStart) {
60
+ let end = Math.min(n, maxLen - 1);
61
+ let found = -1;
62
+ while (end > 0) {
63
+ const tid = idOf.get(WORD_PREFIX + low.slice(0, end));
64
+ if (tid !== undefined) {
65
+ found = tid;
66
+ break;
67
+ }
68
+ end--;
69
+ }
70
+ if (found !== -1) {
71
+ out.push(found);
72
+ pos = end;
73
+ }
74
+ else {
75
+ out.push(SUB_UNK_ID);
76
+ pos++;
77
+ }
78
+ }
79
+ else {
80
+ let end = Math.min(n, pos + maxLen);
81
+ let found = -1;
82
+ while (end > pos) {
83
+ const tid = idOf.get(low.slice(pos, end));
84
+ if (tid !== undefined) {
85
+ found = tid;
86
+ break;
87
+ }
88
+ end--;
89
+ }
90
+ if (found !== -1) {
91
+ out.push(found);
92
+ pos = end;
93
+ }
94
+ else {
95
+ out.push(SUB_UNK_ID);
96
+ pos++;
97
+ }
98
+ }
99
+ }
100
+ }
101
+ /** Deterministic greedy longest-match Turkish subword tokenizer (bit-identical to py/build_tokenizer.py). */
102
+ export function encodeSubwords(text) {
103
+ const { idOf, maxLen } = getSubwordVocab();
104
+ const norm = text.replaceAll("’", "'");
105
+ const out = [];
106
+ SUB_TOKEN_RE.lastIndex = 0;
107
+ let match;
108
+ while ((match = SUB_TOKEN_RE.exec(norm)) !== null) {
109
+ const tok = match[0];
110
+ const ch0 = tok[0];
111
+ if (ch0 >= "0" && ch0 <= "9") {
112
+ out.push(SUB_NUM_ID);
113
+ continue;
114
+ }
115
+ if (tok.length === 1 && !/\p{L}/u.test(ch0)) {
116
+ out.push(idOf.get(ch0) ?? SUB_UNK_ID);
117
+ continue;
118
+ }
119
+ const afterApos = match.index > 0 && norm[match.index - 1] === "'";
120
+ const low = lowerTr(tok);
121
+ if (!afterApos) {
122
+ if (isAllUpper(tok)) {
123
+ out.push(SUB_ALLCAP_ID);
124
+ }
125
+ else if (isUpperInitial(tok)) {
126
+ out.push(SUB_CAP_ID);
127
+ }
128
+ }
129
+ encodeSubwordPiece(low, !afterApos, idOf, maxLen, out);
130
+ }
131
+ return out;
132
+ }
133
+ function ids(text) {
134
+ return [...text.replaceAll("’", "'").replace(/\d/g, "0")].map((char) => CHAR_ID.get(char) ?? 1);
135
+ }
136
+ /** Computes the 8-bit morphology feature mask matching `scripts/extract-morph-features.ts`. */
137
+ export function morphFeatureBits(word, morphology) {
138
+ if (!morphology)
139
+ return 0;
140
+ const analyses = morphology.analyze?.(word);
141
+ if (!analyses)
142
+ return morphology.isWord(word) ? 1 : 0;
143
+ if (analyses.length === 0)
144
+ return 0;
145
+ let bits = 1;
146
+ for (const a of analyses) {
147
+ if (a.pos === "Verb")
148
+ bits |= 2;
149
+ else if (a.pos === "Noun")
150
+ bits |= 4;
151
+ else if (a.pos === "Adj" || a.pos === "Adv")
152
+ bits |= 8;
153
+ else if (FUNC_POS.has(a.pos))
154
+ bits |= 16;
155
+ for (const m of a.morphemes) {
156
+ if (m === "Loc" || m === "Abl")
157
+ bits |= 32;
158
+ else if (POSS_MORPHEMES.has(m))
159
+ bits |= 64;
160
+ else if (FINITE_MORPHEMES.has(m))
161
+ bits |= 128;
162
+ }
163
+ }
164
+ return bits;
165
+ }
166
+ /** Computes the 26-dim feature vector per candidate matching `py/context_data.py:build_features` and `py/build_name_context_data.py`. */
167
+ export function buildContextFeatures(candidates, kind, asciiContext, lexicon, morphology, typoMeta, nameMeta) {
168
+ const logCounts = [];
169
+ const minLogs = [];
170
+ for (const cand of candidates) {
171
+ const low = lowerTr(cand);
172
+ const space = low.indexOf(" ");
173
+ if (space === -1) {
174
+ const c = lexicon.count(low);
175
+ const lc = Math.log(c + 1);
176
+ logCounts.push(lc);
177
+ minLogs.push(lc);
178
+ }
179
+ else {
180
+ const first = low.slice(0, space);
181
+ const second = low.slice(space + 1);
182
+ const pairC = lexicon.pair(first, second);
183
+ const minW = Math.min(lexicon.count(first), lexicon.count(second));
184
+ logCounts.push(Math.log(pairC + 1));
185
+ minLogs.push(Math.log(minW + 1));
186
+ }
187
+ }
188
+ const maxLc = logCounts.length > 0 ? Math.max(...logCounts) : 0;
189
+ const typedLow = candidates.length > 0 ? lowerTr(candidates[0]) : "";
190
+ let maxCoreMargin = -Infinity;
191
+ if (kind === "typo" && typoMeta) {
192
+ for (let i = 1; i < candidates.length; i++) {
193
+ const m = typoMeta[i]?.coreMargin ?? -10;
194
+ if (m > maxCoreMargin)
195
+ maxCoreMargin = m;
196
+ }
197
+ }
198
+ if (!Number.isFinite(maxCoreMargin))
199
+ maxCoreMargin = 0;
200
+ return candidates.map((cand, idx) => {
201
+ const row = new Array(FEATURE_DIM).fill(0);
202
+ const low = lowerTr(cand);
203
+ const space = low.indexOf(" ");
204
+ const head = space === -1 ? low : low.slice(0, space);
205
+ const bits = morphFeatureBits(head, morphology);
206
+ row[0] = logCounts[idx] / 15;
207
+ row[1] = (logCounts[idx] - maxLc) / 10;
208
+ row[2] = minLogs[idx] / 15;
209
+ row[3] = space !== -1 ? 1 : 0;
210
+ row[4] = hasTurkishMarks(cand) ? 1 : 0;
211
+ row[5] = asciiContext ? 1 : 0;
212
+ if (kind === "marks")
213
+ row[6] = 1;
214
+ else if (kind === "de_da")
215
+ row[7] = 1;
216
+ else if (kind === "ki")
217
+ row[8] = 1;
218
+ else if (kind === "mi")
219
+ row[9] = 1;
220
+ for (let b = 0; b < 8; b++) {
221
+ row[10 + b] = (bits >> b) & 1;
222
+ }
223
+ if (kind === "typo") {
224
+ row[18] = 1;
225
+ const meta = typoMeta?.[idx];
226
+ if (meta && idx > 0) {
227
+ row[19] = Math.max(-1.5, Math.min(1.5, meta.coreMargin / 10));
228
+ row[20] = Math.max(-1.5, Math.min(0, (meta.coreMargin - maxCoreMargin) / 10));
229
+ row[21] = Math.min(2.0, meta.slipCost / 5);
230
+ row[22] = low.length > typedLow.length ? 1 : 0;
231
+ row[23] = low.length < typedLow.length ? 1 : 0;
232
+ row[24] = low.length === typedLow.length && low !== typedLow ? 1 : 0;
233
+ row[25] = meta.isMarkVariant ? 1 : 0;
234
+ }
235
+ }
236
+ else if (kind === "name") {
237
+ // Slots 6..9 and 18 stay 0 -> ContextScorerV3 identifies kind === "name" without changing FEATURE_DIM=26.
238
+ const meta = nameMeta?.[idx];
239
+ if (meta) {
240
+ row[19] = meta.isProper ? 1 : 0;
241
+ row[20] = cand.includes("'") ? 1 : 0;
242
+ row[21] = meta.stemCapShare;
243
+ row[22] = meta.aposShare;
244
+ row[23] = meta.isGiven ? 1 : 0;
245
+ row[24] = meta.isGiven ? 0 : 1;
246
+ row[25] = meta.atSentenceStart ? 1 : 0;
247
+ }
248
+ }
249
+ return row;
250
+ });
251
+ }
252
+ /** Packs each candidate between its context: left (segment 1), candidate (2), right (3), no padding between. */
253
+ export function pack(queries) {
254
+ const n = queries.reduce((sum, query) => sum + query.candidates.length, 0);
255
+ const tokens = new BigInt64Array(n * SEQUENCE);
256
+ const segments = new BigInt64Array(n * SEQUENCE);
257
+ const features = new Float32Array(n * FEATURE_DIM);
258
+ let row = 0;
259
+ for (const query of queries) {
260
+ const left = ids(query.left).slice(-LEFT);
261
+ const right = ids(query.right).slice(0, RIGHT);
262
+ for (let candIdx = 0; candIdx < query.candidates.length; candIdx++) {
263
+ const candidate = query.candidates[candIdx];
264
+ const span = ids(candidate).slice(0, SPAN);
265
+ let position = row * SEQUENCE;
266
+ for (const [part, segment] of [
267
+ [left, 1n],
268
+ [span, 2n],
269
+ [right, 3n],
270
+ ]) {
271
+ for (const id of part) {
272
+ tokens[position] = BigInt(id);
273
+ segments[position] = segment;
274
+ position++;
275
+ }
276
+ }
277
+ const feat = query.features?.[candIdx];
278
+ if (feat) {
279
+ const base = row * FEATURE_DIM;
280
+ for (let f = 0; f < FEATURE_DIM && f < feat.length; f++) {
281
+ features[base + f] = feat[f];
282
+ }
283
+ }
284
+ row++;
285
+ }
286
+ }
287
+ return { tokens, segments, features, n };
288
+ }
289
+ /** Packs each candidate into compact dynamic-length subword tensors: [CLS] + left(<=24) + cand(<=8) + right(<=20). */
290
+ export function packSubwords(queries) {
291
+ const n = queries.reduce((sum, query) => sum + query.candidates.length, 0);
292
+ const encodedRows = [];
293
+ let maxLen = 4;
294
+ for (const query of queries) {
295
+ const leftAll = encodeSubwords(query.left);
296
+ const left = leftAll.length > LEFT_SUB ? leftAll.slice(leftAll.length - LEFT_SUB) : leftAll;
297
+ const rightAll = encodeSubwords(query.right);
298
+ const right = rightAll.length > RIGHT_SUB ? rightAll.slice(0, RIGHT_SUB) : rightAll;
299
+ for (let candIdx = 0; candIdx < query.candidates.length; candIdx++) {
300
+ const spanAll = encodeSubwords(query.candidates[candIdx]);
301
+ const span = spanAll.length > SPAN_SUB ? spanAll.slice(0, SPAN_SUB) : spanAll;
302
+ const total = 1 + left.length + span.length + right.length;
303
+ if (total > maxLen)
304
+ maxLen = total;
305
+ encodedRows.push({ left, span, right, feat: query.features?.[candIdx] });
306
+ }
307
+ }
308
+ const seqLen = Math.min(maxLen, MAX_SUB_LEN);
309
+ const subwords = new BigInt64Array(n * seqLen);
310
+ const subSegments = new BigInt64Array(n * seqLen);
311
+ const features = new Float32Array(n * FEATURE_DIM);
312
+ for (let row = 0; row < encodedRows.length; row++) {
313
+ const { left, span, right, feat } = encodedRows[row];
314
+ const base = row * seqLen;
315
+ let pos = base;
316
+ const limit = base + seqLen;
317
+ subwords[pos] = BigInt(SUB_CLS_ID);
318
+ subSegments[pos] = 1n;
319
+ pos++;
320
+ for (let i = 0; i < left.length && pos < limit; i++) {
321
+ subwords[pos] = BigInt(left[i]);
322
+ subSegments[pos] = 1n;
323
+ pos++;
324
+ }
325
+ for (let i = 0; i < span.length && pos < limit; i++) {
326
+ subwords[pos] = BigInt(span[i]);
327
+ subSegments[pos] = 2n;
328
+ pos++;
329
+ }
330
+ for (let i = 0; i < right.length && pos < limit; i++) {
331
+ subwords[pos] = BigInt(right[i]);
332
+ subSegments[pos] = 3n;
333
+ pos++;
334
+ }
335
+ while (pos < limit) {
336
+ subwords[pos] = BigInt(SUB_PAD_ID);
337
+ subSegments[pos] = 0n;
338
+ pos++;
339
+ }
340
+ if (feat) {
341
+ const fBase = row * FEATURE_DIM;
342
+ for (let f = 0; f < FEATURE_DIM && f < feat.length; f++) {
343
+ features[fBase + f] = feat[f];
344
+ }
345
+ }
346
+ }
347
+ return { subwords, subSegments, seqLen, features, n };
348
+ }
349
+ /** Slices 26-dim features down to 18-dim when running a legacy v2 ONNX model. */
350
+ export function sliceLegacyFeatures(features, n) {
351
+ const out = new Float32Array(n * LEGACY_FEATURE_DIM);
352
+ for (let r = 0; r < n; r++) {
353
+ out.set(features.subarray(r * FEATURE_DIM, r * FEATURE_DIM + LEGACY_FEATURE_DIM), r * LEGACY_FEATURE_DIM);
354
+ }
355
+ return out;
356
+ }
357
+ /** Scores every candidate of every query in one model run. */
358
+ export class ContextModel {
359
+ run;
360
+ subwordsOnly;
361
+ constructor(run, options = {}) {
362
+ this.run = run;
363
+ this.subwordsOnly = options.subwordsOnly ?? false;
364
+ }
365
+ /** True when backed by a v3 subword Transformer ONNX model (which supports `kind: "name"`). */
366
+ get supportsNameContext() {
367
+ return this.subwordsOnly;
368
+ }
369
+ async score(queries) {
370
+ if (queries.length === 0)
371
+ return [];
372
+ let flat;
373
+ if (this.subwordsOnly) {
374
+ const packed = packSubwords(queries);
375
+ flat = await this.run(new BigInt64Array(0), new BigInt64Array(0), packed.n, packed.features, packed);
376
+ }
377
+ else {
378
+ const { tokens, segments, features, n } = pack(queries);
379
+ const sub = packSubwords(queries);
380
+ flat = await this.run(tokens, segments, n, features, sub);
381
+ }
382
+ const out = [];
383
+ let index = 0;
384
+ for (const query of queries) {
385
+ out.push(Array.from(flat.subarray(index, index + query.candidates.length)));
386
+ index += query.candidates.length;
387
+ }
388
+ return out;
389
+ }
390
+ }