commit 9d2a19265dee3bf533432766991fabb87282d16f
parent 47f7e7965ed31ea573b3908fef763f90e5be9122
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 09:50:18 -0500
voice ops: a take and its parts are one engine run (one heavy-slot admission, one model load; openvoice embeds the speaker from every part at once); Seed-VC at 10 steps; the bench's derive path end to end in umtool's e2e; changelog
- scripts/voice.mjs takes --more [{input, output}]: further files run the same way in the same run, each held to its own input's length; the convert engines' python takes them as one --batch, so a parted take of twenty parts loads the model once and waits at the heavy slot once (it waited once per part, and a converter re-loaded each time). OpenVoice now embeds the source speaker from all the files together: a 4-second part alone says little about a voice.
- Seed-VC's default diffusion steps 25 -> 10 (the bake-off: 29 min for 40 s at 25 on this CPU under load, 17 min at 10).
- The whisper feature extractor is told its 16 kHz.
- umtool: the bench's "not installed" carries the editor's own sentence (which names the `archilyzer voice setup` to run). The suite's editor stub answers voice-enhance as an editor with no enhance engine installed and runs voice-convert (a copy, with the editor's result line); post-narration.spec.ts converts take #1 onto `zac` from the bench and checks the derived take, its step (the engine the editor's default ran) and the request.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 355 insertions(+), 192 deletions(-)
diff --git a/common/controller/voiceFile.test.ts b/common/controller/voiceFile.test.ts
@@ -47,6 +47,8 @@ if (kind === "openvoice" || kind === "seed-vc") {
const out = argv[argv.indexOf("--output") + 1];
if (fs.readFileSync(input).length < 100) { console.error("voice: engine exploded"); process.exit(3); }
fs.copyFileSync(input, out);
+ const more = argv.includes("--more") ? JSON.parse(argv[argv.indexOf("--more") + 1]) : [];
+ for (const m of more) fs.copyFileSync(m.input, m.output);
console.error("voice: " + kind + " converted");
console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0 }));
process.exit(0);
@@ -277,7 +279,11 @@ test("an enhance runs the real wrapper: a 48 kHz mono WAV exactly the input's le
assert.equal((await wavHeader(partOut)).dataBytes, 0.4 * 48000 * 2);
// No scratch is left beside the result.
assert.deepEqual((await import("node:fs")).readdirSync(OUTSIDE).filter((f) => f.includes(".voice-")), []);
- assert.match(r.log, /Running RNNoise \(ffmpeg arnndn\) behind the heavy slot \(estimate 300 MB\)/);
+ // One run for the take and its part: one admission, one load.
+ assert.match(r.log, /Running RNNoise \(ffmpeg arnndn\) over the take and its 1 part\(s\) behind the heavy slot \(estimate 300 MB\)/);
+ const runs = (await engineRuns()).filter((a) => a.includes(take));
+ assert.equal(runs.length, 1);
+ assert.deepEqual(JSON.parse(runs[0][runs[0].indexOf("--more") + 1]), [{ input: part, output: partOut }]);
});
// A fake openvoice install at its pinned sizes (sparse files), so the install
diff --git a/common/controller/voiceFile.ts b/common/controller/voiceFile.ts
@@ -27,8 +27,9 @@
// under another key (a new model, other Orpheus settings), it is asked of the
// `tts` op first — a `tts-file` job on its own queue, waited for — and kept.
//
-// THE RUN. Each engine run is `scripts/voice.mjs` (paths.voiceBin) behind the
-// machine's heavy slot (scripts/queue-lock.mjs --heavy --estimate <MB>,
+// THE RUN. ONE run of `scripts/voice.mjs` (paths.voiceBin) for the take and
+// all its parts — one model load, one admission — behind the machine's heavy
+// slot (scripts/queue-lock.mjs --heavy --estimate <MB>,
// settings.voice.heavyEstimateMB, default the engine's measured peak plus a
// margin), in a process group of its own that a cancel stops whole. Nothing
// stays resident: the engine is a process per run, and it exits with it.
@@ -367,6 +368,8 @@ export type EngineRunResult = {
sampleRate?: number;
engineMs?: number;
gainDb?: number;
+ // The parts, when the run had more files (scripts/voice.mjs --more).
+ more?: { output: string; seconds: number; samples?: number; gainDb?: number }[];
};
export type RunVoiceEngineOpts = {
@@ -542,33 +545,29 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
await mkdir(path.dirname(targetSe), { recursive: true });
}
}
- const runOne = async (input: string, output: string): Promise<EngineRunResult> => {
- await mkdir(path.dirname(output), { recursive: true });
- const argv = req.engine.build({
- input,
- output,
- installDir,
- params: req.params,
- threads: voice.threads,
- ...(targetRef ? { targetRef } : {}),
- ...(targetSe ? { targetSe } : {}),
- bins: { ffmpegBin: opts.paths.ffmpegBin, voiceModelsDir: opts.paths.voiceModelsDir },
- });
- const res = await runVoiceEngine({ paths: opts.paths, argv, estimateMB, onLog, signal, ...(opts.gate !== undefined ? { gate: opts.gate } : {}) });
- const st = await stat(output).catch(() => null);
- if (!st || st.size <= 44) throw new Error(`the ${req.engine.id} run left no audio at ${output}`);
- return res;
- };
- onLog(`Running ${req.engine.label} behind the heavy slot (estimate ${estimateMB} MB)…`);
- const whole = await runOne(req.file, req.out);
- onLog(`Written to ${req.out}`);
- const parts: { wav: string; seconds: number }[] = [];
- for (const [k, p] of req.parts.entries()) {
- if (signal.aborted) throw new Error("cancelled");
- onLog(`Part ${k + 1} of ${req.parts.length}: ${p.file}`);
- const r = await runOne(p.file, p.out);
- parts.push({ wav: p.out, seconds: r.seconds ?? 0 });
+ // ONE run for the take and its parts: one admission to the heavy slot,
+ // one model load (a parted take may be twenty short files).
+ await mkdir(path.dirname(req.out), { recursive: true });
+ for (const p of req.parts) await mkdir(path.dirname(p.out), { recursive: true });
+ const argv = req.engine.build({
+ input: req.file,
+ output: req.out,
+ ...(req.parts.length ? { more: req.parts.map((p) => ({ input: p.file, output: p.out })) } : {}),
+ installDir,
+ params: req.params,
+ threads: voice.threads,
+ ...(targetRef ? { targetRef } : {}),
+ ...(targetSe ? { targetSe } : {}),
+ bins: { ffmpegBin: opts.paths.ffmpegBin, voiceModelsDir: opts.paths.voiceModelsDir },
+ });
+ onLog(`Running ${req.engine.label}${req.parts.length ? ` over the take and its ${req.parts.length} part(s)` : ""} behind the heavy slot (estimate ${estimateMB} MB)…`);
+ const whole = await runVoiceEngine({ paths: opts.paths, argv, estimateMB, onLog, signal, ...(opts.gate !== undefined ? { gate: opts.gate } : {}) });
+ for (const f of [req.out, ...req.parts.map((p) => p.out)]) {
+ const st = await stat(f).catch(() => null);
+ if (!st || st.size <= 44) throw new Error(`the ${req.engine.id} run left no audio at ${f}`);
}
+ onLog(`Written to ${req.out}${req.parts.length ? ` and ${req.parts.length} part(s)` : ""}`);
+ const parts = req.parts.map((p, k) => ({ wav: p.out, seconds: whole.more?.[k]?.seconds ?? 0 }));
const result: VoiceResult = {
op,
engine: req.engine.id,
diff --git a/common/lib/voiceApps.ts b/common/lib/voiceApps.ts
@@ -66,6 +66,8 @@ export type VoiceParamSpec =
export type VoiceBuildInput = {
input: string;
output: string;
+ // More files run the same way in the same run (a parted take's parts).
+ more?: { input: string; output: string }[];
installDir: string;
params: Record<string, number | boolean>;
threads: number;
@@ -109,6 +111,7 @@ const common = (op: VoiceOp, kind: string, i: VoiceBuildInput) => [
"--input", i.input,
"--output", i.output,
"--params", JSON.stringify(i.params),
+ ...(i.more?.length ? ["--more", JSON.stringify(i.more)] : []),
"--threads", String(i.threads),
"--ffmpeg", i.bins.ffmpegBin,
];
@@ -309,7 +312,7 @@ const seedVc: VoiceEngine = {
files: SEEDVC_FILES,
},
params: {
- steps: { kind: "number", min: 1, max: 100, default: 25, doc: "diffusion steps (more is slower and, to a point, cleaner)" },
+ steps: { kind: "number", min: 1, max: 100, default: 10, doc: "diffusion steps: each is one pass of the model over every window, so the time grows with them (upstream: 4-10 fast, 25-30 cleaner; 10 by the 2026-11-03 bake-off)" },
cfgRate: { kind: "number", min: 0, max: 1, default: 0.7, doc: "classifier-free guidance (upstream's 0.7)" },
refSeconds: { kind: "number", min: 3, max: 25, default: 10, doc: "seconds of the reference the model is prompted with (each window is 30 s less this: less is faster)" },
},
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A recorded take can be cleaned up, or given a stock synthetic voice, by the editor.** umtool's derived takes (`umtool posts narrate <p> <item> --derive <n> --op enhance|convert`, the post bench's **run AI on take #n**) said "not installed": the editor had no voice ops. It now has two, each a job on a new `voice` queue, its engine run behind the machine's heavy slot with a declared memory estimate: `pnpm ops voice-enhance` (denoise, soften the room, level — DeepFilterNet 3, or RNNoise through ffmpeg with nothing to install) and `pnpm ops voice-convert` (the timing and pitch contour kept, the timbre swapped — OpenVoice v2's converter or Seed-VC). The result is a 48 kHz mono WAV exactly as long as the take, so a derived take lines up with its source; a take recorded part by part is processed part by part. A conversion lands only on a STOCK voice of our own TTS engines (`zac`, `orpheus:leah`, `kokoro:am_michael`): a file or a recording is refused as a target, whatever it holds. The engines are installed by `archilyzer voice setup --engine <id>`, which says what it downloads and how big first; `settings.voice` picks the defaults (SETTINGS.md); OPERATING.md, "Enhance or convert a recorded take".
- **X post captures keep the post's context: what it quotes and what it answers.** A post video drew a reply ("you called me a Leftist…") with nothing it answered, because the archive row named no parent, no quote and no links. `capture-posts` on an X channel now reads, off the page it already loads, the post it answers (the archive's in-reply-to id, else the post directly above it) and the post it quotes — author, display name, check, date, words and media links — into the post's `capture.json` as `context`, with no extra page load (`"context": false` turns it off). `"contextOnly": true` loads one page per post for that alone (and the avatars it shows) and writes nothing else: `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<post id>", …],"contextOnly":true}' --wait`. Not verified against live X yet; the first run is the check. Needs a restart of the editor.
- **The X fetcher keeps quoted posts.** A timeline read never recorded what a post quotes (gallery-dl drops the quoted tweet unless asked). Every read now asks for it, and a quote becomes the quoting post's `quoted` — never archived as one of the account's own posts; an account quoting its own older post still archives that post when the walk reaches it. Posts already archived keep what they have (a re-fetch does not rewrite them; their context comes from `contextOnly`). Needs a restart of the editor.
- **`umtool posts context <project>`** fills every post item's quoted post and parent from its capture's `context` where the archive row lacks them, in one write (one undo point), and names the posts with no context yet with the capture call that reads it; `umtool posts reel` and `timeline insert post:` fill them when the entry is made. Needs a restart of umtool.
diff --git a/scripts/voice.mjs b/scripts/voice.mjs
@@ -27,7 +27,7 @@
// limiter, which would move the timing): to --lufs for enhance, to the
// input's own loudness for convert, either capped at -1 dBTP. Moved into
// place atomically. On stdout, one JSON line: {op, engine, sampleRate,
-// seconds, samples, engineMs, gainDb, inputLufs, outputLufs}.
+// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}.
//
// SCRATCH lives beside --output (`<output>.voice-<pid>/`), never in the OS
// temp dir (a RAM tmpfs on this machine), and is removed on every way out.
@@ -37,6 +37,9 @@
//
// Options:
// --params <json> the engine's knobs (see common/lib/voiceApps.ts)
+// --more <json> more files, [{input, output}], run the same way in the
+// same run (a parted take's parts: the model loads once);
+// the result line carries them as `more`
// --python <p> the venv's python [openvoice, seed-vc]
// --install <dir> the engine's install dir [deepfilternet, openvoice, seed-vc]
// --code <dir> the engine's pinned checkout [openvoice, seed-vc]
@@ -49,7 +52,7 @@
// -h, --help
import { spawn } from "node:child_process";
-import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises";
+import { mkdir, open, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
const SAMPLE_RATE = 48_000;
@@ -85,6 +88,17 @@ try {
} catch {
fail("--params must be JSON");
}
+// More files run the same way in the same run (a parted take's parts): one
+// engine load, one admission to the heavy slot.
+let extra = [];
+try {
+ extra = JSON.parse(arg("--more", "[]"));
+} catch {
+ fail("--more must be JSON");
+}
+if (!Array.isArray(extra) || !extra.every((x) => x && typeof x.input === "string" && typeof x.output === "string")) {
+ fail("--more is a list of {input, output}");
+}
const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg");
const threads = String(Math.max(1, Number(arg("--threads", "4")) || 4));
const lufs = typeof params.lufs === "number" ? params.lufs : Number(arg("--lufs", "-20"));
@@ -165,19 +179,17 @@ async function measure(file) {
const num = (v, d) => (typeof v === "number" && Number.isFinite(v) ? v : d);
-try {
- await mkdir(work, { recursive: true });
- // 1. The input, at 48 kHz mono 16-bit: what every engine reads, and the
- // sample count the output is held to.
- const in48 = path.join(work, "input.wav");
- await ff(["-i", path.resolve(input), "-ac", "1", "-ar", String(SAMPLE_RATE), "-c:a", "pcm_s16le", ...BITEXACT, "-f", "wav", in48]);
+// One item: the input normalized, and what the engine reads.
+async function prepare(item, k) {
+ const in48 = path.join(work, `in-${k}.wav`);
+ await ff(["-i", path.resolve(item.input), "-ac", "1", "-ar", String(SAMPLE_RATE), "-c:a", "pcm_s16le", ...BITEXACT, "-f", "wav", in48]);
const samples = (await dataBytes(in48)) / 2;
- if (!(samples > 0)) throw new Error("the input has no audio");
- const before = await measure(in48);
+ if (!(samples > 0)) throw new Error(`${item.input} has no audio`);
+ return { ...item, k, in48, raw: path.join(work, `engine-${k}.wav`), samples, before: await measure(in48) };
+}
- // 2. The engine.
- const raw = path.join(work, "engine.wav");
- const started = Date.now();
+// The enhance engines, one item at a time (each is a process per file anyway).
+async function enhanceOne(it) {
if (kind === "rnnoise") {
const model = arg("--model", "");
if (!model) throw new Error("missing --model (the rnnoise model)");
@@ -190,98 +202,127 @@ try {
// the late frame trimmed off the front and the flush off the end.
const pad = RNNOISE_DELAY * 2;
await ff([
- "-i", in48,
- "-af", `apad=pad_len=${pad},highpass=f=${num(params.highpass, 70)},arnndn=m='${m}':mix=${mix},atrim=start_sample=${RNNOISE_DELAY}:end_sample=${samples + RNNOISE_DELAY}`,
- "-c:a", "pcm_s16le", raw,
+ "-i", it.in48,
+ "-af", `apad=pad_len=${pad},highpass=f=${num(params.highpass, 70)},arnndn=m='${m}':mix=${mix},atrim=start_sample=${RNNOISE_DELAY}:end_sample=${it.samples + RNNOISE_DELAY}`,
+ "-c:a", "pcm_s16le", it.raw,
]);
- } else if (kind === "deepfilternet") {
- const install = arg("--install", "");
- const dfOut = path.join(work, "df");
- await mkdir(dfOut, { recursive: true });
- const a = [
- "-D",
- "-a", String(Math.min(100, Math.max(0, num(params.attenLimDb, 100)))),
- ...(params.postFilter === true ? ["--pf"] : []),
- "-o", dfOut, in48,
- ];
- await run(path.join(install, "deep-filter"), a);
- const made = (await readdir(dfOut)).filter((f) => f.endsWith(".wav"));
- if (made.length !== 1) throw new Error(`deep-filter wrote ${made.length} files`);
- // DeepFilterNet's own highpass is gentle; the rumble below speech goes too.
- await ff(["-i", path.join(dfOut, made[0]), "-af", `highpass=f=${num(params.highpass, 70)}`, "-c:a", "pcm_s16le", raw]);
+ return;
+ }
+ const install = arg("--install", "");
+ const dfOut = path.join(work, `df-${it.k}`);
+ await mkdir(dfOut, { recursive: true });
+ await run(path.join(install, "deep-filter"), [
+ "-D",
+ "-a", String(Math.min(100, Math.max(0, num(params.attenLimDb, 100)))),
+ ...(params.postFilter === true ? ["--pf"] : []),
+ "-o", dfOut, it.in48,
+ ]);
+ const made = (await readdir(dfOut)).filter((f) => f.endsWith(".wav"));
+ if (made.length !== 1) throw new Error(`deep-filter wrote ${made.length} files`);
+ // DeepFilterNet's own highpass is gentle; the rumble below speech goes too.
+ await ff(["-i", path.join(dfOut, made[0]), "-af", `highpass=f=${num(params.highpass, 70)}`, "-c:a", "pcm_s16le", it.raw]);
+}
+
+// The convert engines: ONE python process for every item, so the model loads
+// once (a parted take is many short files of one performance).
+async function convertAll(items) {
+ const python = arg("--python", "");
+ const code = arg("--code", "");
+ const install = arg("--install", "");
+ const ref = arg("--target-ref", "");
+ if (!python || !code || !install) throw new Error(`missing --python, --code or --install (the install \`archilyzer voice setup --engine ${kind}\` made)`);
+ if (!ref) throw new Error("missing --target-ref (the stock target's reference clip)");
+ const batch = path.join(work, "batch.json");
+ await writeFile(batch, JSON.stringify(items.map((it) => ({ input: it.in48, output: it.raw }))));
+ const env = { HF_HUB_OFFLINE: "1", TRANSFORMERS_OFFLINE: "1", HF_HOME: path.join(install, ".hf"), OMP_NUM_THREADS: threads };
+ if (kind === "openvoice") {
+ await run(python, [
+ path.join(import.meta.dirname, "voice_openvoice.py"),
+ "--code", code,
+ "--ckpt", path.join(install, "converter", "checkpoint.pth"),
+ "--config", path.join(install, "converter", "config.json"),
+ "--batch", batch, "--target-ref", ref,
+ ...(arg("--target-se", "") ? ["--target-se", arg("--target-se", "")] : []),
+ "--tau", String(Math.min(1, Math.max(0, num(params.tau, 0.3)))),
+ "--threads", threads,
+ ], { env });
} else {
- const python = arg("--python", "");
- const code = arg("--code", "");
- const install = arg("--install", "");
- const ref = arg("--target-ref", "");
- if (!python || !code || !install) throw new Error(`missing --python, --code or --install (the install \`archilyzer voice setup --engine ${kind}\` made)`);
- if (!ref) throw new Error("missing --target-ref (the stock target's reference clip)");
- const env = { HF_HUB_OFFLINE: "1", TRANSFORMERS_OFFLINE: "1", HF_HOME: path.join(install, ".hf"), OMP_NUM_THREADS: threads };
- if (kind === "openvoice") {
- await run(python, [
- path.join(import.meta.dirname, "voice_openvoice.py"),
- "--code", code,
- "--ckpt", path.join(install, "converter", "checkpoint.pth"),
- "--config", path.join(install, "converter", "config.json"),
- "--input", in48, "--output", raw, "--target-ref", ref,
- ...(arg("--target-se", "") ? ["--target-se", arg("--target-se", "")] : []),
- "--tau", String(Math.min(1, Math.max(0, num(params.tau, 0.3)))),
- "--threads", threads,
- ], { env });
- } else {
- await run(python, [
- path.join(import.meta.dirname, "voice_seedvc.py"),
- "--code", code,
- "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
- "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
- "--whisper", path.join(install, "whisper-small"),
- "--bigvgan", path.join(install, "bigvgan"),
- "--campplus", path.join(install, "campplus_cn_common.bin"),
- "--input", in48, "--output", raw, "--target-ref", ref,
- "--steps", String(Math.round(Math.min(100, Math.max(1, num(params.steps, 25))))),
- "--cfg-rate", String(Math.min(1, Math.max(0, num(params.cfgRate, 0.7)))),
- "--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))),
- "--threads", threads,
- ], { env });
- }
+ await run(python, [
+ path.join(import.meta.dirname, "voice_seedvc.py"),
+ "--code", code,
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ "--whisper", path.join(install, "whisper-small"),
+ "--bigvgan", path.join(install, "bigvgan"),
+ "--campplus", path.join(install, "campplus_cn_common.bin"),
+ "--batch", batch, "--target-ref", ref,
+ "--steps", String(Math.round(Math.min(100, Math.max(1, num(params.steps, 10))))),
+ "--cfg-rate", String(Math.min(1, Math.max(0, num(params.cfgRate, 0.7)))),
+ "--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))),
+ "--threads", threads,
+ ], { env });
}
- const engineMs = Date.now() - started;
- if (!((await stat(raw).catch(() => null))?.size > 44)) throw new Error(`the ${kind} engine produced no audio`);
+}
- // 3. One static gain: enhance to --lufs, convert to the input's loudness;
- // never above -1 dBTP.
- const mid = await measure(raw);
- const goal = op === "enhance" ? lufs : before.lufs;
+// One static gain (enhance to --lufs, convert to the input's own loudness;
+// never above -1 dBTP), then 48 kHz mono 16-bit exactly `samples` long, moved
+// into place.
+async function finish(it) {
+ if (!((await stat(it.raw).catch(() => null))?.size > 44)) throw new Error(`the ${kind} engine produced no audio for ${it.input}`);
+ const mid = await measure(it.raw);
+ const goal = op === "enhance" ? lufs : it.before.lufs;
let gainDb = 0;
if (mid.lufs !== null && goal !== null && Number.isFinite(goal)) gainDb = goal - mid.lufs;
if (mid.tp !== null) gainDb = Math.min(gainDb, TRUE_PEAK_CAP - mid.tp);
gainDb = Math.round(gainDb * 100) / 100;
-
- // 4. 48 kHz mono 16-bit, exactly `samples` long.
- const tmp = path.join(work, "out.wav");
+ const tmp = path.join(work, `out-${it.k}.wav`);
await ff([
- "-i", raw,
- "-af", `volume=${gainDb}dB,aresample=${SAMPLE_RATE},apad=whole_len=${samples},atrim=end_sample=${samples}`,
+ "-i", it.raw,
+ "-af", `volume=${gainDb}dB,aresample=${SAMPLE_RATE},apad=whole_len=${it.samples},atrim=end_sample=${it.samples}`,
"-ac", "1", "-ar", String(SAMPLE_RATE), "-c:a", "pcm_s16le", ...BITEXACT, "-f", "wav", tmp,
]);
const got = (await dataBytes(tmp)) / 2;
- if (got !== samples) throw new Error(`the output is ${got} samples, the input ${samples}`);
+ if (got !== it.samples) throw new Error(`the output is ${got} samples, the input ${it.samples}`);
const after = await measure(tmp);
- await rename(tmp, out);
+ const dest = path.resolve(it.output);
+ await mkdir(path.dirname(dest), { recursive: true });
+ await rename(tmp, dest);
+ return {
+ output: dest,
+ seconds: Math.round((it.samples / SAMPLE_RATE) * 1000) / 1000,
+ samples: it.samples,
+ gainDb,
+ inputLufs: it.before.lufs,
+ outputLufs: after.lufs,
+ };
+}
+
+try {
+ await mkdir(work, { recursive: true });
+ const items = [];
+ for (const [k, item] of [{ input, output }, ...extra].entries()) items.push(await prepare(item, k));
+ const started = Date.now();
+ if (op === "enhance") for (const it of items) await enhanceOne(it);
+ else await convertAll(items);
+ const engineMs = Date.now() - started;
+ const done = [];
+ for (const it of items) done.push(await finish(it));
await cleanup();
+ const [first, ...rest] = done;
const result = {
op,
engine: kind,
sampleRate: SAMPLE_RATE,
- seconds: Math.round((samples / SAMPLE_RATE) * 1000) / 1000,
- samples,
+ seconds: first.seconds,
+ samples: first.samples,
engineMs,
- gainDb,
- inputLufs: before.lufs,
- outputLufs: after.lufs,
+ gainDb: first.gainDb,
+ inputLufs: first.inputLufs,
+ outputLufs: first.outputLufs,
+ ...(rest.length ? { more: rest } : {}),
};
process.stdout.write(JSON.stringify(result) + "\n");
- process.stderr.write(`voice: ${op}/${kind} ${result.seconds}s in ${(engineMs / 1000).toFixed(2)}s -> ${out}\n`);
+ process.stderr.write(`voice: ${op}/${kind} ${result.seconds}s${rest.length ? ` and ${rest.length} more` : ""} in ${(engineMs / 1000).toFixed(2)}s -> ${out}\n`);
} catch (err) {
await cleanup();
fail(err instanceof Error ? err.message : String(err), 1);
diff --git a/scripts/voice.test.mjs b/scripts/voice.test.mjs
@@ -73,3 +73,20 @@ test("rnnoise: 48 kHz mono, the input's exact length, aligned, the same every ru
// No scratch left behind.
assert.deepEqual(readdirSync(dir).filter((f) => f.includes(".voice-")), []);
});
+
+test("--more runs further files the same way, in the same run", { skip: !ffmpeg && "ffmpeg absent" }, () => {
+ const a = path.join(dir, "m-a.wav");
+ const b = path.join(dir, "m-b.wav");
+ execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=300:d=1:r=48000", a]);
+ execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=300:d=0.5:r=22050", b]);
+ const outB = path.join(dir, "m-parts", "p02.wav");
+ const r = run(["--op", "enhance", "--engine-kind", "rnnoise", "--model", MODEL, "--input", a, "--output", path.join(dir, "m-out.wav"), "--more", JSON.stringify([{ input: b, output: outB }])]);
+ assert.equal(r.status, 0, r.stderr);
+ const res = JSON.parse(r.stdout.trim().split("\n").pop());
+ assert.equal(res.samples, 48000);
+ assert.equal(res.more.length, 1);
+ assert.equal(res.more[0].output, outB);
+ assert.equal(res.more[0].samples, 24000);
+ assert.equal(readFileSync(outB).readUInt32LE(40), 48000);
+ assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", a, "--output", "/x.wav", "--more", '[{"input":1}]']).stderr, /--more is a list of \{input, output\}/);
+});
diff --git a/scripts/voice_openvoice.py b/scripts/voice_openvoice.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# OpenVoice v2's TONE-COLOUR CONVERTER, one file in, one file out — run by
+# OpenVoice v2's TONE-COLOUR CONVERTER, files in, files out — run by
# scripts/voice.mjs (--engine-kind openvoice) in the venv `archilyzer voice
# setup --engine openvoice` built. Never run by hand: the editor's
# `voice-convert` op is the way in (common/controller/voiceFile.ts).
@@ -15,7 +15,10 @@
# the package's `api` pulls in its text front end and the watermarker, which
# the converter does not need, so they are not installed.
#
-# stdout: one JSON line {engine, sampleRate, seconds, engineMs}.
+# Several files (--batch) are one performance in parts: the source speaker is
+# embedded from all of them at once, the target once, the model loaded once.
+#
+# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs}.
import argparse
import json
@@ -29,13 +32,17 @@ def main() -> int:
ap.add_argument("--code", required=True, help="the OpenVoice checkout (its openvoice/ package)")
ap.add_argument("--ckpt", required=True)
ap.add_argument("--config", required=True)
- ap.add_argument("--input", required=True)
- ap.add_argument("--output", required=True)
+ ap.add_argument("--input", default="")
+ ap.add_argument("--output", default="")
+ ap.add_argument("--batch", default="", help="a JSON file: [{input, output}], one performance in several files")
ap.add_argument("--target-ref", required=True, help="the stock target's reference clip")
ap.add_argument("--target-se", default="", help="where the target's embedding is cached (.pt)")
ap.add_argument("--tau", type=float, default=0.3)
ap.add_argument("--threads", type=int, default=4)
a = ap.parse_args()
+ items = json.load(open(a.batch)) if a.batch else [{"input": a.input, "output": a.output}]
+ if not items or not all(i.get("input") and i.get("output") for i in items):
+ ap.error("--input and --output, or --batch")
sys.path.insert(0, a.code)
import numpy as np
@@ -78,7 +85,7 @@ def main() -> int:
gs.append(model.ref_enc(spec_of(seg).transpose(1, 2)).unsqueeze(-1))
return torch.stack(gs).mean(0)
- src, _ = librosa.load(a.input, sr=sr, mono=True)
+ srcs = [librosa.load(i["input"], sr=sr, mono=True)[0] for i in items]
if a.target_se and os.path.exists(a.target_se):
tgt_se = torch.load(a.target_se, map_location="cpu", weights_only=False)
else:
@@ -88,18 +95,24 @@ def main() -> int:
tmp = a.target_se + ".part"
torch.save(tgt_se, tmp)
os.replace(tmp, a.target_se)
- src_se = embedding(src)
+ # The source speaker, from every file of the performance at once (a short
+ # part alone says little about a voice).
+ src_se = embedding(np.concatenate(srcs))
- with torch.no_grad():
- spec = spec_of(src)
- lengths = torch.LongTensor([spec.size(-1)])
- out = model.voice_conversion(spec, lengths, sid_src=src_se, sid_tgt=tgt_se, tau=a.tau)[0][0, 0]
- audio = out.data.cpu().float().numpy()
- soundfile.write(a.output, audio.astype(np.float32), sr, subtype="PCM_16")
+ total = 0.0
+ for item, src in zip(items, srcs):
+ with torch.no_grad():
+ spec = spec_of(src)
+ lengths = torch.LongTensor([spec.size(-1)])
+ out = model.voice_conversion(spec, lengths, sid_src=src_se, sid_tgt=tgt_se, tau=a.tau)[0][0, 0]
+ audio = out.data.cpu().float().numpy()
+ soundfile.write(item["output"], audio.astype(np.float32), sr, subtype="PCM_16")
+ total += len(audio) / sr
print(json.dumps({
"engine": "openvoice",
"sampleRate": sr,
- "seconds": round(len(audio) / sr, 3),
+ "seconds": round(total, 3),
+ "files": len(items),
"engineMs": int((time.time() - t0) * 1000),
}))
return 0
diff --git a/scripts/voice_seedvc.py b/scripts/voice_seedvc.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# SEED-VC (v1, the 22 kHz speech model), one file in, one file out — run by
+# SEED-VC (v1, the 22 kHz speech model), files in, files out — run by
# scripts/voice.mjs (--engine-kind seed-vc) in the venv `archilyzer voice
# setup --engine seed-vc` built. Never run by hand: the editor's
# `voice-convert` op is the way in (common/controller/voiceFile.ts).
@@ -17,7 +17,10 @@
# quantizer this model does not use; it is stubbed rather than installed (it
# pulls in a training stack).
#
-# stdout: one JSON line {engine, sampleRate, seconds, engineMs}.
+# Several files (--batch) are converted one after another, the model and the
+# target's features made once.
+#
+# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs}.
import argparse
import json
@@ -35,15 +38,19 @@ def main() -> int:
ap.add_argument("--whisper", required=True, help="a dir with whisper-small's config, preprocessor config and weights")
ap.add_argument("--bigvgan", required=True, help="a dir with BigVGAN's config.json and bigvgan_generator.pt")
ap.add_argument("--campplus", required=True)
- ap.add_argument("--input", required=True)
- ap.add_argument("--output", required=True)
+ ap.add_argument("--input", default="")
+ ap.add_argument("--output", default="")
+ ap.add_argument("--batch", default="", help="a JSON file: [{input, output}], converted one after another, the model loaded once")
ap.add_argument("--target-ref", required=True, help="the stock target's reference clip")
- ap.add_argument("--steps", type=int, default=25, help="diffusion steps")
+ ap.add_argument("--steps", type=int, default=10, help="diffusion steps")
ap.add_argument("--cfg-rate", type=float, default=0.7)
ap.add_argument("--ref-seconds", type=float, default=10.0,
help="how much of the reference prompts the model: each window is 30 s less this, so less is faster")
ap.add_argument("--threads", type=int, default=4)
a = ap.parse_args()
+ items = json.load(open(a.batch)) if a.batch else [{"input": a.input, "output": a.output}]
+ if not items or not all(i.get("input") and i.get("output") for i in items):
+ ap.error("--input and --output, or --batch")
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
@@ -100,7 +107,7 @@ def main() -> int:
feat = AutoFeatureExtractor.from_pretrained(a.whisper, local_files_only=True)
def semantic(w16):
- inputs = feat([w16.squeeze(0).cpu().numpy()], return_tensors="pt", return_attention_mask=True)
+ inputs = feat([w16.squeeze(0).cpu().numpy()], return_tensors="pt", return_attention_mask=True, sampling_rate=16000)
x = whisper._mask_input_features(inputs.input_features, attention_mask=inputs.attention_mask)
with torch.no_grad():
out = whisper.encoder(x.to(whisper.encoder.dtype), head_mask=None, output_attentions=False,
@@ -121,77 +128,85 @@ def main() -> int:
overlap_frames = 16
overlap_wave = overlap_frames * hop
- src = librosa.load(a.input, sr=sr, mono=True)[0]
+ def crossfade(a1, a2, n):
+ fo = np.cos(np.linspace(0, np.pi / 2, n)) ** 2
+ fi = np.cos(np.linspace(np.pi / 2, 0, n)) ** 2
+ if len(a2) < n:
+ a2[:n] = a2[:n] * fi[: len(a2)] + (a1[-n:] * fo)[: len(a2)]
+ else:
+ a2[:n] = a2[:n] * fi + a1[-n:] * fo
+ return a2
+
+ # The target, once: its content features, mel and style.
ref = librosa.load(a.target_ref, sr=sr, mono=True)[0]
with torch.no_grad():
- source = torch.tensor(src).unsqueeze(0).float()
refa = torch.tensor(ref[: int(sr * a.ref_seconds)]).unsqueeze(0).float()
- src16 = torchaudio.functional.resample(source, sr, 16000)
- if src16.size(-1) <= 16000 * 30:
- s_alt = semantic(src16)
- else:
- lap = 5
- parts, buffer, at = [], None, 0
- while at < src16.size(-1):
- if buffer is None:
- chunk = src16[:, at : at + 16000 * 30]
- else:
- chunk = torch.cat([buffer, src16[:, at : at + 16000 * (30 - lap)]], dim=-1)
- s = semantic(chunk)
- parts.append(s if at == 0 else s[:, 50 * lap :])
- buffer = chunk[:, -16000 * lap :]
- at += 30 * 16000 if at == 0 else chunk.size(-1) - 16000 * lap
- s_alt = torch.cat(parts, dim=1)
ref16 = torchaudio.functional.resample(refa, sr, 16000)
s_ori = semantic(ref16)
- mel = to_mel(source)
mel2 = to_mel(refa)
- target_len = torch.LongTensor([mel.size(2)])
target2_len = torch.LongTensor([mel2.size(2)])
fb = torchaudio.compliance.kaldi.fbank(ref16, num_mel_bins=80, dither=0, sample_frequency=16000)
fb = fb - fb.mean(dim=0, keepdim=True)
style = campplus(fb.unsqueeze(0))
- cond, *_ = model.length_regulator(s_alt, ylens=target_len, n_quantizers=3, f0=None)
prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3, f0=None)
+ window = max_context - mel2.size(2)
- def crossfade(a1, a2, n):
- fo = np.cos(np.linspace(0, np.pi / 2, n)) ** 2
- fi = np.cos(np.linspace(np.pi / 2, 0, n)) ** 2
- if len(a2) < n:
- a2[:n] = a2[:n] * fi[: len(a2)] + (a1[-n:] * fo)[: len(a2)]
+ def convert(src):
+ with torch.no_grad():
+ source = torch.tensor(src).unsqueeze(0).float()
+ src16 = torchaudio.functional.resample(source, sr, 16000)
+ if src16.size(-1) <= 16000 * 30:
+ s_alt = semantic(src16)
else:
- a2[:n] = a2[:n] * fi + a1[-n:] * fo
- return a2
-
- window = max_context - mel2.size(2)
- done, chunks, prev = 0, [], None
- while done < cond.size(1):
- c = cond[:, done : done + window]
- last = done + window >= cond.size(1)
- cat = torch.cat([prompt, c], dim=1)
- vc = model.cfm.inference(cat, torch.LongTensor([cat.size(1)]), mel2, style, None, a.steps,
- inference_cfg_rate=a.cfg_rate)
- vc = vc[:, :, mel2.size(-1) :]
- wave = vocoder(vc.float()).squeeze()[None, :]
- if done == 0:
- if last:
- chunks.append(wave[0].cpu().numpy())
+ lap = 5
+ parts, buffer, at = [], None, 0
+ while at < src16.size(-1):
+ if buffer is None:
+ chunk = src16[:, at : at + 16000 * 30]
+ else:
+ chunk = torch.cat([buffer, src16[:, at : at + 16000 * (30 - lap)]], dim=-1)
+ s = semantic(chunk)
+ parts.append(s if at == 0 else s[:, 50 * lap :])
+ buffer = chunk[:, -16000 * lap :]
+ at += 30 * 16000 if at == 0 else chunk.size(-1) - 16000 * lap
+ s_alt = torch.cat(parts, dim=1)
+ mel = to_mel(source)
+ # The input's own frame count: the timing is the input's.
+ cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3, f0=None)
+ done, chunks, prev = 0, [], None
+ while done < cond.size(1):
+ c = cond[:, done : done + window]
+ last = done + window >= cond.size(1)
+ cat = torch.cat([prompt, c], dim=1)
+ vc = model.cfm.inference(cat, torch.LongTensor([cat.size(1)]), mel2, style, None, a.steps,
+ inference_cfg_rate=a.cfg_rate)
+ vc = vc[:, :, mel2.size(-1) :]
+ wave = vocoder(vc.float()).squeeze()[None, :]
+ if done == 0:
+ if last:
+ chunks.append(wave[0].cpu().numpy())
+ break
+ chunks.append(wave[0, :-overlap_wave].cpu().numpy())
+ prev = wave[0, -overlap_wave:]
+ elif last:
+ chunks.append(crossfade(prev.cpu().numpy(), wave[0].cpu().numpy(), overlap_wave))
break
- chunks.append(wave[0, :-overlap_wave].cpu().numpy())
- prev = wave[0, -overlap_wave:]
- elif last:
- chunks.append(crossfade(prev.cpu().numpy(), wave[0].cpu().numpy(), overlap_wave))
- break
- else:
- chunks.append(crossfade(prev.cpu().numpy(), wave[0, :-overlap_wave].cpu().numpy(), overlap_wave))
- prev = wave[0, -overlap_wave:]
- done += vc.size(2) - overlap_frames
- audio = np.concatenate(chunks).astype(np.float32)
- soundfile.write(a.output, np.clip(audio, -1, 1), sr, subtype="PCM_16")
+ else:
+ chunks.append(crossfade(prev.cpu().numpy(), wave[0, :-overlap_wave].cpu().numpy(), overlap_wave))
+ prev = wave[0, -overlap_wave:]
+ done += vc.size(2) - overlap_frames
+ return np.concatenate(chunks).astype(np.float32)
+
+ total = 0.0
+ for item in items:
+ audio = convert(librosa.load(item["input"], sr=sr, mono=True)[0])
+ soundfile.write(item["output"], np.clip(audio, -1, 1), sr, subtype="PCM_16")
+ total += len(audio) / sr
print(json.dumps({
"engine": "seed-vc",
"sampleRate": sr,
- "seconds": round(len(audio) / sr, 3),
+ "seconds": round(total, 3),
+ "files": len(items),
"engineMs": int((time.time() - t0) * 1000),
}))
return 0
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -195,8 +195,10 @@ export async function POST(request: Request) {
} catch (err) {
const status = (err as { status?: number }).status ?? 502;
const msg = err instanceof Error ? err.message : String(err);
- // The editor has no engine for it yet (a follow-up lane adds voice-enhance / voice-convert): say so, plainly.
- if (status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg)) return Response.json({ ok: false, installed: false, error: `the editor has no ${op} engine yet (not installed)` }, { status: 200, headers: noStore });
+ // The editor has no engine for it (an older editor has no route; a newer one names the setup to run): say so, plainly, with its words.
+ if (status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg)) {
+ return Response.json({ ok: false, installed: false, error: `the editor has no ${op} engine installed (not installed: ${msg.replace(/^the editor refused it: /, "")})` }, { status: 200, headers: noStore });
+ }
return Response.json({ error: msg }, { status });
}
}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -1375,6 +1375,53 @@ const server = http.createServer((req, res) => {
});
return;
}
+ // THE VOICE DOORS (release 39): the editor's voice ops, as umtool's derived
+ // takes ask them. voice-enhance answers as an editor with no enhance engine
+ // installed does (its own sentence: umtool shows "not installed"); voice-convert
+ // refuses a recording as a target as the editor does, else "converts" by
+ // copying the take (and its parts) to `out`, a job whose last line is the
+ // editor's `@@voice-result` with the engine and stock voice its defaults chose.
+ if (req.method === "POST" && (url.pathname === "/api/ops/voice-enhance" || url.pathname === "/api/ops/voice-convert")) {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ let body;
+ try {
+ body = JSON.parse(raw);
+ } catch {
+ return json(res, 400, { ok: false, error: "malformed JSON body" });
+ }
+ const route = url.pathname.slice("/api/ops/".length);
+ requests.push({ route, ...body, authorization: auth });
+ record();
+ if (route === "voice-enhance") {
+ return json(res, 400, { ok: false, error: "DeepFilterNet 3 is not installed (/stub/voice/deepfilternet): missing deep-filter — run `archilyzer voice setup --engine deepfilternet`" });
+ }
+ if (typeof body.voice === "string" && /[/\\.]/.test(body.voice)) {
+ return json(res, 400, { ok: false, error: `"${body.voice}" is refused: a convert target is a STOCK synthetic voice` });
+ }
+ if (typeof body.file !== "string" || typeof body.out !== "string" || !existsSync(body.file)) return json(res, 400, { ok: false, error: '"file" and "out" are required' });
+ copyFileSync(body.file, body.out);
+ for (const p of Array.isArray(body.parts) ? body.parts : []) {
+ mkdirSync(path.dirname(p.out), { recursive: true });
+ copyFileSync(p.file, p.out);
+ }
+ const id = `stub-voice-${nextJob++}`;
+ const voice = typeof body.voice === "string" ? body.voice : "zac";
+ ttsJobs.set(id, {
+ polls: 0,
+ kind: "voice-convert",
+ marker: "@@voice-result ",
+ result: {
+ op: "convert", engine: body.engine ?? "openvoice", wav: body.out, seconds: 2, sampleRate: 48000, synthetic: true,
+ target: voice.includes(":") ? voice : `orpheus:${voice}`, voice: voice.includes(":") ? voice.split(":")[1] : voice,
+ disclosure: `Narration: voice converted to a synthetic voice (OpenVoice v2 (tone-colour converter) · orpheus:${voice})`,
+ },
+ });
+ json(res, 200, { ok: true, jobId: id });
+ });
+ return;
+ }
const opsJob = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname);
if (req.method === "GET" && opsJob && ttsJobs.has(opsJob[1])) {
req.resume();
@@ -1386,8 +1433,8 @@ const server = http.createServer((req, res) => {
const status = j.polls <= 1 ? "running" : "done";
return json(res, 200, {
ok: true,
- job: { id: opsJob[1], kind: "tts-file", status },
- ...(tail ? { tail: ["tts: synthesizing (stub)", `@@tts-result ${JSON.stringify(j.result)}`] } : {}),
+ job: { id: opsJob[1], kind: j.kind ?? "tts-file", status },
+ ...(tail ? { tail: ["tts: synthesizing (stub)", `${j.marker ?? "@@tts-result "}${JSON.stringify(j.result)}`] } : {}),
});
}
diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -46,7 +46,7 @@ test.beforeEach(() => {
copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
rmSync(path.join(DIR, "notes.json"), { force: true });
- for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true });
+ for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav", "take-2.convert-zac.wav", "take-3.convert-zac.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true });
rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true });
rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true });
rmSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"), { recursive: true, force: true });
@@ -152,6 +152,25 @@ test("the post bench: the lanes, a re-take with direction (the editor's tts job)
await expect(page.locator("[data-post-take]")).toHaveCount(1);
expect(existsSync(path.join(DIR, "narration", "posts", "11", "take-2.orpheus-zac.wav"))).toBe(false);
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench-takes.png"), fullPage: true });
+ // Run AI on take #1, converted onto a stock voice (the editor's voice-convert, stubbed): a NEW take derived from
+ // it, the original kept, the step naming the engine the editor ran and the voice it landed on.
+ await page.locator("[data-post-derive-op]").selectOption("convert");
+ await page.locator("[data-post-derive-voice]").fill("zac");
+ await page.locator("[data-post-derive-run]").click();
+ await expect(page.locator("[data-post-take]")).toHaveCount(2, { timeout: 20_000 });
+ const d = narr("p-11").takes![1] as Take & { source?: unknown; steps?: Record<string, unknown>[] };
+ expect(d).toMatchObject({ engine: "derived", voice: "zac", source: { kind: "take", from: "take-1.orpheus-zac" } });
+ expect(d.file).toMatch(/^narration\/posts\/11\/take-\d+\.convert-zac\.wav$/);
+ expect(d.steps![0]).toMatchObject({ op: "convert", engine: "openvoice", voice: "zac" });
+ expect(existsSync(path.join(DIR, d.file))).toBe(true);
+ expect(narr("p-11").takes![0].file).toBe("narration/posts/11/take-1.orpheus-zac.wav");
+ const asked = (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; voice?: string; file?: string; out?: string }[]).filter((r) => r.route === "voice-convert").at(-1)!;
+ expect(asked.voice).toBe("zac");
+ expect(asked.file).toMatch(/narration\/posts\/11\/take-1\.orpheus-zac\.wav$/);
+ // The tree: the derived take under its source, its step said.
+ await expect(page.locator('[data-post-take="2"]')).toContainText("convert");
+ await expect(page.locator('[data-post-take="2"]')).toContainText("zac");
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench-derived.png"), fullPage: true });
});
test.describe("the recording session", () => {