commit ce47ea7627d3afdfb7bffcff8fc38fedbd39ce4f
parent 31fcfff17c3c32fbc1840deb23cb28047a89a19c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 11 Oct 2026 00:45:36 -0400
ops: POST /api/ops/tts and `pnpm ops tts`
The route is an adapter over enqueueTtsFile: the token, the body keys
{text, file, voice, engine, speed, out}, the controller's refusals as 400s.
`pnpm ops tts --wait` follows the job and prints the @@tts-result JSON on
stdout. COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
5 files changed, 212 insertions(+), 1 deletion(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -118,6 +118,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?}, ...\], "requestedBy", "manifest"?} fetches a list. "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
| `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` |
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
+| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...), "speed" (0.5-2) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are stripped for an engine that cannot perform them; any other <...> is refused. Years are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro needs `archilyzer tts setup` first. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
diff --git a/editor/app/api/ops/tts/route.test.ts b/editor/app/api/ops/tts/route.test.ts
@@ -0,0 +1,121 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/tts/route.test.ts"
+//
+// The adapter's surface: the token, the body's keys, the controller's
+// refusals answered as 400s before any job exists — and one synthesis through
+// the route with espeak-ng (the zero-install engine), read back from the job's
+// log as `pnpm ops tts --wait` reads it. The job itself is covered by
+// common/controller/ttsFile.test.ts. In a temp corpus with its own cache.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-route-"));
+const CORPUS = path.join(ROOT, "transcripts");
+const CACHE = path.join(ROOT, "cache");
+await mkdir(CORPUS, { recursive: true });
+const SETTINGS_FILE = path.join(ROOT, "settings.json");
+const SETTINGS_TEXT = JSON.stringify({
+ workers: [],
+ tts: { engine: "espeak-ng", voice: "en-us", dir: CACHE, home: path.join(ROOT, "home") },
+});
+await writeFile(SETTINGS_FILE, SETTINGS_TEXT);
+// Set before the route (and getPaths, which caches) is first imported.
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = SETTINGS_FILE;
+const { POST } = await import("./route");
+const { TTS_RESULT_MARKER } = await import("yt-dlp-transcript-common/controller/ttsFile");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function post(
+ body: Record<string, unknown>,
+ token = "test-token",
+): Promise<{ status: number; json: { ok?: boolean; error?: string; jobId?: string } }> {
+ const res = await POST(
+ new Request("http://localhost/api/ops/tts", {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: await res.json() };
+}
+
+test("a wrong token is a 401", async () => {
+ const { status } = await post({ text: "hi" }, "wrong");
+ assert.equal(status, 401);
+});
+
+test("an unknown key is a 400 naming the accepted ones", async () => {
+ const { status, json } = await post({ text: "hi", reference: "/voice.wav" });
+ assert.equal(status, 400);
+ assert.match(json.error!, /unknown key\(s\): reference — this route accepts text, file, voice, engine, speed, out/);
+});
+
+test("the controller's refusals come back as 400s", async () => {
+ const cases: [Record<string, unknown>, RegExp][] = [
+ [{}, /"text" .* or "file" .* is required/],
+ [{ text: "a", file: "/a.txt" }, /not both/],
+ [{ file: "a.txt" }, /"file" must be an absolute path/],
+ [{ file: path.join(ROOT, "missing.txt") }, /does not exist/],
+ [{ text: "hi", engine: "piper" }, /no text-to-speech engine "piper"/],
+ [{ text: "hi", voice: "af_heart" }, /espeak-ng has no stock voice "af_heart"/],
+ [{ text: "hi", speed: 9 }, /"speed" must be between 0.5 and 2/],
+ [{ text: "oh <lagh> no" }, /a tag no engine knows: <lagh>/],
+ [{ text: "hi", engine: "kokoro" }, /Kokoro-82M is not installed .* run `archilyzer tts setup`/],
+ [{ text: "hi", out: path.join(CORPUS, "a.wav") }, /inside the corpus/],
+ [{ text: "hi", out: path.join(ROOT, "a.mp3") }, /must name a \.wav file/],
+ ];
+ for (const [body, re] of cases) {
+ const { status, json } = await post(body);
+ assert.equal(status, 400, JSON.stringify(body));
+ assert.equal(json.ok, false);
+ assert.match(json.error!, re);
+ assert.equal(json.jobId, undefined);
+ }
+ assert.equal(await readFile(SETTINGS_FILE, "utf8"), SETTINGS_TEXT);
+});
+
+let real = true;
+try {
+ execFileSync("espeak-ng", ["--version"], { stdio: "ignore" });
+ execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+} catch {
+ real = false;
+}
+
+test("a synthesis through the route: a job whose log ends with the result", { skip: !real && "espeak-ng or ffmpeg absent" }, async () => {
+ const { status, json } = await post({ text: "Narrated <sigh> in 2025." });
+ assert.equal(status, 200);
+ assert.equal(json.ok, true);
+ assert.ok(json.jobId);
+ const logFile = path.join(CORPUS, ".jobs", `${json.jobId}.log`);
+ let line: string | undefined;
+ for (let i = 0; i < 300 && !line; i++) {
+ const log = await readFile(logFile, "utf8").catch(() => "");
+ line = log.split("\n").find((l) => l.startsWith(TTS_RESULT_MARKER));
+ if (!line) await new Promise((r) => setTimeout(r, 50));
+ }
+ assert.ok(line, "the result line");
+ const r = JSON.parse(line!.slice(TTS_RESULT_MARKER.length));
+ assert.deepEqual(Object.keys(r), [
+ "wav", "seconds", "engine", "voice", "cached", "durationMs", "waitedMs",
+ "sha", "sampleRate", "speed", "disclosure",
+ ]);
+ assert.equal(r.engine, "espeak-ng");
+ assert.equal(r.cached, false);
+ assert.equal(r.wav, path.join(CACHE, `${r.sha}.wav`));
+ assert.equal(r.sampleRate, 48000);
+ assert.match(r.disclosure, /^Narration: synthetic voice \(eSpeak NG · en-us\)$/);
+ const side = JSON.parse(await readFile(path.join(CACHE, `${r.sha}.json`), "utf8"));
+ assert.equal(side.text, "Narrated in twenty twenty-five.");
+ assert.equal(side.synthetic, true);
+});
diff --git a/editor/app/api/ops/tts/route.ts b/editor/app/api/ops/tts/route.ts
@@ -0,0 +1,38 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ TTS_FILE_BODY_KEYS,
+ enqueueTtsFile,
+} from "yt-dlp-transcript-common/controller/ttsFile";
+import { jobResponse, ops } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { text | file, voice?, engine?, speed?, out? } -> { ok: true, jobId }
+//
+// Speak a line with a local text-to-speech engine and a STOCK voice, as a job on
+// /jobs (`tts-file`, the `tts` queue, one synthesis at a time) — narration is
+// never synthesized by hand. `text` is the words, or `file` an absolute path to
+// a UTF-8 text file holding them (at most 20,000 characters); `engine`
+// (`kokoro` | `espeak-ng`), `voice` (one of the engine's stock voices) and
+// `speed` (0.5-2) default to settings.tts (kokoro · af_heart · 1); `out` is an
+// absolute .wav path the result is copied to. The expressive tags (`<laugh>`,
+// `<sigh>`, ... lib/ttsText.ts TTS_EXPRESSIVE_TAGS) are stripped for an engine
+// that cannot perform them; any other `<...>` is refused.
+//
+// The job's log ends with the result as ONE line, `@@tts-result {json}`:
+// `{wav, seconds, engine, voice, cached, durationMs (the engine's time), waitedMs
+// (the wait on the queue), sha, sampleRate, speed, disclosure}`. `wav` is an
+// absolute path this editor wrote: `out` when given, else the cache file
+// (`<settings.tts.dir>/<sha>.wav`, 48 kHz mono 16-bit, a `<sha>.json` sidecar
+// beside it). The same ask again is a `done` job with `cached: true` that runs
+// no engine. `pnpm ops tts --wait` prints that JSON on stdout.
+//
+// AN ADAPTER: every refusal is the controller's (controller/ttsFile.ts) — both
+// or neither of text and file, an unknown engine or voice, a speed out of
+// range, an unknown tag, an engine not installed (`archilyzer tts setup`), an
+// `out` or a cache dir inside the corpus.
+export async function POST(request: Request) {
+ return ops(request, TTS_FILE_BODY_KEYS, async (body) =>
+ jobResponse(await enqueueTtsFile(body, { paths: getPaths() })),
+ );
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -90,6 +90,8 @@
// pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'
// pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait
// pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait
+// pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait
+// pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -333,6 +335,11 @@ const ACTIONS = [
// ({path, start?, end?, workerId?, out?}) — the corpus's own engine and
// model, as a job. With --wait the result JSON is what stdout carries.
"transcribe",
+ // Speak a line with a local text-to-speech engine and a stock voice
+ // ({text | file, voice?, engine?, speed?, out?}), as a job on the `tts`
+ // queue; the same ask again is answered from the cache. With --wait the
+ // result JSON is what stdout carries.
+ "tts",
// ARCHIVAL WRITES (release 19, A4). settings.json through the editor's one
// writer ({patch}); a platform's rate-limit hold cleared ({platform});
// workers switched on, off or drained ({op, ids}); one video transcribed
@@ -352,6 +359,9 @@ const ACTIONS = [
// compact JSON. The same string is TRANSCRIBE_RESULT_MARKER in
// common/controller/transcribeFile.ts.
export const TRANSCRIBE_RESULT_MARKER = "@@transcribe-result ";
+// The same for a text-to-speech job (TTS_RESULT_MARKER in
+// common/controller/ttsFile.ts).
+export const TTS_RESULT_MARKER = "@@tts-result ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
@@ -576,6 +586,7 @@ export function parseArgs(argv) {
...(action === "tag-videos" ? { defaultSource: agentSource() } : {}),
// A job whose log carries a RESULT, which --wait prints on stdout.
...(action === "transcribe" ? { resultMarker: TRANSCRIBE_RESULT_MARKER } : {}),
+ ...(action === "tts" ? { resultMarker: TTS_RESULT_MARKER } : {}),
...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}),
wait,
quiet,
@@ -1031,6 +1042,21 @@ export function usage() {
" With --wait it is printed on stdout (the response and the log go to",
" stderr), so `pnpm ops transcribe ... --wait | jq -r .text` works.",
"",
+ 'tts speaks a line with a local text-to-speech engine and a STOCK voice, as a',
+ ' job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8,',
+ ' at most 20,000 characters), "engine" (kokoro | espeak-ng), "voice" (one of',
+ ' the engine\'s stock voices; kokoro: af_heart, bm_george, ...), "speed"',
+ ' (0.5-2) — defaults from settings.tts (kokoro, af_heart, 1) — and "out" (an',
+ ' absolute .wav path the result is copied to, never inside the corpus). The',
+ " expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn>",
+ " <gasp> are stripped for an engine that cannot perform them; any other <...>",
+ " is refused. Years are spoken (2024: \"twenty twenty-four\"). The result is",
+ " {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate,",
+ " speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its",
+ " cache), disclosure the line a narrated export carries. The same ask again is",
+ " answered from the cache (cached: true, no engine run). Kokoro needs",
+ " `archilyzer tts setup` first. With --wait the result is printed on stdout.",
+ "",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
" WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from",
@@ -1321,7 +1347,7 @@ export async function followJob(jobId, quiet, opts = {}) {
// Follow every id to its end, one after another, and say how each ended.
// 0 only when every one finished `done`. A job still queued says where it waits
// (followJob), so a list of ids behind one long job reads as a queue, not a
-// hang. In result mode (transcribe) each job's RESULT goes to stdout.
+// hang. In result mode (transcribe, tts, remote-listing) each job's RESULT goes to stdout.
async function followAll(jobIds, parsed, resultMode = false) {
let worst = 0;
for (const jobId of jobIds) {
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -8,6 +8,7 @@ import test from "node:test";
import {
REMOTE_LISTING_RESULT_MARKER,
TRANSCRIBE_RESULT_MARKER,
+ TTS_RESULT_MARKER,
editorEnvFiles,
followJob,
loadEditorEnv,
@@ -655,6 +656,30 @@ test("transcribe posts its body and carries the result marker", () => {
assert.match(usage(), /it is printed on stdout/);
});
+test("tts posts its body and carries its own result marker", () => {
+ const p = parseArgs([
+ "tts",
+ "--json",
+ '{"text":"In 2024 the archive spoke.","voice":"bm_george","out":"/abs/line.wav"}',
+ "--wait",
+ ]);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, "/api/ops/tts");
+ assert.deepEqual(p.body, { text: "In 2024 the archive spoke.", voice: "bm_george", out: "/abs/line.wav" });
+ assert.equal(p.wait, true);
+ assert.equal(TTS_RESULT_MARKER, "@@tts-result ");
+ assert.equal(p.resultMarker, TTS_RESULT_MARKER);
+ assert.match(usage(), /tts speaks a line with a local text-to-speech engine and a STOCK voice/);
+ assert.match(usage(), /<laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn>/);
+ assert.match(usage(), /\{wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate,/);
+ // The result line comes out of the log as transcribe's does.
+ const result = { wav: "/c/x.wav", seconds: 2.5, cached: true };
+ const cap = makeResultCapture(TTS_RESULT_MARKER);
+ const echoed = cap.feed(`Speak 12 characters\n${TTS_RESULT_MARKER}${JSON.stringify(result)}\n`);
+ assert.equal(echoed, "Speak 12 characters\n");
+ assert.deepEqual(cap.finish().result, result);
+});
+
test("the result line is taken out of the log, across chunk boundaries", () => {
const result = { cues: [{ start: 120.5, end: 121, text: "hi" }], text: "hi" };
const line = `${TRANSCRIBE_RESULT_MARKER}${JSON.stringify(result)}`;