diff --git a/speech/default.nix b/speech/default.nix index b4b8afe..fa3ab75 100644 --- a/speech/default.nix +++ b/speech/default.nix @@ -16,6 +16,8 @@ buildNpmPackage { }; 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 = '' diff --git a/speech/gate.js b/speech/gate.js index ab0acf2..dc1f5bb 100644 --- a/speech/gate.js +++ b/speech/gate.js @@ -10,18 +10,29 @@ import { createHash, timingSafeEqual } from 'node:crypto'; const digest = (s) => createHash('sha256').update(String(s)).digest(); /** - * @param {string} key unguessable, from a credential file - * @param {object} cap what open(key) hands out + * @template T */ -export const makeGate = (key, cap) => { - const want = digest(key); - class Gate extends RpcTarget { - /** @param {string} k */ - open(k) { - // Digests are the same length whatever k is, so the comparison takes the same time. - if (!timingSafeEqual(digest(k), want)) throw new Error('no such key'); - return cap; - } +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; } - return new Gate(); -}; + + /** + * @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 index f6dfff9..6be3c0f 100644 --- a/speech/gate.test.js +++ b/speech/gate.test.js @@ -1,13 +1,50 @@ -// Tests for the gate, in process: no network. +// 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 { makeGate } from './gate.js'; +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 = makeGate('k3y', cap); + 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 old mode 100644 new mode 100755 index 75a7c3d..78c914b --- a/speech/hear-client.js +++ b/speech/hear-client.js @@ -1,16 +1,37 @@ +#!/usr/bin/env node /** * @file hear-client: send one clip to the speech capability and print the transcript. - * usage: node hear-client.js URL < clip.wav + * 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'; -const main = async ([url], env, stdin, stdout) => { - const key = (await readFile(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim(); +/** + * 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 = newWebSocketRpcSession(url); + const gate = connect(url); try { // Pipelined: open and transcribe in one round trip. stdout.write(`${await gate.open(key).transcribe(clip)}\n`); @@ -19,7 +40,7 @@ const main = async ([url], env, stdin, stdout) => { } }; -main(process.argv.slice(2), process.env, process.stdin, process.stdout).catch((err) => { +main().catch((err) => { console.error(`hear-client: ${err.message ?? err}`); - process.exit(1); + process.exitCode = 1; }); diff --git a/speech/run.js b/speech/run.js index 9705b79..f1329fa 100644 --- a/speech/run.js +++ b/speech/run.js @@ -1,10 +1,17 @@ /** - * @file Helpers for the servers: run a script, and time and log a job. + * @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. */ -import { spawn } from 'node:child_process'; -/** Run cmd with input on stdin; resolve to its stdout bytes, or reject with its stderr. */ -export const runWith = (cmd, args, input) => new Promise((resolve, reject) => { +/** + * 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)); @@ -16,15 +23,23 @@ export const runWith = (cmd, args, input) => new Promise((resolve, reject) => { child.stdin.end(input); }); -/** Time a job and log how it went; failures are logged and rethrown. */ -export const timed = async (what, job, describe) => { - const t0 = Date.now(); +/** + * 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 ${Date.now() - t0} ms: ${describe(result)}`); + console.log(`${what} in ${now() - t0} ms: ${describe(result)}`); return result; } catch (err) { - console.error(`${what} failed after ${Date.now() - t0} ms: ${err.message}`); + console.error(`${what} failed after ${now() - t0} ms: ${err.message}`); throw err; } }; diff --git a/speech/server.js b/speech/server.js old mode 100644 new mode 100755 index c0c584d..1f3e3a1 --- a/speech/server.js +++ b/speech/server.js @@ -1,36 +1,62 @@ +#!/usr/bin/env node /** * @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 + * 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). + * SPEAK_SH VOICE reads text on stdin and writes piper's WAV of it (speak.sh), with any PIPER_OPTIONs. */ -import { WebSocketServer } from 'ws'; import { newWebSocketRpcSession } from 'capnweb'; +import { spawn as spawnChild } from 'node:child_process'; 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'; +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'; -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`), +/** + * 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 = makeGate(key, speech); + const gate = new Gate(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) }); + 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}`); - newWebSocketRpcSession(ws, gate); + serve(ws, gate); }); console.log(`speech-server: listening on ${host}:${port}`); }; -main(process.argv.slice(2), process.env).catch((err) => { +main().catch((err) => { console.error(err); - process.exit(1); + process.exitCode = 1; }); diff --git a/speech/server.nix b/speech/server.nix index 6d4abce..24feee2 100644 --- a/speech/server.nix +++ b/speech/server.nix @@ -1,5 +1,5 @@ # 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 +# 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 }: @@ -14,7 +14,8 @@ runCommand "pdtv26-speech" { } '' chmod +x $out/bin/hear.sh $out/bin/speak.sh cat > $out/bin/speech-server < $out/bin/$c diff --git a/speech/smoke.sh b/speech/smoke.sh index 88dd37e..58fefb8 100755 --- a/speech/smoke.sh +++ b/speech/smoke.sh @@ -1,6 +1,7 @@ #!/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, +# 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 @@ -12,7 +13,7 @@ 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" > "$tmp/server.log" 2>&1 & +"$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 diff --git a/speech/speak-client.js b/speech/speak-client.js old mode 100644 new mode 100755 index 1dbe5ba..07d8d59 --- a/speech/speak-client.js +++ b/speech/speak-client.js @@ -1,16 +1,37 @@ +#!/usr/bin/env node /** * @file speak-client: have the speech capability speak text; write the WAV to stdout. - * usage: node speak-client.js URL < text > speech.wav + * 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'; -const main = async ([url], env, stdin, stdout) => { - const key = (await readFile(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim(); +/** + * 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 = newWebSocketRpcSession(url); + const gate = connect(url); try { stdout.write(await gate.open(key).speak(words)); } finally { @@ -18,7 +39,7 @@ const main = async ([url], env, stdin, stdout) => { } }; -main(process.argv.slice(2), process.env, process.stdin, process.stdout).catch((err) => { +main().catch((err) => { console.error(`speak-client: ${err.message ?? err}`); - process.exit(1); + process.exitCode = 1; }); diff --git a/speech/speak.sh b/speech/speak.sh index 510c26f..4b290d1 100755 --- a/speech/speak.sh +++ b/speech/speak.sh @@ -1,9 +1,11 @@ #!/bin/sh -# speak.sh VOICE: text on stdin, piper's WAV of it on stdout. VOICE is an .onnx with its .onnx.json beside it. +# 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; } +@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 index 4fd118b..07326ec 100644 --- a/speech/speech.js +++ b/speech/speech.js @@ -12,33 +12,49 @@ export const MAX_CLIP_BYTES = 4_000_000; export const MAX_SPEAK_CHARS = 1000; /** - * Speech: transcribe(clip) returns the text; speak(text) returns a WAV of it. + * 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)); - } +export class Speech extends RpcTarget { + #transcribe; + #speak; + /** @type {Promise} the job before this one */ + #last = Promise.resolve(); - /** @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)); - } + /** + * @param {(clip: Uint8Array) => Promise} transcribe + * @param {(text: string) => Promise} [speak] + */ + constructor(transcribe, speak) { + super(); + this.#transcribe = transcribe; + this.#speak = speak; } - return new Speech(); -}; + + /** + * @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 index e120118..b00116c 100644 --- a/speech/speech.test.js +++ b/speech/speech.test.js @@ -1,12 +1,12 @@ // 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 { makeSpeech, MAX_CLIP_BYTES, MAX_SPEAK_CHARS } from './speech.js'; +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 = makeSpeech(async (c) => `${c.length} bytes`); + 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/); @@ -15,7 +15,7 @@ test('transcribe takes bytes, and not too many', async () => { test('one clip at a time, and a failure does not stall the next', async () => { const log = []; let n = 0; - const speech = makeSpeech(async () => { + const speech = new Speech(async () => { const i = ++n; log.push(`start ${i}`); await new Promise((r) => setTimeout(r, 10)); @@ -31,7 +31,7 @@ test('one clip at a time, and a failure does not stall the next', async () => { test('speak takes text, not too much, and shares the one-at-a-time turn', async () => { const log = []; - const speech = makeSpeech( + const speech = new Speech( async () => { log.push('transcribe'); return 'hi'; }, async (text) => { log.push(`speak ${text}`); return new Uint8Array([82, 73, 70, 70]); }, ); @@ -41,5 +41,5 @@ test('speak takes text, not too much, and shares the one-at-a-time turn', async 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(() => makeSpeech(async () => '').speak('hi'), /no voice/); + assert.throws(() => new Speech(async () => '').speak('hi'), /no voice/); });