@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.
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Confusion-weighted edit distance.
3
+ *
4
+ * Damerau-Levenshtein (Levenshtein plus adjacent transposition) with per-pair
5
+ * substitution costs drawn from the OCR confusion model, and an early cutoff so
6
+ * that scanning a lexicon of tens of thousands of words stays cheap: most
7
+ * candidates are rejected after a few rows.
8
+ */
9
+
10
+ import { indelCost, substitutionCost } from './confusions.js';
11
+
12
+ /**
13
+ * Weighted edit distance between two words.
14
+ *
15
+ * @param {string} a
16
+ * @param {string} b
17
+ * @param {number} [maxCost] abandon once the best possible result exceeds this;
18
+ * the return value is then `Infinity` rather than the true distance
19
+ * @returns {number}
20
+ */
21
+ export function editDistance(a, b, maxCost = Infinity) {
22
+ if (a === b) return 0;
23
+ if (!a.length) return costOfAll(b);
24
+ if (!b.length) return costOfAll(a);
25
+
26
+ // A length difference already implies at least that many cheapest indels.
27
+ // Rejecting on it first avoids allocating for hopeless pairs.
28
+ if (Math.abs(a.length - b.length) * MIN_INDEL_COST > maxCost) return Infinity;
29
+
30
+ const n = a.length;
31
+ const m = b.length;
32
+
33
+ // Three rows are enough for Damerau-Levenshtein with adjacent transpositions.
34
+ // Shared buffers: this runs tens of thousands of times per lookup, and three
35
+ // allocations per pair dominated the cost.
36
+ ensureRows(m + 1);
37
+ let twoAgo = rowA;
38
+ let previous = rowB;
39
+ let current = rowC;
40
+
41
+ previous[0] = 0;
42
+ for (let j = 1; j <= m; j++) previous[j] = previous[j - 1] + indel(b.charCodeAt(j - 1));
43
+
44
+ for (let i = 1; i <= n; i++) {
45
+ const ca = a.charCodeAt(i - 1);
46
+ const caPrev = i > 1 ? a.charCodeAt(i - 2) : -1;
47
+ const delA = indel(ca);
48
+ current[0] = previous[0] + delA;
49
+ let rowMin = current[0];
50
+
51
+ for (let j = 1; j <= m; j++) {
52
+ const cb = b.charCodeAt(j - 1);
53
+ const deletion = previous[j] + delA;
54
+ const insertion = current[j - 1] + indel(cb);
55
+ const substitution = previous[j - 1] + substitute(ca, cb);
56
+
57
+ let best = deletion < insertion ? deletion : insertion;
58
+ if (substitution < best) best = substitution;
59
+
60
+ // Adjacent transposition. Two letters swapped is one OCR event, not two,
61
+ // and it happens often enough in cursive script to be worth modelling.
62
+ if (i > 1 && j > 1 && ca === b.charCodeAt(j - 2) && caPrev === cb) {
63
+ const swap = twoAgo[j - 2] + TRANSPOSITION_COST;
64
+ if (swap < best) best = swap;
65
+ }
66
+
67
+ current[j] = best;
68
+ if (best < rowMin) rowMin = best;
69
+ }
70
+
71
+ // Every remaining row can only add cost, so once the cheapest cell in this
72
+ // row exceeds the budget the pair cannot come back.
73
+ if (rowMin > maxCost) return Infinity;
74
+
75
+ const spare = twoAgo;
76
+ twoAgo = previous;
77
+ previous = current;
78
+ current = spare;
79
+ }
80
+
81
+ return previous[m];
82
+ }
83
+
84
+ let rowA = new Float64Array(32);
85
+ let rowB = new Float64Array(32);
86
+ let rowC = new Float64Array(32);
87
+ function ensureRows(size) {
88
+ if (rowA.length >= size) return;
89
+ rowA = new Float64Array(size * 2);
90
+ rowB = new Float64Array(size * 2);
91
+ rowC = new Float64Array(size * 2);
92
+ }
93
+
94
+ // Cost tables over the Arabic block (U+0600-U+06FF), indexed by code point
95
+ // offset, so the inner loop does array reads rather than string-keyed lookups.
96
+ // Characters outside the block fall back to the general functions.
97
+ const BLOCK = 0x0600;
98
+ const SPAN = 0x100;
99
+ const SUB_TABLE = new Float64Array(SPAN * SPAN);
100
+ const INDEL_TABLE = new Float64Array(SPAN);
101
+ for (let x = 0; x < SPAN; x++) {
102
+ const cx = String.fromCharCode(BLOCK + x);
103
+ INDEL_TABLE[x] = indelCost(cx);
104
+ for (let y = 0; y < SPAN; y++) SUB_TABLE[x * SPAN + y] = substitutionCost(cx, String.fromCharCode(BLOCK + y));
105
+ }
106
+
107
+ function indel(code) {
108
+ const x = code - BLOCK;
109
+ return x >= 0 && x < SPAN ? INDEL_TABLE[x] : indelCost(String.fromCharCode(code));
110
+ }
111
+
112
+ function substitute(ca, cb) {
113
+ if (ca === cb) return 0;
114
+ const x = ca - BLOCK;
115
+ const y = cb - BLOCK;
116
+ if (x >= 0 && x < SPAN && y >= 0 && y < SPAN) return SUB_TABLE[x * SPAN + y];
117
+ return substitutionCost(String.fromCharCode(ca), String.fromCharCode(cb));
118
+ }
119
+
120
+ /** Cheapest possible indel, used to bound the length-difference check. */
121
+ const MIN_INDEL_COST = 0.3;
122
+
123
+ /** A swap of two adjacent letters is one error, priced below two substitutions. */
124
+ const TRANSPOSITION_COST = 0.8;
125
+
126
+ function costOfAll(word) {
127
+ let total = 0;
128
+ for (const char of word) total += indelCost(char);
129
+ return total;
130
+ }
131
+
132
+ /**
133
+ * Normalise a distance to a 0..1 similarity, so scores are comparable between
134
+ * words of different lengths — a one-letter error in a three-letter word is a
135
+ * far weaker match than the same error in a twelve-letter word.
136
+ *
137
+ * @param {string} a
138
+ * @param {string} b
139
+ * @param {number} distance
140
+ * @returns {number} 1 for identical, approaching 0 as they diverge
141
+ */
142
+ export function similarity(a, b, distance) {
143
+ const longest = Math.max(a.length, b.length);
144
+ if (longest === 0) return 1;
145
+ if (!Number.isFinite(distance)) return 0;
146
+ return Math.max(0, 1 - distance / longest);
147
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,181 @@
1
+ // Type declarations for @uyghurcommunity/spell.
2
+
3
+ export interface Suggestion {
4
+ /** The proposed replacement, in the original inflected form. */
5
+ text: string;
6
+ /** 0..1 */
7
+ similarity: number;
8
+ /** Why the two were likely confused, when it is a single substitution. */
9
+ reason?: string;
10
+ }
11
+
12
+ export interface Issue {
13
+ type: 'unknown-word' | 'ambiguous-character';
14
+ /** UTF-16 offset into the original text. */
15
+ start: number;
16
+ /** Exclusive UTF-16 offset into the original text. */
17
+ end: number;
18
+ original: string;
19
+ suggestions: Suggestion[];
20
+ note?: string;
21
+ }
22
+
23
+ export interface NormalizationChange {
24
+ type: string;
25
+ from: string;
26
+ to: string;
27
+ count: number;
28
+ note: string;
29
+ }
30
+
31
+ export interface Analysis {
32
+ /** The text that was analysed, unchanged. */
33
+ text: string;
34
+ /** The text with safe normalizations applied. */
35
+ normalized: string;
36
+ /** What `normalize` would change. */
37
+ normalizations: NormalizationChange[];
38
+ issues: Issue[];
39
+ stats: { words: number; known: number; unknown: number };
40
+ }
41
+
42
+ export interface Edit {
43
+ start: number;
44
+ end: number;
45
+ replacement: string;
46
+ }
47
+
48
+ export interface WordAnalysis {
49
+ known: boolean;
50
+ stem: string | null;
51
+ suffixes: object[];
52
+ /** A very common look-alike, when the word is suspicious despite segmenting. */
53
+ shadow?: string;
54
+ }
55
+
56
+ export interface Neighbour {
57
+ word: string;
58
+ distance: number;
59
+ similarity: number;
60
+ }
61
+
62
+ export type Frequencies = Map<string, number> | Record<string, number>;
63
+
64
+ export class Lexicon {
65
+ constructor(words?: Iterable<string>, meta?: { name?: string; frequencies?: Frequencies });
66
+ readonly name: string;
67
+ readonly size: number;
68
+ /** Exact membership, without morphology. */
69
+ has(word: string): boolean;
70
+ add(word: string): void;
71
+ remove(word: string): boolean;
72
+ prefer(word: string): void;
73
+ isPreferred(word: string): boolean;
74
+ /** 0..1, on a log scale relative to the most frequent word. */
75
+ commonness(word: string): number;
76
+ /** Whether a surface form is recognised, directly or through a reachable stem. */
77
+ analyze(word: string): WordAnalysis;
78
+ neighbours(word: string, options?: { maxDistance?: number; limit?: number }): Neighbour[];
79
+ }
80
+
81
+ export interface StorageLike {
82
+ getItem(key: string): string | null;
83
+ setItem(key: string, value: string): void;
84
+ removeItem(key: string): void;
85
+ }
86
+
87
+ export class UserDictionary {
88
+ /** In memory unless `storage` is given (for example `localStorage`). */
89
+ constructor(options?: { storage?: StorageLike | null; storageKey?: string });
90
+ readonly size: number;
91
+ has(word: string): boolean;
92
+ list(): string[];
93
+ /** Learn one word, several words, or whitespace-separated text. Returns how many were new. */
94
+ learn(input: string | string[]): number;
95
+ forget(word: string): boolean;
96
+ clear(): void;
97
+ /** One word per line. */
98
+ export(): string;
99
+ /** Add the learned words to a lexicon (the default one if omitted) and keep it in sync. */
100
+ apply(lexicon?: Lexicon): Lexicon;
101
+ subscribe(listener: () => void): () => void;
102
+ }
103
+
104
+ export interface SpellChecker {
105
+ readonly lexicon: Lexicon;
106
+ /** Find issues in text. Offsets refer to the original text; nothing is rewritten. */
107
+ check(text: string, options?: { maxIssues?: number }): Analysis;
108
+ /** Ranked correction candidates for one word. */
109
+ suggest(word: string): Suggestion[];
110
+ /** Whether a word is recognised, directly or through its suffixes. */
111
+ isKnown(word: string): boolean;
112
+ /** Treat words as known from now on (and save them, if a dictionary was given). */
113
+ learn(input: string | string[]): number | void;
114
+ }
115
+
116
+ export interface SpellCheckerOptions {
117
+ /** Extra known words, for example a full word list. */
118
+ words?: Iterable<string>;
119
+ /** Corpus counts, used for ranking only. */
120
+ frequencies?: Frequencies;
121
+ /** Also include the built-in seed list. Default true. */
122
+ includeSeed?: boolean;
123
+ name?: string;
124
+ /** Personal words to treat as known, kept in sync as they change. */
125
+ dictionary?: UserDictionary;
126
+ }
127
+
128
+ export function createSpellChecker(options?: SpellCheckerOptions): SpellChecker;
129
+
130
+ export function normalize(text: string, options?: { collapseWhitespace?: boolean }): string;
131
+ export function describeNormalization(text: string): NormalizationChange[];
132
+ export function findAmbiguousCharacters(text: string): Array<{ index: number; char: string; candidates: string[]; note: string }>;
133
+
134
+ export function analyze(text: string, options?: { lexicon?: Lexicon; maxIssues?: number }): Analysis;
135
+ export function suggestFor(word: string, lexicon?: Lexicon): Suggestion[];
136
+ export function applyCorrections(text: string, accepted: Edit[]): string;
137
+ export function applyTopSuggestions(analysis: Analysis, options?: { types?: Array<Issue['type']>; minSimilarity?: number }): string;
138
+
139
+ /** The shared default lexicon (seed list unless replaced). Prefer `createSpellChecker` in libraries. */
140
+ export function getLexicon(): Lexicon;
141
+ export function loadLexicon(words: Iterable<string>, options?: { name?: string; includeSeed?: boolean; frequencies?: Map<string, number> }): Lexicon;
142
+ export function resetLexicon(): void;
143
+ export function addLexiconInitializer(fn: (lexicon: Lexicon) => void): () => void;
144
+
145
+ export const DEFAULT_LEXICON_URL: string;
146
+ export function parseLexiconTsv(text: string): { words: string[]; frequencies: Map<string, number> };
147
+ export const parseWordList: typeof parseLexiconTsv;
148
+ /** Fetch a "word<TAB>count" list once and make it the default lexicon. Resolves null on failure. */
149
+ export function ensureFullLexicon(options?: { url?: string; fetchImpl?: typeof fetch }): Promise<Lexicon | null>;
150
+
151
+ export interface Segmentation {
152
+ stem: string;
153
+ suffixes: object[];
154
+ depth: number;
155
+ }
156
+ export function segment(word: string, options?: { includeDerivational?: boolean; maxDepth?: number }): Segmentation[];
157
+ export function candidateStems(word: string): string[];
158
+ export function reattach(stem: string, suffixes: Array<{ suffix: string }>): string;
159
+
160
+ export interface Token {
161
+ text: string;
162
+ start: number;
163
+ end: number;
164
+ isWord: boolean;
165
+ }
166
+ export function tokenize(text: string): Token[];
167
+ export function words(text: string): Token[];
168
+ export function applyEdits(text: string, edits: Edit[]): string;
169
+ export function isArabicScript(text: string): boolean;
170
+ export function isNumeric(text: string): boolean;
171
+
172
+ export function editDistance(a: string, b: string, maxCost?: number): number;
173
+ export function similarity(a: string, b: string, distance?: number): number;
174
+
175
+ export const CONFUSION_GROUPS: ReadonlyArray<{ letters: string[]; cost: number; note?: string }>;
176
+ export function substitutionCost(a: string, b: string): number;
177
+ export function areConfusable(a: string, b: string): boolean;
178
+ export function explainDifference(a: string, b: string): { from: string; to: string; reason: string } | null;
179
+
180
+ export const SEED_ROOTS: readonly string[];
181
+ export const SEED_EXCEPTIONS: readonly string[];
package/src/index.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @uyghurcommunity/spell — Uyghur spell-checking and correction.
3
+ *
4
+ * Two capabilities, kept apart because they carry very different risk:
5
+ *
6
+ * normalize(text) Lossless encoding fixes: presentation forms folded to base
7
+ * letters, ک → ك, tatweel and zero-width characters removed.
8
+ * Safe to apply automatically.
9
+ *
10
+ * check(text) Everything that involves a judgement: characters that are
11
+ * not Uyghur but whose replacement depends on the word, and
12
+ * words the lexicon does not recognise. Returns suggestions
13
+ * with spans; it never rewrites text.
14
+ *
15
+ * Start with `createSpellChecker()`. The lower-level modules are exported too.
16
+ */
17
+
18
+ import { Lexicon } from './lexicon.js';
19
+ import { SEED_EXCEPTIONS, SEED_ROOTS } from './data/roots.js';
20
+ import { analyze, suggestFor } from './suggest.js';
21
+ import { normalize } from './normalize.js';
22
+
23
+ /**
24
+ * Create an independent spell checker.
25
+ *
26
+ * Without `words` it uses the small built-in seed list (a few hundred roots),
27
+ * which recognises inflected forms through morphology but flags most other
28
+ * words. For real text, pass a full word list such as the one in
29
+ * `@uyghurcommunity/spell-lexicon-wiki`.
30
+ *
31
+ * @param {object} [options]
32
+ * @param {Iterable<string>} [options.words] extra known words
33
+ * @param {Map<string, number>|Record<string, number>} [options.frequencies]
34
+ * corpus counts, used for ranking
35
+ * @param {boolean} [options.includeSeed=true] also include the built-in seed list
36
+ * @param {string} [options.name] label for the lexicon
37
+ * @param {import('./userDictionary.js').UserDictionary} [options.dictionary]
38
+ * personal words to treat as known
39
+ */
40
+ export function createSpellChecker({ words, frequencies, includeSeed = true, name, dictionary } = {}) {
41
+ const list = [...(includeSeed ? [...SEED_ROOTS, ...SEED_EXCEPTIONS] : []), ...(words ?? [])];
42
+ const lexicon = new Lexicon(list, { name: name ?? (words ? 'custom' : 'seed'), frequencies });
43
+ dictionary?.apply(lexicon);
44
+
45
+ return {
46
+ lexicon,
47
+ /** Find issues in text. Offsets refer to the original text. */
48
+ check: (text, options = {}) => analyze(text, { ...options, lexicon }),
49
+ /** Ranked correction candidates for one word. */
50
+ suggest: (word) => suggestFor(word, lexicon),
51
+ /** Whether a word is recognised, directly or through its suffixes. */
52
+ isKnown: (word) => lexicon.analyze(normalize(String(word ?? '').trim())).known,
53
+ /** Treat words as known from now on (and save them, if a dictionary was given). */
54
+ learn: (input) => (dictionary ? dictionary.learn(input) : void [].concat(input).forEach((w) => lexicon.add(w))),
55
+ };
56
+ }
57
+
58
+ export { normalize, describeNormalization, findAmbiguousCharacters } from './normalize.js';
59
+ export { analyze, suggestFor, applyCorrections, applyTopSuggestions } from './suggest.js';
60
+ export { Lexicon, getLexicon, loadLexicon, resetLexicon, addLexiconInitializer } from './lexicon.js';
61
+ export { parseLexiconTsv, parseWordList, ensureFullLexicon, DEFAULT_LEXICON_URL } from './lexiconLoader.js';
62
+ export { segment, candidateStems, reattach } from './morphology.js';
63
+ export { tokenize, words, applyEdits, isArabicScript, isNumeric } from './tokenize.js';
64
+ export { editDistance, similarity } from './distance.js';
65
+ export { CONFUSION_GROUPS, substitutionCost, areConfusable, explainDifference } from './confusions.js';
66
+ export { UserDictionary } from './userDictionary.js';
67
+ export { SEED_ROOTS, SEED_EXCEPTIONS } from './data/roots.js';