Compare commits
2
Commits
main
...
429bafe9c0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
429bafe9c0 | ||
|
|
646dfee4c6 |
No files matched your search
@@ -0,0 +1,35 @@
|
|||||||
|
name: check
|
||||||
|
|
||||||
|
# nix flake check: every check in flake.nix, such as ir-pico's doctests.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
# Nix comes from its own image, pinned by digest, not a floating tag: a tag can be moved.
|
||||||
|
container:
|
||||||
|
image: nixos/nix:2.35.6@sha256:b49cb33f3a7e5cf3933ad8774529de0e3807ec5cf54987aa7ccdfb49f2fc55ed
|
||||||
|
env:
|
||||||
|
# A container can't make the namespaces Nix's build sandbox needs.
|
||||||
|
NIX_CONFIG: |
|
||||||
|
experimental-features = nix-command flakes
|
||||||
|
sandbox = false
|
||||||
|
steps:
|
||||||
|
# No actions/checkout: it runs on node, which this image doesn't have, and git does the job.
|
||||||
|
- name: Check out
|
||||||
|
env:
|
||||||
|
SERVER: ${{ gitea.server_url }}
|
||||||
|
REPO: ${{ gitea.repository }}
|
||||||
|
REF: ${{ gitea.ref }}
|
||||||
|
SHA: ${{ gitea.sha }}
|
||||||
|
# The server won't hand out a bare commit, so fetch the ref that was pushed, then the commit.
|
||||||
|
run: |
|
||||||
|
git init -q src
|
||||||
|
git -C src fetch -q --depth 20 "$SERVER/$REPO.git" "$REF"
|
||||||
|
git -C src checkout -q --detach "$SHA"
|
||||||
|
|
||||||
|
- name: nix flake check
|
||||||
|
working-directory: src
|
||||||
|
run: nix flake check -L
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
result
|
result
|
||||||
__pycache__/
|
__pycache__/
|
||||||
ir-pico/cache/
|
ir-pico/cache/
|
||||||
|
speech/cache/
|
||||||
|
node_modules/
|
||||||
+23
-2
@@ -2,6 +2,27 @@
|
|||||||
|
|
||||||
The [README](README.md) says what pdtv26 does and why; this is how to work on it.
|
The [README](README.md) says what pdtv26 does and why; this is how to work on it.
|
||||||
|
|
||||||
## Working on it
|
## Development
|
||||||
|
|
||||||
The tools come from the flake: `nix develop --command make test` in any folder, or `nix develop` once and then `make`. `nix flake check` runs every folder's tests. `make help` in each folder lists what it does, and each module's docstring says what it is. Docs are only for what isn't code, such as [wiring](ir-pico/wiring.md).
|
The tools come from the flake. To run every folder's tests, as [CI](.gitea/workflows/check.yaml) should on each push:
|
||||||
|
|
||||||
|
```
|
||||||
|
nix flake check
|
||||||
|
```
|
||||||
|
|
||||||
|
To work in one folder:
|
||||||
|
|
||||||
|
```
|
||||||
|
cd speech
|
||||||
|
nix develop
|
||||||
|
make help
|
||||||
|
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.
|
||||||
@@ -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.
|
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
|
## Parts
|
||||||
|
|
||||||
The agent is built from parts you can buy and solder:
|
The agent is built from parts you can buy and solder:
|
||||||
|
|||||||
@@ -10,6 +10,11 @@
|
|||||||
python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ]);
|
python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ]);
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
|
packages = forAll (pkgs: {
|
||||||
|
speech = pkgs.callPackage ./speech/server.nix { };
|
||||||
|
speech-js = pkgs.callPackage ./speech/default.nix { };
|
||||||
|
});
|
||||||
|
|
||||||
# nix develop --command make test
|
# nix develop --command make test
|
||||||
devShells = forAll (pkgs: {
|
devShells = forAll (pkgs: {
|
||||||
default = pkgs.mkShellNoCC {
|
default = pkgs.mkShellNoCC {
|
||||||
@@ -23,6 +28,7 @@
|
|||||||
python3 -I -m doctest ir_commands.py pico_tty.py
|
python3 -I -m doctest ir_commands.py pico_tty.py
|
||||||
touch $out
|
touch $out
|
||||||
'';
|
'';
|
||||||
|
speech = self.packages.${pkgs.stdenv.hostPlatform.system}.speech-js;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -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)'
|
||||||
@@ -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 = [ ];
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
});
|
||||||
Executable
+46
@@ -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<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 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;
|
||||||
|
});
|
||||||
Executable
+12
@@ -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; }
|
||||||
Generated
+44
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<T>} 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
Executable
+62
@@ -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<string, string | undefined>} [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;
|
||||||
|
});
|
||||||
@@ -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 <<EOF
|
||||||
|
#!/bin/sh
|
||||||
|
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
|
||||||
|
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
|
||||||
|
done
|
||||||
|
chmod +x $out/bin/speech-server $out/bin/hear-client $out/bin/speak-client
|
||||||
|
''
|
||||||
Executable
+34
@@ -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"
|
||||||
Executable
+45
@@ -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<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 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;
|
||||||
|
});
|
||||||
Executable
+11
@@ -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"
|
||||||
@@ -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<unknown>} the job before this one */
|
||||||
|
#last = Promise.resolve();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {(clip: Uint8Array) => Promise<string>} transcribe
|
||||||
|
* @param {(text: string) => Promise<Uint8Array>} [speak]
|
||||||
|
*/
|
||||||
|
constructor(transcribe, speak) {
|
||||||
|
super();
|
||||||
|
this.#transcribe = transcribe;
|
||||||
|
this.#speak = speak;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template T
|
||||||
|
* @param {() => Promise<T>} job
|
||||||
|
* @returns {Promise<T>}
|
||||||
|
*/
|
||||||
|
#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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user