Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

customWords.ts

228 lines9.0 KB

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