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:
@@ -38,6 +38,9 @@ STT_PROVIDER=builtin
|
|||||||
# STT_API_KEY=replace-with-your-stt-key
|
# STT_API_KEY=replace-with-your-stt-key
|
||||||
# STT_MODEL=whisper-1
|
# STT_MODEL=whisper-1
|
||||||
|
|
||||||
|
# How often the bridge asks Hermes whether a run has finished (milliseconds).
|
||||||
|
# HERMES_POLL_INTERVAL_MS=150
|
||||||
|
|
||||||
# --- Budgets (defaults shown) ------------------------------------------------
|
# --- Budgets (defaults shown) ------------------------------------------------
|
||||||
# HERMEVEN_CAPTURE_MAX_SECONDS=30
|
# HERMEVEN_CAPTURE_MAX_SECONDS=30
|
||||||
# HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS=30
|
# HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS=30
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export interface ControllerOptions {
|
|||||||
onChange?: (snapshot: Snapshot) => void;
|
onChange?: (snapshot: Snapshot) => void;
|
||||||
/** Receives each diagnostic entry (ids, codes, timings; never content). */
|
/** Receives each diagnostic entry (ids, codes, timings; never content). */
|
||||||
onNote?: (entry: DiagEntry) => void;
|
onNote?: (entry: DiagEntry) => void;
|
||||||
|
/** Override the poll schedule with one fixed interval (tests). */
|
||||||
pollIntervalMs?: number;
|
pollIntervalMs?: number;
|
||||||
submitAttempts?: number;
|
submitAttempts?: number;
|
||||||
submitRetryMs?: number;
|
submitRetryMs?: number;
|
||||||
@@ -88,7 +89,7 @@ export class Controller {
|
|||||||
private readonly device: DevicePort;
|
private readonly device: DevicePort;
|
||||||
private readonly now: () => number;
|
private readonly now: () => number;
|
||||||
private readonly newId: () => string;
|
private readonly newId: () => string;
|
||||||
private readonly pollIntervalMs: number;
|
private readonly pollIntervalMs: number | null;
|
||||||
private readonly submitAttempts: number;
|
private readonly submitAttempts: number;
|
||||||
private readonly submitRetryMs: number;
|
private readonly submitRetryMs: number;
|
||||||
private readonly micStallMs: number;
|
private readonly micStallMs: number;
|
||||||
@@ -97,7 +98,7 @@ export class Controller {
|
|||||||
this.device = options.device;
|
this.device = options.device;
|
||||||
this.now = options.now ?? Date.now;
|
this.now = options.now ?? Date.now;
|
||||||
this.newId = options.newId ?? (() => crypto.randomUUID());
|
this.newId = options.newId ?? (() => crypto.randomUUID());
|
||||||
this.pollIntervalMs = options.pollIntervalMs ?? 700;
|
this.pollIntervalMs = options.pollIntervalMs ?? null;
|
||||||
this.submitAttempts = options.submitAttempts ?? 4;
|
this.submitAttempts = options.submitAttempts ?? 4;
|
||||||
this.submitRetryMs = options.submitRetryMs ?? 1500;
|
this.submitRetryMs = options.submitRetryMs ?? 1500;
|
||||||
this.micStallMs = options.micStallMs ?? 3000;
|
this.micStallMs = options.micStallMs ?? 3000;
|
||||||
@@ -422,8 +423,10 @@ export class Controller {
|
|||||||
private async poll(generation: number, requestId: string): Promise<void> {
|
private async poll(generation: number, requestId: string): Promise<void> {
|
||||||
if (!this.client) return;
|
if (!this.client) return;
|
||||||
let failures = 0;
|
let failures = 0;
|
||||||
|
const started = this.now();
|
||||||
for (;;) {
|
for (;;) {
|
||||||
await sleep(failures ? Math.min(5000, this.pollIntervalMs * 2 ** Math.min(failures, 3)) : this.pollIntervalMs);
|
const interval = this.pollIntervalMs ?? pollDelay(this.now() - started);
|
||||||
|
await sleep(failures ? Math.min(5000, Math.max(interval, 250) * 2 ** Math.min(failures, 3)) : interval);
|
||||||
if (this.stale(generation)) return;
|
if (this.stale(generation)) return;
|
||||||
try {
|
try {
|
||||||
const result = await this.client.getTurn(requestId);
|
const result = await this.client.getTurn(requestId);
|
||||||
@@ -656,6 +659,17 @@ export class Controller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long to wait before asking the bridge again, given how long this turn has been running.
|
||||||
|
* Most answers arrive within a few seconds, so checks are frequent then; a long agent run is
|
||||||
|
* checked less often to spare the phone's radio and battery.
|
||||||
|
*/
|
||||||
|
export function pollDelay(elapsedMs: number): number {
|
||||||
|
if (elapsedMs < 8_000) return 200;
|
||||||
|
if (elapsedMs < 30_000) return 400;
|
||||||
|
return 1000;
|
||||||
|
}
|
||||||
|
|
||||||
function describe(err: unknown): string {
|
function describe(err: unknown): string {
|
||||||
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
|
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
|
||||||
if (err instanceof Error) return `${err.name}: ${err.message}`;
|
if (err instanceof Error) return `${err.name}: ${err.message}`;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
||||||
|
import { pollDelay } from '../src/core/controller.ts';
|
||||||
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
|
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
|
||||||
|
|
||||||
const ID1 = '11111111-1111-4111-8111-111111111111';
|
const ID1 = '11111111-1111-4111-8111-111111111111';
|
||||||
@@ -39,6 +40,18 @@ function result(requestId: string, over: Partial<TurnResult> = {}): TurnResult {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe('poll schedule', () => {
|
||||||
|
it('checks often while an answer is likely, and eases off for long runs', () => {
|
||||||
|
expect(pollDelay(0)).toBe(200);
|
||||||
|
expect(pollDelay(7_999)).toBe(200);
|
||||||
|
expect(pollDelay(8_000)).toBe(400);
|
||||||
|
expect(pollDelay(30_000)).toBe(1000);
|
||||||
|
expect(pollDelay(600_000)).toBe(1000);
|
||||||
|
// Stays far inside the bridge's 600 requests per minute per device.
|
||||||
|
expect(60_000 / pollDelay(0)).toBeLessThan(600);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('happy path', () => {
|
describe('happy path', () => {
|
||||||
it('READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER', () => {
|
it('READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER', () => {
|
||||||
let s = ready();
|
let s = ready();
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ calls no tools. They need a run against a real model with a tool that requires a
|
|||||||
|
|
||||||
## Consequences
|
## Consequences
|
||||||
|
|
||||||
- Polling adds up to one poll interval (500 ms by default) of latency to every answer.
|
- Polling adds up to one poll interval (150 ms by default) of latency to every answer.
|
||||||
- No token streaming to the HUD. Acceptable: the HUD shows whole pages, and streaming through the
|
- No token streaming to the HUD. Acceptable: the HUD shows whole pages, and streaming through the
|
||||||
Even WebView is undocumented.
|
Even WebView is undocumented.
|
||||||
- If the target Hermes runs without the durable run ledger, the idempotency guarantee weakens.
|
- If the target Hermes runs without the durable run ledger, the idempotency guarantee weakens.
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ weights:
|
|||||||
| 11 s of speech, process pinned to one core | about 1.7 s |
|
| 11 s of speech, process pinned to one core | about 1.7 s |
|
||||||
| Same, `whisper-tiny` | about 1.2 s, about 0.6 GB |
|
| Same, `whisper-tiny` | about 1.2 s, about 0.6 GB |
|
||||||
| Model download on first start | about 80 MB (`base`), cached afterwards |
|
| Model download on first start | about 80 MB (`base`), cached afterwards |
|
||||||
| Longest pause of the bridge's event loop while transcribing | about 0.4 s |
|
| Longest pause of the bridge's event loop while transcribing | 3 ms (the model runs in a worker thread) |
|
||||||
|
|
||||||
Pinning to one core made no difference to speed, so extra cores will not help; a single droplet
|
Pinning to one core made no difference to speed, so extra cores will not help; a single droplet
|
||||||
vCPU is the relevant unit. **A shared droplet vCPU is slower than that desktop core by an amount
|
vCPU is the relevant unit. **A shared droplet vCPU is slower than that desktop core by an amount
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ DigitalOcean droplet.
|
|||||||
| Tests | `services/bridge/test/builtinWhisper.test.ts`, `tests/real-stt/*` (with a public-domain speech fixture) |
|
| Tests | `services/bridge/test/builtinWhisper.test.ts`, `tests/real-stt/*` (with a public-domain speech fixture) |
|
||||||
| Deployment examples, **not run on a droplet** | `deploy/*`, `docs/deploy-droplet.md` |
|
| Deployment examples, **not run on a droplet** | `deploy/*`, `docs/deploy-droplet.md` |
|
||||||
| New dependency | `@huggingface/transformers` 4.3.2 (brings ONNX Runtime and `sharp`) |
|
| New dependency | `@huggingface/transformers` 4.3.2 (brings ONNX Runtime and `sharp`) |
|
||||||
|
| Whisper moved to a worker thread; polling shortened (bridge 150 ms; app 200/400/1000 ms by elapsed time) | `services/bridge/src/stt/whisperWorker.mjs`, `builtinWhisper.ts`, `config.ts`, `apps/even-client/src/core/controller.ts` |
|
||||||
|
|
||||||
## Changed files
|
## Changed files
|
||||||
|
|
||||||
@@ -54,8 +55,8 @@ Full detail, including failures along the way, is in `docs/test-evidence.md`.
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `npm ci` | clean install, 0 vulnerabilities reported |
|
| `npm ci` | clean install, 0 vulnerabilities reported |
|
||||||
| `npm run typecheck` | exit 0 |
|
| `npm run typecheck` | exit 0 |
|
||||||
| `npm test` | 130 passed, 0 failed (8 files) |
|
| `npm test` | 131 passed, 0 failed (8 files) |
|
||||||
| `npm run test:real-stt` | 4 passed, 0 failed |
|
| `npm run test:real-stt` | 7 passed, 0 failed |
|
||||||
| `npm run test:simulator` | 6 passed, 0 failed; 10 consecutive runs of the final revision |
|
| `npm run test:simulator` | 6 passed, 0 failed; 10 consecutive runs of the final revision |
|
||||||
| `npm run test:real-hermes` | 9 passed, 0 failed |
|
| `npm run test:real-hermes` | 9 passed, 0 failed |
|
||||||
| `npm run client:build` | built; bundle searched for server secrets, none |
|
| `npm run client:build` | built; bundle searched for server secrets, none |
|
||||||
@@ -68,7 +69,7 @@ Full detail, including failures along the way, is in `docs/test-evidence.md`.
|
|||||||
| Fakes only | 122 tests |
|
| Fakes only | 122 tests |
|
||||||
| Even simulator 0.9.5 | 6 scenarios, screenshots in `docs/evidence/simulator/` |
|
| Even simulator 0.9.5 | 6 scenarios, screenshots in `docs/evidence/simulator/` |
|
||||||
| Real Hermes v0.23.1, stub model | 9 scenarios |
|
| Real Hermes v0.23.1, stub model | 9 scenarios |
|
||||||
| Real STT | 4 scenarios: built-in Whisper on one clean archive recording |
|
| Real STT | 7 scenarios: built-in Whisper on one clean archive recording |
|
||||||
| Real model or tools | none |
|
| Real model or tools | none |
|
||||||
| Physical device | **none** |
|
| Physical device | **none** |
|
||||||
|
|
||||||
@@ -107,7 +108,8 @@ Offered as places to look, not as findings.
|
|||||||
- The client holds captured audio in memory for a possible resend until the user discards it.
|
- The client holds captured audio in memory for a possible resend until the user discards it.
|
||||||
- The real-Hermes test covers neither approvals nor the `unknown` status.
|
- The real-Hermes test covers neither approvals nor the `unknown` status.
|
||||||
- The built-in speech model is fetched from the Hugging Face hub at first start with no pinned
|
- The built-in speech model is fetched from the Hugging Face hub at first start with no pinned
|
||||||
revision or hash, and runs in the bridge's own process (a measured 0.4 s event-loop pause).
|
revision or hash. It runs in a worker thread of the bridge process, in plain JavaScript
|
||||||
|
(`whisperWorker.mjs`) that the type checker does not cover.
|
||||||
- The silence threshold in `builtinWhisper.ts` was chosen without any audio from the glasses.
|
- The silence threshold in `builtinWhisper.ts` was chosen without any audio from the glasses.
|
||||||
- The systemd hardening options in `deploy/` have never been run with ONNX Runtime.
|
- The systemd hardening options in `deploy/` have never been run with ONNX Runtime.
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -56,9 +56,10 @@ Stated so they are not mistaken for protections.
|
|||||||
3a. **The built-in model's files are downloaded from the Hugging Face hub on first start** and
|
3a. **The built-in model's files are downloaded from the Hugging Face hub on first start** and
|
||||||
are not pinned to a revision or checked against a known hash. A compromised hub account or
|
are not pinned to a revision or checked against a known hash. A compromised hub account or
|
||||||
path could serve different weights. Pinning a revision is a follow-up.
|
path could serve different weights. Pinning a revision is a follow-up.
|
||||||
3b. **While a recording is being transcribed the bridge can pause for a few hundred
|
3b. **The speech model runs in a worker thread of the bridge process**, not a separate
|
||||||
milliseconds** (measured about 0.4 s), because the model runs in the same process. Harmless
|
sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the
|
||||||
for one user; a worker thread would remove it.
|
native runtime could still take the bridge down; systemd restarts it and in-flight turns are
|
||||||
|
recovered or failed honestly.
|
||||||
4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone
|
4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone
|
||||||
does the same is unknown and is on the device checklist. If it does, recordings would be
|
does the same is unknown and is on the device checklist. If it does, recordings would be
|
||||||
visible to whoever can read that console.
|
visible to whoever can read that console.
|
||||||
|
|||||||
+22
-5
@@ -29,7 +29,7 @@ Exit 0, no diagnostics, for contracts, bridge, client and tests.
|
|||||||
```
|
```
|
||||||
$ npm test
|
$ npm test
|
||||||
Test Files 8 passed (8)
|
Test Files 8 passed (8)
|
||||||
Tests 130 passed (130)
|
Tests 131 passed (131)
|
||||||
```
|
```
|
||||||
|
|
||||||
Run after a clean `npm ci`. Six consecutive full runs were green after the fix described under
|
Run after a clean `npm ci`. Six consecutive full runs were green after the fix described under
|
||||||
@@ -40,7 +40,7 @@ Run after a clean `npm ci`. Six consecutive full runs were green after the fix d
|
|||||||
| `packages/contracts/test/contracts.test.ts` | 4 | Schema acceptance and rejection, error-code retryability |
|
| `packages/contracts/test/contracts.test.ts` | 4 | Schema acceptance and rejection, error-code retryability |
|
||||||
| `services/bridge/test/units.test.ts` | 13 | Config guards, credential expiry and renewal, pairing codes, adapter helpers |
|
| `services/bridge/test/units.test.ts` | 13 | Config guards, credential expiry and renewal, pairing codes, adapter helpers |
|
||||||
| `services/bridge/test/builtinWhisper.test.ts` | 8 | Built-in STT adapter with a stand-in recogniser: silence gate, language, ordering, cancel, load failure |
|
| `services/bridge/test/builtinWhisper.test.ts` | 8 | Built-in STT adapter with a stand-in recogniser: silence gate, language, ordering, cancel, load failure |
|
||||||
| `apps/even-client/test/reducer.test.ts` | 24 | State transitions, cancellation, stale and late results, connection loss |
|
| `apps/even-client/test/reducer.test.ts` | 25 | State transitions, cancellation, stale and late results, connection loss |
|
||||||
| `apps/even-client/test/layout.test.ts` | 16 | Pagination, Unicode, long answers, plain-text conversion, HUD frames fit |
|
| `apps/even-client/test/layout.test.ts` | 16 | Pagination, Unicode, long answers, plain-text conversion, HUD frames fit |
|
||||||
| `apps/even-client/test/events.test.ts` | 8 | Gesture mapping through the SDK's parser, the tap-has-no-eventType quirk |
|
| `apps/even-client/test/events.test.ts` | 8 | Gesture mapping through the SDK's parser, the tap-has-no-eventType quirk |
|
||||||
| `tests/integration/bridge.test.ts` | 40 | Auth, device binding, limits, rate limiting, STT and Hermes outcomes, duplicates, cancel, restart, redaction |
|
| `tests/integration/bridge.test.ts` | 40 | Auth, device binding, limits, rate limiting, STT and Hermes outcomes, duplicates, cancel, restart, redaction |
|
||||||
@@ -150,10 +150,10 @@ later turns well under 1 s. These are not performance figures for anything real.
|
|||||||
|
|
||||||
```
|
```
|
||||||
$ npm run test:real-stt
|
$ npm run test:real-stt
|
||||||
Tests 4 passed (4)
|
Tests 7 passed (7)
|
||||||
```
|
```
|
||||||
|
|
||||||
`onnx-community/whisper-base`, 8-bit weights, run in the bridge process on the CPU. The input is
|
`onnx-community/whisper-base`, 8-bit weights, run on the CPU in a worker thread of the bridge. The input is
|
||||||
`tests/real-stt/fixtures/jfk.wav`, 11.0 s of clean archive speech, uploaded through
|
`tests/real-stt/fixtures/jfk.wav`, 11.0 s of clean archive speech, uploaded through
|
||||||
`POST /v1/turns` as raw PCM exactly as the client uploads a capture.
|
`POST /v1/turns` as raw PCM exactly as the client uploads a capture.
|
||||||
|
|
||||||
@@ -163,6 +163,9 @@ $ npm run test:real-stt
|
|||||||
| Three seconds of digital silence: `stt_empty`, the agent is not called | pass |
|
| Three seconds of digital silence: `stt_empty`, the agent is not called | pass |
|
||||||
| Three seconds of very quiet noise: `stt_empty` | pass |
|
| Three seconds of very quiet noise: `stt_empty` | pass |
|
||||||
| A second recording with the model already loaded | pass |
|
| A second recording with the model already loaded | pass |
|
||||||
|
| Two devices submit recordings at the same moment: both transcribed, in turn | pass |
|
||||||
|
| A model id that does not exist: speech is `unavailable`, the bridge keeps answering | pass |
|
||||||
|
| Closing the adapter stops the worker; a closed adapter refuses work | pass |
|
||||||
|
|
||||||
Transcript produced: "And so my fellow Americans, ask not what your country can do for you, ask
|
Transcript produced: "And so my fellow Americans, ask not what your country can do for you, ask
|
||||||
what you can do for your country." That matches the recording.
|
what you can do for your country." That matches the recording.
|
||||||
@@ -174,7 +177,7 @@ Measurements from this run, one sample each, on an Intel i7-13850HX desktop:
|
|||||||
| Model load (files already cached) | 1.2 to 3.8 s |
|
| Model load (files already cached) | 1.2 to 3.8 s |
|
||||||
| 11.0 s of speech | 1.6 s |
|
| 11.0 s of speech | 1.6 s |
|
||||||
| Memory (resident) after loading / after transcribing | about 0.5 GB / 0.8 GB |
|
| Memory (resident) after loading / after transcribing | about 0.5 GB / 0.8 GB |
|
||||||
| Longest event-loop pause during transcription | 0.39 s |
|
| Longest event-loop pause during transcription | 0.39 s with the model in the bridge's main thread; **3 ms** after moving it to a worker thread |
|
||||||
| Same clip with the process pinned to one core | 1.7 s (no slower) |
|
| Same clip with the process pinned to one core | 1.7 s (no slower) |
|
||||||
|
|
||||||
Things this run also showed that are worth knowing:
|
Things this run also showed that are worth knowing:
|
||||||
@@ -190,6 +193,20 @@ Things this run also showed that are worth knowing:
|
|||||||
The bridge process was also started with default settings: it logged `stt.loading`, then
|
The bridge process was also started with default settings: it logged `stt.loading`, then
|
||||||
`stt.ready`, and answered `/healthz` throughout.
|
`stt.ready`, and answered `/healthz` throughout.
|
||||||
|
|
||||||
|
### Polling intervals
|
||||||
|
|
||||||
|
Shortened at Dan's request. These are settings, and their effect on a real answer has not been
|
||||||
|
measured on a phone.
|
||||||
|
|
||||||
|
| Loop | Before | Now |
|
||||||
|
|---|---|---|
|
||||||
|
| Bridge asks Hermes for run status | every 500 ms | every 150 ms (`HERMES_POLL_INTERVAL_MS`) |
|
||||||
|
| App asks the bridge for the turn | every 700 ms | every 200 ms for the first 8 s, 400 ms until 30 s, then 1 s |
|
||||||
|
|
||||||
|
Worst-case delay added by polling to an answer that arrives within 8 s: about 0.35 s, down from
|
||||||
|
about 1.2 s. The app's schedule eases off for long agent runs to limit radio use; battery impact
|
||||||
|
is unmeasured.
|
||||||
|
|
||||||
### Build and packaging
|
### Build and packaging
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ export async function createBridge(
|
|||||||
clearInterval(purge);
|
clearInterval(purge);
|
||||||
await app.close();
|
await app.close();
|
||||||
await engine.shutdown();
|
await engine.shutdown();
|
||||||
|
await stt.close?.();
|
||||||
db.close();
|
db.close();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
|||||||
apiKey: hermesKey,
|
apiKey: hermesKey,
|
||||||
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
||||||
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
|
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),
|
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
|
||||||
},
|
},
|
||||||
stt: {
|
stt: {
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ export class SttError extends Error {
|
|||||||
export interface SttAdapter {
|
export interface SttAdapter {
|
||||||
readonly configured: boolean;
|
readonly configured: boolean;
|
||||||
transcribe(request: TranscribeRequest): Promise<string>;
|
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. */
|
/** 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 { AUDIO_FORMAT } from '@hermeven/contracts';
|
||||||
import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
|
import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Built-in speech-to-text: OpenAI's Whisper model run inside the bridge process
|
* Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU
|
||||||
* on the CPU (ONNX Runtime via @huggingface/transformers). No audio leaves the
|
* (ONNX Runtime via @huggingface/transformers). No audio leaves the bridge host
|
||||||
* bridge host and no provider account is needed.
|
* 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
|
* The model files are downloaded from the Hugging Face hub the first time the
|
||||||
* bridge starts and are then read from `cacheDir`.
|
* bridge starts and are then read from `cacheDir`.
|
||||||
@@ -15,7 +19,7 @@ export interface BuiltinWhisperOptions {
|
|||||||
/** Weight precision. `q8` is the small, CPU-friendly default. */
|
/** Weight precision. `q8` is the small, CPU-friendly default. */
|
||||||
dtype: string;
|
dtype: string;
|
||||||
cacheDir: string;
|
cacheDir: string;
|
||||||
/** Test seam: replaces the model loader. */
|
/** Test seam: replaces the worker thread with an in-process recogniser. */
|
||||||
load?: () => Promise<Recognizer>;
|
load?: () => Promise<Recognizer>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,6 +56,8 @@ export function cleanTranscript(text: string): string {
|
|||||||
export class BuiltinWhisperStt implements SttAdapter {
|
export class BuiltinWhisperStt implements SttAdapter {
|
||||||
readonly configured = true;
|
readonly configured = true;
|
||||||
private recognizer: Promise<Recognizer> | null = null;
|
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. */
|
/** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */
|
||||||
private queue: Promise<unknown> = Promise.resolve();
|
private queue: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
@@ -64,7 +70,7 @@ export class BuiltinWhisperStt implements SttAdapter {
|
|||||||
|
|
||||||
private load(): Promise<Recognizer> {
|
private load(): Promise<Recognizer> {
|
||||||
if (!this.recognizer) {
|
if (!this.recognizer) {
|
||||||
const loading = (this.opts.load ?? (() => this.loadModel()))();
|
const loading = (this.opts.load ?? (() => this.startWorker()))();
|
||||||
this.recognizer = loading;
|
this.recognizer = loading;
|
||||||
// A failed load (no network on first start) must be retried on the next request.
|
// A failed load (no network on first start) must be retried on the next request.
|
||||||
loading.catch(() => {
|
loading.catch(() => {
|
||||||
@@ -74,13 +80,60 @@ export class BuiltinWhisperStt implements SttAdapter {
|
|||||||
return this.recognizer;
|
return this.recognizer;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async loadModel(): Promise<Recognizer> {
|
/** Start the worker, load the model in it, and return a function that runs one clip there. */
|
||||||
const { pipeline } = await import('@huggingface/transformers');
|
private startWorker(): Promise<Recognizer> {
|
||||||
const asr = await pipeline('automatic-speech-recognition', this.opts.model, {
|
return new Promise<Recognizer>((resolve, reject) => {
|
||||||
dtype: this.opts.dtype as never,
|
if (this.closed) return reject(new Error('closed'));
|
||||||
cache_dir: this.opts.cacheDir,
|
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> {
|
async transcribe(request: TranscribeRequest): Promise<string> {
|
||||||
@@ -110,8 +163,8 @@ export class BuiltinWhisperStt implements SttAdapter {
|
|||||||
});
|
});
|
||||||
this.queue = run.catch(() => undefined);
|
this.queue = run.catch(() => undefined);
|
||||||
|
|
||||||
// Inference cannot be interrupted. On cancel or deadline the caller stops waiting; the
|
// A clip already in the model is left to finish. On cancel or deadline the caller stops
|
||||||
// result is discarded when it arrives and the queue keeps later requests in order.
|
// waiting; the result is discarded when it arrives and the queue keeps later requests in order.
|
||||||
return new Promise<string>((resolve, reject) => {
|
return new Promise<string>((resolve, reject) => {
|
||||||
const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));
|
const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));
|
||||||
if (request.signal.aborted) return onAbort();
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -90,6 +90,43 @@ describe('built-in Whisper speech-to-text', () => {
|
|||||||
expect(done.error?.code).toBe('stt_empty');
|
expect(done.error?.code).toBe('stt_empty');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('two recordings submitted together are both transcribed, one after the other', async () => {
|
||||||
|
const other = await h.pair('second-device');
|
||||||
|
const otherConversation = await h.conversation(other.token);
|
||||||
|
const [a, b] = await Promise.all([
|
||||||
|
h.audioTurn(token, conversation, Buffer.from(speech)),
|
||||||
|
h.audioTurn(other.token, otherConversation, Buffer.from(speech)),
|
||||||
|
]);
|
||||||
|
const [doneA, doneB] = await Promise.all([
|
||||||
|
h.waitTerminal(token, a.body.request_id, 120_000),
|
||||||
|
h.waitTerminal(other.token, b.body.request_id, 120_000),
|
||||||
|
]);
|
||||||
|
expect(doneA.input_text).toContain('fellow Americans');
|
||||||
|
expect(doneB.input_text).toContain('fellow Americans');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a model that cannot be loaded makes speech "unavailable" without taking the bridge down', async () => {
|
||||||
|
const broken = new BuiltinWhisperStt({ model: 'hermeven-test/does-not-exist', dtype: 'q8', cacheDir: resolve(here, '.cache') });
|
||||||
|
try {
|
||||||
|
const err = await broken
|
||||||
|
.transcribe({ pcm: Buffer.from(speech.subarray(0, 32000)), locale: 'en-US', signal: new AbortController().signal })
|
||||||
|
.catch((e) => e);
|
||||||
|
expect(err).toMatchObject({ name: 'SttError', kind: 'unavailable' });
|
||||||
|
} finally {
|
||||||
|
await broken.close();
|
||||||
|
}
|
||||||
|
expect((await h.api('GET', '/healthz')).status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closing the adapter stops its worker thread, and a closed adapter refuses further work', async () => {
|
||||||
|
const stt = new BuiltinWhisperStt({ model: h.config.stt.model, dtype: h.config.stt.dtype, cacheDir: resolve(here, '.cache') });
|
||||||
|
const signal = new AbortController().signal;
|
||||||
|
expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans');
|
||||||
|
await stt.close();
|
||||||
|
await stt.close();
|
||||||
|
await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' });
|
||||||
|
});
|
||||||
|
|
||||||
it('a second recording is transcribed with the model already warm', async () => {
|
it('a second recording is transcribed with the model already warm', async () => {
|
||||||
const res = await h.audioTurn(token, conversation, Buffer.from(speech.subarray(0, 6 * 32000)));
|
const res = await h.audioTurn(token, conversation, Buffer.from(speech.subarray(0, 6 * 32000)));
|
||||||
const done = await h.waitTerminal(token, res.body.request_id, 120_000);
|
const done = await h.waitTerminal(token, res.body.request_id, 120_000);
|
||||||
|
|||||||
Reference in New Issue
Block a user