The agent's ears and voice: a server on the home server transcribes a clip (sox, whisper.cpp) and speaks text (piper), one job at a time. A gate hands the capability to whoever presents its key; the key comes from systemd's credentials, not argv. make test runs the unit tests in Nix's sandbox; make smoke starts a real server on localhost, speaks a phrase, and hears it back. Generated-by: Claude Opus 5.5
45 lines
1.6 KiB
JavaScript
45 lines
1.6 KiB
JavaScript
/**
|
|
* @file The speech capability: the agent's ears and voice.
|
|
* Who can transcribe a clip, or have text spoken, is who holds a Speech.
|
|
* @see gate.js, which hands one out; server.js, which serves it
|
|
*/
|
|
import { RpcTarget } from 'capnweb';
|
|
|
|
/** About 30 s of 32-bit stereo at 16 kHz, the box's mics' own format. */
|
|
export const MAX_CLIP_BYTES = 4_000_000;
|
|
|
|
/** A spoken reply: a few sentences. */
|
|
export const MAX_SPEAK_CHARS = 1000;
|
|
|
|
/**
|
|
* Speech: transcribe(clip) returns the text; speak(text) returns a WAV of it.
|
|
* One job at a time: whisper and piper each use all of a small server's cores.
|
|
* @param {(clip: Uint8Array) => Promise<string>} transcribe
|
|
* @param {(text: string) => Promise<Uint8Array>} [speak]
|
|
*/
|
|
export const makeSpeech = (transcribe, speak) => {
|
|
let last = Promise.resolve();
|
|
const inTurn = (job) => {
|
|
const result = last.then(job);
|
|
last = result.catch(() => {});
|
|
return result;
|
|
};
|
|
class Speech extends RpcTarget {
|
|
/** @param {Uint8Array} clip a WAV file */
|
|
transcribe(clip) {
|
|
if (!(clip instanceof Uint8Array)) throw new TypeError('clip must be bytes');
|
|
if (clip.length > MAX_CLIP_BYTES) throw new RangeError(`clip over ${MAX_CLIP_BYTES} bytes`);
|
|
return inTurn(() => transcribe(clip));
|
|
}
|
|
|
|
/** @param {string} text */
|
|
speak(text) {
|
|
if (!speak) throw new Error('no voice here');
|
|
if (typeof text !== 'string' || !text.trim()) throw new TypeError('speak needs text');
|
|
if (text.length > MAX_SPEAK_CHARS) throw new RangeError(`text over ${MAX_SPEAK_CHARS} chars`);
|
|
return inTurn(() => speak(text));
|
|
}
|
|
}
|
|
return new Speech();
|
|
};
|