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

speech.test.ts

339 lines10.8 KB

1import { describe, expect, it } from "vite-plus/test";
2import { DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, SPEECH_MAX_OPTIONS_BYTES } from "@t3tools/contracts";
3​
4import {
5 chooseSetupSpeechModel,
6 recommendSpeechModels,
7 decodeSpeechPcmRequest,
8 encodeSpeechPcmRequest,
9 resolveSpeechVocabulary,
10 speechModelDownloadPercent,
11} from "./speech.ts";
12​
13describe("speechModelDownloadPercent", () => {
14 it.each([
15 { downloaded: 995, percent: 99 },
16 { downloaded: 1_000, percent: 99 },
17 ])("reads $downloaded of 1000 bytes as $percent", ({ downloaded, percent }) => {
18 expect(speechModelDownloadPercent(downloaded, 1_000)).toBe(percent);
19 });
20});
21​
22describe("speech PCM request framing", () => {
23 it("round-trips options and unaligned PCM without changing audio bytes", () => {
24 const pcm = new Uint8Array(new Float32Array([0.25, -0.5]).buffer);
25 const options = { ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, speechLanguage: "fr" };
26 const body = encodeSpeechPcmRequest(pcm, options);
27 const pool = new Uint8Array(body.length + 3);
28 pool.set(body, 3);
29 expect(decodeSpeechPcmRequest(pool.subarray(3))).toEqual({ pcm, options });
30 });
31​
32 it("accepts recordings from clients that predate silence filtering", () => {
33 const metadata = new TextEncoder().encode(
34 JSON.stringify({
35 speechLanguage: "fr",
36 speechTranslateToEnglish: false,
37 speechCustomWords: [],
38 speechRemoveFillerWords: false,
39 }),
40 );
41 const body = new Uint8Array(4 + metadata.length + 4);
42 new DataView(body.buffer).setUint32(0, metadata.length, true);
43 body.set(metadata, 4);
44 expect(decodeSpeechPcmRequest(body).options).toEqual({
45 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
46 speechLanguage: "fr",
47 speechRemoveFillerWords: false,
48 speechSilenceFiltering: true,
49 });
50 });
51​
52 it("rejects truncated frames, oversized option lengths and missing audio", () => {
53 expect(() => decodeSpeechPcmRequest(new Uint8Array(3))).toThrow();
54 const oversized = new Uint8Array(5);
55 new DataView(oversized.buffer).setUint32(0, SPEECH_MAX_OPTIONS_BYTES + 1, true);
56 expect(() => decodeSpeechPcmRequest(oversized)).toThrow();
57 expect(() =>
58 decodeSpeechPcmRequest(
59 encodeSpeechPcmRequest(new Uint8Array(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS),
60 ),
61 ).toThrow();
62 });
63});
64​
65describe("resolveSpeechVocabulary", () => {
66 it("prefers project spellings and keeps hints out of the dictionary", () => {
67 const personal = Array.from({ length: 100 }, (_, index) => ({
68 term: `word${index}`,
69 aliases: index === 0 ? ["Effect"] : [],
70 }));
71 const resolved = resolveSpeechVocabulary({
72 personal,
73 project: [{ term: "effect", aliases: ["a fact"] }],
74 hints: [" T3 Code ", "word1", "", "x".repeat(51), "t3 code"],
75 });
76 expect(resolved.speechHints).toEqual(["T3 Code"]);
77 expect(resolved.speechCustomWords).toHaveLength(100);
78 expect(resolved.speechCustomWords.slice(0, 2)).toEqual([
79 { term: "effect", aliases: ["a fact"] },
80 { term: "word0", aliases: [] },
81 ]);
82 expect(resolved.speechCustomWords.at(-1)?.term).toBe("word98");
83 });
84});
85​
86describe("chooseSetupSpeechModel", () => {
87 const model = (
88 id: string,
89 languages: string[],
90 supportsLanguageDetection: boolean,
91 recommended: boolean,
92 ) => ({
93 id,
94 languages,
95 supportsLanguageDetection,
96 recommended,
97 benchmark: {
98 accuracy: Object.fromEntries(
99 languages.map((language) => [language, { errorPercent: recommended ? 4 : 10 }]),
100 ),
101 secondsPer30s: { accelerated: 2, cpu: 3 },
102 },
103 });
104 const catalog = [
105 model("unrecommended", ["en", "de", "es"], true, false),
106 model("english", ["en"], false, true),
107 model("fixed", ["en", "de"], false, true),
108 model("detecting", ["en", "de", "fr"], true, true),
109 ];
110​
111 it.each([
112 [
113 "keeps the selected English model for an English speaker",
114 "english",
115 "auto",
116 ["en"],
117 { id: "english", language: "en" },
118 ],
119 [
120 "skips models that would transcribe English instead of German",
121 "english",
122 "auto",
123 ["de", "en"],
124 { id: "detecting", language: "de" },
125 ],
126 [
127 "accepts a model without detection for a chosen language",
128 "english",
129 "de",
130 ["en"],
131 { id: "fixed", language: "de" },
132 ],
133 [
134 "keeps a selected model that transcribes the language",
135 "unrecommended",
136 "auto",
137 ["de"],
138 { id: "unrecommended", language: "de" },
139 ],
140 [
141 "moves on to the next preferred language a model transcribes",
142 "english",
143 "auto",
144 ["ja", "fr"],
145 { id: "detecting", language: "fr" },
146 ],
147 [
148 "falls back to a model that is not recommended",
149 "english",
150 "auto",
151 ["es"],
152 { id: "unrecommended", language: "es" },
153 ],
154 ["offers nothing when no model transcribes the language", "english", "auto", ["ja"], undefined],
155 [
156 "offers the selected model without a language recommendation when Auto has no preferences",
157 "fixed",
158 "auto",
159 [],
160 { id: "fixed", language: null },
161 ],
162 [
163 "does not guess another model when Auto has no preferences or selection",
164 "gone",
165 "auto",
166 [],
167 undefined,
168 ],
169 ] as const)("%s", (_, selectedModelId, intent, preferred, expected) => {
170 const choice = chooseSetupSpeechModel(catalog, {
171 selectedModelId,
172 intent,
173 preferred,
174 benchmarkTier: "accelerated",
175 });
176 expect(choice && { id: choice.model.id, language: choice.language }).toEqual(expected);
177 });
178​
179 it("keeps suitable selections and preference order, and falls back safely without measurements", () => {
180 const best = {
181 ...catalog[0]!,
182 benchmark: {
183 accuracy: { de: { errorPercent: 1 } },
184 secondsPer30s: { accelerated: 1, cpu: 2 },
185 },
186 };
187 expect(
188 chooseSetupSpeechModel([...catalog, { ...best, id: "best" }], {
189 benchmarkTier: "accelerated",
190 selectedModelId: "gone",
191 intent: "auto",
192 preferred: ["de", "en"],
193 }),
194 ).toMatchObject({ model: { id: "best" }, language: "de", recommended: true });
195 expect(
196 chooseSetupSpeechModel([...catalog, { ...best, id: "best" }], {
197 benchmarkTier: "accelerated",
198 selectedModelId: "detecting",
199 intent: "auto",
200 preferred: ["de", "en"],
201 }),
202 ).toMatchObject({ model: { id: "detecting" }, language: "de", recommended: false });
203 const unmeasured = catalog.map(({ benchmark: _benchmark, ...model }) => model);
204 expect(
205 chooseSetupSpeechModel(unmeasured, {
206 benchmarkTier: "accelerated",
207 selectedModelId: "gone",
208 intent: "auto",
209 preferred: ["de", "en"],
210 }),
211 ).toMatchObject({ model: { id: "unrecommended" }, language: "de", recommended: false });
212 expect(
213 chooseSetupSpeechModel([], {
214 benchmarkTier: "accelerated",
215 selectedModelId: "gone",
216 intent: "auto",
217 preferred: [],
218 }),
219 ).toBeUndefined();
220 });
221});
222​
223describe("recommendSpeechModels", () => {
224 const model = (
225 id: string,
226 errors: Record<string, number>,
227 wait: number | null,
228 cpu: number | null,
229 ) => ({
230 id,
231 languages: Object.keys(errors),
232 benchmark: {
233 accuracy: Object.fromEntries(
234 Object.entries(errors).map(([language, errorPercent]) => [language, { errorPercent }]),
235 ),
236 secondsPer30s: { accelerated: wait, cpu },
237 },
238 });
239 const models = [
240 model("balanced", { en: 4, de: 16 }, 2, 7),
241 model("fast", { en: 7, de: 7 }, 1, 3),
242 model("accurate", { en: 2, de: 2 }, 8, 20),
243 model("incomplete", { en: 1 }, 1, 1),
244 ];
245​
246 it("balances all requested languages and assigns each model its first role", () => {
247 expect([...recommendSpeechModels(models.slice(0, 3), ["en"], "accelerated")]).toEqual([
248 ["balanced", "recommended"],
249 ["fast", "faster"],
250 ["accurate", "accurate"],
251 ]);
252 expect([...recommendSpeechModels(models, ["en", "de", "de"], "accelerated")]).toEqual([
253 ["fast", "recommended"],
254 ["accurate", "accurate"],
255 ]);
256 expect([...recommendSpeechModels(models.slice(0, 3), ["en"], "cpu")]).toEqual([
257 ["fast", "recommended"],
258 ["balanced", "accurate"],
259 ]);
260 expect([...recommendSpeechModels(models, ["en", "de"], "cpu")]).toEqual([
261 ["fast", "recommended"],
262 ]);
263 });
264​
265 it("offers alternatives only when they improve on the balanced pick on the same tier", () => {
266 expect([
267 ...recommendSpeechModels(
268 [model("cpu-fast-gpu-slow", { en: 3 }, 4, 1), model("balanced", { en: 3.2 }, 1, 8)],
269 ["en"],
270 "accelerated",
271 ),
272 ]).toEqual([
273 ["balanced", "recommended"],
274 ["cpu-fast-gpu-slow", "accurate"],
275 ]);
276 expect([
277 ...recommendSpeechModels(
278 [model("equal-accuracy", { en: 4 }, 8, 20), model("balanced", { en: 4 }, 2, 20)],
279 ["en"],
280 "accelerated",
281 ),
282 ]).toEqual([["balanced", "recommended"]]);
283 expect([
284 ...recommendSpeechModels(
285 [model("balanced", { en: 4 }, 12, 20), model("outside-budget", { en: 2 }, 30, 40)],
286 ["en"],
287 "accelerated",
288 ),
289 ]).toEqual([["balanced", "recommended"]]);
290 });
291​
292 it("does not invent measurements, preferences, or a model covering missing languages", () => {
293 expect(recommendSpeechModels(models, [], "accelerated").size).toBe(0);
294 expect(recommendSpeechModels(models, ["ja"], "accelerated").size).toBe(0);
295 expect(
296 recommendSpeechModels(
297 [
298 model("missing-speed", { en: 1, de: 1 }, null, 1),
299 { ...model("missing-accuracy", { en: 1 }, 1, 1), languages: ["en", "de"] },
300 ],
301 ["en", "de"],
302 "accelerated",
303 ).size,
304 ).toBe(0);
305 expect([
306 ...recommendSpeechModels([model("no-cpu", { en: 1 }, 1, null)], ["en"], "accelerated"),
307 ]).toEqual([["no-cpu", "recommended"]]);
308 expect(recommendSpeechModels([model("no-cpu", { en: 1 }, 1, null)], ["en"], "cpu").size).toBe(
309 0,
310 );
311 expect([
312 ...recommendSpeechModels([model("cpu-only", { en: 1 }, null, 2)], ["en"], "cpu"),
313 ]).toEqual([["cpu-only", "recommended"]]);
314 });
315​
316 it("prefers useful accuracy before speed and relaxes the wait budget before quality", () => {
317 expect([
318 ...recommendSpeechModels(
319 [model("poor", { en: 25 }, 1, 1), model("slow", { en: 4 }, 12, 20)],
320 ["en"],
321 "accelerated",
322 ),
323 ]).toEqual([["slow", "recommended"]]);
324 expect([
325 ...recommendSpeechModels(
326 [model("worse", { en: 30, de: 40 }, 1, 1), model("least-poor", { en: 29, de: 30 }, 20, 40)],
327 ["en", "de"],
328 "accelerated",
329 ),
330 ]).toEqual([["least-poor", "recommended"]]);
331 expect([
332 ...recommendSpeechModels(
333 [model("zero", { en: 0, de: 0 }, 1, 1)],
334 ["en", "de"],
335 "accelerated",
336 ),
337 ]).toEqual([["zero", "recommended"]]);
338 });
339});