STT_PROVIDER now defaults to "builtin": Whisper (onnx-community/whisper-base, q8) runs in the bridge process on the CPU via @huggingface/transformers, so no provider account is needed and recordings stay on the bridge host. Silent captures are detected by level before the model runs. The external OpenAI-compatible adapter remains available. Tests: 130 unit/integration; 4 scenarios with the real model on a real speech recording (npm run test:real-stt). Not tested on audio from the glasses or on a droplet. deploy/ and docs/deploy-droplet.md are examples that have not been run. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
123 lines
4.9 KiB
TypeScript
123 lines
4.9 KiB
TypeScript
import { AUDIO_FORMAT } from '@hermeven/contracts';
|
|
import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
|
|
|
|
/**
|
|
* Built-in speech-to-text: OpenAI's Whisper model run inside the bridge process
|
|
* on the CPU (ONNX Runtime via @huggingface/transformers). No audio leaves the
|
|
* bridge host and no provider account is needed.
|
|
*
|
|
* The model files are downloaded from the Hugging Face hub the first time the
|
|
* bridge starts and are then read from `cacheDir`.
|
|
*/
|
|
export interface BuiltinWhisperOptions {
|
|
/** Hub id, for example `onnx-community/whisper-base` (multilingual) or `...-base.en`. */
|
|
model: string;
|
|
/** Weight precision. `q8` is the small, CPU-friendly default. */
|
|
dtype: string;
|
|
cacheDir: string;
|
|
/** Test seam: replaces the model loader. */
|
|
load?: () => Promise<Recognizer>;
|
|
}
|
|
|
|
export type Recognizer = (audio: Float32Array, options: Record<string, unknown>) => Promise<{ text?: unknown } | Array<{ text?: unknown }>>;
|
|
|
|
/**
|
|
* Below this RMS level the capture is treated as silence and not transcribed.
|
|
* Whisper invents short phrases ("Thank you.") for silent input, which would
|
|
* otherwise be sent to the agent as if the user had said them. -55 dBFS.
|
|
*/
|
|
export const SILENCE_RMS = 0.0018;
|
|
|
|
export function pcmToFloat32(pcm: Buffer): Float32Array {
|
|
const samples = new Float32Array(Math.floor(pcm.length / 2));
|
|
for (let i = 0; i < samples.length; i++) samples[i] = pcm.readInt16LE(i * 2) / 32768;
|
|
return samples;
|
|
}
|
|
|
|
export function rms(samples: Float32Array): number {
|
|
if (samples.length === 0) return 0;
|
|
let sum = 0;
|
|
for (let i = 0; i < samples.length; i++) sum += samples[i]! * samples[i]!;
|
|
return Math.sqrt(sum / samples.length);
|
|
}
|
|
|
|
/** Whisper marks non-speech with bracketed or parenthesised tags; those are not words. */
|
|
export function cleanTranscript(text: string): string {
|
|
return text
|
|
.replace(/\[[^\]]*\]|\([^)]*\)/g, ' ')
|
|
.replace(/\s+/g, ' ')
|
|
.trim();
|
|
}
|
|
|
|
export class BuiltinWhisperStt implements SttAdapter {
|
|
readonly configured = true;
|
|
private recognizer: Promise<Recognizer> | null = null;
|
|
/** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */
|
|
private queue: Promise<unknown> = Promise.resolve();
|
|
|
|
constructor(private readonly opts: BuiltinWhisperOptions) {}
|
|
|
|
/** Load the model now (downloading it on first use) so the first question is not slow. */
|
|
async warm(): Promise<void> {
|
|
await this.load();
|
|
}
|
|
|
|
private load(): Promise<Recognizer> {
|
|
if (!this.recognizer) {
|
|
const loading = (this.opts.load ?? (() => this.loadModel()))();
|
|
this.recognizer = loading;
|
|
// A failed load (no network on first start) must be retried on the next request.
|
|
loading.catch(() => {
|
|
if (this.recognizer === loading) this.recognizer = null;
|
|
});
|
|
}
|
|
return this.recognizer;
|
|
}
|
|
|
|
private async loadModel(): Promise<Recognizer> {
|
|
const { pipeline } = await import('@huggingface/transformers');
|
|
const asr = await pipeline('automatic-speech-recognition', this.opts.model, {
|
|
dtype: this.opts.dtype as never,
|
|
cache_dir: this.opts.cacheDir,
|
|
});
|
|
return asr as unknown as Recognizer;
|
|
}
|
|
|
|
async transcribe(request: TranscribeRequest): Promise<string> {
|
|
const samples = pcmToFloat32(request.pcm);
|
|
if (samples.length < AUDIO_FORMAT.sampleRate / 10 || rms(samples) < SILENCE_RMS) return '';
|
|
|
|
const run = this.queue.then(async () => {
|
|
if (request.signal.aborted) throw new DOMException('Aborted', 'AbortError');
|
|
let recognizer: Recognizer;
|
|
try {
|
|
recognizer = await this.load();
|
|
} catch {
|
|
throw new SttError('unavailable', 'The speech model could not be loaded');
|
|
}
|
|
// English-only models take no language argument; multilingual ones are told the
|
|
// language from the device locale rather than left to guess it from a short clip.
|
|
const options: Record<string, unknown> = this.opts.model.endsWith('.en')
|
|
? {}
|
|
: { language: request.locale.split('-')[0]!.toLowerCase(), task: 'transcribe' };
|
|
try {
|
|
const out = await recognizer(samples, options);
|
|
const text = Array.isArray(out) ? out.map((o) => String(o.text ?? '')).join(' ') : String(out.text ?? '');
|
|
return cleanTranscript(text);
|
|
} catch {
|
|
throw new SttError('failed', 'The speech model failed on this recording');
|
|
}
|
|
});
|
|
this.queue = run.catch(() => undefined);
|
|
|
|
// Inference cannot be interrupted. On cancel or deadline the caller stops waiting; the
|
|
// result is discarded when it arrives and the queue keeps later requests in order.
|
|
return new Promise<string>((resolve, reject) => {
|
|
const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));
|
|
if (request.signal.aborted) return onAbort();
|
|
request.signal.addEventListener('abort', onAbort, { once: true });
|
|
run.then(resolve, reject).finally(() => request.signal.removeEventListener('abort', onAbort));
|
|
});
|
|
}
|
|
}
|