/** * @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; /** * 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. */ export class Speech extends RpcTarget { #transcribe; #speak; /** @type {Promise} the job before this one */ #last = Promise.resolve(); /** * @param {(clip: Uint8Array) => Promise} transcribe * @param {(text: string) => Promise} [speak] */ constructor(transcribe, speak) { super(); this.#transcribe = transcribe; this.#speak = speak; } /** * @template T * @param {() => Promise} job * @returns {Promise} */ #inTurn(job) { const result = this.#last.then(job); this.#last = result.catch(() => {}); return result; } /** @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 this.#inTurn(() => this.#transcribe(clip)); } /** @param {string} text */ speak(text) { const speak = this.#speak; 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 this.#inTurn(() => speak(text)); } }