Open History to see the last commit
1import type { SpeechCustomWords } from "@t3tools/contracts";
2
3/** Fuzzy-matches preferred terms and rewrites aliases to their preferred spelling. */
4export function makeSpeechTextCorrector(
5 words: readonly string[],
6 dictionary: SpeechCustomWords = [],
7) {
8 const MATCH_THRESHOLD = 0.18;
9
10 const matchKey = (value: string) =>
11 [...value]
12 .filter((character) => /[\p{L}\p{N}]/u.test(character))
13 .join("")
14 .toLocaleLowerCase();
15
16 const isAsciiKey = (value: string) => /^[a-z0-9]+$/i.test(value);
17
18 const soundex = (value: string) => {
19 const upper = value.toUpperCase();
20 const first = upper[0] ?? "";
21 const code = (character: string) => {
22 if ("BFPV".includes(character)) return "1";
23 if ("CGJKQSXZ".includes(character)) return "2";
24 if ("DT".includes(character)) return "3";
25 if (character === "L") return "4";
26 if ("MN".includes(character)) return "5";
27 if (character === "R") return "6";
28 return "0";
29 };
30 let previous = code(first);
31 let result = first;
32 for (const character of upper.slice(1)) {
33 const next = code(character);
34 if (next !== "0" && next !== previous) result += next;
35 previous = next;
36 }
37 return `${result}000`.slice(0, 4);
38 };
39
40 const editDistance = (left: string, right: string) => {
41 let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
42 for (let leftIndex = 0; leftIndex < left.length; leftIndex += 1) {
43 const current = [leftIndex + 1];
44 for (let rightIndex = 0; rightIndex < right.length; rightIndex += 1) {
45 current.push(
46 Math.min(
47 current[rightIndex]! + 1,
48 previous[rightIndex + 1]! + 1,
49 previous[rightIndex]! + (left[leftIndex] === right[rightIndex] ? 0 : 1),
50 ),
51 );
52 }
53 previous = current;
54 }
55 return previous[right.length]!;
56 };
57
58 const preserveCase = (original: string, replacement: string) => {
59 const letters = [...original].filter((character) => /\p{L}/u.test(character));
60 if (letters.length > 0 && letters.every((character) => character === character.toUpperCase()))
61 return replacement.toUpperCase();
62 const firstLetter = [...original].find((character) => /\p{L}/u.test(character));
63 if (firstLetter && firstLetter === firstLetter.toUpperCase()) {
64 const [first = "", ...rest] = [...replacement];
65 return first.toUpperCase() + rest.join("");
66 }
67 return replacement;
68 };
69
70 type CustomWordKey = { readonly word: string; readonly key: string };
71
72 const customWordKeys = (words: readonly string[]): CustomWordKey[] =>
73 words.flatMap((word) => {
74 const keys = [matchKey(word)];
75 if (word.includes("&")) keys.push(matchKey(word.replaceAll("&", " and ")));
76 return [...new Set(keys)].filter(isAsciiKey).map((key) => ({ word, key }));
77 });
78
79 const possessive = /['’]s$/iu;
80 const innerPossessives = (value: string) => value.match(/['’]s(?=\s)/giu)?.length ?? 0;
81 type Match = { readonly word: string; readonly score: number; readonly suffix: string };
82 const bestMatch = (phrase: string, keys: readonly CustomWordKey[]) => {
83 const key = matchKey(phrase);
84 const suffix = phrase.match(possessive)?.[0] ?? "";
85 const stem = suffix ? key.slice(0, -1) : key;
86 if (!isAsciiKey(stem) || stem.length > 50) return undefined;
87 const inner = innerPossessives(phrase);
88 let best: Match | undefined;
89 for (const custom of keys) {
90 if (inner > 0 && inner > innerPossessives(custom.word)) continue;
91 const keepSuffix = suffix !== "" && !possessive.test(custom.word);
92 const candidate = keepSuffix ? stem : key;
93 if (Math.min(candidate.length, custom.key.length) < 4 && candidate !== custom.key) continue;
94 const longest = Math.max(candidate.length, custom.key.length);
95 if (Math.abs(candidate.length - custom.key.length) > Math.max(longest * 0.25, 2)) continue;
96 const distance = editDistance(candidate, custom.key) / longest;
97 const phonetic = /^[a-z]+$/i.test(candidate) && /^[a-z]+$/i.test(custom.key);
98 const score =
99 phonetic && soundex(candidate) === soundex(custom.key) ? distance * 0.3 : distance;
100 if (score < MATCH_THRESHOLD && (!best || score < best.score))
101 best = { word: custom.word, score, suffix: keepSuffix ? suffix : "" };
102 }
103 return best;
104 };
105
106 const apply = (text: string): string => {
107 if (keys.length === 0) return text;
108 // Leave surrounding punctuation in the source; only horizontal whitespace can join words.
109 const tokens = [...text.matchAll(/[\p{L}\p{M}\p{N}](?:\S*[\p{L}\p{M}\p{N}])?/gu)]
110 .filter(([word]) => /^[\p{L}\p{M}\p{N}'’-]+$/u.test(word))
111 .map((match) => ({
112 value: match[0],
113 start: match.index,
114 end: match.index + match[0].length,
115 }));
116 const output: string[] = [];
117 let cursor = 0;
118 for (let index = 0; index < tokens.length;) {
119 let best: (Match & { readonly count: number }) | undefined;
120 for (let count = Math.min(4, tokens.length - index); count >= 1; count -= 1) {
121 const slice = tokens.slice(index, index + count);
122 if (
123 slice
124 .slice(0, -1)
125 .some(
126 (token, offset) =>
127 !/^[\t\p{Zs}]+$/u.test(text.slice(token.end, slice[offset + 1]!.start)),
128 )
129 )
130 continue;
131 const match = bestMatch(text.slice(slice[0]!.start, slice[count - 1]!.end), keys);
132 if (
133 match &&
134 (!best || match.score < best.score || (match.score === best.score && count < best.count))
135 )
136 best = { count, ...match };
137 }
138 if (!best) {
139 index += 1;
140 continue;
141 }
142 const first = tokens[index]!;
143 output.push(
144 text.slice(cursor, first.start),
145 preserveCase(first.value, best.word),
146 best.suffix,
147 );
148 cursor = tokens[index + best.count - 1]!.end;
149 index += best.count;
150 }
151 output.push(text.slice(cursor));
152 return output.join("");
153 };
154
155 const keys = customWordKeys(words);
156 const escapePattern = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
157
158 const spellings = dictionary
159 .flatMap(({ term, aliases }) => [term, ...aliases].map((spelling) => ({ spelling, term })))
160 .sort((left, right) => right.spelling.length - left.spelling.length);
161 if (spellings.length === 0) return apply;
162 const lookup = new Map(
163 spellings.map(({ spelling, term }) => [spelling.toLocaleLowerCase(), term]),
164 );
165 const word = "[\\p{L}\\p{M}\\p{N}\\p{Pc}]";
166 const pattern = new RegExp(
167 `(?<!${word})(?:${spellings.map(({ spelling }) => escapePattern(spelling)).join("|")})(?!${word})`,
168 "giu",
169 );
170 return (text: string) => {
171 let output = "";
172 let cursor = 0;
173 for (const match of text.matchAll(pattern)) {
174 output += apply(text.slice(cursor, match.index));
175 output += lookup.get(match[0].toLocaleLowerCase()) ?? match[0];
176 cursor = match.index + match[0].length;
177 }
178 return output + apply(text.slice(cursor));
179 };
180}
181
182export function applySpeechAliases(text: string, words: SpeechCustomWords): string {
183 return makeSpeechTextCorrector([], words)(text);
184}
185
186const normalizeWord = (word: string) => word.replace(/\s+/g, " ").trim();
187
188export function normalizeSpeechCustomWords(words: SpeechCustomWords): SpeechCustomWords {
189 const seen = new Set<string>();
190 return words
191 .flatMap(({ term, aliases }) => {
192 const preferred = normalizeWord(term);
193 const key = preferred.toLocaleLowerCase();
194 if (!preferred || preferred.length > 50 || seen.has(key)) return [];
195 seen.add(key);
196 const normalizedAliases = aliases.flatMap((alias) => {
197 const value = normalizeWord(alias);
198 const aliasKey = value.toLocaleLowerCase();
199 if (!value || value.length > 50 || seen.has(aliasKey)) return [];
200 seen.add(aliasKey);
201 return [value];
202 });
203 return [{ term: preferred, aliases: normalizedAliases.slice(0, 8) }];
204 })
205 .slice(0, 100);
206}