Run Whisper in a worker thread; shorten polling
The speech model now lives in a worker thread (whisperWorker.mjs), so loading and transcribing no longer block the bridge's HTTP server or its Hermes polling. Measured longest event-loop pause during transcription: 387 ms before, 3 ms after. A dead worker is replaced on the next request; closing the bridge terminates it. Polling: bridge to Hermes every 150 ms (was 500). The app polls the bridge every 200 ms for the first 8 s of a turn, 400 ms until 30 s, then 1 s (was a fixed 700 ms). Tests: 131 unit/integration, 7 real-speech, 9 real-Hermes, 6 simulator, all passing. Effect on a phone or a droplet is not measured. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -83,6 +83,7 @@ export async function createBridge(
|
||||
clearInterval(purge);
|
||||
await app.close();
|
||||
await engine.shutdown();
|
||||
await stt.close?.();
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -161,7 +161,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
apiKey: hermesKey,
|
||||
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
||||
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
|
||||
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 500, 20, 10_000),
|
||||
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 150, 20, 10_000),
|
||||
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
|
||||
},
|
||||
stt: {
|
||||
|
||||
@@ -22,6 +22,8 @@ export class SttError extends Error {
|
||||
export interface SttAdapter {
|
||||
readonly configured: boolean;
|
||||
transcribe(request: TranscribeRequest): Promise<string>;
|
||||
/** Release anything the adapter holds (threads, models). */
|
||||
close?(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Used when no provider is configured: audio turns fail cleanly, typed text still works. */
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { Worker } from 'node:worker_threads';
|
||||
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.
|
||||
* Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU
|
||||
* (ONNX Runtime via @huggingface/transformers). No audio leaves the bridge host
|
||||
* and no provider account is needed.
|
||||
*
|
||||
* The model lives in a worker thread (whisperWorker.mjs), so loading it and
|
||||
* transcribing never block the bridge's HTTP server or its Hermes polling.
|
||||
*
|
||||
* The model files are downloaded from the Hugging Face hub the first time the
|
||||
* bridge starts and are then read from `cacheDir`.
|
||||
@@ -15,7 +19,7 @@ export interface BuiltinWhisperOptions {
|
||||
/** Weight precision. `q8` is the small, CPU-friendly default. */
|
||||
dtype: string;
|
||||
cacheDir: string;
|
||||
/** Test seam: replaces the model loader. */
|
||||
/** Test seam: replaces the worker thread with an in-process recogniser. */
|
||||
load?: () => Promise<Recognizer>;
|
||||
}
|
||||
|
||||
@@ -52,6 +56,8 @@ export function cleanTranscript(text: string): string {
|
||||
export class BuiltinWhisperStt implements SttAdapter {
|
||||
readonly configured = true;
|
||||
private recognizer: Promise<Recognizer> | null = null;
|
||||
private worker: Worker | null = null;
|
||||
private closed = false;
|
||||
/** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
@@ -64,7 +70,7 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
|
||||
private load(): Promise<Recognizer> {
|
||||
if (!this.recognizer) {
|
||||
const loading = (this.opts.load ?? (() => this.loadModel()))();
|
||||
const loading = (this.opts.load ?? (() => this.startWorker()))();
|
||||
this.recognizer = loading;
|
||||
// A failed load (no network on first start) must be retried on the next request.
|
||||
loading.catch(() => {
|
||||
@@ -74,13 +80,60 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
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,
|
||||
/** Start the worker, load the model in it, and return a function that runs one clip there. */
|
||||
private startWorker(): Promise<Recognizer> {
|
||||
return new Promise<Recognizer>((resolve, reject) => {
|
||||
if (this.closed) return reject(new Error('closed'));
|
||||
const worker = new Worker(new URL('./whisperWorker.mjs', import.meta.url));
|
||||
this.worker = worker;
|
||||
// The model must never keep a stopping bridge alive.
|
||||
worker.unref();
|
||||
const waiting = new Map<number, { resolve: (text: string) => void; reject: (err: Error) => void }>();
|
||||
let nextId = 1;
|
||||
let loaded = false;
|
||||
|
||||
const fail = (reason: string) => {
|
||||
// Worker died or was terminated: forget it so the next request starts a fresh one.
|
||||
if (this.worker === worker) this.worker = null;
|
||||
if (this.recognizer && loaded) this.recognizer = null;
|
||||
for (const pending of waiting.values()) pending.reject(new Error(reason));
|
||||
waiting.clear();
|
||||
if (!loaded) reject(new Error(reason));
|
||||
};
|
||||
worker.on('error', () => fail('worker error'));
|
||||
worker.on('exit', () => fail('worker exited'));
|
||||
worker.on('message', (message: { type: string; id?: number; text?: string }) => {
|
||||
if (message.type === 'loaded') {
|
||||
loaded = true;
|
||||
resolve(
|
||||
(audio, options) =>
|
||||
new Promise((res, rej) => {
|
||||
const id = nextId++;
|
||||
waiting.set(id, { resolve: (text) => res({ text }), reject: rej });
|
||||
// Transfer, not copy: the samples are not needed on this side again.
|
||||
worker.postMessage({ type: 'run', id, samples: audio, options }, [audio.buffer as ArrayBuffer]);
|
||||
}),
|
||||
);
|
||||
} else if (message.type === 'load_failed') {
|
||||
void worker.terminate();
|
||||
} else if (message.id !== undefined) {
|
||||
const pending = waiting.get(message.id);
|
||||
waiting.delete(message.id);
|
||||
if (message.type === 'result') pending?.resolve(message.text ?? '');
|
||||
else pending?.reject(new Error('recognition failed'));
|
||||
}
|
||||
});
|
||||
worker.postMessage({ type: 'load', model: this.opts.model, dtype: this.opts.dtype, cacheDir: this.opts.cacheDir });
|
||||
});
|
||||
return asr as unknown as Recognizer;
|
||||
}
|
||||
|
||||
/** Stop the worker thread and free the model. Safe to call more than once. */
|
||||
async close(): Promise<void> {
|
||||
this.closed = true;
|
||||
const worker = this.worker;
|
||||
this.worker = null;
|
||||
this.recognizer = null;
|
||||
if (worker) await worker.terminate();
|
||||
}
|
||||
|
||||
async transcribe(request: TranscribeRequest): Promise<string> {
|
||||
@@ -110,8 +163,8 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
});
|
||||
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.
|
||||
// A clip already in the model is left to finish. 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();
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Worker thread that owns the Whisper model. Plain JavaScript on purpose: it is loaded
|
||||
// directly by `new Worker(...)`, so it must run without any TypeScript loader.
|
||||
//
|
||||
// Protocol (all messages are plain objects):
|
||||
// in : { type: 'load', model, dtype, cacheDir }
|
||||
// out: { type: 'loaded' } | { type: 'load_failed' }
|
||||
// in : { type: 'run', id, samples: Float32Array, options }
|
||||
// out: { type: 'result', id, text } | { type: 'failed', id }
|
||||
// Error details are deliberately not sent back: they could contain file paths, and nothing
|
||||
// derived from audio content should travel as an error string.
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
|
||||
let recognizer = null;
|
||||
|
||||
parentPort.on('message', async (message) => {
|
||||
if (message.type === 'load') {
|
||||
try {
|
||||
const { pipeline } = await import('@huggingface/transformers');
|
||||
recognizer = await pipeline('automatic-speech-recognition', message.model, {
|
||||
dtype: message.dtype,
|
||||
cache_dir: message.cacheDir,
|
||||
});
|
||||
parentPort.postMessage({ type: 'loaded' });
|
||||
} catch {
|
||||
parentPort.postMessage({ type: 'load_failed' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.type === 'run') {
|
||||
try {
|
||||
const out = await recognizer(message.samples, message.options);
|
||||
const text = Array.isArray(out) ? out.map((o) => String(o.text ?? '')).join(' ') : String(out.text ?? '');
|
||||
parentPort.postMessage({ type: 'result', id: message.id, text });
|
||||
} catch {
|
||||
parentPort.postMessage({ type: 'failed', id: message.id });
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user