@uyghurcommunity/spell 0.0.0-stage → 0.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.
package/src/lexicon.js ADDED
@@ -0,0 +1,406 @@
1
+ /**
2
+ * Lexicon container and lookup.
3
+ *
4
+ * Holds a set of known roots and answers two questions: is this word known, and
5
+ * what known words are near it. The near-neighbour search is the expensive one,
6
+ * so the lexicon is indexed by length and by first letter to avoid scanning
7
+ * every entry for every query.
8
+ */
9
+
10
+ import { editDistance, similarity } from './distance.js';
11
+ import { CONFUSION_GROUPS, SKELETON_CLASS, SKELETON_CLASS_COUNT } from './confusions.js';
12
+ import { attachesCleanly, harmonizes, particleHosts, segment, unraise, verbRoots } from './morphology.js';
13
+ import { SEED_ROOTS, SEED_EXCEPTIONS } from './data/roots.js';
14
+
15
+ /**
16
+ * @typedef {object} Neighbour
17
+ * @property {string} word
18
+ * @property {number} distance
19
+ * @property {number} similarity
20
+ */
21
+
22
+ /**
23
+ * See Lexicon#shadowOf. Chosen on the benchmark: at 300 every additional flag
24
+ * was a real OCR error; a lower count catches more errors but starts flagging
25
+ * correct words.
26
+ */
27
+ export const SHADOW_MIN_COUNT = 300;
28
+
29
+ const INITIAL_HAMZA_MISREADS = new Set(['گ', 'ك', 'ق']);
30
+ /** Letters Tesseract confuses cheaply (cost ≤ 0.5 in CONFUSION_GROUPS). */
31
+ const LOOKALIKES = new Map();
32
+ for (const group of CONFUSION_GROUPS) {
33
+ if (group.cost > 0.5) continue;
34
+ for (const a of group.letters) {
35
+ const others = LOOKALIKES.get(a) ?? new Set();
36
+ for (const b of group.letters) if (b !== a) others.add(b);
37
+ LOOKALIKES.set(a, others);
38
+ }
39
+ }
40
+
41
+ /** Spellings one look-alike letter swap away. */
42
+ export function lookalikeSwaps(word) {
43
+ const out = [];
44
+ for (let i = 0; i < word.length; i++) {
45
+ for (const b of LOOKALIKES.get(word[i]) ?? []) out.push(word.slice(0, i) + b + word.slice(i + 1));
46
+ }
47
+ return out;
48
+ }
49
+
50
+ export class Lexicon {
51
+ /**
52
+ * @param {Iterable<string>} [words]
53
+ * @param {{name?: string, frequencies?: Map<string, number>|Record<string, number>}} [meta]
54
+ */
55
+ constructor(words = [], meta = {}) {
56
+ /** @type {Set<string>} */
57
+ this.words = new Set();
58
+ /** Index from word length to the words of that length. */
59
+ this.byLength = new Map();
60
+ this.name = meta.name ?? 'lexicon';
61
+ /** Words the user has confirmed; ranked ahead at equal similarity. */
62
+ this.preferred = new Set();
63
+ /** Corpus counts, when the word list came with them. Used for ranking only. */
64
+ this.frequencies = meta.frequencies instanceof Map
65
+ ? meta.frequencies
66
+ : new Map(Object.entries(meta.frequencies ?? {}));
67
+ this.maxFrequency = 0;
68
+ for (const n of this.frequencies.values()) if (n > this.maxFrequency) this.maxFrequency = n;
69
+
70
+ for (const word of words) this.add(word);
71
+ }
72
+
73
+ /**
74
+ * How common a word is, on a 0..1 log scale relative to the most frequent
75
+ * word. 0 for words without a count (seed entries, learned words).
76
+ * @param {string} word
77
+ */
78
+ commonness(word) {
79
+ const n = this.frequencies.get(word);
80
+ if (!n || this.maxFrequency <= 1) return 0;
81
+ return Math.log(n + 1) / Math.log(this.maxFrequency + 1);
82
+ }
83
+
84
+ /** @param {string} word */
85
+ remove(word) {
86
+ if (!this.words.delete(word)) return false;
87
+ const bucket = this.byLength.get(word.length);
88
+ if (bucket) {
89
+ const index = bucket.indexOf(word);
90
+ if (index !== -1) bucket.splice(index, 1);
91
+ }
92
+ this.preferred.delete(word);
93
+ return true;
94
+ }
95
+
96
+ /** Mark a word as preferred when ranking suggestions. @param {string} word */
97
+ prefer(word) {
98
+ if (typeof word === 'string' && word.trim()) this.preferred.add(word.trim());
99
+ }
100
+
101
+ /** @param {string} word */
102
+ isPreferred(word) {
103
+ return this.preferred.has(word);
104
+ }
105
+
106
+ /** @param {string} word */
107
+ add(word) {
108
+ if (typeof word !== 'string') return;
109
+ const trimmed = word.trim();
110
+ if (!trimmed || this.words.has(trimmed)) return;
111
+
112
+ this.words.add(trimmed);
113
+ const bucket = this.byLength.get(trimmed.length);
114
+ if (bucket) bucket.push(trimmed);
115
+ else this.byLength.set(trimmed.length, [trimmed]);
116
+ }
117
+
118
+ get size() {
119
+ return this.words.size;
120
+ }
121
+
122
+ /** Exact membership, with no morphological analysis. */
123
+ has(word) {
124
+ return this.words.has(word);
125
+ }
126
+
127
+ /**
128
+ * Whether a surface form is recognised, trying the word itself and then each
129
+ * stem the morphology module can reach.
130
+ *
131
+ * @param {string} word
132
+ * @returns {{known: boolean, stem: string|null, suffixes: Array<object>}}
133
+ */
134
+ analyze(word) {
135
+ const result = this.analyzeAll(word);
136
+ if (result.known && result.suffixes.length) {
137
+ const shadow = this.shadowOf(word);
138
+ if (shadow) return { known: false, stem: null, suffixes: [], shadow };
139
+ }
140
+ return result;
141
+ }
142
+
143
+ /**
144
+ * A very common word one cheap OCR slip away from `word`, if any.
145
+ *
146
+ * A form that is only recognised through its suffixes, never seen whole, can
147
+ * be an OCR error that happens to segment: ئۈنىڭ parses as ئۈن + ىڭ, but is
148
+ * far likelier to be ئۇنىڭ with one vowel misread. When the lexicon holds
149
+ * such a look-alike SHADOW_MIN_COUNT times or more, the form is flagged and
150
+ * the look-alike suggested; the reader decides.
151
+ *
152
+ * @param {string} word
153
+ * @returns {string|null}
154
+ */
155
+ shadowOf(word) {
156
+ if (this.maxFrequency < SHADOW_MIN_COUNT) return null;
157
+ let best = null;
158
+ let bestCount = SHADOW_MIN_COUNT - 1;
159
+ const consider = (candidate) => {
160
+ const n = this.frequencies.get(candidate) ?? 0;
161
+ if (n > bestCount) {
162
+ best = candidate;
163
+ bestCount = n;
164
+ }
165
+ };
166
+ // Up to two look-alike letter swaps (Tesseract's usual slips: ۇ/ۈ، ن/ت…).
167
+ // Generating them is a few hundred map lookups, far cheaper than scanning
168
+ // the lexicon for neighbours.
169
+ for (const one of lookalikeSwaps(word)) {
170
+ consider(one);
171
+ for (const two of lookalikeSwaps(one)) consider(two);
172
+ }
173
+ // Tesseract reads a word-initial ئ as گ، ك or ق (گۇنىڭ for ئۇنىڭ).
174
+ if (INITIAL_HAMZA_MISREADS.has(word[0])) {
175
+ const fixed = 'ئ' + word.slice(1);
176
+ consider(fixed);
177
+ for (const one of lookalikeSwaps(fixed)) consider(one);
178
+ }
179
+ return best === word ? null : best;
180
+ }
181
+
182
+ /** @private */
183
+ analyzeAll(word) {
184
+ const direct = this.analyzeWithoutParticle(word);
185
+ if (direct.known) return direct;
186
+
187
+ for (const { host, particle } of particleHosts(word)) {
188
+ const result = this.analyzeWithoutParticle(host);
189
+ if (result.known) {
190
+ return { ...result, suffixes: [{ suffix: particle, label: 'particle', layer: 'particle' }, ...result.suffixes] };
191
+ }
192
+ }
193
+ return direct;
194
+ }
195
+
196
+ /** @private */
197
+ analyzeWithoutParticle(word) {
198
+ if (this.words.has(word)) return { known: true, stem: word, suffixes: [] };
199
+
200
+ for (const segmentation of segmentCached(word)) {
201
+ if (this.words.has(segmentation.stem) && harmonizes(segmentation.stem, segmentation.suffixes) && attachesCleanly(segmentation.stem, segmentation.suffixes)) {
202
+ return { known: true, stem: segmentation.stem, suffixes: segmentation.suffixes };
203
+ }
204
+ }
205
+
206
+ // A suffix may have raised the stem's last vowel: مەسىلىسى ← مەسىلە.
207
+ for (const segmentation of segmentCached(word)) {
208
+ if (!segmentation.suffixes.length) continue;
209
+ for (const stem of unraise(segmentation.stem)) {
210
+ if (this.words.has(stem) && harmonizes(stem, segmentation.suffixes) && attachesCleanly(stem, segmentation.suffixes)) {
211
+ return { known: true, stem, suffixes: segmentation.suffixes };
212
+ }
213
+ }
214
+ }
215
+
216
+ // Verb forms the lexicon's source text rarely uses (see VERB_ENDINGS).
217
+ for (const { root, suffix, label, forms } of verbRoots(word)) {
218
+ if (forms.some((form) => this.words.has(form))) {
219
+ return { known: true, stem: root, suffixes: [{ suffix, label, layer: 'verb' }] };
220
+ }
221
+ }
222
+ return { known: false, stem: null, suffixes: [] };
223
+ }
224
+
225
+ /**
226
+ * Known words within `maxDistance` of `word`, best first.
227
+ *
228
+ * Only lengths within the distance budget are scanned — a word cannot be two
229
+ * cheap edits away if it differs by five letters — which is what keeps this
230
+ * usable against a large lexicon.
231
+ *
232
+ * @param {string} word
233
+ * @param {{maxDistance?: number, limit?: number}} [options]
234
+ * @returns {Neighbour[]}
235
+ */
236
+ neighbours(word, { maxDistance = 1.2, limit = 5 } = {}) {
237
+ if (!word) return [];
238
+
239
+ const results = [];
240
+ // The cheapest possible indel is 0.3, so a length difference of n costs at
241
+ // least 0.3n; anything beyond that cannot fit the budget.
242
+ const maxLengthDelta = Math.floor(maxDistance / 0.3);
243
+ const bound = new SkeletonBound(word);
244
+
245
+ for (let length = word.length - maxLengthDelta; length <= word.length + maxLengthDelta; length++) {
246
+ const bucket = this.byLength.get(length);
247
+ if (!bucket) continue;
248
+
249
+ for (const candidate of bucket) {
250
+ if (bound.of(candidate) > maxDistance) continue;
251
+ const distance = editDistance(word, candidate, maxDistance);
252
+ // The row cutoff in editDistance is a bound, not a filter: a pair can
253
+ // survive it and still finish over budget. Enforce the budget here.
254
+ if (!(distance <= maxDistance)) continue;
255
+ results.push({ word: candidate, distance, similarity: similarity(word, candidate, distance) });
256
+ }
257
+ }
258
+
259
+ // At equal distance the more common word is the better guess.
260
+ results.sort(
261
+ (a, b) => a.distance - b.distance
262
+ || (this.frequencies.get(b.word) ?? 0) - (this.frequencies.get(a.word) ?? 0)
263
+ || a.word.localeCompare(b.word),
264
+ );
265
+ return results.slice(0, limit);
266
+ }
267
+ }
268
+
269
+ /**
270
+ * A cheap lower bound on `editDistance(query, candidate)`.
271
+ *
272
+ * Every cheap substitution in the confusion model stays inside one skeleton
273
+ * class (see `SKELETON_CLASS`), so it leaves per-class letter counts unchanged.
274
+ * What changes them is a cross-class substitution (cost 1, moves two counts) or
275
+ * an insertion/deletion (cost ≥ 0.5 for any letter, moves one count). Half the
276
+ * summed count difference is therefore a true lower bound, and it rejects most
277
+ * of a large lexicon without running the dynamic programme. Combining marks are
278
+ * ignored (treated as free), which only weakens the bound, never breaks it.
279
+ */
280
+ class SkeletonBound {
281
+ constructor(query) {
282
+ this.counts = new Int16Array(CLASS_SLOTS);
283
+ this.scratch = new Int16Array(CLASS_SLOTS);
284
+ this.touched = new Int32Array(64);
285
+ this.total = 0;
286
+ for (let i = 0; i < query.length; i++) {
287
+ const k = classSlot(query.charCodeAt(i));
288
+ if (k < 0) continue;
289
+ this.counts[k]++;
290
+ this.total++;
291
+ }
292
+ }
293
+
294
+ /** @param {string} candidate */
295
+ of(candidate) {
296
+ const { counts, scratch } = this;
297
+ let touched = this.touched;
298
+ if (touched.length < candidate.length) touched = this.touched = new Int32Array(candidate.length * 2);
299
+ let nTouched = 0;
300
+ for (let i = 0; i < candidate.length; i++) {
301
+ const k = classSlot(candidate.charCodeAt(i));
302
+ if (k < 0) continue;
303
+ if (scratch[k]++ === 0) touched[nTouched++] = k;
304
+ }
305
+ // Σ|q−c| over all classes = total(q) + Σ over touched (|q−c| − q).
306
+ let diff = this.total;
307
+ for (let t = 0; t < nTouched; t++) {
308
+ const k = touched[t];
309
+ const q = counts[k];
310
+ const c = scratch[k];
311
+ diff += (q > c ? q - c : c - q) - q;
312
+ scratch[k] = 0;
313
+ }
314
+ return diff * 0.5;
315
+ }
316
+ }
317
+
318
+ /** Skeleton classes, then 64 hashed slots for every other character. */
319
+ const CLASS_SLOTS = SKELETON_CLASS_COUNT + 64;
320
+ const SLOT_BY_CODE = new Map([...SKELETON_CLASS].map(([letter, k]) => [letter.charCodeAt(0), k]));
321
+
322
+ /** Class slot for a character, or -1 for combining marks (ignored). */
323
+ function classSlot(code) {
324
+ const k = SLOT_BY_CODE.get(code);
325
+ if (k !== undefined) return k;
326
+ if ((code >= 0x064b && code <= 0x065f) || code === 0x0670) return -1;
327
+ return SKELETON_CLASS_COUNT + (code & 63);
328
+ }
329
+
330
+ /**
331
+ * Segmentation is called repeatedly for the same words while the user edits, so
332
+ * the results are memoised. Bounded so a long session cannot grow it without
333
+ * limit.
334
+ */
335
+ const segmentationCache = new Map();
336
+ const SEGMENTATION_CACHE_LIMIT = 5000;
337
+
338
+ function segmentCached(word) {
339
+ const cached = segmentationCache.get(word);
340
+ if (cached) return cached;
341
+
342
+ const result = segment(word);
343
+ if (segmentationCache.size >= SEGMENTATION_CACHE_LIMIT) segmentationCache.clear();
344
+ segmentationCache.set(word, result);
345
+ return result;
346
+ }
347
+
348
+ /** The default lexicon, built from the seed list. */
349
+ let defaultLexicon = null;
350
+
351
+ /**
352
+ * The lexicon in use. Built from the seed roots on first call.
353
+ * @returns {Lexicon}
354
+ */
355
+ export function getLexicon() {
356
+ if (!defaultLexicon) {
357
+ defaultLexicon = new Lexicon([...SEED_ROOTS, ...SEED_EXCEPTIONS], { name: 'seed' });
358
+ runInitializers(defaultLexicon);
359
+ }
360
+ return defaultLexicon;
361
+ }
362
+
363
+ /** Callbacks run on every newly built default lexicon. */
364
+ const initializers = new Set();
365
+
366
+ /**
367
+ * Register a callback that extends each new default lexicon — how the personal
368
+ * dictionary survives `loadLexicon` and `resetLexicon` without this module
369
+ * having to know about it.
370
+ *
371
+ * @param {(lexicon: Lexicon) => void} fn
372
+ * @returns {() => void} unregister
373
+ */
374
+ export function addLexiconInitializer(fn) {
375
+ initializers.add(fn);
376
+ if (defaultLexicon) fn(defaultLexicon);
377
+ return () => initializers.delete(fn);
378
+ }
379
+
380
+ function runInitializers(lexicon) {
381
+ for (const fn of initializers) fn(lexicon);
382
+ }
383
+
384
+ /**
385
+ * Replace the active lexicon.
386
+ *
387
+ * The seed list is small and unreviewed (see `data/roots.js`); this is how a
388
+ * real word list is adopted. Any iterable of words works — one word per line
389
+ * from a fetched file, an imported array, an IndexedDB cursor.
390
+ *
391
+ * @param {Iterable<string>} words
392
+ * @param {{name?: string, includeSeed?: boolean, frequencies?: Map<string, number>}} [options]
393
+ * @returns {Lexicon}
394
+ */
395
+ export function loadLexicon(words, { name = 'custom', includeSeed = true, frequencies } = {}) {
396
+ const combined = includeSeed ? [...SEED_ROOTS, ...SEED_EXCEPTIONS, ...words] : words;
397
+ defaultLexicon = new Lexicon(combined, { name, frequencies });
398
+ runInitializers(defaultLexicon);
399
+ return defaultLexicon;
400
+ }
401
+
402
+ /** Restore the seed lexicon. Test seam, and an escape hatch in the UI. */
403
+ export function resetLexicon() {
404
+ defaultLexicon = null;
405
+ segmentationCache.clear();
406
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Loading a full word list at runtime.
3
+ *
4
+ * The bundled seed (`data/roots.js`) is a few hundred words so the engine works
5
+ * offline from the first byte. The full lexicon — 60k word forms with corpus
6
+ * frequencies, published separately as `@uyghurcommunity/spell-lexicon-wiki`
7
+ * (CC BY-SA 4.0) — is ~1.2 MB, so it is a static file fetched once, on first
8
+ * use, rather than part of the JavaScript bundle.
9
+ */
10
+
11
+ import { loadLexicon } from './lexicon.js';
12
+
13
+ /**
14
+ * Default URL for `ensureFullLexicon`: where an app serves the word list from
15
+ * `@uyghurcommunity/spell-lexicon-wiki` (copy `ug-wiki.tsv` into its static
16
+ * files). Pass `url` to load it from anywhere else.
17
+ */
18
+ export const DEFAULT_LEXICON_URL = '/lexicon/ug-wiki.tsv';
19
+
20
+ /**
21
+ * Parse "word<TAB>count" lines. Lines without a count are accepted (count 0),
22
+ * so a plain one-word-per-line list works too — e.g. one exported from the
23
+ * personal dictionary.
24
+ *
25
+ * @param {string} text
26
+ * @returns {{words: string[], frequencies: Map<string, number>}}
27
+ */
28
+ export function parseLexiconTsv(text) {
29
+ const words = [];
30
+ const frequencies = new Map();
31
+ for (const line of String(text ?? '').split('\n')) {
32
+ const [word, count] = line.split('\t');
33
+ const w = word?.trim();
34
+ if (!w || w.startsWith('#')) continue;
35
+ words.push(w);
36
+ const n = Number(count);
37
+ if (Number.isFinite(n) && n > 0) frequencies.set(w, n);
38
+ }
39
+ return { words, frequencies };
40
+ }
41
+
42
+ let pending = null;
43
+
44
+ /**
45
+ * Fetch and activate the full lexicon. Safe to call repeatedly: the download
46
+ * happens once and every caller shares it. A failure (offline on first visit,
47
+ * file missing from a deploy) leaves the seed lexicon in place and resolves to
48
+ * null — correction degrades, it does not break.
49
+ *
50
+ * @param {{url?: string, fetchImpl?: typeof fetch}} [options]
51
+ * @returns {Promise<import('./lexicon').Lexicon|null>}
52
+ */
53
+ export function ensureFullLexicon({ url = DEFAULT_LEXICON_URL, fetchImpl = globalThis.fetch } = {}) {
54
+ if (!pending) {
55
+ pending = (async () => {
56
+ try {
57
+ const response = await fetchImpl(url);
58
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
59
+ const { words, frequencies } = parseLexiconTsv(await response.text());
60
+ if (!words.length) throw new Error('empty lexicon');
61
+ return loadLexicon(words, { name: 'ug-wiki', frequencies });
62
+ } catch (error) {
63
+ console.warn(`Full Uyghur lexicon unavailable (${error.message}); using the seed list.`);
64
+ pending = null; // allow a later retry, e.g. once back online
65
+ return null;
66
+ }
67
+ })();
68
+ }
69
+ return pending;
70
+ }
71
+
72
+ /** Test seam. */
73
+ export function resetFullLexicon() {
74
+ pending = null;
75
+ }
76
+
77
+ /** Alias of `parseLexiconTsv`, for word lists that are not TSV files. */
78
+ export const parseWordList = parseLexiconTsv;