From 2e7156dc365101075f4669e866378964163161b5 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Wed, 2 Dec 2026 15:27:50 -0600 Subject: [PATCH] feat(speech): the speech capability over Cap'n Web, behind a gate 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 --- .gitignore | 2 ++ CONTRIBUTING.md | 6 ++++ README.md | 6 ++++ flake.nix | 6 ++++ speech/Makefile | 39 +++++++++++++++++++++++++ speech/default.nix | 31 ++++++++++++++++++++ speech/gate.js | 38 ++++++++++++++++++++++++ speech/gate.test.js | 50 ++++++++++++++++++++++++++++++++ speech/hear-client.js | 46 +++++++++++++++++++++++++++++ speech/hear.sh | 12 ++++++++ speech/package-lock.json | 44 ++++++++++++++++++++++++++++ speech/package.json | 15 ++++++++++ speech/run.js | 45 +++++++++++++++++++++++++++++ speech/server.js | 62 ++++++++++++++++++++++++++++++++++++++++ speech/server.nix | 24 ++++++++++++++++ speech/smoke.sh | 34 ++++++++++++++++++++++ speech/speak-client.js | 45 +++++++++++++++++++++++++++++ speech/speak.sh | 11 +++++++ speech/speech.js | 60 ++++++++++++++++++++++++++++++++++++++ speech/speech.test.js | 45 +++++++++++++++++++++++++++++ 20 files changed, 621 insertions(+) create mode 100644 speech/Makefile create mode 100644 speech/default.nix create mode 100644 speech/gate.js create mode 100644 speech/gate.test.js create mode 100755 speech/hear-client.js create mode 100755 speech/hear.sh create mode 100644 speech/package-lock.json create mode 100644 speech/package.json create mode 100644 speech/run.js create mode 100755 speech/server.js create mode 100644 speech/server.nix create mode 100755 speech/smoke.sh create mode 100755 speech/speak-client.js create mode 100755 speech/speak.sh create mode 100644 speech/speech.js create mode 100644 speech/speech.test.js diff --git a/.gitignore b/.gitignore index eb0fb52..a486efc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ result __pycache__/ ir-pico/cache/ +speech/cache/ +node_modules/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3630b43..f742b74 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,3 +20,9 @@ make test ``` Each module's docstring says what it is. Docs are only for what isn't code, such as [wiring](ir-pico/wiring.md). + +## Design + +### Capabilities on the wire + +The connections are [Cap'n Web](https://github.com/cloudflare/capnweb) over WebSockets, on a private network such as a Tailscale tailnet. A server listens with a [gate](speech/gate.js), not the capability itself: the gate hands the capability to whoever presents its key, compared in constant time, and a client can open and call in one round trip. Keys reach services through systemd's `LoadCredential` (`$CREDENTIALS_DIRECTORY`), never through argv, the environment, or the Nix store. diff --git a/README.md b/README.md index 398618c..09ece6f 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,12 @@ Agent: Here's the game. It started ten minutes ago. The game isn't on 4, 5, or 9. It's on a sports network in the hundreds, behind two **Power** buttons, the **Input** button, and the cable box's remote. Our elders have done their share; let the agent do this. +## Capabilities and confinement + +An agent in the living room should be able to do what it's for, and no more. A capability is a reference that both names a service and grants the right to use it. Each part holds capabilities for exactly the services it uses. The brain can press IR buttons and take one camera frame, but it can't reach a shell on the box or anyone's files. + +The parts talk over [Cap'n Web](https://github.com/cloudflare/capnweb); [CONTRIBUTING](CONTRIBUTING.md#capabilities-on-the-wire) says how. + ## Parts The agent is built from parts you can buy and solder: diff --git a/flake.nix b/flake.nix index 819188a..cdfb379 100644 --- a/flake.nix +++ b/flake.nix @@ -10,6 +10,11 @@ python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ]); in { + packages = forAll (pkgs: { + speech = pkgs.callPackage ./speech/server.nix { }; + speech-js = pkgs.callPackage ./speech/default.nix { }; + }); + # nix develop --command make test devShells = forAll (pkgs: { default = pkgs.mkShellNoCC { @@ -23,6 +28,7 @@ python3 -I -m doctest ir_commands.py pico_tty.py touch $out ''; + speech = self.packages.${pkgs.stdenv.hostPlatform.system}.speech-js; }); }; } diff --git a/speech/Makefile b/speech/Makefile new file mode 100644 index 0000000..51e7ea5 --- /dev/null +++ b/speech/Makefile @@ -0,0 +1,39 @@ +# speech: the agent's ears and voice, as a capability over Cap'n Web. +# Tools come from the flake: nix develop --command make test + +WHISPER = https://huggingface.co/ggerganov/whisper.cpp/resolve/main +MODEL = cache/ggml-base.en.bin +VOICES = https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/danny/low +VOICE = cache/en_US-danny-low.onnx +PORT = 18024 +PHRASE = Put on the ballgame. +UA = pdtv26-speech-setup (curl) + +.PHONY: help test smoke +.DELETE_ON_ERROR: + +## list targets +help: + @awk -f ../make-help.awk $(MAKEFILE_LIST) + +## the unit tests, in Nix's build sandbox: no network, no models +test: + nix build -L --no-link ..#speech-js + +## the server and clients, with node, sox, whisper, and piper +cache/speech: $(wildcard *.js *.sh *.nix package*.json) ../flake.nix ../flake.lock + nix build -L --out-link $@ ..#speech + +## whisper's English model (about 150 MB; once, kept in cache/) +$(MODEL): + mkdir -p cache + curl -fsSL -A '$(UA)' -o $@ $(WHISPER)/$(notdir $@) + +## a piper voice and its config (once, kept in cache/) +cache/en_US-danny-low.%: + mkdir -p cache + curl -fsSL -A '$(UA)' -o $@ $(VOICES)/$(notdir $@) + +## a round trip through a real server: speak PHRASE, hear it back, compare +smoke: cache/speech $(MODEL) $(VOICE) $(VOICE).json + ./smoke.sh cache/speech/bin $(MODEL) $(VOICE) $(PORT) '$(PHRASE)' diff --git a/speech/default.nix b/speech/default.nix new file mode 100644 index 0000000..fa3ab75 --- /dev/null +++ b/speech/default.nix @@ -0,0 +1,31 @@ +# pdtv26-speech: the speech capability's JavaScript, and its clients. +# npm runs here, in Nix's build sandbox, from package-lock.json; so do the tests. +# The output is plain JavaScript, the same on every architecture (allowedReferences keeps it so): +# each user supplies its own node, at lib/node_modules/pdtv26-speech/*.js. +{ lib, buildNpmPackage }: +buildNpmPackage { + pname = "pdtv26-speech"; + version = "0.1.0"; + src = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./package.json ./package-lock.json ./run.js + ./gate.js ./gate.test.js ./speech.js ./speech.test.js + ./server.js ./hear-client.js ./speak-client.js + ]; + }; + npmDepsHash = "sha256-C7Em37Mm3+mUHqQ2n37JshgLCByzMOlhgoQEex3CnlU="; + dontNpmBuild = true; + # The scripts' #!/usr/bin/env node stays as is: patched, it would tie the package to one node. + dontPatchShebangs = true; + npmInstallFlags = [ "--ignore-scripts" ]; + doCheck = true; + checkPhase = '' + runHook preCheck + # Every file parses, the server and clients included: no test imports them. + for f in *.js; do node --check "$f"; done + node --test + runHook postCheck + ''; + allowedReferences = [ ]; +} diff --git a/speech/gate.js b/speech/gate.js new file mode 100644 index 0000000..dc1f5bb --- /dev/null +++ b/speech/gate.js @@ -0,0 +1,38 @@ +/** + * @file The gate: hands a capability to whoever presents its key. + * A server listens with a gate, not the capability itself, so a connection gets nothing + * until it shows the key: open(key) returns the capability, and pipelines, so a client + * can open and call in one round trip. + */ +import { RpcTarget } from 'capnweb'; +import { createHash, timingSafeEqual } from 'node:crypto'; + +const digest = (s) => createHash('sha256').update(String(s)).digest(); + +/** + * @template T + */ +export class Gate extends RpcTarget { + #want; + #cap; + + /** + * @param {string} key unguessable, from a credential file + * @param {T} cap what open(key) hands out + */ + constructor(key, cap) { + super(); + this.#want = digest(key); + this.#cap = cap; + } + + /** + * @param {string} k + * @returns {T} + */ + open(k) { + // Digests are the same length whatever k is, so the comparison takes the same time. + if (!timingSafeEqual(digest(k), this.#want)) throw new Error('no such key'); + return this.#cap; + } +} diff --git a/speech/gate.test.js b/speech/gate.test.js new file mode 100644 index 0000000..6be3c0f --- /dev/null +++ b/speech/gate.test.js @@ -0,0 +1,50 @@ +// Tests for the gate: in process, and over a real Cap'n Web session on a MessageChannel; no network. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { newMessagePortRpcSession } from 'capnweb'; +import { Gate } from './gate.js'; +import { Speech } from './speech.js'; + +test('the right key opens the gate; a wrong one is refused', () => { + const cap = { it: 'the capability' }; + const gate = new Gate('k3y', cap); + assert.equal(gate.open('k3y'), cap); + assert.throws(() => gate.open('guess'), /no such key/); + assert.throws(() => gate.open(''), /no such key/); + assert.throws(() => gate.open(undefined), /no such key/); +}); + +/** A client's stub for a gate served across a MessageChannel. */ +const serve = (gate) => { + const { port1, port2 } = new MessageChannel(); + newMessagePortRpcSession(port1, gate); + const stub = newMessagePortRpcSession(port2); + return { stub, close: () => { stub[Symbol.dispose](); port1.close(); port2.close(); } }; +}; + +test('over a session: open and call in one round trip; a wrong key is refused', async () => { + const { stub, close } = serve(new Gate('k3y', new Speech(async (c) => `${c.length} bytes`))); + try { + assert.equal(await stub.open('k3y').transcribe(new Uint8Array(4)), '4 bytes'); + await assert.rejects(async () => stub.open('guess').transcribe(new Uint8Array(4)), /no such key/); + } finally { + close(); + } +}); + +test('over a session: only public methods reach across; private fields do not', async () => { + const transcribe = async () => 'secret'; + const { stub, close } = serve(new Gate('k3y', new Speech(transcribe))); + try { + // #want and #cap aren't properties at all; neither are Speech's #transcribe or #inTurn. + for (const name of ['want', 'cap', '#want', '#cap', 'constructor']) { + await assert.rejects(async () => stub[name](), undefined, `gate.${name}`); + } + const speech = stub.open('k3y'); + for (const name of ['transcribe_', '#transcribe', 'inTurn', '#inTurn', 'last']) { + await assert.rejects(async () => speech[name](), undefined, `speech.${name}`); + } + } finally { + close(); + } +}); diff --git a/speech/hear-client.js b/speech/hear-client.js new file mode 100755 index 0000000..78c914b --- /dev/null +++ b/speech/hear-client.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node +/** + * @file hear-client: send one clip to the speech capability and print the transcript. + * usage: hear-client.js URL < clip.wav + * The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv, where ps would show it. + */ +import { newWebSocketRpcSession } from 'capnweb'; +import { readFile } from 'node:fs/promises'; +import process from 'node:process'; +import { buffer } from 'node:stream/consumers'; + +/** + * Transcribe the clip on stdin, by way of the speech capability at URL. + * + * @param {object} [io] what it reaches; the process's own, by default + * @param {string[]} [io.argv] [URL] + * @param {Record} [io.env] for CREDENTIALS_DIRECTORY + * @param {typeof readFile} [io.read] reads the key + * @param {AsyncIterable} [io.stdin] the clip, a WAV file + * @param {{ write(s: string): unknown }} [io.stdout] the transcript goes here + * @param {typeof newWebSocketRpcSession} [io.connect] opens a session with the gate at URL + */ +const main = async ({ + argv = process.argv.slice(2), + env = process.env, + read = readFile, + stdin = process.stdin, + stdout = process.stdout, + connect = newWebSocketRpcSession, +} = {}) => { + const [url] = argv; + const key = (await read(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim(); + const clip = new Uint8Array(await buffer(stdin)); + const gate = connect(url); + try { + // Pipelined: open and transcribe in one round trip. + stdout.write(`${await gate.open(key).transcribe(clip)}\n`); + } finally { + gate[Symbol.dispose](); + } +}; + +main().catch((err) => { + console.error(`hear-client: ${err.message ?? err}`); + process.exitCode = 1; +}); diff --git a/speech/hear.sh b/speech/hear.sh new file mode 100755 index 0000000..9dc0e27 --- /dev/null +++ b/speech/hear.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# hear.sh MODEL: a WAV clip on stdin, whisper's transcript on stdout. +# The Nix build fills in @sox@ and @whisper@ (server.nix). +set -eu +model=$1 +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +cat > "$tmp/in.wav" +# mono, 16-bit, normalized: the box's mics are quiet (speech peaks near -27 dBFS) +@sox@/bin/sox "$tmp/in.wav" -r 16000 -c 1 -b 16 "$tmp/clip.wav" remix - gain -n -3 +@whisper@/bin/whisper-cli -m "$model" -f "$tmp/clip.wav" -t 4 -nt -np 2>"$tmp/err" \ + || { cat "$tmp/err" >&2; exit 1; } diff --git a/speech/package-lock.json b/speech/package-lock.json new file mode 100644 index 0000000..cbe2429 --- /dev/null +++ b/speech/package-lock.json @@ -0,0 +1,44 @@ +{ + "name": "pdtv26-speech", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pdtv26-speech", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "capnweb": "0.13.1", + "ws": "8.23.1" + } + }, + "node_modules/capnweb": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/capnweb/-/capnweb-0.13.1.tgz", + "integrity": "sha512-JEE/MYKv41blYv5MGGzKiT3DT4qz00AQ+NsmPSdVFVSKuy2/ggUI4aDGJO+jEvAXNXuZURoxo7hCfx+VKbM32g==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz", + "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/speech/package.json b/speech/package.json new file mode 100644 index 0000000..6687e95 --- /dev/null +++ b/speech/package.json @@ -0,0 +1,15 @@ +{ + "name": "pdtv26-speech", + "version": "0.1.0", + "description": "Speech for the agent at the TV: hear (transcribe) and speak, as a capability over Cap'n Web", + "private": true, + "type": "module", + "license": "Apache-2.0", + "scripts": { + "test": "node --test" + }, + "dependencies": { + "capnweb": "0.13.1", + "ws": "8.23.1" + } +} diff --git a/speech/run.js b/speech/run.js new file mode 100644 index 0000000..f1329fa --- /dev/null +++ b/speech/run.js @@ -0,0 +1,45 @@ +/** + * @file Helpers for the servers: run one command, and time and log a job. + * They reach only what they're given: spawn, and a clock. + */ + +/** + * A command bound to one program and its arguments: run(input) feeds it stdin and + * resolves to its stdout bytes, or rejects with its stderr. + * + * @param {typeof import('node:child_process').spawn} spawn + * @param {string} cmd + * @param {string[]} args + */ +export const makeCommand = (spawn, cmd, args) => (input) => new Promise((resolve, reject) => { + const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] }); + const out = [], err = []; + child.stdout.on('data', (d) => out.push(d)); + child.stderr.on('data', (d) => err.push(d)); + child.on('error', reject); + child.on('close', (code) => code === 0 + ? resolve(Buffer.concat(out)) + : reject(new Error(`${cmd} exit ${code}: ${Buffer.concat(err).toString().trim().slice(-500)}`))); + child.stdin.end(input); +}); + +/** + * Time a job and log how it went; failures are logged and rethrown. + * + * @template T + * @param {() => number} now milliseconds + * @param {string} what + * @param {() => Promise} job + * @param {(result: T) => string} describe + */ +export const timed = async (now, what, job, describe) => { + const t0 = now(); + try { + const result = await job(); + console.log(`${what} in ${now() - t0} ms: ${describe(result)}`); + return result; + } catch (err) { + console.error(`${what} failed after ${now() - t0} ms: ${err.message}`); + throw err; + } +}; diff --git a/speech/server.js b/speech/server.js new file mode 100755 index 0000000..1f3e3a1 --- /dev/null +++ b/speech/server.js @@ -0,0 +1,62 @@ +#!/usr/bin/env node +/** + * @file speech-server: the speech capability over Cap'n Web, behind a gate. + * usage: server.js HOST PORT HEAR_SH MODEL SPEAK_SH VOICE [PIPER_OPTION...] + * 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), with any PIPER_OPTIONs. + */ +import { newWebSocketRpcSession } from 'capnweb'; +import { spawn as spawnChild } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import process from 'node:process'; +import { WebSocketServer } from 'ws'; +import { Gate } from './gate.js'; +import { makeCommand, timed } from './run.js'; +import { Speech, MAX_CLIP_BYTES } from './speech.js'; + +/** + * Serve the speech capability, behind a gate, at HOST:PORT. + * + * @param {object} [io] what it reaches; the process's own, by default + * @param {string[]} [io.argv] HOST PORT HEAR_SH MODEL SPEAK_SH VOICE [PIPER_OPTION...] + * @param {Record} [io.env] for CREDENTIALS_DIRECTORY + * @param {typeof readFile} [io.read] reads the key + * @param {typeof spawnChild} [io.spawn] runs HEAR_SH and SPEAK_SH, and nothing else + * @param {() => number} [io.now] the clock, for timing jobs + * @param {(options: import('ws').ServerOptions) => WebSocketServer} [io.listen] + * @param {typeof newWebSocketRpcSession} [io.serve] serves the gate on one connection + */ +const main = async ({ + argv = process.argv.slice(2), + env = process.env, + read = readFile, + spawn = spawnChild, + now = Date.now, + listen = (options) => new WebSocketServer(options), + serve = newWebSocketRpcSession, +} = {}) => { + const [host, port, hearSh, model, speakSh, voice, ...piper] = argv; + const key = (await read(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim(); + const hear = makeCommand(spawn, hearSh, [model]); + const say = makeCommand(spawn, speakSh, [voice, ...piper]); + const speech = new Speech( + (clip) => timed(now, `heard ${clip.length} bytes`, + async () => (await hear(clip)).toString().trim(), (text) => text), + (text) => timed(now, `spoke ${text.length} chars`, + async () => new Uint8Array(await say(text)), (wav) => `${wav.length} bytes of WAV`), + ); + const gate = new Gate(key, speech); + // A clip travels as base64 inside JSON: 4/3 of its size, plus a little. + const wss = listen({ host, port: Number(port), maxPayload: Math.ceil(MAX_CLIP_BYTES * 1.4) }); + wss.on('connection', (ws, req) => { + console.log(`connection from ${req.socket.remoteAddress}`); + serve(ws, gate); + }); + console.log(`speech-server: listening on ${host}:${port}`); +}; + +main().catch((err) => { + console.error(err); + process.exitCode = 1; +}); diff --git a/speech/server.nix b/speech/server.nix new file mode 100644 index 0000000..24feee2 --- /dev/null +++ b/speech/server.nix @@ -0,0 +1,24 @@ +# The speech server and clients, with node, and the sox, whisper, and piper the server's scripts use. +# bin/speech-server HOST PORT MODEL VOICE [PIPER_OPTION...] +# bin/hear-client URL < clip.wav +# bin/speak-client URL < text > speech.wav +{ callPackage, runCommand, nodejs-slim, sox, whisper-cpp, piper-tts }: +let + js = callPackage ./default.nix { }; + dir = "${js}/lib/node_modules/pdtv26-speech"; +in +runCommand "pdtv26-speech" { } '' + mkdir -p $out/bin + substitute ${./hear.sh} $out/bin/hear.sh --subst-var-by sox ${sox} --subst-var-by whisper ${whisper-cpp} + substitute ${./speak.sh} $out/bin/speak.sh --subst-var-by piper ${piper-tts} + chmod +x $out/bin/hear.sh $out/bin/speak.sh + cat > $out/bin/speech-server < $out/bin/$c + done + chmod +x $out/bin/speech-server $out/bin/hear-client $out/bin/speak-client +'' diff --git a/speech/smoke.sh b/speech/smoke.sh new file mode 100755 index 0000000..58fefb8 --- /dev/null +++ b/speech/smoke.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# smoke.sh BIN MODEL VOICE PORT PHRASE: a speech round trip, by way of a real server and clients. +# Starts BIN/speech-server on localhost with a throwaway key, has it speak PHRASE +# with piper's noise off, so the same words come out the same way every time, +# then hear the WAV back, and compares the words, ignoring case and punctuation. +set -eu +bin=$1 model=$2 voice=$3 port=$4 phrase=$5 +tmp=$(mktemp -d) +pid= +trap '[ -n "$pid" ] && kill "$pid" 2>/dev/null; rm -rf "$tmp"' EXIT + +umask 077 +head -c 20 /dev/urandom | base32 > "$tmp/speech-key" +export CREDENTIALS_DIRECTORY="$tmp" + +"$bin/speech-server" 127.0.0.1 "$port" "$model" "$voice" --noise-scale 0 --noise-w-scale 0 > "$tmp/server.log" 2>&1 & +pid=$! +tries=0 +until grep -q listening "$tmp/server.log"; do + tries=$((tries + 1)) + [ "$tries" -le 50 ] || { cat "$tmp/server.log" >&2; exit 1; } + sleep 0.2 +done + +url=ws://127.0.0.1:$port/ +printf '%s\n' "$phrase" | "$bin/speak-client" "$url" > "$tmp/said.wav" +heard=$("$bin/hear-client" "$url" < "$tmp/said.wav") +cat "$tmp/server.log" + +words() { printf '%s' "$1" | tr -cd 'A-Za-z' | tr A-Z a-z; } +echo "said: $phrase" +echo "heard: $heard" +[ "$(words "$phrase")" = "$(words "$heard")" ] || { echo "smoke: they differ" >&2; exit 1; } +echo "smoke: same words" diff --git a/speech/speak-client.js b/speech/speak-client.js new file mode 100755 index 0000000..07d8d59 --- /dev/null +++ b/speech/speak-client.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node +/** + * @file speak-client: have the speech capability speak text; write the WAV to stdout. + * usage: speak-client.js URL < text > speech.wav + * The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv. + */ +import { newWebSocketRpcSession } from 'capnweb'; +import { readFile } from 'node:fs/promises'; +import process from 'node:process'; +import { text } from 'node:stream/consumers'; + +/** + * Speak the text on stdin, by way of the speech capability at URL. + * + * @param {object} [io] what it reaches; the process's own, by default + * @param {string[]} [io.argv] [URL] + * @param {Record} [io.env] for CREDENTIALS_DIRECTORY + * @param {typeof readFile} [io.read] reads the key + * @param {AsyncIterable} [io.stdin] the text + * @param {{ write(b: Uint8Array): unknown }} [io.stdout] the WAV goes here + * @param {typeof newWebSocketRpcSession} [io.connect] opens a session with the gate at URL + */ +const main = async ({ + argv = process.argv.slice(2), + env = process.env, + read = readFile, + stdin = process.stdin, + stdout = process.stdout, + connect = newWebSocketRpcSession, +} = {}) => { + const [url] = argv; + const key = (await read(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim(); + const words = (await text(stdin)).trim(); + const gate = connect(url); + try { + stdout.write(await gate.open(key).speak(words)); + } finally { + gate[Symbol.dispose](); + } +}; + +main().catch((err) => { + console.error(`speak-client: ${err.message ?? err}`); + process.exitCode = 1; +}); diff --git a/speech/speak.sh b/speech/speak.sh new file mode 100755 index 0000000..4b290d1 --- /dev/null +++ b/speech/speak.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# speak.sh VOICE [PIPER_OPTION...]: text on stdin, piper's WAV of it on stdout. +# VOICE is an .onnx with its .onnx.json beside it; options go to piper as they are. +# The Nix build fills in @piper@ (server.nix). +set -eu +voice=$1 +shift +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +@piper@/bin/piper -m "$voice" "$@" -f "$tmp/out.wav" 2>"$tmp/err" || { cat "$tmp/err" >&2; exit 1; } +cat "$tmp/out.wav" diff --git a/speech/speech.js b/speech/speech.js new file mode 100644 index 0000000..07326ec --- /dev/null +++ b/speech/speech.js @@ -0,0 +1,60 @@ +/** + * @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)); + } +} diff --git a/speech/speech.test.js b/speech/speech.test.js new file mode 100644 index 0000000..b00116c --- /dev/null +++ b/speech/speech.test.js @@ -0,0 +1,45 @@ +// Tests for the speech capability, in process: no network, no whisper, no piper. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { Speech, MAX_CLIP_BYTES, MAX_SPEAK_CHARS } from './speech.js'; + +const clip = new Uint8Array([82, 73, 70, 70]); // "RIFF" + +test('transcribe takes bytes, and not too many', async () => { + const speech = new Speech(async (c) => `${c.length} bytes`); + assert.equal(await speech.transcribe(clip), '4 bytes'); + assert.throws(() => speech.transcribe('UklGRg=='), /must be bytes/); + assert.throws(() => speech.transcribe(new Uint8Array(MAX_CLIP_BYTES + 1)), /over/); +}); + +test('one clip at a time, and a failure does not stall the next', async () => { + const log = []; + let n = 0; + const speech = new Speech(async () => { + const i = ++n; + log.push(`start ${i}`); + await new Promise((r) => setTimeout(r, 10)); + log.push(`end ${i}`); + if (i === 1) throw new Error('whisper failed'); + return `text ${i}`; + }); + const [a, b] = await Promise.allSettled([speech.transcribe(clip), speech.transcribe(clip)]); + assert.equal(a.status, 'rejected'); + assert.equal(b.value, 'text 2'); + assert.deepEqual(log, ['start 1', 'end 1', 'start 2', 'end 2']); +}); + +test('speak takes text, not too much, and shares the one-at-a-time turn', async () => { + const log = []; + const speech = new Speech( + async () => { log.push('transcribe'); return 'hi'; }, + async (text) => { log.push(`speak ${text}`); return new Uint8Array([82, 73, 70, 70]); }, + ); + const [heard, wav] = await Promise.all([speech.transcribe(clip), speech.speak('Hello.')]); + assert.equal(heard, 'hi'); + assert.deepEqual([...wav], [82, 73, 70, 70]); + assert.deepEqual(log, ['transcribe', 'speak Hello.']); + assert.throws(() => speech.speak(''), /needs text/); + assert.throws(() => speech.speak('x'.repeat(MAX_SPEAK_CHARS + 1)), /over/); + assert.throws(() => new Speech(async () => '').speak('hi'), /no voice/); +});