/** * @file speech-server: the speech capability over Cap'n Web, behind a gate. * usage: node server.js HOST PORT HEAR_SH MODEL SPEAK_SH VOICE * The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv, where ps would show it. * HEAR_SH MODEL reads a WAV on stdin and prints whisper's transcript (hear.sh). * SPEAK_SH VOICE reads text on stdin and writes piper's WAV of it (speak.sh). */ import { WebSocketServer } from 'ws'; import { newWebSocketRpcSession } from 'capnweb'; import { readFile } from 'node:fs/promises'; import { makeGate } from './gate.js'; import { makeSpeech, MAX_CLIP_BYTES } from './speech.js'; import { runWith, timed } from './run.js'; const main = async ([host, port, hearSh, model, speakSh, voice], env) => { const key = (await readFile(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim(); const speech = makeSpeech( (clip) => timed(`heard ${clip.length} bytes`, async () => (await runWith(hearSh, [model], clip)).toString().trim(), (text) => text), (text) => timed(`spoke ${text.length} chars`, async () => new Uint8Array(await runWith(speakSh, [voice], text)), (wav) => `${wav.length} bytes of WAV`), ); const gate = makeGate(key, speech); // A clip travels as base64 inside JSON: 4/3 of its size, plus a little. const wss = new WebSocketServer({ host, port: Number(port), maxPayload: Math.ceil(MAX_CLIP_BYTES * 1.4) }); wss.on('connection', (ws, req) => { console.log(`connection from ${req.socket.remoteAddress}`); newWebSocketRpcSession(ws, gate); }); console.log(`speech-server: listening on ${host}:${port}`); }; main(process.argv.slice(2), process.env).catch((err) => { console.error(err); process.exit(1); });