import { describe, expect, it } from 'vitest'; import { SttError } from '../src/stt/adapter.ts'; import { BuiltinWhisperStt, cleanTranscript, pcmToFloat32, rms, SILENCE_RMS, type Recognizer } from '../src/stt/builtinWhisper.ts'; /** These use a stand-in recogniser. The real model is exercised by `npm run test:real-stt`. */ function tone(seconds: number, amplitude = 8000): Buffer { const buf = Buffer.alloc(Math.floor(seconds * 16000) * 2); for (let i = 0; i < buf.length / 2; i++) buf.writeInt16LE(Math.round(Math.sin(i / 5) * amplitude), i * 2); return buf; } const never = new AbortController().signal; const manifestFor = (model: string) => ({ name: 'test', model, revision: 'a'.repeat(40), dtype: 'q8', files: [] }); function make(recognizer: Recognizer, model = 'onnx-community/whisper-base') { let loads = 0; const calls: Array<{ samples: number; options: Record }> = []; const stt = new BuiltinWhisperStt({ manifest: manifestFor(model), modelDir: '/nonexistent', load: async () => { loads += 1; return async (audio, options) => { calls.push({ samples: audio.length, options }); return recognizer(audio, options); }; }, }); return { stt, calls, loads: () => loads }; } describe('built-in Whisper adapter', () => { it('converts PCM to normalised floats', () => { const buf = Buffer.alloc(6); buf.writeInt16LE(32767, 0); buf.writeInt16LE(-32768, 2); buf.writeInt16LE(0, 4); const f = pcmToFloat32(buf); expect(f[0]).toBeCloseTo(1, 3); expect(f[1]).toBe(-1); expect(f[2]).toBe(0); expect(rms(pcmToFloat32(tone(1)))).toBeGreaterThan(SILENCE_RMS * 50); }); it('never loads or runs the model for silence or for a clip too short to hold a word', async () => { const { stt, calls, loads } = make(async () => ({ text: 'Thank you.' })); expect(await stt.transcribe({ pcm: Buffer.alloc(32000), locale: 'en-US', signal: never })).toBe(''); expect(await stt.transcribe({ pcm: tone(1, 20), locale: 'en-US', signal: never })).toBe(''); expect(await stt.transcribe({ pcm: tone(0.05), locale: 'en-US', signal: never })).toBe(''); expect(calls).toHaveLength(0); expect(loads()).toBe(0); }); it('passes the device language to a multilingual model and nothing to an English-only one', async () => { const multi = make(async () => ({ text: ' Bonjour. ' })); expect(await multi.stt.transcribe({ pcm: tone(1), locale: 'fr-CA', signal: never })).toBe('Bonjour.'); expect(multi.calls[0]).toEqual({ samples: 16000, options: { language: 'fr', task: 'transcribe' } }); const en = make(async () => ({ text: 'Hello.' }), 'onnx-community/whisper-base.en'); await en.stt.transcribe({ pcm: tone(1), locale: 'fr-CA', signal: never }); expect(en.calls[0]!.options).toEqual({}); }); it('strips non-speech tags, so a clip of only noise tags is empty', () => { expect(cleanTranscript(' [BLANK_AUDIO] ')).toBe(''); expect(cleanTranscript('(wind blowing) Hello there [MUSIC]')).toBe('Hello there'); }); it('runs one transcription at a time, in order', async () => { let running = 0; let peak = 0; const { stt } = make(async (audio) => { running += 1; peak = Math.max(peak, running); await new Promise((r) => setTimeout(r, 30)); running -= 1; return { text: `len ${audio.length}` }; }); const results = await Promise.all([1, 2, 3].map((s) => stt.transcribe({ pcm: tone(s), locale: 'en-US', signal: never }))); expect(results).toEqual(['len 16000', 'len 32000', 'len 48000']); expect(peak).toBe(1); }); it('a cancelled request stops waiting at once and does not block the next one', async () => { const { stt } = make(async () => { await new Promise((r) => setTimeout(r, 150)); return { text: 'slow' }; }); const abort = new AbortController(); const first = stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: abort.signal }); setTimeout(() => abort.abort(), 20); const started = Date.now(); await expect(first).rejects.toMatchObject({ name: 'AbortError' }); expect(Date.now() - started).toBeLessThan(120); expect(await stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never })).toBe('slow'); const already = new AbortController(); already.abort(); await expect(stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: already.signal })).rejects.toMatchObject({ name: 'AbortError' }); }); it('a model that fails to load is "unavailable" and is retried next time', async () => { let attempts = 0; const stt = new BuiltinWhisperStt({ manifest: manifestFor('onnx-community/whisper-base'), modelDir: '/nonexistent', load: async () => { attempts += 1; if (attempts === 1) throw new Error('no network'); return async () => ({ text: 'recovered' }); }, }); await expect(stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never })).rejects.toMatchObject({ kind: 'unavailable' }); await new Promise((r) => setTimeout(r, 5)); expect(await stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never })).toBe('recovered'); expect(attempts).toBe(2); }); it('a model that throws on a recording is "failed", not a crash', async () => { const { stt } = make(async () => { throw new Error('bad tensor'); }); const err = await stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never }).catch((e) => e); expect(err).toBeInstanceOf(SttError); expect(err.kind).toBe('failed'); }); });