/** * @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} transcribe * @param {(text: string) => Promise} [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(); };