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

speech.test.ts

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