fixup! feat(speech): the speech capability over Cap'n Web, behind a gate
check / check (push) Canceled after 0s

This commit is contained in:
dckc committed 2026-12-02 15:41:18 -06:00
1 parent 372f6a2b96
commit a97ba6c174
12 files changed
+228 -75

No files matched your search

+2
View File
@@ -16,6 +16,8 @@ buildNpmPackage {
}; };
npmDepsHash = "sha256-C7Em37Mm3+mUHqQ2n37JshgLCByzMOlhgoQEex3CnlU="; npmDepsHash = "sha256-C7Em37Mm3+mUHqQ2n37JshgLCByzMOlhgoQEex3CnlU=";
dontNpmBuild = true; 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" ]; npmInstallFlags = [ "--ignore-scripts" ];
doCheck = true; doCheck = true;
checkPhase = '' checkPhase = ''
+21 -10
View File
@@ -10,18 +10,29 @@ import { createHash, timingSafeEqual } from 'node:crypto';
const digest = (s) => createHash('sha256').update(String(s)).digest(); const digest = (s) => createHash('sha256').update(String(s)).digest();
/** /**
* @param {string} key unguessable, from a credential file * @template T
* @param {object} cap what open(key) hands out */
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}
*/ */
export const makeGate = (key, cap) => {
const want = digest(key);
class Gate extends RpcTarget {
/** @param {string} k */
open(k) { open(k) {
// Digests are the same length whatever k is, so the comparison takes the same time. // 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'); if (!timingSafeEqual(digest(k), this.#want)) throw new Error('no such key');
return cap; return this.#cap;
} }
} }
return new Gate();
};
+40 -3
View File
@@ -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 { test } from 'node:test';
import assert from 'node:assert/strict'; 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', () => { test('the right key opens the gate; a wrong one is refused', () => {
const cap = { it: 'the capability' }; const cap = { it: 'the capability' };
const gate = makeGate('k3y', cap); const gate = new Gate('k3y', cap);
assert.equal(gate.open('k3y'), cap); assert.equal(gate.open('k3y'), cap);
assert.throws(() => gate.open('guess'), /no such key/); assert.throws(() => gate.open('guess'), /no such key/);
assert.throws(() => gate.open(''), /no such key/); assert.throws(() => gate.open(''), /no such key/);
assert.throws(() => gate.open(undefined), /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();
}
});
Regular → Executable
+27 -6
View File
@@ -1,16 +1,37 @@
#!/usr/bin/env node
/** /**
* @file hear-client: send one clip to the speech capability and print the transcript. * @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. * The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv, where ps would show it.
*/ */
import { newWebSocketRpcSession } from 'capnweb'; import { newWebSocketRpcSession } from 'capnweb';
import { readFile } from 'node:fs/promises'; import { readFile } from 'node:fs/promises';
import process from 'node:process';
import { buffer } from 'node:stream/consumers'; 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<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key
* @param {AsyncIterable<Uint8Array>} [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 clip = new Uint8Array(await buffer(stdin));
const gate = newWebSocketRpcSession(url); const gate = connect(url);
try { try {
// Pipelined: open and transcribe in one round trip. // Pipelined: open and transcribe in one round trip.
stdout.write(`${await gate.open(key).transcribe(clip)}\n`); 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}`); console.error(`hear-client: ${err.message ?? err}`);
process.exit(1); process.exitCode = 1;
}); });
+24 -9
View File
@@ -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 child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] });
const out = [], err = []; const out = [], err = [];
child.stdout.on('data', (d) => out.push(d)); 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); child.stdin.end(input);
}); });
/** Time a job and log how it went; failures are logged and rethrown. */ /**
export const timed = async (what, job, describe) => { * Time a job and log how it went; failures are logged and rethrown.
const t0 = Date.now(); *
* @template T
* @param {() => number} now milliseconds
* @param {string} what
* @param {() => Promise<T>} job
* @param {(result: T) => string} describe
*/
export const timed = async (now, what, job, describe) => {
const t0 = now();
try { try {
const result = await job(); 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; return result;
} catch (err) { } 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; throw err;
} }
}; };
Regular → Executable
+44 -18
View File
@@ -1,36 +1,62 @@
#!/usr/bin/env node
/** /**
* @file speech-server: the speech capability over Cap'n Web, behind a gate. * @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. * 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). * 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 { newWebSocketRpcSession } from 'capnweb';
import { spawn as spawnChild } from 'node:child_process';
import { readFile } from 'node:fs/promises'; import { readFile } from 'node:fs/promises';
import { makeGate } from './gate.js'; import process from 'node:process';
import { makeSpeech, MAX_CLIP_BYTES } from './speech.js'; import { WebSocketServer } from 'ws';
import { runWith, timed } from './run.js'; 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(); * Serve the speech capability, behind a gate, at HOST:PORT.
const speech = makeSpeech( *
(clip) => timed(`heard ${clip.length} bytes`, * @param {object} [io] what it reaches; the process's own, by default
async () => (await runWith(hearSh, [model], clip)).toString().trim(), (text) => text), * @param {string[]} [io.argv] HOST PORT HEAR_SH MODEL SPEAK_SH VOICE [PIPER_OPTION...]
(text) => timed(`spoke ${text.length} chars`, * @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
async () => new Uint8Array(await runWith(speakSh, [voice], text)), (wav) => `${wav.length} bytes of WAV`), * @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. // 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) => { wss.on('connection', (ws, req) => {
console.log(`connection from ${req.socket.remoteAddress}`); console.log(`connection from ${req.socket.remoteAddress}`);
newWebSocketRpcSession(ws, gate); serve(ws, gate);
}); });
console.log(`speech-server: listening on ${host}:${port}`); console.log(`speech-server: listening on ${host}:${port}`);
}; };
main(process.argv.slice(2), process.env).catch((err) => { main().catch((err) => {
console.error(err); console.error(err);
process.exit(1); process.exitCode = 1;
}); });
+3 -2
View File
@@ -1,5 +1,5 @@
# The speech server and clients, with node, and the sox, whisper, and piper the server's scripts use. # 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/hear-client URL < clip.wav
# bin/speak-client URL < text > speech.wav # bin/speak-client URL < text > speech.wav
{ callPackage, runCommand, nodejs-slim, sox, whisper-cpp, piper-tts }: { 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 chmod +x $out/bin/hear.sh $out/bin/speak.sh
cat > $out/bin/speech-server <<EOF cat > $out/bin/speech-server <<EOF
#!/bin/sh #!/bin/sh
exec ${nodejs-slim}/bin/node ${dir}/server.js "\$1" "\$2" $out/bin/hear.sh "\$3" $out/bin/speak.sh "\$4" host=\$1 port=\$2 model=\$3 voice=\$4; shift 4
exec ${nodejs-slim}/bin/node ${dir}/server.js "\$host" "\$port" $out/bin/hear.sh "\$model" $out/bin/speak.sh "\$voice" "\$@"
EOF EOF
for c in hear-client speak-client; do for c in hear-client speak-client; do
printf '#!/bin/sh\nexec %s %s/%s.js "$@"\n' ${nodejs-slim}/bin/node ${dir} $c > $out/bin/$c printf '#!/bin/sh\nexec %s %s/%s.js "$@"\n' ${nodejs-slim}/bin/node ${dir} $c > $out/bin/$c
+3 -2
View File
@@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
# smoke.sh BIN MODEL VOICE PORT PHRASE: a speech round trip, by way of a real server and clients. # 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. # then hear the WAV back, and compares the words, ignoring case and punctuation.
set -eu set -eu
bin=$1 model=$2 voice=$3 port=$4 phrase=$5 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" head -c 20 /dev/urandom | base32 > "$tmp/speech-key"
export CREDENTIALS_DIRECTORY="$tmp" 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=$! pid=$!
tries=0 tries=0
until grep -q listening "$tmp/server.log"; do until grep -q listening "$tmp/server.log"; do
Regular → Executable
+27 -6
View File
@@ -1,16 +1,37 @@
#!/usr/bin/env node
/** /**
* @file speak-client: have the speech capability speak text; write the WAV to stdout. * @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. * The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv.
*/ */
import { newWebSocketRpcSession } from 'capnweb'; import { newWebSocketRpcSession } from 'capnweb';
import { readFile } from 'node:fs/promises'; import { readFile } from 'node:fs/promises';
import process from 'node:process';
import { text } from 'node:stream/consumers'; 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<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key
* @param {AsyncIterable<Uint8Array>} [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 words = (await text(stdin)).trim();
const gate = newWebSocketRpcSession(url); const gate = connect(url);
try { try {
stdout.write(await gate.open(key).speak(words)); stdout.write(await gate.open(key).speak(words));
} finally { } 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}`); console.error(`speak-client: ${err.message ?? err}`);
process.exit(1); process.exitCode = 1;
}); });
+4 -2
View File
@@ -1,9 +1,11 @@
#!/bin/sh #!/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). # The Nix build fills in @piper@ (server.nix).
set -eu set -eu
voice=$1 voice=$1
shift
tmp=$(mktemp -d) tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT 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" cat "$tmp/out.wav"
+28 -12
View File
@@ -12,33 +12,49 @@ export const MAX_CLIP_BYTES = 4_000_000;
export const MAX_SPEAK_CHARS = 1000; 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. * 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<unknown>} the job before this one */
#last = Promise.resolve();
/**
* @param {(clip: Uint8Array) => Promise<string>} transcribe * @param {(clip: Uint8Array) => Promise<string>} transcribe
* @param {(text: string) => Promise<Uint8Array>} [speak] * @param {(text: string) => Promise<Uint8Array>} [speak]
*/ */
export const makeSpeech = (transcribe, speak) => { constructor(transcribe, speak) {
let last = Promise.resolve(); super();
const inTurn = (job) => { this.#transcribe = transcribe;
const result = last.then(job); this.#speak = speak;
last = result.catch(() => {}); }
/**
* @template T
* @param {() => Promise<T>} job
* @returns {Promise<T>}
*/
#inTurn(job) {
const result = this.#last.then(job);
this.#last = result.catch(() => {});
return result; return result;
}; }
class Speech extends RpcTarget {
/** @param {Uint8Array} clip a WAV file */ /** @param {Uint8Array} clip a WAV file */
transcribe(clip) { transcribe(clip) {
if (!(clip instanceof Uint8Array)) throw new TypeError('clip must be bytes'); 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`); if (clip.length > MAX_CLIP_BYTES) throw new RangeError(`clip over ${MAX_CLIP_BYTES} bytes`);
return inTurn(() => transcribe(clip)); return this.#inTurn(() => this.#transcribe(clip));
} }
/** @param {string} text */ /** @param {string} text */
speak(text) { speak(text) {
const speak = this.#speak;
if (!speak) throw new Error('no voice here'); if (!speak) throw new Error('no voice here');
if (typeof text !== 'string' || !text.trim()) throw new TypeError('speak needs text'); 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`); if (text.length > MAX_SPEAK_CHARS) throw new RangeError(`text over ${MAX_SPEAK_CHARS} chars`);
return inTurn(() => speak(text)); return this.#inTurn(() => speak(text));
} }
} }
return new Speech();
};
+5 -5
View File
@@ -1,12 +1,12 @@
// Tests for the speech capability, in process: no network, no whisper, no piper. // Tests for the speech capability, in process: no network, no whisper, no piper.
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; 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" const clip = new Uint8Array([82, 73, 70, 70]); // "RIFF"
test('transcribe takes bytes, and not too many', async () => { 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.equal(await speech.transcribe(clip), '4 bytes');
assert.throws(() => speech.transcribe('UklGRg=='), /must be bytes/); assert.throws(() => speech.transcribe('UklGRg=='), /must be bytes/);
assert.throws(() => speech.transcribe(new Uint8Array(MAX_CLIP_BYTES + 1)), /over/); 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 () => { test('one clip at a time, and a failure does not stall the next', async () => {
const log = []; const log = [];
let n = 0; let n = 0;
const speech = makeSpeech(async () => { const speech = new Speech(async () => {
const i = ++n; const i = ++n;
log.push(`start ${i}`); log.push(`start ${i}`);
await new Promise((r) => setTimeout(r, 10)); 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 () => { test('speak takes text, not too much, and shares the one-at-a-time turn', async () => {
const log = []; const log = [];
const speech = makeSpeech( const speech = new Speech(
async () => { log.push('transcribe'); return 'hi'; }, async () => { log.push('transcribe'); return 'hi'; },
async (text) => { log.push(`speak ${text}`); return new Uint8Array([82, 73, 70, 70]); }, 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.deepEqual(log, ['transcribe', 'speak Hello.']);
assert.throws(() => speech.speak(''), /needs text/); assert.throws(() => speech.speak(''), /needs text/);
assert.throws(() => speech.speak('x'.repeat(MAX_SPEAK_CHARS + 1)), /over/); 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/);
}); });