Build speech-to-text into the bridge; add droplet deployment examples
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>
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.4.3",
|
||||
"@hermeven/contracts": "*",
|
||||
"@huggingface/transformers": "^4.3.2",
|
||||
"@sinclair/typebox": "^0.34.52",
|
||||
"better-sqlite3": "^13.2.0",
|
||||
"fastify": "^5.12.8",
|
||||
|
||||
@@ -7,11 +7,13 @@ import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { HermesRunsAdapter } from './hermes/runsAdapter.ts';
|
||||
import { buildServer } from './server.ts';
|
||||
import { NoSttAdapter, type SttAdapter } from './stt/adapter.ts';
|
||||
import { BuiltinWhisperStt } from './stt/builtinWhisper.ts';
|
||||
import { OpenAiCompatibleStt } from './stt/openaiCompatible.ts';
|
||||
import { TurnEngine, type EngineLog, type EngineTiming } from './turns.ts';
|
||||
|
||||
export interface Bridge {
|
||||
app: FastifyInstance;
|
||||
stt: SttAdapter;
|
||||
db: Db;
|
||||
devices: Devices;
|
||||
engine: TurnEngine;
|
||||
@@ -35,6 +37,9 @@ export function sttFromConfig(config: BridgeConfig): SttAdapter {
|
||||
if (config.stt.provider === 'openai-compatible') {
|
||||
return new OpenAiCompatibleStt({ baseUrl: config.stt.baseUrl, apiKey: config.stt.apiKey, model: config.stt.model });
|
||||
}
|
||||
if (config.stt.provider === 'builtin') {
|
||||
return new BuiltinWhisperStt({ model: config.stt.model, dtype: config.stt.dtype, cacheDir: config.stt.cacheDir });
|
||||
}
|
||||
return new NoSttAdapter();
|
||||
}
|
||||
|
||||
@@ -70,6 +75,7 @@ export async function createBridge(
|
||||
|
||||
return {
|
||||
app,
|
||||
stt,
|
||||
db,
|
||||
devices,
|
||||
engine,
|
||||
|
||||
@@ -22,10 +22,14 @@ export interface BridgeConfig {
|
||||
requestTimeoutMs: number;
|
||||
};
|
||||
stt: {
|
||||
provider: 'none' | 'openai-compatible';
|
||||
provider: 'none' | 'builtin' | 'openai-compatible';
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
/** Hub model id for `builtin`; provider model name for `openai-compatible`. */
|
||||
model: string;
|
||||
/** `builtin` only: weight precision and where model files are cached. */
|
||||
dtype: string;
|
||||
cacheDir: string;
|
||||
};
|
||||
limits: {
|
||||
captureMaxSeconds: number;
|
||||
@@ -122,9 +126,19 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
if (parsed.origin !== origin) throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry must be scheme://host[:port]: ${origin}`);
|
||||
}
|
||||
|
||||
const sttProvider = (env.STT_PROVIDER || 'none') as BridgeConfig['stt']['provider'];
|
||||
if (sttProvider !== 'none' && sttProvider !== 'openai-compatible') {
|
||||
throw new ConfigError('STT_PROVIDER must be "none" or "openai-compatible"');
|
||||
// Built-in Whisper is the default: voice works with no provider account and no audio
|
||||
// leaving the bridge host.
|
||||
const sttProvider = (env.STT_PROVIDER || 'builtin') as BridgeConfig['stt']['provider'];
|
||||
if (sttProvider !== 'none' && sttProvider !== 'builtin' && sttProvider !== 'openai-compatible') {
|
||||
throw new ConfigError('STT_PROVIDER must be "builtin", "openai-compatible" or "none"');
|
||||
}
|
||||
const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'onnx-community/whisper-base' : '');
|
||||
if (sttProvider === 'builtin' && !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(sttModel)) {
|
||||
throw new ConfigError('STT_MODEL must be a Hugging Face model id such as onnx-community/whisper-base');
|
||||
}
|
||||
const sttDtype = env.STT_DTYPE || 'q8';
|
||||
if (!['q8', 'q4', 'fp32', 'fp16', 'int8', 'uint8'].includes(sttDtype)) {
|
||||
throw new ConfigError('STT_DTYPE must be one of q8, q4, fp32, fp16, int8, uint8');
|
||||
}
|
||||
let sttBaseUrl = '';
|
||||
if (sttProvider === 'openai-compatible') {
|
||||
@@ -154,7 +168,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
provider: sttProvider,
|
||||
baseUrl: sttBaseUrl,
|
||||
apiKey: env.STT_API_KEY || '',
|
||||
model: env.STT_MODEL || '',
|
||||
model: sttModel,
|
||||
dtype: sttDtype,
|
||||
cacheDir: env.STT_CACHE_DIR || './data/models',
|
||||
},
|
||||
limits: {
|
||||
captureMaxSeconds,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { LOG_REDACT, createBridge } from './app.ts';
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { loadEnvFile } from './env.ts';
|
||||
import { BuiltinWhisperStt } from './stt/builtinWhisper.ts';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
loadEnvFile();
|
||||
@@ -10,6 +11,17 @@ async function main(): Promise<void> {
|
||||
});
|
||||
await bridge.app.listen({ host: config.host, port: config.port });
|
||||
|
||||
// Load the built-in speech model in the background so the first spoken question is not
|
||||
// slowed by it. On a first start this downloads the model files.
|
||||
if (bridge.stt instanceof BuiltinWhisperStt) {
|
||||
const started = Date.now();
|
||||
bridge.app.log.info({ model: config.stt.model, dtype: config.stt.dtype }, 'stt.loading');
|
||||
bridge.stt.warm().then(
|
||||
() => bridge.app.log.info({ load_ms: Date.now() - started }, 'stt.ready'),
|
||||
() => bridge.app.log.error({ model: config.stt.model }, 'stt.load_failed'),
|
||||
);
|
||||
}
|
||||
|
||||
let closing = false;
|
||||
const stop = (signal: string) => {
|
||||
if (closing) return;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
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));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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;
|
||||
|
||||
function make(recognizer: Recognizer, model = 'onnx-community/whisper-base') {
|
||||
let loads = 0;
|
||||
const calls: Array<{ samples: number; options: Record<string, unknown> }> = [];
|
||||
const stt = new BuiltinWhisperStt({
|
||||
model,
|
||||
dtype: 'q8',
|
||||
cacheDir: '/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({
|
||||
model: 'onnx-community/whisper-base',
|
||||
dtype: 'q8',
|
||||
cacheDir: '/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');
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { mapRunStatus } from '../src/hermes/runsAdapter.ts';
|
||||
import { RateLimiter } from '../src/ratelimit.ts';
|
||||
import { pcmToWav } from '../src/stt/adapter.ts';
|
||||
|
||||
const base = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:' };
|
||||
const base = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:', STT_PROVIDER: 'none' };
|
||||
|
||||
describe('configuration', () => {
|
||||
it('binds loopback by default and refuses a public bind without an explicit acknowledgement', () => {
|
||||
|
||||
Reference in New Issue
Block a user