commit bbba2860323e75c8c6bfa6f03f069fe25c993712
parent 87d47f3b4be1a2765f9aabf43ea1a3cf91a4b036
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 18:02:01 -0500
Merge lane/voice-pitch: a converted recording can follow the reader's pitch -- Seed-VC's f0 model behind voice-convert's pitch (target, source, contour) and semitones, an optional f0 file group in voice setup, the cast's convert entry and the take panel carry them
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
37 files changed, 1375 insertions(+), 140 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -103,7 +103,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer docs cli` | `[--check]` | write COMMANDS.md from this command table and `pnpm ops --help` |
| `archilyzer settings example` | `[--check]` | write settings.json.example + SETTINGS.md from the schema |
| `archilyzer tts setup` | `[--engine kokoro\|orpheus\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/<engine> (default ~/.local/share/archilyzer/tts/<engine>): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python <py> -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8\_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from <dir> takes already-downloaded model files from <dir> instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is |
-| `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is |
+| `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--with f0] [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB; --with f0 adds seed-vc's OPTIONAL f0-conditioned 44.1 kHz model, its BigVGAN and the RMVPE pitch tracker, 1.49 GB — what voice-convert's pitch source and contour run on, and an install without it still converts at the target's pitch) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is (an optional group is said, and counted only with --with) |
| `archilyzer service install` | `[--mode docker\|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>\|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--no-housekeeping] [--linger] [--no-start] [--force] [--dry-run]` | install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-<id>.service per --sites (a built bundle on 127.0.0.1) and archilyzer-housekeeping.timer, weekly and Persistent, starting the oneshot archilyzer-housekeeping.service (`archilyzer housekeeping --by timer`; a run the heavy slot turns away exits 75 and is retried hourly for a day; --no-housekeeping leaves the pair out); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only |
| `archilyzer service status` | | read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container; for archilyzer-housekeeping.timer its next and last trigger and the last recorded run |
| `archilyzer service logs` | `[--apps <a,b>] [--lines <n>] [--follow]` | the units' journal (journalctl --user), the last 200 lines by default |
@@ -184,7 +184,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. 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 \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — 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 performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times 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 and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. 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` |
| `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | |
-| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). The target's reference is synthesized once through the tts op and kept. The result adds target, voice, synthetic: true and the disclosure line. | |
+| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
| `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":{"diarization":{"cleanAfterCapture":true}}}'`<br>`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. | |
| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -916,21 +916,41 @@ pnpm ops get generation-usage
pnpm archilyzer voice setup --engine deepfilternet --dry-run # what it fetches, how big; then without --dry-run
pnpm archilyzer voice setup --engine openvoice
pnpm archilyzer voice setup --engine seed-vc --check
+pnpm archilyzer voice setup --engine seed-vc --with f0 # the optional f0 model (1.49 GB): a conversion that follows your pitch
pnpm ops voice-enhance --json '{"file":"/abs/take.wav","out":"/abs/take.clean.wav"}' --wait
pnpm ops voice-convert --json '{"file":"/abs/take.wav","out":"/abs/take.zac.wav","voice":"orpheus:zac"}' --wait
umtool posts narrate <project> <item> --derive 1 --op enhance
umtool posts narrate <project> <item> --derive 2 --op convert --voice zac --engine seed-vc
+pnpm ops voice-convert --json '{"file":"/abs/take.wav","out":"/abs/take.bella.wav","voice":"kokoro:af_bella","engine":"seed-vc","pitch":"source","semitones":2}' --wait
+umtool posts narrate <project> <item> --derive 2 --op convert --voice kokoro:af_bella --engine seed-vc --pitch contour
+umtool cast set <character> --convert-engine seed-vc --convert-pitch contour --convert-semitones 2
```
- Two editor ops over a speech recording, each a job on the `voice` queue, one at a time, its engine run behind the
heavy slot with the engine's declared estimate (`settings.voice.heavyEstimateMB`): **enhance** (denoise, soften the
- room, level by one static gain) and **convert** (the timing and pitch contour kept, the timbre swapped for a STOCK
- synthetic voice). The result is a 48 kHz mono WAV exactly as long as the input; `out` is never inside the corpus.
+ room, level by one static gain) and **convert** (the timing kept, the timbre swapped for a STOCK
+ synthetic voice; the pitch as `pitch` says, below). The result is a 48 kHz mono WAV exactly as long as the input; `out` is never inside the corpus.
umtool's derived takes are the usual caller: a new take from take n, the original kept, a parted take part by part.
- **A convert target is a stock voice of our own TTS engines** — `orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`,
or a bare name one engine has (`zac`). A file, a path or a recording is refused, whatever it holds: these engines
clone from seconds of audio, so no real person's voice is ever a target. Its reference (the voice reading "The North
Wind and the Sun") is asked of the `tts` op the first time and kept under `settings.voice.home/targets/`.
+- **The pitch a conversion lands on** is `pitch` (default `settings.voice.convert.pitch`, `target`):
+ - `target`: the stock voice's own pitch. The converter is given none of yours, so a read with a median of 128 Hz and
+ one of 237 Hz both come out near 197 Hz, and the range narrows — voice acting is flattened.
+ - `source`: the pitch you read at. Raise your voice for a character and the result is raised the same.
+ - `contour`: your rises and falls, moved as a whole so their median sits on the stock voice's. Read in your ordinary
+ voice and the character speaks in its own register with your intonation.
+ - `semitones` (-12 to 12) moves a followed pitch (`source`, `contour`); with `target` it is refused.
+ - `source` and `contour` are seed-vc's, on its f0-conditioned 44.1 kHz model: optional files, fetched by `voice setup
+ --engine seed-vc --with f0`. openvoice refuses them; without the files the op refuses, naming that command. An
+ install without them still converts at the target's pitch. It takes about 1.7 times as long as seed-vc's plain run (measured: 170 s against 103 s for a 7 s read on a busy machine) and
+ declares its own estimate (`settings.voice.heavyEstimateMB["seed-vc-f0"]`, 6500 MB: a take of 20 s or more peaks near 5.8 GB).
+ - The result says what was done: `pitch`, `semitones`, and `f0` — the median pitch heard in the target's reference
+ and in your take, and the whole move applied, in semitones.
+ - In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch …`), so every recording
+ made that character's lands the same way; `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive`
+ are for one read.
- Engines (`settings.voice`): enhance `deepfilternet` (DeepFilterNet 3, the default) or `rnnoise` (ffmpeg's arnndn,
nothing to install); convert `openvoice` (OpenVoice v2's converter, the default) or `seed-vc` (Seed-VC v1, closer
to the target, several times slower). All on the CPU. `voice setup` says what it fetches first; `--check` lists
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -1057,8 +1057,8 @@ The voice ops (release 39): a speech recording ENHANCED (denoised, de-reverbed,
| `home` | `""` | Where `archilyzer voice setup` installs the voice engines, one directory per engine (`<home>/deepfilternet`: its binary; `<home>/openvoice`, `<home>/seed-vc`: a python venv, a pinned checkout and the weights), and where the stock targets' reference clips are kept (`<home>/targets/`). Blank = `~/.local/share/archilyzer/voice`. Absolute, or `~/`-relative. |
| `threads` | `4` | CPU threads a torch engine (openvoice, seed-vc) may use. 1–16. |
| `enhance` | object — see below | The enhance op's default engine. See VoiceEnhanceSettings (`voice.enhance` below). |
-| `convert` | object — see below | The convert op's default engine and target. See VoiceConvertSettings (`voice.convert` below). |
-| `heavyEstimateMB` | object — see below | Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with (`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. The defaults are the 2026-11-03 bake-off's measured peaks plus a margin. An engine left out takes its default; 0 declares nothing (the job then runs ALONE in the slot). |
+| `convert` | object — see below | The convert op's default engine, target and pitch. See VoiceConvertSettings (`voice.convert` below). |
+| `heavyEstimateMB` | object — see below | Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with (`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. The defaults are the 2026-11-03 bake-off's measured peaks plus a margin; `seed-vc-f0` is seed-vc's run when it follows the input's pitch (`pitch: source \| contour` — another, bigger model; measured 2026-11-11 over a take long enough to fill a 30 s window: 5.8 GB). An engine left out takes its default; 0 declares nothing (the job then runs ALONE in the slot). |
#### `voice.enhance`
@@ -1072,6 +1072,8 @@ The voice ops (release 39): a speech recording ENHANCED (denoised, de-reverbed,
|---|---|---|
| `engine` | `"openvoice"` | The engine `voice-convert` uses when the request names none: `openvoice` (OpenVoice v2's tone-colour converter, MIT, light) or `seed-vc` (Seed-VC v1, GPL-3.0, a closer timbre match, slower). Both run on the CPU; `archilyzer voice setup --engine <id>` installs one. An unknown id falls back to the default. |
| `target` | `"orpheus:zac"` | The stock synthetic voice a conversion lands on when the request names none: `<tts engine>:<stock voice>` (`orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`, …). Never a file or a recording — no real person's voice is a target. Its reference clip is synthesized once through the `tts` op and kept under `home`. Anything else falls back to `orpheus:zac`. |
+| `pitch` | `"target"` | The pitch a conversion lands on when the request names none — for an engine that can follow the input's (seed-vc, with its optional f0 model: `archilyzer voice setup --engine seed-vc --with f0`; openvoice always lands on the target's). `target`: the stock voice's own pitch — the read's intonation is flattened to it (what there was before). `source`: the pitch the take was read at — raise your voice and the result rises. `contour`: the read's rises and falls, moved as a whole so their median sits on the stock voice's. Anything else falls back to `target`. |
+| `semitones` | `0` | Semitones a FOLLOWED pitch (`source`, `contour`) is moved by when the request names none: -12 to 12, 0 = as followed. Ignored for `target`. It applies to a request that names its own `pitch` too: `{"pitch": "source"}` with no `semitones` is moved by this many — send `"semitones": 0` for none. |
Default:
@@ -1084,13 +1086,16 @@ Default:
},
"convert": {
"engine": "openvoice",
- "target": "orpheus:zac"
+ "target": "orpheus:zac",
+ "pitch": "target",
+ "semitones": 0
},
"heavyEstimateMB": {
"deepfilternet": 400,
"rnnoise": 300,
"openvoice": 2000,
- "seed-vc": 3500
+ "seed-vc": 3500,
+ "seed-vc-f0": 6500
}
}
```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -1131,11 +1131,12 @@ export const COMMANDS: Command[] = [
{
path: ["voice", "setup"],
usage:
- "--engine deepfilternet|openvoice|seed-vc|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check] install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is",
- flags: { engine: "string", from: "string", python: "string", home: "string", "dry-run": "boolean", check: "boolean" },
+ "--engine deepfilternet|openvoice|seed-vc|rnnoise [--with f0] [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check] install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB; --with f0 adds seed-vc's OPTIONAL f0-conditioned 44.1 kHz model, its BigVGAN and the RMVPE pitch tracker, 1.49 GB — what voice-convert's pitch source and contour run on, and an install without it still converts at the target's pitch) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is (an optional group is said, and counted only with --with)",
+ flags: { engine: "string", with: "string", from: "string", python: "string", home: "string", "dry-run": "boolean", check: "boolean" },
run: async ({ flags }) =>
(await import("./voice-setup")).main({
...(typeof flags.engine === "string" ? { engine: flags.engine } : {}),
+ ...(typeof flags.with === "string" ? { with: flags.with.split(",").map((x) => x.trim()).filter(Boolean) } : {}),
...(typeof flags.from === "string" ? { from: flags.from } : {}),
...(typeof flags.python === "string" ? { python: flags.python } : {}),
...(typeof flags.home === "string" ? { home: flags.home } : {}),
diff --git a/common/bin/voice-setup.test.ts b/common/bin/voice-setup.test.ts
@@ -1,10 +1,11 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
-import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, mkdir, open, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { main, voiceSetupPlan } from "./voice-setup";
-import { VOICE_ENGINES } from "../lib/voiceApps";
+import { SEEDVC_F0_FILES, SEEDVC_FILES, VOICE_ENGINES } from "../lib/voiceApps";
+import { VOICE_CODE_MARKER, voiceGroupState, voiceInstallState } from "../lib/voiceInstall";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test bin/voice-setup.test.ts
@@ -32,7 +33,16 @@ test("the plan names every file, its size and its source, and the total", () =>
assert.ok(plan.some((l) => /a python 3\.12 venv \(uv\), with: torch==2\.4\.0\+cpu/.test(l)));
assert.ok(plan.some((l) => /the code: https:\/\/github\.com\/Plachtaa\/seed-vc at 51383efd/.test(l)));
assert.ok(plan.some((l) => /whisper-small\/model\.safetensors — 967\.0 MB from https:\/\/huggingface\.co\/openai\/whisper-small\/resolve\/973afd24/.test(l)));
- assert.match(plan.at(-1)!, /files: 1\.88 GB/);
+ // The optional f0 group is listed after the total, not fetched or counted…
+ const total = plan.findIndex((l) => /^ {2}files: /.test(l));
+ assert.match(plan[total], /files: 1\.88 GB/);
+ assert.match(plan[total + 1], /optional, not fetched without `--with f0` — the f0-conditioned 44\.1 kHz model/);
+ assert.ok(plan.slice(total).some((l) => /rmvpe\.pt — 181\.2 MB from https:\/\/huggingface\.co\/lj1995\/VoiceConversionWebUI\/resolve\/e6d0c1a1/.test(l)));
+ assert.match(plan.at(-1)!, /1\.49 GB more/);
+ // …and with --with f0 it is part of what is fetched.
+ const withF0 = voiceSetupPlan(VOICE_ENGINES["seed-vc"], ["f0"]);
+ assert.ok(withF0.some((l) => /bigvgan-44k\/bigvgan_generator\.pt — 489\.0 MB from https:\/\/huggingface\.co\/nvidia\/bigvgan_v2_44khz_128band_512x\/resolve\/95a9d1dc/.test(l)));
+ assert.match(withF0.at(-1)!, /files: 3\.38 GB/);
assert.match(voiceSetupPlan(VOICE_ENGINES.deepfilternet).at(-1)!, /files: 36\.4 MB$/);
assert.match(voiceSetupPlan(VOICE_ENGINES.rnnoise)[0], /nothing to download/);
});
@@ -55,6 +65,58 @@ test("--check over an empty home lists what is missing and exits 1", async () =>
assert.match(c.lines.join("\n"), /DeepFilterNet 3 at .*empty\/deepfilternet — missing:\n {2}- deep-filter\nRun `archilyzer voice setup --engine deepfilternet`/);
});
+async function sparse(dir: string, files: readonly { name: string; bytes: number }[]) {
+ for (const f of files) {
+ const p = path.join(dir, f.name);
+ await mkdir(path.dirname(p), { recursive: true });
+ const fh = await open(p, "w");
+ await fh.truncate(f.bytes);
+ await fh.close();
+ }
+}
+
+test("seed-vc's f0 files are optional: an install without them checks out, --with f0 counts them", async () => {
+ const home = path.join(ROOT, "seed-home");
+ const dir = path.join(home, "seed-vc");
+ const seed = VOICE_ENGINES["seed-vc"];
+ assert.ok(seed.setup.kind === "python-venv");
+ if (seed.setup.kind !== "python-venv") return;
+ await mkdir(path.join(dir, "venv", "bin"), { recursive: true });
+ await writeFile(path.join(dir, "venv", "bin", "python"), "");
+ await mkdir(path.join(dir, "code"), { recursive: true });
+ await writeFile(path.join(dir, "code", VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`);
+ await sparse(dir, SEEDVC_FILES);
+ // The install made before the group existed is installed; the group is said.
+ const state = voiceInstallState(seed, { home, voiceModelsDir: ROOT });
+ assert.equal(state.installed, true);
+ assert.deepEqual(state.optional.map((g) => [g.id, g.installed, g.missing.length]), [["f0", false, SEEDVC_F0_FILES.length]]);
+ // --check (the venv here is a stub, so the import fails: read the lines about the group).
+ const plain = capture();
+ await main({ engine: "seed-vc", check: true, home, log: plain.log });
+ assert.ok(plain.lines.some((l) => /optional f0 \(.*follows the input's pitch.*\): not installed — `archilyzer voice setup --engine seed-vc --with f0` fetches it/.test(l)), plain.lines.join("\n"));
+ assert.equal(plain.lines.some((l) => /- rmvpe\.pt/.test(l)), false);
+ const asked = capture();
+ assert.equal(await main({ engine: "seed-vc", check: true, with: ["f0"], home, log: asked.log }), 1);
+ assert.ok(asked.lines.some((l) => /^ {2}- rmvpe\.pt$/.test(l)));
+ assert.match(asked.lines.at(-1)!, /Run `archilyzer voice setup --engine seed-vc --with f0`/);
+ // There: said as installed.
+ await sparse(dir, SEEDVC_F0_FILES);
+ assert.equal(voiceGroupState(seed, "f0", { home })!.installed, true);
+ const there = capture();
+ await main({ engine: "seed-vc", check: true, with: ["f0"], home, log: there.log });
+ assert.ok(there.lines.some((l) => /with f0 \(.*\): installed/.test(l)));
+ assert.equal(there.lines.some((l) => /rmvpe/.test(l)), false);
+ // A group the engine does not have.
+ const no = capture();
+ assert.equal(await main({ engine: "seed-vc", with: ["f1"], dryRun: true, home, log: no.log }), 2);
+ assert.match(no.lines[0], /seed-vc has no optional group "f1" — --with is one of f0/);
+ assert.equal(await main({ engine: "openvoice", with: ["f0"], dryRun: true, home, log: no.log }), 2);
+ // --dry-run --with f0 lists them as fetched.
+ const dry = capture();
+ assert.equal(await main({ engine: "seed-vc", with: ["f0"], dryRun: true, home, log: dry.log }), 0);
+ assert.ok(dry.lines.some((l) => /with f0 — the f0-conditioned/.test(l)));
+});
+
test("an engine is required, by its id", async () => {
const c = capture();
assert.equal(await main({ log: c.log }), 2);
diff --git a/common/bin/voice-setup.ts b/common/bin/voice-setup.ts
@@ -15,6 +15,11 @@
// code/ Plachtaa/seed-vc at a pinned commit
// … the DiT (440 MB), whisper-small (967
// MB), BigVGAN v2 (449 MB), CAM++ (28 MB)
+// … (--with f0) OPTIONAL: the f0-conditioned 44.1 kHz
+// DiT (821 MB), its BigVGAN (489 MB) and
+// RMVPE (181 MB) — what `pitch: source |
+// contour` runs on; an install without
+// them converts at the target's pitch
// install.json what was installed, and when
// rnnoise has nothing to install (ffmpeg, and the model in the repo): setup
// says whether ffmpeg has `arnndn`.
@@ -31,7 +36,9 @@
//
// `--check` installs nothing: it lists what is missing (the venv, the package
// importing, the checkout at its commit, each file at its size) and exits 1
-// when anything is.
+// when anything is. An optional group that is not there is SAID (with the
+// command that fetches it) and does not fail the check, unless it was asked
+// for (`--check --with f0`).
//
// Scratch (pip's build dirs) goes to `<install dir>/.tmp`, never the OS temp
// dir: it may be a small RAM tmpfs.
@@ -48,6 +55,7 @@ import {
voiceInstallDir,
voiceVenvPython,
type VoiceEngine,
+ type VoiceFileGroup,
} from "../lib/voiceApps";
import { VOICE_CODE_MARKER, voiceInstallState } from "../lib/voiceInstall";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome } from "../lib/voiceSettings";
@@ -58,6 +66,8 @@ import { adoptModelFile, downloadModelFile, verifyModelFile } from "./tts-setup"
export type VoiceSetupOptions = {
engine?: string;
from?: string;
+ // Optional file groups to install too (seed-vc: "f0").
+ with?: string[];
python?: string;
check?: boolean;
dryRun?: boolean;
@@ -76,8 +86,22 @@ function mb(n: number): string {
return n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)} MB` : `${(n / 1000).toFixed(1)} kB`;
}
-/** What setup fetches for an engine, in words: one line each, then the total. */
-export function voiceSetupPlan(engine: VoiceEngine): string[] {
+/** The engine's optional groups by these ids, or the ids it does not have. */
+export function pickVoiceGroups(engine: VoiceEngine, ids: readonly string[]): { groups: VoiceFileGroup[]; unknown: string[]; known: string[] } {
+ const all = engine.setup.kind === "python-venv" ? engine.setup.optional ?? [] : [];
+ return {
+ groups: all.filter((g) => ids.includes(g.id)),
+ unknown: ids.filter((id) => !all.some((g) => g.id === id)),
+ known: all.map((g) => g.id),
+ };
+}
+
+/**
+ * What setup fetches for an engine, in words: one line each, then the total.
+ * The optional groups asked for (`withGroups`) are fetched and counted; the
+ * others are listed after, as what `--with <id>` would add.
+ */
+export function voiceSetupPlan(engine: VoiceEngine, withGroups: readonly string[] = []): string[] {
const s = engine.setup;
if (s.kind === "bundled") return [`${engine.label}: nothing to download (${s.hint})`];
const lines: string[] = [];
@@ -90,7 +114,20 @@ export function voiceSetupPlan(engine: VoiceEngine): string[] {
lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
total += f.bytes;
}
+ const optional = s.kind === "python-venv" ? s.optional ?? [] : [];
+ for (const g of optional.filter((x) => withGroups.includes(x.id))) {
+ lines.push(` with ${g.id} — ${g.label}:`);
+ for (const f of g.files) {
+ lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
+ total += f.bytes;
+ }
+ }
lines.push(` files: ${mb(total)}${s.kind === "python-venv" ? " (plus the packages: torch's CPU wheels are ~200 MB)" : ""}`);
+ for (const g of optional.filter((x) => !withGroups.includes(x.id))) {
+ lines.push(` optional, not fetched without \`--with ${g.id}\` — ${g.label}:`);
+ for (const f of g.files) lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
+ lines.push(` ${mb(g.files.reduce((n, f) => n + f.bytes, 0))} more`);
+ }
return lines;
}
@@ -138,24 +175,43 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
}
const dir = voiceInstallDir(home, engine);
+ const picked = pickVoiceGroups(engine, opts.with ?? []);
+ if (picked.unknown.length) {
+ log(`voice setup: ${engine.id} has no optional group "${picked.unknown.join('", "')}" — ${picked.known.length ? `--with is one of ${picked.known.join(", ")}` : "it has none"}`);
+ return 2;
+ }
+ const withIds = picked.groups.map((g) => g.id);
if (opts.check) {
const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir });
const missing = [...state.missing];
if (setup.kind === "python-venv" && !missing.some((m) => m.startsWith("the python venv"))) {
if ((await importsAt(voiceVenvPython(dir), setup.importName)) === null) missing.push(`${setup.importName} does not import in the venv`);
}
+ // A group asked for is part of the check; one not asked for is only said.
+ for (const g of state.optional) if (withIds.includes(g.id)) missing.push(...g.missing);
+ const said = () => {
+ for (const g of state.optional) {
+ if (g.installed) log(` with ${g.id} (${g.label}): installed`);
+ else if (!withIds.includes(g.id)) {
+ log(` optional ${g.id} (${g.label}): not installed — \`archilyzer voice setup --engine ${engine.id} --with ${g.id}\` fetches it`);
+ }
+ }
+ };
+ const withArg = withIds.map((id) => ` --with ${id}`).join("");
if (missing.length === 0) {
log(`${engine.label}: installed at ${dir}`);
+ said();
return 0;
}
log(`${engine.label} at ${dir} — missing:`);
for (const m of missing) log(` - ${m}`);
- log(`Run \`archilyzer voice setup --engine ${engine.id}\` to install it.`);
+ said();
+ log(`Run \`archilyzer voice setup --engine ${engine.id}${withArg}\` to install it.`);
return 1;
}
log(`${opts.dryRun ? "Would install" : "Installing"} ${engine.label} (${engine.license}) at ${dir}:`);
- for (const l of voiceSetupPlan(engine)) log(l);
+ for (const l of voiceSetupPlan(engine, withIds)) log(l);
if (opts.dryRun) return 0;
const scratch = path.join(dir, ".tmp");
@@ -215,7 +271,7 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
}
}
// 4. The files, one at a time.
- for (const spec of setup.files) {
+ for (const spec of [...setup.files, ...picked.groups.flatMap((g) => g.files)]) {
const target = path.join(dir, spec.name);
await mkdir(path.dirname(target), { recursive: true });
if ((await verifyModelFile(target, spec)) === "ok") {
@@ -238,10 +294,14 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
return 1;
}
const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir });
- if (!state.installed) {
- log(`voice setup: still missing ${state.missing.join("; ")}`);
+ const stillMissing = [...state.missing, ...state.optional.filter((g) => withIds.includes(g.id)).flatMap((g) => g.missing)];
+ if (stillMissing.length) {
+ log(`voice setup: still missing ${stillMissing.join("; ")}`);
return 1;
}
+ // What is there now, whichever run fetched it.
+ const groupsThere = picked.known.filter((id) => state.optional.find((g) => g.id === id)?.installed);
+ const optionalGroups = pickVoiceGroups(engine, groupsThere).groups;
await writeJsonAtomic(
path.join(dir, "install.json"),
{
@@ -250,10 +310,13 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
license: engine.license,
...(setup.kind === "python-venv" ? { packages: setup.packages, code: setup.code } : {}),
files: setup.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })),
+ ...(optionalGroups.length
+ ? { optional: optionalGroups.map((g) => ({ id: g.id, files: g.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })) })) }
+ : {}),
installedAt: new Date().toISOString(),
},
{ indent: 2 },
);
- log(`${engine.label} installed: ${dir}`);
+ log(`${engine.label} installed: ${dir}${optionalGroups.length ? ` (with ${optionalGroups.map((g) => g.id).join(", ")})` : ""}`);
return 0;
}
diff --git a/common/controller/voiceFile.test.ts b/common/controller/voiceFile.test.ts
@@ -50,7 +50,8 @@ if (kind === "openvoice" || kind === "seed-vc") {
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 }));
+ const f0 = argv.includes("--pitch") ? { f0: { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 } } : {};
+ console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0, ...f0 }));
process.exit(0);
}
const r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...argv], { stdio: "inherit" });
@@ -83,7 +84,7 @@ const {
} = await import("./voiceFile");
const { getPaths } = await import("../lib/paths");
const { DEFAULT_VOICE_SETTINGS } = await import("../lib/voiceSettings");
-const { OPENVOICE_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps");
+const { OPENVOICE_FILES, SEEDVC_F0_FILES, SEEDVC_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps");
const { VOICE_CODE_MARKER } = await import("../lib/voiceInstall");
const paths = getPaths();
@@ -122,7 +123,7 @@ async function engineRuns(): Promise<string[][]> {
test("the body keys are umtool's contract", () => {
assert.deepEqual([...VOICE_ENHANCE_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts"]);
- assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target"]);
+ assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target", "pitch", "semitones"]);
});
test("the body's shape is judged before the disk", () => {
@@ -191,6 +192,74 @@ test("an engine is the op's own, and its params are checked", () => {
}
});
+test("a pitch is the engine's to follow: openvoice refuses one, seed-vc takes source and contour", () => {
+ const v = DEFAULT_VOICE_SETTINGS;
+ const ask = (b: Record<string, unknown>, voice = v) => {
+ const p = parseVoiceBody("convert", { file: "/a.wav", out: "/b.wav", ...b });
+ assert.ok(p.ok, !p.ok ? p.error : "");
+ return resolveVoiceRequest("convert", p.ok ? p.value : ({} as never), voice);
+ };
+ const refused = (b: Record<string, unknown>, re: RegExp, voice = v) => {
+ const r = ask(b, voice);
+ assert.ok(!r.ok, JSON.stringify(b));
+ if (!r.ok) {
+ assert.match(r.error, re);
+ // One sentence.
+ assert.equal(r.error.includes("\n"), false);
+ }
+ };
+ // Nothing asked: the target's own pitch, on every engine.
+ for (const engine of ["openvoice", "seed-vc"]) {
+ const r = ask({ engine });
+ assert.ok(r.ok);
+ if (r.ok) assert.deepEqual(r.value.pitch, { pitch: "target", semitones: 0 });
+ }
+ // An enhance has no pitch at all.
+ const en = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "rnnoise" }, v);
+ assert.ok(en.ok && en.value.pitch === undefined);
+ // OpenVoice has one pitch.
+ refused({ engine: "openvoice", pitch: "source" }, /^OpenVoice v2 \(tone-colour converter\) has no pitch control — .* "pitch" and "semitones" are seed-vc's/);
+ refused({ engine: "openvoice", semitones: 2 }, /has no pitch control/);
+ assert.ok(ask({ engine: "openvoice", pitch: "target", semitones: 0 }).ok);
+ // The values.
+ refused({ engine: "seed-vc", pitch: "up" }, /"pitch" is one of target, source, contour \(got "up"\)/);
+ refused({ engine: "seed-vc", pitch: "source", semitones: 13 }, /"semitones" is a number from -12 to 12 \(got 13\)/);
+ refused({ engine: "seed-vc", pitch: "source", semitones: "2" }, /"semitones" is a number from -12 to 12/);
+ // Semitones move a FOLLOWED pitch.
+ refused({ engine: "seed-vc", semitones: 2 }, /"semitones" moves a followed pitch — give "pitch": "source" or "contour"/);
+ refused({ engine: "seed-vc", pitch: "target", semitones: -1 }, /moves a followed pitch/);
+ const src = ask({ engine: "seed-vc", pitch: "source" });
+ assert.ok(src.ok);
+ if (src.ok) assert.deepEqual(src.value.pitch, { pitch: "source", semitones: 0 });
+ const con = ask({ engine: "seed-vc", pitch: "contour", semitones: -1.5 });
+ assert.ok(con.ok);
+ if (con.ok) assert.deepEqual(con.value.pitch, { pitch: "contour", semitones: -1.5 });
+ // settings.voice.convert's defaults: for the engine that can follow, and
+ // never a refusal for the one that cannot.
+ const follow = { ...v, convert: { ...v.convert, pitch: "contour" as const, semitones: 2 } };
+ const d = ask({ engine: "seed-vc" }, follow);
+ assert.ok(d.ok);
+ if (d.ok) assert.deepEqual(d.value.pitch, { pitch: "contour", semitones: 2 });
+ // A request naming its own followed pitch and no semitones takes the default semitones; 0 says none.
+ const named = ask({ engine: "seed-vc", pitch: "source" }, follow);
+ assert.ok(named.ok);
+ if (named.ok) assert.deepEqual(named.value.pitch, { pitch: "source", semitones: 2 });
+ const zero = ask({ engine: "seed-vc", pitch: "source", semitones: 0 }, follow);
+ assert.ok(zero.ok);
+ if (zero.ok) assert.deepEqual(zero.value.pitch, { pitch: "source", semitones: 0 });
+ const over = ask({ engine: "seed-vc", pitch: "target" }, follow);
+ assert.ok(over.ok);
+ if (over.ok) assert.deepEqual(over.value.pitch, { pitch: "target", semitones: 0 });
+ const ov = ask({ engine: "openvoice" }, follow);
+ assert.ok(ov.ok);
+ if (ov.ok) assert.deepEqual(ov.value.pitch, { pitch: "target", semitones: 0 });
+ // The argv: nothing new for the target's pitch.
+ const seed = getVoiceEngine("seed-vc")!;
+ const base = { input: "/a.wav", output: "/b.wav", installDir: "/i", params: {}, threads: 4, targetRef: "/r.wav", bins: { ffmpegBin: "ffmpeg", voiceModelsDir: "/m" } };
+ assert.equal(seed.build({ ...base, pitch: { pitch: "target", semitones: 0 } }).includes("--pitch"), false);
+ assert.deepEqual(seed.build({ ...base, pitch: { pitch: "contour", semitones: 2 } }).slice(-4), ["--pitch", "contour", "--semitones", "2"]);
+});
+
// --- the disk checks -----------------------------------------------------------
test("the disk checks: the input, the out, the install", { skip: SKIP }, async () => {
@@ -353,6 +422,68 @@ test("an engine that fails fails the job with its words", { skip: SKIP }, async
assert.match(r.log, /the voice engine exited 3: voice: engine exploded/);
});
+// A seed-vc install, faked to the pinned sizes with sparse files; `f0` adds the
+// optional group a followed pitch runs on.
+async function fakeSeedVcInstall(f0: boolean): Promise<string> {
+ const dir = path.join(HOME, "seed-vc");
+ await mkdir(path.join(dir, "venv", "bin"), { recursive: true });
+ await writeFile(path.join(dir, "venv", "bin", "python"), "");
+ const seed = getVoiceEngine("seed-vc")!;
+ if (seed.setup.kind !== "python-venv") throw new Error("seed-vc is a venv engine");
+ await mkdir(voiceCodeDir(dir), { recursive: true });
+ await writeFile(path.join(voiceCodeDir(dir), VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`);
+ for (const f of [...SEEDVC_FILES, ...(f0 ? SEEDVC_F0_FILES : [])]) {
+ const p = path.join(dir, f.name);
+ await mkdir(path.dirname(p), { recursive: true });
+ const fh = await open(p, "w");
+ await fh.truncate(f.bytes);
+ await fh.close();
+ }
+ return dir;
+}
+
+test("a followed pitch needs seed-vc's f0 model: refused naming the setup command, then run with its own estimate", { skip: SKIP }, async () => {
+ await fakeSeedVcInstall(false);
+ const askTts = async (body: Record<string, unknown>) => {
+ await tone(String(body.out), 2);
+ return { ok: true as const, jobId: "tts-job-2", stream: new ReadableStream<string>(), done: Promise.resolve({ status: "done" as const, jobId: "tts-job-2" }) };
+ };
+ const take = path.join(OUTSIDE, "p-take.wav");
+ await tone(take, 1);
+ const before = (await engineRuns()).length;
+ // An install without the f0 files still converts at the target's pitch…
+ const plain = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-plain.wav"), engine: "seed-vc", voice: "espeak-ng:en-us" }, { askTts });
+ assert.equal(plain.status, "done", plain.log ?? plain.error);
+ assert.equal(plain.result.pitch, "target");
+ assert.equal("semitones" in plain.result, false);
+ assert.equal("f0" in plain.result, false);
+ assert.match(plain.log!, /estimate 3500 MB/);
+ const plainRun = (await engineRuns()).at(-1)!;
+ assert.equal(plainRun.includes("--pitch"), false);
+ // …and refuses a followed one, in one sentence, before any job.
+ const runs = (await engineRuns()).length;
+ assert.equal(runs, before + 1);
+ const refused = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-src.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "source" }, { askTts });
+ assert.match(
+ refused.error!,
+ /^pitch "source" needs Seed-VC \(v1, 22 kHz speech\)'s f0 model, which is not installed \(.*voice-home\/seed-vc: missing DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2\.pth; .*rmvpe\.pt; .*\) — run `archilyzer voice setup --engine seed-vc --with f0`$/,
+ );
+ assert.equal(refused.error!.includes("\n"), false);
+ assert.equal((await engineRuns()).length, runs);
+ // With them: the wrapper is told, the f0 run's estimate is declared, the result says what was done.
+ await fakeSeedVcInstall(true);
+ const r = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-con.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "contour", semitones: 2 }, { askTts });
+ assert.equal(r.status, "done", r.log ?? r.error);
+ const run = (await engineRuns()).at(-1)!;
+ assert.equal(run[run.indexOf("--pitch") + 1], "contour");
+ assert.equal(run[run.indexOf("--semitones") + 1], "2");
+ assert.match(r.log!, /Convert to espeak-ng:en-us \(pitch: contour \+2 st\)/);
+ assert.match(r.log!, new RegExp(`estimate ${getVoiceEngine("seed-vc")!.pitch!.defaultEstimateMB} MB`));
+ assert.equal(r.result.pitch, "contour");
+ assert.equal(r.result.semitones, 2);
+ assert.deepEqual(r.result.f0, { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 });
+});
+
test("a cancelled run stops the engine's whole process group", async () => {
const slow = path.join(BIN, "slow-engine");
await writeFile(slow, `#!/bin/sh\nsleep 30 &\nwait\n`);
diff --git a/common/controller/voiceFile.ts b/common/controller/voiceFile.ts
@@ -8,7 +8,13 @@
// THE BODY is umtool's contract (umtool/lib/report/postNarrationCli.mjs
// deriveTake): `{file, out, engine?, params?, parts?}`, and for convert
// `voice?` — the stock target (`target` is the same key's other name; `path`
-// is `file`'s). `file` is an absolute path to the recording (any format ffmpeg
+// is `file`'s) — and `pitch?` / `semitones?`: the pitch the conversion lands on
+// (lib/voiceApps.ts VoicePitch: `target`, the stock voice's own; `source`, the
+// read's; `contour`, the read's rises and falls at the stock voice's register;
+// `semitones` moves a followed one; defaults settings.voice.convert). An engine
+// with one pitch (openvoice) refuses another; a followed pitch whose model is
+// not installed (seed-vc's optional `f0` files) is refused naming the setup
+// command. `file` is an absolute path to the recording (any format ffmpeg
// reads, at most VOICE_MAX_SECONDS); `out` an absolute `.wav` path the result
// is written to — never inside the corpus, its directory existing; `engine`
// one of the op's engines (default settings.voice.<op>.engine); `params` the
@@ -37,7 +43,9 @@
// THE RESULT is logged as ONE line starting with VOICE_RESULT_MARKER (the
// marker umtool's askEditorOp reads): `{op, engine, wav, seconds, samples,
// sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?,
-// target?, voice?, synthetic, disclosure?}`. `wav` is `out`, 48 kHz mono 16-bit, as
+// target?, voice?, pitch?, semitones?, f0?, synthetic, disclosure?}` (`pitch`
+// on every conversion; `f0` — {targetHz, sourceHz, shiftSemitones}, the medians
+// the tracker heard and the whole move — on a followed one). `wav` is `out`, 48 kHz mono 16-bit, as
// long as the input to the sample.
//
// WHAT IT TOUCHES: reads `file` and each part (anywhere); writes `out`, each
@@ -55,9 +63,11 @@ import type { StorageLocation } from "../lib/storageLocations";
import {
NO_CLONING,
VOICE_REFERENCE_TEXT,
+ describeVoicePitch,
getVoiceEngine,
parseStockTarget,
resolveVoiceParams,
+ resolveVoicePitch,
stockTargetPaths,
voiceConvertDisclosure,
voiceEngineIds,
@@ -65,8 +75,9 @@ import {
type StockTarget,
type VoiceEngine,
type VoiceOp,
+ type VoicePitchChoice,
} from "../lib/voiceApps";
-import { voiceInstallState } from "../lib/voiceInstall";
+import { voiceGroupState, voiceInstallState } from "../lib/voiceInstall";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, type VoiceSettings } from "../lib/voiceSettings";
import { getTtsEngine } from "../lib/ttsApps";
import { ttsInstallState } from "../lib/ttsInstall";
@@ -86,7 +97,7 @@ export const VOICE_RESULT_MARKER = "@@voice-result ";
// The bodies the routes accept; anything else is a 400.
export const VOICE_ENHANCE_BODY_KEYS = ["file", "path", "out", "engine", "params", "parts"] as const;
-export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target"] as const;
+export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target", "pitch", "semitones"] as const;
// The longest recording one op takes (a post read in full runs ~25 minutes).
export const VOICE_MAX_SECONDS = 1800;
@@ -103,6 +114,9 @@ export type VoiceFileBody = {
params?: unknown;
parts?: VoicePart[];
target?: string;
+ // Convert: as given, judged against the engine by resolveVoiceRequest.
+ pitch?: unknown;
+ semitones?: unknown;
};
function absWav(key: string, v: unknown, wav: boolean): Check<string> {
@@ -164,6 +178,8 @@ export function parseVoiceBody(op: VoiceOp, body: Record<string, unknown>): Chec
...(body.params !== undefined ? { params: body.params } : {}),
...(parts ? { parts } : {}),
...(target !== undefined ? { target } : {}),
+ ...(op === "convert" && body.pitch !== undefined ? { pitch: body.pitch } : {}),
+ ...(op === "convert" && body.semitones !== undefined ? { semitones: body.semitones } : {}),
},
};
}
@@ -178,6 +194,8 @@ export type VoiceRequest = {
out: string;
parts: VoicePart[];
target?: StockTarget;
+ // Convert: the pitch it lands on (target = the stock voice's own).
+ pitch?: VoicePitchChoice;
};
// The body plus settings.voice, resolved against the registry. Pure.
@@ -194,14 +212,27 @@ export function resolveVoiceRequest(
const params = resolveVoiceParams(engine, body.params);
if (!params.ok) return params;
let target: StockTarget | undefined;
+ let pitch: VoicePitchChoice | undefined;
if (op === "convert") {
const t = parseStockTarget(body.target ?? voice.convert.target);
if (!t.ok) return t;
target = t.value;
+ const p = resolveVoicePitch(engine, { pitch: body.pitch, semitones: body.semitones }, voice.convert);
+ if (!p.ok) return p;
+ pitch = p.value;
}
return {
ok: true,
- value: { op, engine, params: params.value, file: body.file, out: body.out, parts: body.parts ?? [], ...(target ? { target } : {}) },
+ value: {
+ op,
+ engine,
+ params: params.value,
+ file: body.file,
+ out: body.out,
+ parts: body.parts ?? [],
+ ...(target ? { target } : {}),
+ ...(pitch ? { pitch } : {}),
+ },
};
}
@@ -293,6 +324,18 @@ export async function checkVoiceRequest(req: VoiceRequest, ctx: VoiceFileContext
(req.engine.setup.kind === "bundled" ? req.engine.setup.hint : `run \`archilyzer voice setup --engine ${req.engine.id}\``),
};
}
+ // A followed pitch runs on the engine's optional model.
+ if (req.pitch && req.pitch.pitch !== "target" && req.engine.pitch) {
+ const group = voiceGroupState(req.engine, req.engine.pitch.group, { home: ctx.home });
+ if (group && !group.installed) {
+ return {
+ ok: false,
+ error:
+ `pitch "${req.pitch.pitch}" needs ${req.engine.label}'s ${group.id} model, which is not installed (${install.dir}: missing ${group.missing.join("; ")}) — ` +
+ `run \`archilyzer voice setup --engine ${req.engine.id} --with ${group.id}\``,
+ };
+ }
+ }
if (req.target) {
const tts = ctx.tts ?? DEFAULT_TTS_SETTINGS;
const ref = await stockReferenceState(req.target, ctx.home, tts);
@@ -368,6 +411,8 @@ export type EngineRunResult = {
sampleRate?: number;
engineMs?: number;
gainDb?: number;
+ // A followed pitch: the medians the tracker heard and the whole move applied.
+ f0?: { targetHz: number | null; sourceHz: number | null; shiftSemitones: number };
// The parts, when the run had more files (scripts/voice.mjs --more).
more?: { output: string; seconds: number; samples?: number; gainDb?: number }[];
};
@@ -482,12 +527,17 @@ export type VoiceResult = {
// shape a umtool take records).
target?: string;
voice?: string;
+ // Convert: the pitch it landed on, and for a followed one what was heard.
+ pitch?: VoicePitchChoice["pitch"];
+ semitones?: number;
+ f0?: EngineRunResult["f0"];
synthetic: boolean;
disclosure?: string;
};
function describe(req: VoiceRequest, seconds: number): string {
- const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}`;
+ const followed = describeVoicePitch(req.pitch);
+ const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}${followed ? ` (pitch: ${followed})` : ""}`;
const parts = req.parts.length ? ` and its ${req.parts.length} part(s)` : "";
return `${what}: ${Math.round(seconds * 10) / 10} s of ${req.file}${parts} with ${req.engine.id}`;
}
@@ -520,7 +570,11 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
if (!checked.ok) return checked;
const req = checked.value;
const installDir = voiceInstallDir(home, req.engine);
- const estimateMB = voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB;
+ // A followed pitch is another model's run, with its own estimate.
+ const follows = req.pitch && req.pitch.pitch !== "target" ? req.engine.pitch : undefined;
+ const estimateMB = follows
+ ? (voice.heavyEstimateMB[follows.estimateKey] ?? follows.defaultEstimateMB)
+ : (voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB);
const asked = Date.now();
return runManagedFunction({
kind: VOICE_JOB_KIND[op],
@@ -558,6 +612,7 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
threads: voice.threads,
...(targetRef ? { targetRef } : {}),
...(targetSe ? { targetSe } : {}),
+ ...(req.pitch ? { pitch: req.pitch } : {}),
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)…`);
@@ -582,6 +637,8 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
params: req.params,
...(parts.length ? { parts } : {}),
...(req.target ? { target: req.target.id, voice: req.target.voice, disclosure: voiceConvertDisclosure(req.engine, req.target) } : {}),
+ ...(req.pitch ? { pitch: req.pitch.pitch, ...(req.pitch.pitch !== "target" ? { semitones: req.pitch.semitones } : {}) } : {}),
+ ...(follows && whole.f0 ? { f0: whole.f0 } : {}),
synthetic: op === "convert",
};
onLog(`${VOICE_RESULT_MARKER}${JSON.stringify(result)}`);
diff --git a/common/lib/voiceApps.ts b/common/lib/voiceApps.ts
@@ -53,8 +53,19 @@ export type VoiceSetup =
importName: string;
code: { repo: string; commit: string };
files: readonly VoiceModelFile[];
+ // Files the engine runs without, in named groups: fetched only when
+ // setup is asked for the group (`--with <id>`), never counted against
+ // "installed" — an install made before a group existed keeps working.
+ optional?: readonly VoiceFileGroup[];
};
+export type VoiceFileGroup = {
+ id: string;
+ // What the group is for, as setup says it.
+ label: string;
+ files: readonly VoiceModelFile[];
+};
+
// A downloaded file, verified by size and sha256 like a TTS model file. `name`
// may hold a subdirectory (`whisper-small/model.safetensors`).
export type VoiceModelFile = TtsModelFile & { executable?: boolean };
@@ -63,6 +74,22 @@ export type VoiceParamSpec =
| { kind: "number"; min: number; max: number; default: number; doc: string }
| { kind: "boolean"; default: boolean; doc: string };
+// THE PITCH A CONVERSION LANDS ON (operator, 11 Nov: both converters threw the
+// read's intonation away — inputs with a median f0 of 128 to 237 Hz all came
+// out at 196-199 Hz, a 152-321 Hz range as 165-240 Hz).
+// target the stock voice's own pitch: the converter is given none of the
+// input's (every engine; what there was before).
+// source the input's f0 as it was read: raise the voice and the output
+// rises with it.
+// contour the input's f0 curve moved as a whole so its median sits on the
+// stock voice's: every rise and fall kept, the register the target's.
+// `semitones` then moves a followed curve (source, contour) up or down.
+export type VoicePitch = "target" | "source" | "contour";
+export const VOICE_PITCH_MODES: readonly VoicePitch[] = ["target", "source", "contour"];
+export const VOICE_SEMITONES_MAX = 12;
+export type VoicePitchChoice = { pitch: VoicePitch; semitones: number };
+export const DEFAULT_VOICE_PITCH: VoicePitchChoice = { pitch: "target", semitones: 0 };
+
export type VoiceBuildInput = {
input: string;
output: string;
@@ -74,6 +101,8 @@ export type VoiceBuildInput = {
// The stock target's reference clip and openvoice's embedding cache (convert).
targetRef?: string;
targetSe?: string;
+ // A followed pitch (an engine with `pitch`); absent = target.
+ pitch?: VoicePitchChoice;
bins: { ffmpegBin: string; voiceModelsDir: string };
};
@@ -93,6 +122,11 @@ export type VoiceEngine = {
// plus swapped — rnnoise 112 MB, deepfilternet 111 MB, openvoice 1625 MB,
// seed-vc 2865 MB; no GPU memory, they are CPU engines) plus a margin.
defaultEstimateMB: number;
+ // A convert engine that can FOLLOW the input's pitch (source, contour): the
+ // optional file group that mode runs on, and the memory ITS run declares
+ // (another, bigger model) — kept in settings.voice.heavyEstimateMB under
+ // `estimateKey`. An engine without it has one pitch: the target's.
+ pitch?: { group: string; estimateKey: string; defaultEstimateMB: number };
// Args to paths.voiceBin (scripts/voice.mjs).
build: (input: VoiceBuildInput) => string[];
};
@@ -232,6 +266,13 @@ const openvoice: VoiceEngine = {
],
};
+// The f0 model's run, declared to the heavy slot: its peak measured 2026-11-11
+// (RSS plus swap of the wrapper and python, sampled twice a second) — 3706 MB
+// over 6.9 s reads, 5781 MB over a 34 s one, whose first window is a full one
+// (30 s less the reference: the 44.1 kHz vocoder's activations grow with the
+// window, and no take makes a longer one) — plus a margin.
+const SEEDVC_F0_ESTIMATE_MB = 6500;
+
const SEEDVC_HF = "https://huggingface.co/Plachta/Seed-VC/resolve/257283f9f41585055e8f858fba4fd044e5caed6e";
const WHISPER_HF = "https://huggingface.co/openai/whisper-small/resolve/973afd24965f72e36ca33b3055d56a652f456b4d";
const BIGVGAN_HF = "https://huggingface.co/nvidia/bigvgan_v2_22khz_80band_256x/resolve/633ff708ed5b74903e86ff1298cf4a98e921c513";
@@ -288,6 +329,52 @@ export const SEEDVC_FILES: readonly VoiceModelFile[] = [
},
];
+// The f0-conditioned model (upstream's `inference.py --f0-condition`): a 44.1
+// kHz DiT, its 128-band BigVGAN, and RMVPE, the pitch tracker whose curve
+// conditions it. Optional (`voice setup --engine seed-vc --with f0`, 1.49 GB):
+// `pitch: source | contour` runs on these, `target` never touches them.
+const RMVPE_HF = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d";
+const BIGVGAN_44K_HF = "https://huggingface.co/nvidia/bigvgan_v2_44khz_128band_512x/resolve/95a9d1dcb12906c03edd938d77b9333d6ded7dfb";
+
+export const SEEDVC_F0_FILES: readonly VoiceModelFile[] = [
+ {
+ name: "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth",
+ url: `${SEEDVC_HF}/DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth`,
+ bytes: 820_865_494,
+ sha256: "42aef93ffe65857c840d270252fa040f7ba04514945ec460f3ac1ac2a96de684",
+ },
+ {
+ name: "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml",
+ url: `${SEEDVC_HF}/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml`,
+ bytes: 2_408,
+ sha256: "ff86f343b08c2def405f075022eeb10dafba23c4eda36d151010f4ca6d7a1a0a",
+ },
+ {
+ name: "rmvpe.pt",
+ url: `${RMVPE_HF}/rmvpe.pt`,
+ bytes: 181_184_272,
+ sha256: "6d62215f4306e3ca278246188607209f09af3dc77ed4232efdd069798c4ec193",
+ },
+ {
+ name: "bigvgan-44k/bigvgan_generator.pt",
+ url: `${BIGVGAN_44K_HF}/bigvgan_generator.pt`,
+ bytes: 489_041_291,
+ sha256: "d9fe7ec6bd0b44ed9d66973d5012d8181c1570b01e5c72df51973e241dccd357",
+ },
+ {
+ name: "bigvgan-44k/config.json",
+ url: `${BIGVGAN_44K_HF}/config.json`,
+ bytes: 1_403,
+ sha256: "65b7f487bfaf15256056a75f6667ef5f640214c981922a111927873705ea4ddb",
+ },
+];
+
+export const SEEDVC_F0_GROUP: VoiceFileGroup = {
+ id: "f0",
+ label: "the f0-conditioned 44.1 kHz model, for a conversion that follows the input's pitch (pitch: source | contour)",
+ files: SEEDVC_F0_FILES,
+};
+
// Seed-VC v1, its 22 kHz speech model (Whisper-small content features, a
// diffusion transformer, BigVGAN v2): zero-shot, the stronger timbre match,
// several times slower than OpenVoice on the CPU. GPL-3.0 code, run as a
@@ -312,6 +399,7 @@ const seedVc: VoiceEngine = {
importName: "transformers",
code: { repo: "https://github.com/Plachtaa/seed-vc", commit: "51383efd921027683c89e5348211d93ff12ac2a8" },
files: SEEDVC_FILES,
+ optional: [SEEDVC_F0_GROUP],
},
params: {
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)" },
@@ -319,12 +407,14 @@ const seedVc: VoiceEngine = {
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)" },
},
defaultEstimateMB: 3500,
+ pitch: { group: SEEDVC_F0_GROUP.id, estimateKey: "seed-vc-f0", defaultEstimateMB: SEEDVC_F0_ESTIMATE_MB },
build: (i) => [
...common("convert", "seed-vc", i),
"--python", voiceVenvPython(i.installDir),
"--code", voiceCodeDir(i.installDir),
"--install", i.installDir,
"--target-ref", i.targetRef ?? "",
+ ...(i.pitch && i.pitch.pitch !== "target" ? ["--pitch", i.pitch.pitch, "--semitones", String(i.pitch.semitones)] : []),
],
};
@@ -355,6 +445,58 @@ export function voiceInstallDir(home: string, engine: Pick<VoiceEngine, "id">):
type Check<T> = { ok: true; value: T } | { ok: false; error: string };
/**
+ * The pitch a conversion lands on: the request's `pitch` / `semitones` over the
+ * defaults (settings.voice.convert). An engine with one pitch refuses a request
+ * for another (the defaults are not a request: they are for the engines that
+ * can); `semitones` asked of the target's own pitch is refused, since nothing
+ * is followed to move. A request that names a followed `pitch` and no
+ * `semitones` takes the DEFAULT semitones (settings.voice.convert.semitones),
+ * whichever pitch the settings name — say `"semitones": 0` for none. Pure.
+ */
+export function resolveVoicePitch(
+ engine: Pick<VoiceEngine, "id" | "label" | "pitch">,
+ given: { pitch?: unknown; semitones?: unknown },
+ defaults: VoicePitchChoice = DEFAULT_VOICE_PITCH,
+): Check<VoicePitchChoice> {
+ if (given.pitch !== undefined && !VOICE_PITCH_MODES.includes(given.pitch as VoicePitch)) {
+ return { ok: false, error: `"pitch" is one of ${VOICE_PITCH_MODES.join(", ")} (got ${JSON.stringify(given.pitch)})` };
+ }
+ if (given.semitones !== undefined) {
+ const n = given.semitones;
+ if (typeof n !== "number" || !Number.isFinite(n) || Math.abs(n) > VOICE_SEMITONES_MAX) {
+ return { ok: false, error: `"semitones" is a number from -${VOICE_SEMITONES_MAX} to ${VOICE_SEMITONES_MAX} (got ${JSON.stringify(n)})` };
+ }
+ }
+ const askedPitch = given.pitch as VoicePitch | undefined;
+ const askedSemitones = given.semitones as number | undefined;
+ if (!engine.pitch) {
+ if ((askedPitch && askedPitch !== "target") || askedSemitones) {
+ const can = Object.values(VOICE_ENGINES).filter((e) => e.pitch).map((e) => e.id);
+ return {
+ ok: false,
+ error: `${engine.label} has no pitch control — it lands every read on the target's own pitch; "pitch" and "semitones" are ${can.join(", ")}'s (engine: "${can[0]}")`,
+ };
+ }
+ return { ok: true, value: { pitch: "target", semitones: 0 } };
+ }
+ const pitch = askedPitch ?? defaults.pitch;
+ if (pitch === "target") {
+ if (askedSemitones) {
+ return { ok: false, error: `"semitones" moves a followed pitch — give "pitch": "source" or "contour" with it (pitch is "target": the stock voice's own)` };
+ }
+ return { ok: true, value: { pitch, semitones: 0 } };
+ }
+ return { ok: true, value: { pitch, semitones: askedSemitones ?? defaults.semitones } };
+}
+
+/** How a result, a take or a page says a pitch choice: "contour +2 st", "source", "" for the target's own. */
+export function describeVoicePitch(p: Partial<VoicePitchChoice> | undefined): string {
+ if (!p?.pitch || p.pitch === "target") return "";
+ const n = p.semitones ?? 0;
+ return n ? `${p.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : p.pitch;
+}
+
+/**
* An engine's knobs from a body's `params`: each key one the engine has, each
* value of its kind and in its range; the rest from the defaults. Pure.
*/
@@ -445,8 +587,8 @@ export function voiceConvertDisclosure(engine: Pick<VoiceEngine, "label">, targe
}
// A client-safe view (no functions).
-export type VoiceEngineDescriptor = { id: string; op: VoiceOp; label: string; license: string; params: Record<string, VoiceParamSpec> };
+export type VoiceEngineDescriptor = { id: string; op: VoiceOp; label: string; license: string; params: Record<string, VoiceParamSpec>; pitch: boolean };
export function listVoiceEngines(): VoiceEngineDescriptor[] {
- return Object.values(VOICE_ENGINES).map((e) => ({ id: e.id, op: e.op, label: e.label, license: e.license, params: { ...e.params } }));
+ return Object.values(VOICE_ENGINES).map((e) => ({ id: e.id, op: e.op, label: e.label, license: e.license, params: { ...e.params }, pitch: Boolean(e.pitch) }));
}
diff --git a/common/lib/voiceInstall.ts b/common/lib/voiceInstall.ts
@@ -7,18 +7,51 @@
// the pinned checkout's marker, each file at its pinned size (an executable
// one executable); setup's `--check` goes further and imports the package and
// reads the checkout's commit. Read-only: never creates anything.
+//
+// An engine's OPTIONAL file groups (seed-vc's `f0`: the model a followed pitch
+// runs on) are reported beside, never counted: `installed` is the required
+// files alone, so an install made before a group existed is still installed.
import fs from "node:fs";
import path from "node:path";
-import { voiceCodeDir, voiceInstallDir, voiceVenvPython, type VoiceEngine } from "./voiceApps";
+import { voiceCodeDir, voiceInstallDir, voiceVenvPython, type VoiceEngine, type VoiceModelFile } from "./voiceApps";
export type VoiceInstallState = {
engine: string;
dir: string;
installed: boolean;
missing: string[];
+ // Each optional group: there whole, or what of it is missing.
+ optional: VoiceGroupState[];
};
+export type VoiceGroupState = { id: string; label: string; installed: boolean; missing: string[] };
+
+function missingFiles(dir: string, files: readonly VoiceModelFile[]): string[] {
+ const missing: string[] = [];
+ for (const f of files) {
+ const p = path.join(dir, f.name);
+ let st: fs.Stats | null = null;
+ try {
+ st = fs.statSync(p);
+ } catch {
+ st = null;
+ }
+ if (!st) missing.push(f.name);
+ else if (st.size !== f.bytes) missing.push(`${f.name} (${st.size} bytes, expected ${f.bytes})`);
+ else if (f.executable && (st.mode & 0o111) === 0) missing.push(`${f.name} (not executable)`);
+ }
+ return missing;
+}
+
+/** One optional group of an engine's install, or undefined when the engine has none by that id. */
+export function voiceGroupState(engine: VoiceEngine, group: string, opts: { home: string }): VoiceGroupState | undefined {
+ const g = engine.setup.kind === "python-venv" ? engine.setup.optional?.find((x) => x.id === group) : undefined;
+ if (!g) return undefined;
+ const missing = missingFiles(voiceInstallDir(opts.home, engine), g.files);
+ return { id: g.id, label: g.label, installed: missing.length === 0, missing };
+}
+
// The file a finished checkout leaves: the commit it is at.
export const VOICE_CODE_MARKER = ".archilyzer-commit";
@@ -30,7 +63,7 @@ export function voiceInstallState(
if (setup.kind === "bundled") {
const model = path.join(opts.voiceModelsDir, "sh.rnnn");
const ok = fs.existsSync(model);
- return { engine: engine.id, dir: opts.voiceModelsDir, installed: ok, missing: ok ? [] : [`${model} (shipped in the repo)`] };
+ return { engine: engine.id, dir: opts.voiceModelsDir, installed: ok, missing: ok ? [] : [`${model} (shipped in the repo)`], optional: [] };
}
const dir = voiceInstallDir(opts.home, engine);
const missing: string[] = [];
@@ -47,17 +80,7 @@ export function voiceInstallState(
missing.push(at ? `the checkout of ${setup.code.repo} is at ${at.slice(0, 10)}, pinned ${setup.code.commit.slice(0, 10)}` : `the checkout of ${setup.code.repo} (${voiceCodeDir(dir)})`);
}
}
- for (const f of setup.files) {
- const p = path.join(dir, f.name);
- let st: fs.Stats | null = null;
- try {
- st = fs.statSync(p);
- } catch {
- st = null;
- }
- if (!st) missing.push(f.name);
- else if (st.size !== f.bytes) missing.push(`${f.name} (${st.size} bytes, expected ${f.bytes})`);
- else if (f.executable && (st.mode & 0o111) === 0) missing.push(`${f.name} (not executable)`);
- }
- return { engine: engine.id, dir, installed: missing.length === 0, missing };
+ missing.push(...missingFiles(dir, setup.files));
+ const optional = (setup.kind === "python-venv" ? setup.optional ?? [] : []).map((g) => voiceGroupState(engine, g.id, opts)!);
+ return { engine: engine.id, dir, installed: missing.length === 0, missing, optional };
}
diff --git a/common/lib/voiceSettings.test.ts b/common/lib/voiceSettings.test.ts
@@ -1,7 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, sanitizeVoice } from "./voiceSettings";
-import { NO_CLONING, VOICE_ENGINES, listVoiceEngines, parseStockTarget, resolveVoiceParams, voiceEngineIds } from "./voiceApps";
+import { NO_CLONING, VOICE_ENGINES, describeVoicePitch, listVoiceEngines, parseStockTarget, resolveVoiceParams, voiceEngineIds } from "./voiceApps";
// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/voiceSettings.test.ts
@@ -25,7 +25,16 @@ test("settings.voice: defaults, and every field falls back rather than throws",
assert.equal(s.heavyEstimateMB["seed-vc"], 4200);
assert.equal(s.heavyEstimateMB.openvoice, 0);
assert.equal("nope" in s.heavyEstimateMB, false);
- assert.deepEqual(Object.keys(s.heavyEstimateMB).sort(), Object.keys(VOICE_ENGINES).sort());
+ // Every engine, and the f0 run of the one that can follow a pitch.
+ assert.deepEqual(Object.keys(s.heavyEstimateMB).sort(), [...Object.keys(VOICE_ENGINES), "seed-vc-f0"].sort());
+ assert.equal(s.heavyEstimateMB["seed-vc-f0"], VOICE_ENGINES["seed-vc"].pitch!.defaultEstimateMB);
+ assert.equal(sanitizeVoice({ heavyEstimateMB: { "seed-vc-f0": 5000 } }).heavyEstimateMB["seed-vc-f0"], 5000);
+ // The pitch a conversion lands on: the target's own unless said, the semitones clamped.
+ assert.deepEqual([s.convert.pitch, s.convert.semitones], ["target", 0]);
+ const p = sanitizeVoice({ convert: { pitch: "contour", semitones: 40 } }).convert;
+ assert.deepEqual([p.pitch, p.semitones], ["contour", 12]);
+ const q = sanitizeVoice({ convert: { pitch: "higher", semitones: "2" } }).convert;
+ assert.deepEqual([q.pitch, q.semitones], ["target", 0]);
const ok = sanitizeVoice({ home: "~/voice", convert: { engine: "seed-vc", target: "kokoro:bm_george" }, enhance: { engine: "rnnoise" } });
assert.equal(ok.convert.engine, "seed-vc");
assert.equal(ok.convert.target, "kokoro:bm_george");
@@ -62,7 +71,24 @@ test("the registry: two engines per op, every knob has a default in range", () =
}
assert.ok(e.defaultEstimateMB > 0, e.id);
if (e.setup.kind !== "bundled") for (const f of e.setup.files) assert.match(f.sha256, /^[0-9a-f]{64}$/, f.name);
+ // An optional group: pinned by revision, size and sha256 like the rest, and no name of the required set.
+ if (e.setup.kind === "python-venv") {
+ const required = new Set(e.setup.files.map((f) => f.name));
+ for (const g of e.setup.optional ?? []) {
+ for (const f of g.files) {
+ assert.match(f.sha256, /^[0-9a-f]{64}$/, f.name);
+ assert.match(f.url, /\/resolve\/[0-9a-f]{40}\//, f.name);
+ assert.ok(f.bytes > 0 && !required.has(f.name), f.name);
+ }
+ }
+ if (e.pitch) assert.ok(e.setup.optional?.some((g) => g.id === e.pitch!.group), e.id);
+ }
+ assert.equal(Boolean(e.pitch), e.id === "seed-vc", e.id);
}
+ assert.equal(describeVoicePitch({ pitch: "target", semitones: 0 }), "");
+ assert.equal(describeVoicePitch({ pitch: "source", semitones: 0 }), "source");
+ assert.equal(describeVoicePitch({ pitch: "contour", semitones: 2 }), "contour +2 st");
+ assert.equal(describeVoicePitch({ pitch: "source", semitones: -1.5 }), "source −1.5 st");
assert.equal(listVoiceEngines().length, 4);
assert.equal(resolveVoiceParams(VOICE_ENGINES.rnnoise, []).ok, false);
});
diff --git a/common/lib/voiceSettings.ts b/common/lib/voiceSettings.ts
@@ -14,13 +14,17 @@ import {
DEFAULT_VOICE_ENGINE,
DEFAULT_VOICE_TARGET,
VOICE_ENGINES,
+ DEFAULT_VOICE_PITCH,
+ VOICE_PITCH_MODES,
+ VOICE_SEMITONES_MAX,
getVoiceEngine,
parseStockTarget,
type VoiceOp,
+ type VoicePitch,
} from "./voiceApps";
export type VoiceEnhanceSettings = { engine: string };
-export type VoiceConvertSettings = { engine: string; target: string };
+export type VoiceConvertSettings = { engine: string; target: string; pitch: VoicePitch; semitones: number };
export type VoiceSettings = {
home: string;
@@ -31,15 +35,20 @@ export type VoiceSettings = {
heavyEstimateMB: Record<string, number>;
};
+// An engine's own estimate, and — for one that can follow the input's pitch on
+// another model — that run's, under the engine's `pitch.estimateKey`.
export const DEFAULT_VOICE_HEAVY_ESTIMATES: Record<string, number> = Object.fromEntries(
- Object.values(VOICE_ENGINES).map((e) => [e.id, e.defaultEstimateMB]),
+ Object.values(VOICE_ENGINES).flatMap((e) => [
+ [e.id, e.defaultEstimateMB] as const,
+ ...(e.pitch ? [[e.pitch.estimateKey, e.pitch.defaultEstimateMB] as const] : []),
+ ]),
);
export const DEFAULT_VOICE_SETTINGS: VoiceSettings = {
home: "",
threads: 4,
enhance: { engine: DEFAULT_VOICE_ENGINE.enhance },
- convert: { engine: DEFAULT_VOICE_ENGINE.convert, target: DEFAULT_VOICE_TARGET },
+ convert: { engine: DEFAULT_VOICE_ENGINE.convert, target: DEFAULT_VOICE_TARGET, ...DEFAULT_VOICE_PITCH },
heavyEstimateMB: DEFAULT_VOICE_HEAVY_ESTIMATES,
};
@@ -51,11 +60,13 @@ export const VOICE_SETTINGS_FIELD_DOCS: FieldDocs<VoiceSettings> = {
"(`<home>/targets/`). Blank = `~/.local/share/archilyzer/voice`. Absolute, or `~/`-relative.",
threads: "CPU threads a torch engine (openvoice, seed-vc) may use. 1–16.",
enhance: "The enhance op's default engine. See VoiceEnhanceSettings (`voice.enhance` below).",
- convert: "The convert op's default engine and target. See VoiceConvertSettings (`voice.convert` below).",
+ convert: "The convert op's default engine, target and pitch. See VoiceConvertSettings (`voice.convert` below).",
heavyEstimateMB:
"Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with " +
"(`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. " +
- "The defaults are the 2026-11-03 bake-off's measured peaks plus a margin. An engine left out " +
+ "The defaults are the 2026-11-03 bake-off's measured peaks plus a margin; `seed-vc-f0` is seed-vc's " +
+ "run when it follows the input's pitch (`pitch: source | contour` — another, bigger model; measured " +
+ "2026-11-11 over a take long enough to fill a 30 s window: 5.8 GB). An engine left out " +
"takes its default; 0 declares nothing (the job then runs ALONE in the slot).",
};
@@ -78,6 +89,17 @@ export const VOICE_CONVERT_SETTINGS_FIELD_DOCS: FieldDocs<VoiceConvertSettings>
"`<tts engine>:<stock voice>` (`orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`, …). Never a " +
"file or a recording — no real person's voice is a target. Its reference clip is synthesized " +
"once through the `tts` op and kept under `home`. Anything else falls back to `orpheus:zac`.",
+ pitch:
+ "The pitch a conversion lands on when the request names none — for an engine that can follow the " +
+ "input's (seed-vc, with its optional f0 model: `archilyzer voice setup --engine seed-vc --with f0`; " +
+ "openvoice always lands on the target's). `target`: the stock voice's own pitch — the read's " +
+ "intonation is flattened to it (what there was before). `source`: the pitch the take was read at — " +
+ "raise your voice and the result rises. `contour`: the read's rises and falls, moved as a whole so " +
+ "their median sits on the stock voice's. Anything else falls back to `target`.",
+ semitones:
+ "Semitones a FOLLOWED pitch (`source`, `contour`) is moved by when the request names none: -12 to 12, " +
+ "0 = as followed. Ignored for `target`. It applies to a request that names its own `pitch` too: " +
+ "`{\"pitch\": \"source\"}` with no `semitones` is moved by this many — send `\"semitones\": 0` for none.",
};
// "" (the default), an absolute path, or a `~/` one; anything else is "".
@@ -109,7 +131,15 @@ export function sanitizeVoice(value: unknown): VoiceSettings {
home: dirSetting(r.home),
threads: Math.min(16, Math.max(1, threads)),
enhance: { engine: engineFor("enhance", en.engine) },
- convert: { engine: engineFor("convert", cv.engine), target: target.ok ? target.value.id : DEFAULT_VOICE_TARGET },
+ convert: {
+ engine: engineFor("convert", cv.engine),
+ target: target.ok ? target.value.id : DEFAULT_VOICE_TARGET,
+ pitch: VOICE_PITCH_MODES.includes(cv.pitch as VoicePitch) ? (cv.pitch as VoicePitch) : DEFAULT_VOICE_PITCH.pitch,
+ semitones:
+ typeof cv.semitones === "number" && Number.isFinite(cv.semitones)
+ ? Math.min(VOICE_SEMITONES_MAX, Math.max(-VOICE_SEMITONES_MAX, Math.round(cv.semitones * 100) / 100))
+ : DEFAULT_VOICE_PITCH.semitones,
+ },
heavyEstimateMB,
};
}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A converted read can follow your pitch.** Converting a recorded read to a stock voice threw the voice acting away. On 11 Nov, reads with a median pitch of 128, 212, 225 and 237 Hz all came out at 196–199 Hz, and a 152–321 Hz range came out as 165–240 Hz: both converters speak at the stock voice's own pitch. `pnpm ops voice-convert` now takes `"pitch"`: `target` (as before), `source` (the pitch you read at: raise your voice and the result rises) or `contour` (your rises and falls, moved as a whole to the stock voice's register), and `"semitones"` (-12 to 12) moves a followed pitch. The same read that came out at 197 Hz now comes out at 211 Hz with a 148–314 Hz range, against 212 Hz and 152–321 Hz read. `source` and `contour` are seed-vc's, on its f0-conditioned model: optional files, fetched by `archilyzer voice setup --engine seed-vc --with f0` (1.49 GB). An install without them converts as before, and a followed pitch is refused naming that command; openvoice refuses a pitch it cannot follow. It takes about 1.7 times as long, and more memory (5.8 GB at its peak on a take of 20 s or more). `settings.voice.convert.pitch` and `.semitones` are the defaults (`target`, 0). In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch contour --convert-semitones 2`, shown on Voices), and `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive <n> --op convert` set it for one read; the post bench's **run AI on take** has the same two controls for a convert on seed-vc, starting from the character's. The disclosure line is unchanged.
- **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text.
- **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it.
- **The drive watch no longer overwrites a tier you change while it is pausing channels.** The five-minute storage watch, which pauses the channels on a drive that went away and restores them when it comes back, could save its change in the middle of yours and undo it. It now waits for the same settings lock that the channel-priority save uses. The editor's `dev` script also gives Node 16 file-access threads, as `start`, the systemd unit and the container already do.
diff --git a/editor/app/api/ops/voice-convert/route.ts b/editor/app/api/ops/voice-convert/route.ts
@@ -7,7 +7,7 @@ import { jobResponse, ops } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { file, out, voice?, engine?, params?, parts? } -> { ok: true, jobId }
+// POST { file, out, voice?, engine?, pitch?, semitones?, params?, parts? } -> { ok: true, jobId }
//
// Keep a recording's PERFORMANCE — its timing, pitch contour and emphasis —
// and give it a STOCK synthetic voice's timbre, as a job on /jobs
@@ -22,7 +22,12 @@ export const dynamic = "force-dynamic";
// `engine` is `openvoice` (OpenVoice v2's converter) or `seed-vc` (Seed-VC v1),
// default settings.voice.convert.engine — `archilyzer voice setup --engine
// <id>` installs one; `file`/`path`, `out`, `params` and `parts` as for
-// voice-enhance. umtool's derived takes (`umtool posts narrate … --derive <n>
+// voice-enhance. `pitch` says where the result's pitch comes from — `target`
+// (the stock voice's own: the read's intonation is flattened to it), `source`
+// (the pitch the take was read at) or `contour` (the read's rises and falls at
+// the stock voice's register) — and `semitones` (-12 to 12) moves a followed
+// one; defaults settings.voice.convert. source and contour are seed-vc's, on
+// its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`). umtool's derived takes (`umtool posts narrate … --derive <n>
// --op convert`) are the caller.
//
// The job's log ends with `@@voice-result {json}` — voice-enhance's shape plus
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -559,7 +559,8 @@ const ACTIONS = [
"tts",
// Run an engine over a speech RECORDING ({file, out, engine?, params?,
// parts?}; convert also takes voice — a stock synthetic voice
- // `<tts engine>:<voice>`, never a recording), as a job on the `voice` queue
+ // `<tts engine>:<voice>`, never a recording — and pitch / semitones, the
+ // pitch the result lands on), as a job on the `voice` queue
// behind the heavy slot. With --wait the result JSON is what stdout carries.
"voice-enhance",
"voice-convert",
@@ -2005,8 +2006,17 @@ export function usage() {
" kokoro:am_michael, ...; settings.voice.convert.target); a file, a path or a",
" recording is REFUSED as a target (no real person's voice) — and \"engine\"",
" (openvoice | seed-vc, each installed by `archilyzer voice setup --engine <id>`).",
+ ' "pitch" is where the result\'s pitch comes from (settings.voice.convert.pitch):',
+ ' "target" — the stock voice\'s own, the read\'s intonation flattened to it;',
+ ' "source" — the pitch the take was read at (raise your voice and it rises);',
+ ' "contour" — the read\'s rises and falls, moved as a whole to the stock voice\'s',
+ ' register. "semitones" (-12 to 12) then moves a followed pitch; left out, a',
+ " followed pitch takes settings.voice.convert.semitones (0 unless set). source and",
+ " contour are seed-vc's, on its optional f0 model (`archilyzer voice setup",
+ " --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them.",
" The target's reference is synthesized once through the tts op and kept. The",
- " result adds target, voice, synthetic: true and the disclosure line.",
+ " result adds target, voice, pitch (semitones and f0 — the medians heard and the",
+ " move applied — when followed), synthetic: true and the disclosure line.",
"",
'web-search searches the web (DuckDuckGo\'s HTML page) and answers the',
' results: {"query", "n"?: 6 (at most 20)} -> {results: [{title, url,',
diff --git a/scripts/voice.mjs b/scripts/voice.mjs
@@ -15,7 +15,9 @@
// its delay compensated (-D) so the timing holds.
// convert openvoice OpenVoice v2's tone-colour converter
// (scripts/voice_openvoice.py, torch on the CPU).
-// seed-vc Seed-VC v1's 22 kHz speech model
+// seed-vc Seed-VC v1's 22 kHz speech model, or with
+// --pitch source|contour its 44.1 kHz f0-conditioned
+// one, whose output follows the input's pitch
// (scripts/voice_seedvc.py, torch on the CPU).
// A convert engine is given --target-ref: a STOCK voice's reference clip,
// made by our own TTS engines (the controller refuses anything else).
@@ -27,7 +29,8 @@
// 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, more?}.
+// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}, and for
+// a followed pitch {pitch, semitones, f0: {targetHz, sourceHz, shiftSemitones}}.
//
// 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.
@@ -45,6 +48,10 @@
// --code <dir> the engine's pinned checkout [openvoice, seed-vc]
// --target-ref <wav> the stock target's reference clip [convert]
// --target-se <pt> where openvoice caches the target's embedding
+// --pitch <mode> target (default: the stock voice's own pitch), source
+// (the input's pitch) or contour (the input's intonation
+// at the stock voice's register) [seed-vc]
+// --semitones <n> moves a followed pitch, -12 to 12 [seed-vc, with --pitch source|contour]
// --model <f> the rnnoise model [rnnoise]
// --threads <n> CPU threads for torch (default 4)
// --lufs <x> enhance's level when params has no `lufs` (default -20)
@@ -101,6 +108,14 @@ if (!Array.isArray(extra) || !extra.every((x) => x && typeof x.input === "string
}
const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg");
const threads = String(Math.max(1, Number(arg("--threads", "4")) || 4));
+// The pitch a conversion lands on (seed-vc; scripts/voice_seedvc.py's header).
+const PITCH_MODES = ["target", "source", "contour"];
+const pitch = arg("--pitch", "target");
+const semitones = Number(arg("--semitones", "0"));
+if (!PITCH_MODES.includes(pitch)) fail(`--pitch is one of ${PITCH_MODES.join(", ")} (got '${pitch}')`);
+if (!Number.isFinite(semitones) || semitones < -12 || semitones > 12) fail(`--semitones is a number from -12 to 12 (got '${arg("--semitones", "")}')`);
+if (pitch !== "target" && kind !== "seed-vc") fail(`--pitch ${pitch} is seed-vc's: ${kind} has no pitch control`);
+if (semitones !== 0 && pitch === "target") fail("--semitones moves a followed pitch: it needs --pitch source or contour");
const lufs = typeof params.lufs === "number" ? params.lufs : Number(arg("--lufs", "-20"));
const out = path.resolve(output);
@@ -247,13 +262,27 @@ async function convertAll(items) {
"--threads", threads,
], { env });
} else {
- await run(python, [
+ const { stdout } = 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"),
+ // A followed pitch is the f0-conditioned model's (44.1 kHz, its own
+ // vocoder, RMVPE): the optional files `voice setup --engine seed-vc
+ // --with f0` fetches (common/lib/voiceApps.ts SEEDVC_F0_FILES).
+ ...(pitch === "target"
+ ? [
+ "--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"),
+ "--bigvgan", path.join(install, "bigvgan"),
+ ]
+ : [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml"),
+ "--bigvgan", path.join(install, "bigvgan-44k"),
+ "--rmvpe", path.join(install, "rmvpe.pt"),
+ "--pitch", pitch,
+ "--semitones", String(semitones),
+ ]),
"--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))))),
@@ -261,7 +290,15 @@ async function convertAll(items) {
"--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))),
"--threads", threads,
], { env });
+ // A followed pitch: what the tracker heard and how far the curve was moved.
+ try {
+ const said = JSON.parse(stdout.trim().split("\n").pop() ?? "{}");
+ if (pitch !== "target" && said.f0 && typeof said.f0 === "object") return { pitch, semitones, f0: said.f0 };
+ } catch {
+ /* the result line is the wrapper's own */
+ }
}
+ return {};
}
// One static gain (enhance to --lufs, convert to the input's own loudness;
@@ -302,8 +339,9 @@ try {
const items = [];
for (const [k, item] of [{ input, output }, ...extra].entries()) items.push(await prepare(item, k));
const started = Date.now();
+ const engineSaid = {};
if (op === "enhance") for (const it of items) await enhanceOne(it);
- else await convertAll(items);
+ else Object.assign(engineSaid, await convertAll(items));
const engineMs = Date.now() - started;
const done = [];
for (const it of items) done.push(await finish(it));
@@ -319,6 +357,7 @@ try {
gainDb: first.gainDb,
inputLufs: first.inputLufs,
outputLufs: first.outputLufs,
+ ...engineSaid,
...(rest.length ? { more: rest } : {}),
};
process.stdout.write(JSON.stringify(result) + "\n");
diff --git a/scripts/voice.test.mjs b/scripts/voice.test.mjs
@@ -31,6 +31,13 @@ test("the argv is checked before anything runs", () => {
assert.match(run(["--op", "enhance", "--engine-kind", "seed-vc"]).stderr, /--engine-kind for enhance is one of rnnoise, deepfilternet/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise"]).stderr, /--input and --output are required/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", "/a", "--output", "/b", "--params", "{"]).stderr, /--params must be JSON/);
+ // The pitch a conversion lands on is seed-vc's to follow, and semitones move a followed one.
+ const conv = (kind, ...more) => run(["--op", "convert", "--engine-kind", kind, "--input", "/a", "--output", "/b", ...more]);
+ assert.match(conv("seed-vc", "--pitch", "higher").stderr, /--pitch is one of target, source, contour \(got 'higher'\)/);
+ assert.match(conv("seed-vc", "--pitch", "source", "--semitones", "13").stderr, /--semitones is a number from -12 to 12 \(got '13'\)/);
+ assert.match(conv("seed-vc", "--semitones", "2").stderr, /--semitones moves a followed pitch: it needs --pitch source or contour/);
+ assert.match(conv("openvoice", "--pitch", "contour").stderr, /--pitch contour is seed-vc's: openvoice has no pitch control/);
+ for (const r of [conv("seed-vc", "--pitch", "higher"), conv("openvoice", "--pitch", "contour")]) assert.equal(r.status, 2);
});
test("rnnoise: 48 kHz mono, the input's exact length, aligned, the same every run", { skip: !ffmpeg && "ffmpeg absent" }, () => {
@@ -90,3 +97,43 @@ test("--more runs further files the same way, in the same run", { skip: !ffmpeg
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\}/);
});
+
+// scripts/voice_seedvc.py's contour shift over a batch (a take and its parts): measured once, on the first file with
+// a voiced frame. The function is stdlib-only (torch and the model are imported inside main).
+let python = true;
+try {
+ execFileSync("python3", ["-c", "import math"], { stdio: "ignore" });
+} catch {
+ python = false;
+}
+
+test("seed-vc's contour shift: set by the first file with a voiced frame, never locked at 0 by a silent one", { skip: !python && "python3 absent" }, () => {
+ const code = `
+import json, math, sys
+sys.path.insert(0, ${JSON.stringify(import.meta.dirname)})
+from voice_seedvc import pitch_move
+ref, src = math.log(200.0), math.log(100.0)
+out = {}
+# A silent first file: nothing measured, a factor of the semitones alone.
+m, hz, f = pitch_move(None, None, None, ref, "contour", 0)
+out["silent"] = [m, hz, f]
+# The next, voiced: an octave up to the reference's median, and it is kept.
+m, hz, f = pitch_move(m, hz, src, ref, "contour", 0)
+out["voiced"] = [round(m, 6), hz, round(f, 6)]
+m2, hz2, f2 = pitch_move(m, hz, math.log(150.0), ref, "contour", 0)
+out["later"] = [round(m2, 6), hz2, round(f2, 6)]
+# Source: no move, the semitones alone; contour with semitones: both.
+out["source"] = [round(x, 6) if isinstance(x, float) else x for x in pitch_move(None, None, src, ref, "source", 12)]
+out["both"] = round(pitch_move(None, None, src, ref, "contour", -12)[2], 6)
+# A silent file after the move is set does not unset it.
+out["after"] = round(pitch_move(m, hz, None, ref, "contour", 0)[0], 6)
+print(json.dumps(out))
+`;
+ const out = JSON.parse(execFileSync("python3", ["-c", code], { encoding: "utf8", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }));
+ assert.deepEqual(out.silent, [null, null, 1]);
+ assert.deepEqual(out.voiced, [0.693147, 100, 2]);
+ assert.deepEqual(out.later, [0.693147, 100, 2]);
+ assert.deepEqual(out.source, [0, 100, 2]);
+ assert.equal(out.both, 1);
+ assert.equal(out.after, 0.693147);
+});
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), files in, files out — run by
+# SEED-VC (v1: the 22 kHz speech model, or the 44.1 kHz f0-conditioned one), 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,19 +17,56 @@
# quantizer this model does not use; it is stubbed rather than installed (it
# pulls in a training stack).
#
+# PITCH (--pitch). The 22 kHz model is given no pitch at all: it speaks every
+# input at the TARGET's own pitch and narrows the range (measured 2026-11-11:
+# inputs with a median f0 of 128 to 237 Hz all came out at 196-199 Hz) — the
+# read's intonation is thrown away. `--pitch target` is that, unchanged. The
+# other two run upstream's f0-conditioned model (`inference.py --f0-condition`:
+# 44.1 kHz, a 128-band BigVGAN, RMVPE as the pitch tracker — voice.mjs passes
+# those files as --dit/--config/--bigvgan and --rmvpe): the input's f0 curve
+# conditions the content, so the output's pitch FOLLOWS the read.
+# source the input's f0 as it is: the output is at the pitch it was read at.
+# contour the input's curve moved, as a whole, so its median lands on the
+# target reference's median (upstream's --auto-f0-adjust): every rise
+# and fall is kept, the register is the stock voice's.
+# --semitones then moves the followed curve up or down (2^(n/12)). In a batch
+# the contour's move is measured ONCE, on the first file (the take), and used
+# for the rest (its parts): a part must sit where it sits in the whole. A file
+# with no voiced frame (silence, a breath) has no median to measure: it leaves
+# the move unset, and the first file that has one sets it.
+#
# 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}.
+# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs, pitch,
+# semitones, f0?: {targetHz, sourceHz, shiftSemitones}} — f0 is the medians
+# RMVPE heard in the reference and the first file, and the whole move applied.
import argparse
import json
+import math
import os
import sys
import time
import types
+def pitch_move(move, source_hz, median, ref_median, pitch, semitones):
+ """The followed curve's factor for one file, and the batch's state after it.
+
+ `move` is the batch's shift in log-f0 (None: not measured yet), `median` this
+ file's median log-f0 (None: no voiced frame), `ref_median` the reference's.
+ The shift is measured ONCE, on the first file with a voiced frame — contour:
+ the reference's median less the file's; source: 0 — and a file before it
+ (unvoiced: nothing in it is multiplied anyway) leaves it unset rather than
+ locking it at 0. Returns (move, source_hz, factor).
+ """
+ if move is None and median is not None:
+ source_hz = round(math.exp(median), 1)
+ move = (ref_median - median) if pitch == "contour" and ref_median is not None else 0.0
+ return move, source_hz, math.exp(move or 0.0) * 2 ** (semitones / 12)
+
+
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--code", required=True, help="the seed-vc checkout")
@@ -46,11 +83,22 @@ def main() -> int:
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("--pitch", choices=["target", "source", "contour"], default="target",
+ help="target: the stock voice's own pitch (the 22 kHz model); source / contour: the input's f0 conditions the 44.1 kHz f0 model")
+ ap.add_argument("--semitones", type=float, default=0.0, help="moves the followed f0 (source, contour); -12 to 12")
+ ap.add_argument("--rmvpe", default="", help="rmvpe.pt, the pitch tracker (source, contour)")
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")
+ follow = a.pitch != "target"
+ if follow and not a.rmvpe:
+ ap.error("--pitch source|contour needs --rmvpe")
+ if not follow and a.semitones != 0:
+ ap.error("--semitones moves a followed pitch: it needs --pitch source or contour")
+ if not -12 <= a.semitones <= 12:
+ ap.error("--semitones is between -12 and 12")
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
@@ -106,6 +154,34 @@ def main() -> int:
whisper.eval()
feat = AutoFeatureExtractor.from_pretrained(a.whisper, local_files_only=True)
+ # The pitch tracker (source, contour): f0 in Hz per 10 ms of 16 kHz audio,
+ # 0 where unvoiced. A long input goes in 30 s pieces, each heard with a
+ # second of context either side — RMVPE over half an hour at once is GBs.
+ f0_of = None
+ if follow:
+ from modules.rmvpe import RMVPE
+
+ rmvpe = RMVPE(a.rmvpe, is_half=False, device=device)
+ PIECE, CTX, HOP16 = 16000 * 30, 16000, 160
+
+ def f0_of(w16):
+ w16 = w16.squeeze(0).cpu().numpy()
+ n = len(w16)
+ if n <= PIECE + 2 * CTX:
+ return rmvpe.infer_from_audio(w16, thred=0.03)
+ out, at = [], 0
+ while at < n:
+ lo, end = max(0, at - CTX), min(n, at + PIECE)
+ f = rmvpe.infer_from_audio(w16[lo : min(n, end + CTX)], thred=0.03)
+ first = (at - lo) // HOP16
+ out.append(f[first:] if end == n else f[first : first + (end - at) // HOP16])
+ at = end
+ return np.concatenate(out)
+
+ def median_log(f0):
+ v = f0[f0 > 1]
+ return float(np.median(np.log(v))) if len(v) else None
+
def semantic(w16):
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)
@@ -148,8 +224,23 @@ def main() -> int:
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))
- prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3, f0=None)
+ f0_ref = f0_of(ref16) if follow else None
+ prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3,
+ f0=torch.from_numpy(f0_ref)[None] if follow else None)
window = max_context - mel2.size(2)
+ ref_median = median_log(f0_ref) if follow else None
+ # What was heard and done, for the result line; `move` is the contour's
+ # shift in log-f0, measured on the first file that has a voiced frame and
+ # kept for the rest (None until then: a file with none has nothing to move).
+ heard = {"move": None, "sourceHz": None}
+
+ def followed_f0(src16):
+ f0 = f0_of(src16)
+ heard["move"], heard["sourceHz"], factor = pitch_move(heard["move"], heard["sourceHz"], median_log(f0), ref_median, a.pitch, a.semitones)
+ voiced = f0 > 1
+ out = f0.copy()
+ out[voiced] = f0[voiced] * factor
+ return torch.from_numpy(out.astype(np.float32))[None]
def convert(src):
with torch.no_grad():
@@ -172,7 +263,8 @@ def main() -> int:
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)
+ cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3,
+ f0=followed_f0(src16) if follow else None)
done, chunks, prev = 0, [], None
while done < cond.size(1):
c = cond[:, done : done + window]
@@ -208,6 +300,13 @@ def main() -> int:
"seconds": round(total, 3),
"files": len(items),
"engineMs": int((time.time() - t0) * 1000),
+ "pitch": a.pitch,
+ "semitones": a.semitones,
+ **({"f0": {
+ "targetHz": round(float(np.exp(ref_median)), 1) if ref_median is not None else None,
+ "sourceHz": heard["sourceHz"],
+ "shiftSemitones": round(12 * (heard["move"] or 0.0) / float(np.log(2)) + a.semitones, 2),
+ }} if follow else {}),
}))
return 0
diff --git a/settings.json.example b/settings.json.example
@@ -268,13 +268,16 @@
},
"convert": {
"engine": "openvoice",
- "target": "orpheus:zac"
+ "target": "orpheus:zac",
+ "pitch": "target",
+ "semitones": 0
},
"heavyEstimateMB": {
"deepfilternet": 400,
"rnnoise": 300,
"openvoice": 2000,
- "seed-vc": 3500
+ "seed-vc": 3500,
+ "seed-vc-f0": 6500
}
},
"generation": {
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -21,6 +21,9 @@ import { fitPostItem } from "@/lib/report/postFit.mjs";
import { itemReadVoice } from "@/lib/report/readVoice.mjs";
import { projectRedaction } from "@/lib/report/postRedaction.mjs";
import { spokenRead } from "umtool-report-to-video/post-redact";
+import { characterOf, convertTargetOf, narratorOf } from "umtool-report-to-video/cast";
+import { castForProject } from "@/lib/report/castStore.mjs";
+import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
export const dynamic = "force-dynamic";
@@ -41,10 +44,15 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// POST {project, op: "take", id, note?, voice?, engine?, speed?, script?}
// a new take asked of the EDITOR's tts op (a job)
// POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit)
-// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?}
+// GET ?project&id&convert=1 what a convert of this post defaults to: its author's character in
+// the cast (else the narrator) and that character's convert
+// target -- {character, convert: {engine, voice, pitch?, semitones?}}
+// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?, pitch?, semitones?}
// a NEW take made from take `from` by the editor's voice op
-// (a job; kept by GET ?job&derive=<from>); `installed: false`
-// when the editor has no engine for it
+// (a job; kept by GET ?job&derive=<from>[&pitch&semitones]);
+// `installed: false` when the editor has no engine for it. A
+// convert's `pitch` (target | source | contour) and `semitones`
+// are the pitch the read lands on (lib/report/derivePitch.mjs)
// POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft)
// POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece
// POST {project, op: "reread", id, tempo: "4-16=1.35", stretch?} its parts RE-TIMED (no TTS); {…, yell: true, yellGain?, yellStyle?}: its caps raised
@@ -77,6 +85,14 @@ export async function GET(request: Request) {
const render = (m.render ?? {}) as Record<string, unknown>;
const id = q.get("id");
const job = q.get("job");
+ if (id && !job && q.get("convert") !== null) {
+ // What a convert of this post defaults to (`posts narrate --recording`'s rule: the author's character, else the narrator).
+ const e = postsOf(m).find((x) => x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ const { cast } = await castForProject(r.project.dir);
+ const c = characterOf(cast, String((e as { handle?: unknown }).handle ?? "")) ?? narratorOf(cast);
+ return Response.json({ character: c ? { id: c.id, name: c.name } : null, convert: c ? convertTargetOf(c) : null }, { headers: noStore });
+ }
if (id && job) {
// A GET that WRITES the manifest (a job followed to done): the proxy passes reads, so an <img> on another site
// could ask it; refused cross-site here (lib/report/sameOrigin.mjs).
@@ -109,13 +125,16 @@ export async function GET(request: Request) {
if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore });
const op = String(q.get("op") ?? "");
// The editor's defaults, when the ask named none (its `@@voice-result` line).
- const vr = resultLine<{ engine?: string; voice?: string }>(st.tail, "@@voice-result ") ?? {};
+ const vr = resultLine<{ engine?: string; voice?: string; pitch?: string; semitones?: number }>(st.tail, "@@voice-result ") ?? {};
+ // The pitch it landed on, as the editor ran it (else as it was asked); the target's own is not recorded.
+ const asked = derivePitchOf({ pitch: q.get("pitch"), semitones: q.get("semitones") });
+ const pitched = op === "convert" ? stepPitchOf(asked.ok ? asked.value : {}, vr) : {};
const engine = q.get("engine") ?? vr.engine ?? null;
const voice = op === "convert" ? (q.get("voice") ?? vr.voice ?? null) : null;
const partsRel = rel.replace(/\.wav$/, ".parts");
const derived = {
file: rel, engine: "derived", voice: (voice ? voice.split(":").pop() : null) ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) },
- steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ranAt: new Date().toISOString(), job }],
+ steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...pitched, ranAt: new Date().toISOString(), job }],
script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}),
...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}),
};
@@ -250,6 +269,9 @@ async function postHere(request: Request) {
if (!(POST_DERIVE_OPS as readonly string[]).includes(op)) return Response.json({ error: `op2 is one of ${POST_DERIVE_OPS.join(", ")}` }, { status: 400 });
const engine = body.engine ? String(body.engine) : null;
const voice = body.voice ? String(body.voice) : null;
+ // A convert's pitch (target | source | contour) and semitones, checked here; the editor refuses what its engine cannot do.
+ const pitched = derivePitchOf({ pitch: body.pitch, semitones: body.semitones }, op);
+ if (!pitched.ok) return Response.json({ error: pitched.error }, { status: 400 });
const pid = postIdOf(e);
const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
@@ -261,15 +283,15 @@ async function postHere(request: Request) {
: null;
try {
// `voice` is the convert op's stock target; enhance takes none.
- const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...(parts ? { parts } : {}) });
- return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice }, { headers: noStore });
+ const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...pitched.value, ...(parts ? { parts } : {}) });
+ return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice, ...pitched.value }, { headers: noStore });
} 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 (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 });
- }
+ // A missing optional model (`… --with f0`) is passed through in the editor's words (derivePitch.mjs deriveRefusalOf).
+ const refusal = deriveRefusalOf(op, status, msg);
+ if (refusal) return Response.json({ ok: false, ...refusal }, { status: 200, headers: noStore });
return Response.json({ error: msg }, { status });
}
}
diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts
@@ -32,7 +32,7 @@ export const dynamic = "force-dynamic";
// POST { project, op: "use", who, voice, scope: "project" | "cast" } umtool cast use <p> <who> <voice> [--everywhere]
// POST { project, op: "reread", who } QUEUED: one `posts narrate … --take [--thread …]` step per item
// whose picked read says them in another voice (the argv built here)
-// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, narrator? }
+// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, convertPitch?, convertSemitones?, narrator? }
// POST multipart { project, op: "recording", item, as?, clean?, convert?, file } a JOB: posts narrate <p> <item>
// --recording <file> (kept, cleaned, converted to a STOCK voice)
const headers = { "cache-control": "no-store" };
@@ -169,6 +169,9 @@ export async function POST(request: Request) {
if (op === "cast-set") {
const args = ["set", s("id")];
if (s("convertEngine")) args.push("--convert-engine", s("convertEngine"));
+ // The pitch a converted read lands on (castCli.mjs refuses what makes no sense).
+ if (s("convertPitch")) args.push("--convert-pitch", s("convertPitch"));
+ if (typeof b.convertSemitones === "number" || s("convertSemitones")) args.push("--convert-semitones", String(b.convertSemitones ?? s("convertSemitones")));
if (b.narrator === true || s("narrator") === "on") args.push("--narrator");
if (b.narrator === false || s("narrator") === "off") args.push("--no-narrator");
if (s("name")) args.push("--name", s("name"));
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -7,6 +7,7 @@ import Waveform from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { postBenchHref } from "@/lib/hrefs";
+import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_PITCH_ENGINES, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast";
import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration";
import { projectFileMedia } from "./bench/benchMedia";
import { usePeaks } from "./bench/usePeaks";
@@ -37,7 +38,15 @@ import PostAttachmentLane from "./PostAttachmentLane";
// `umtool posts narrate` runs; the bench takes the entry it returns.
// ---------------------------------------------------------------------------
-type Step = { op: string; engine?: string; voice?: string };
+// A derived take's step. A convert's `pitch` / `semitones`: the pitch the converted read lands on (knobs.md, "The
+// pitch a converted read lands on") -- absent for the stock voice's own.
+type Step = { op: string; engine?: string; voice?: string; pitch?: string; semitones?: number };
+// The engines whose convert can FOLLOW the read's pitch (cast.mjs CAST_PITCH_ENGINES), and the modes in plain words.
+const PITCH_WORDS: Record<string, string> = {
+ target: "the stock voice's own pitch",
+ source: "follow my pitch",
+ contour: "my intonation, at the voice's register",
+};
type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }>; words?: Array<{ w: string; start: number; end: number }> };
type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>;
type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> };
@@ -212,20 +221,20 @@ export default function PostNarrationPanel({
// ---- a re-take with direction (the editor's tts op) --------------------------
const [dir, setDir] = useState({ note: "", voice: "", speed: "" });
- const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null } } | null>(null);
+ const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null; pitch?: string | null; semitones?: number | null } } | null>(null);
// Derived takes still to make after a re-record ("re-run the chain"), from the new take.
const [chain, setChain] = useState<Array<{ from: number; step: Step }>>([]);
const [rerunChain, setRerunChain] = useState(true);
const [notInstalled, setNotInstalled] = useState<string | null>(null);
const derive = async (from: number, step: Step) => {
setNotInstalled(null);
- const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null;
+ const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined, ...(step.op === "convert" && step.pitch ? { pitch: step.pitch, ...(typeof step.semitones === "number" ? { semitones: step.semitones } : {}) } : {}) })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null;
if (j && j.installed === false) {
setNotInstalled(j.error ?? `the editor has no ${step.op} engine yet`);
setChain([]);
return;
}
- if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null } });
+ if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null, pitch: step.pitch ?? null, semitones: step.semitones ?? null } });
};
const retake = async () => {
const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script });
@@ -236,7 +245,7 @@ export default function PostNarrationPanel({
const t = setTimeout(async () => {
const q = new URLSearchParams({
project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}),
- ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}) } : {}),
+ ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}), ...(job.derive.pitch ? { pitch: job.derive.pitch } : {}), ...(typeof job.derive.semitones === "number" ? { semitones: String(job.derive.semitones) } : {}) } : {}),
});
const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" });
const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string };
@@ -279,7 +288,47 @@ export default function PostNarrationPanel({
roots.forEach((i) => walk(i, 0));
return { rows: out, kids };
}, [takes]);
- const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string }>({ op: "enhance", engine: "", voice: "" });
+ const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string; pitch: string; semitones: string }>({ op: "enhance", engine: "", voice: "", pitch: "target", semitones: "" });
+ // What a convert of THIS post defaults to: its author's character in the cast (else the narrator) -- the engine, the
+ // stock voice and the pitch every recording made that character's lands on (`umtool cast set <id> --convert-pitch …`).
+ const [castConvert, setCastConvert] = useState<{ name: string; engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null>(null);
+ useEffect(() => {
+ let live = true;
+ setCastConvert(null);
+ fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&convert=1`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j: { character?: { name: string } | null; convert?: { engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null } | null) => {
+ if (live && j?.character && j.convert) setCastConvert({ name: j.character.name, ...j.convert });
+ })
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ }, [project, entry.id]);
+ // Choosing the op: a convert starts from the character's entry (its engine and voice only where the field is
+ // empty); an enhance drops a convert engine left in the field.
+ const chooseDeriveOp = (op: string) =>
+ setDeriveDraft((d) =>
+ op !== "convert"
+ ? { ...d, op, engine: (CAST_CONVERT_ENGINES as readonly string[]).includes(d.engine.trim()) ? "" : d.engine }
+ : {
+ op,
+ engine: d.engine || castConvert?.engine || "",
+ voice: d.voice || castConvert?.voice || "",
+ pitch: castConvert?.pitch ?? "target",
+ semitones: castConvert?.semitones ? String(castConvert.semitones) : "",
+ },
+ );
+ // The pitch controls are an engine's that can follow one; without it the convert lands on the stock voice's own.
+ const derivePitched = deriveDraft.op === "convert" && (CAST_PITCH_ENGINES as readonly string[]).includes(deriveDraft.engine.trim());
+ const deriveSemitones = Number(deriveDraft.semitones || 0);
+ const deriveSemitonesBad = derivePitched && deriveDraft.pitch !== "target" && !(Number.isFinite(deriveSemitones) && Math.abs(deriveSemitones) <= CAST_SEMITONES_MAX);
+ const deriveStep = (): Step => ({
+ op: deriveDraft.op,
+ ...(deriveDraft.engine.trim() ? { engine: deriveDraft.engine.trim() } : {}),
+ ...(deriveDraft.op === "convert" && deriveDraft.voice.trim() ? { voice: deriveDraft.voice.trim() } : {}),
+ ...(derivePitched ? { pitch: deriveDraft.pitch, ...(deriveDraft.pitch !== "target" ? { semitones: deriveSemitones } : {}) } : {}),
+ });
// ---- the lanes ------------------------------------------------------------------
// One lane per timed attachment (a video, a GIF), its in and out the bench's draft (onTrim).
@@ -589,7 +638,7 @@ export default function PostNarrationPanel({
<div className="flex flex-wrap items-center gap-2">
<span className="font-mono">{depth ? "└ " : ""}#{i + 1}</span>
<span>
- {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
+ {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}${convertPitchLabel(step) ? ` · pitch: ${convertPitchLabel(step)}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
</span>
<span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span>
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
@@ -642,7 +691,7 @@ export default function PostNarrationPanel({
{picked && (
<div className="flex flex-wrap items-center gap-1.5" data-post-derive="">
<span className="micro">run AI on take #{picked.index + 1}</span>
- <select value={deriveDraft.op} onChange={(e) => setDeriveDraft({ ...deriveDraft, op: e.target.value })} data-post-derive-op="">
+ <select value={deriveDraft.op} onChange={(e) => chooseDeriveOp(e.target.value)} data-post-derive-op="">
{POST_DERIVE_OPS.map((o) => (
<option key={o} value={o}>
{o === "enhance" ? "enhance (denoise, level)" : "convert (to a stock synthetic voice)"}
@@ -653,7 +702,30 @@ export default function PostNarrationPanel({
{deriveDraft.op === "convert" && (
<input value={deriveDraft.voice} onChange={(e) => setDeriveDraft({ ...deriveDraft, voice: e.target.value })} placeholder="stock voice" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-voice="" />
)}
- <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(picked.index, { op: deriveDraft.op, ...(deriveDraft.engine ? { engine: deriveDraft.engine } : {}), ...(deriveDraft.voice ? { voice: deriveDraft.voice } : {}) })} data-post-derive-run="">
+ {derivePitched && (
+ <label className="flex items-center gap-1" title="where the converted read's pitch comes from: the stock voice's own (your intonation is flattened to it), the pitch you read at, or your rises and falls moved to the stock voice's register">
+ <span className="micro">pitch</span>
+ <select value={deriveDraft.pitch} onChange={(e) => setDeriveDraft({ ...deriveDraft, pitch: e.target.value })} aria-label="the pitch the converted read lands on" data-post-derive-pitch="">
+ {CAST_CONVERT_PITCH.map((p) => (
+ <option key={p} value={p}>
+ {PITCH_WORDS[p] ?? p}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {derivePitched && deriveDraft.pitch !== "target" && (
+ <label className="flex items-center gap-1" title={`moves the followed pitch up or down, in semitones (-${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}); 0: as followed`}>
+ <input type="number" min={-CAST_SEMITONES_MAX} max={CAST_SEMITONES_MAX} step={0.5} value={deriveDraft.semitones} onChange={(e) => setDeriveDraft({ ...deriveDraft, semitones: e.target.value })} placeholder="0" aria-label="semitones the followed pitch is moved by" aria-invalid={deriveSemitonesBad || undefined} className="w-14 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-semitones="" />
+ <span className="micro">semitones</span>
+ </label>
+ )}
+ {deriveDraft.op === "convert" && castConvert && (
+ <span className="micro text-text-2" data-post-derive-cast="">
+ {castConvert.name}'s in the cast: {[castConvert.engine, castConvert.voice, convertPitchLabel(castConvert) ? `pitch ${convertPitchLabel(castConvert)}` : null].filter(Boolean).join(" · ")}
+ </span>
+ )}
+ <button type="button" className={btn} disabled={job?.state === "running" || deriveSemitonesBad} onClick={() => void derive(picked.index, deriveStep())} data-post-derive-run="">
Run → a new take
</button>
{notInstalled && (
diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx
@@ -26,13 +26,24 @@ type Voice = { engine: string; voice: string; spec: string; from: string };
type Drift = { id: string; handle: string; role: string; reads: string; want: string; from: string | null; kind: string; thread: boolean };
type Character = {
key: string; name: string; handles: string[];
- character: { id: string; name: string; voice: string; convert?: { engine?: string; voice?: string }; note?: string; narrator?: boolean } | null;
+ character: { id: string; name: string; voice: string; convert?: Convert; note?: string; narrator?: boolean } | null;
items: number; context: number; itemIds: string[]; contextIds: string[];
voice: Voice; contextVoice?: Voice; weight: string;
reads: { id: string; role: string; spec: string; kind: string }[];
drift: Drift[]; speaker: string | null; lines: { item: string; text: string; own: boolean }[];
};
-type CastChar = { id: string; name: string; handles?: string[]; voice: string; convert?: { engine?: string; voice?: string }; speakers?: string[]; note?: string; narrator?: boolean };
+// What a recording of the character is made into: the stock voice, the engine, and the pitch the converted read
+// lands on (`umtool cast set <id> --convert-pitch source|contour|target --convert-semitones n`).
+type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number };
+type CastChar = { id: string; name: string; handles?: string[]; voice: string; convert?: Convert; speakers?: string[]; note?: string; narrator?: boolean };
+
+/** A convert entry's pitch in words — "follows your pitch", "your intonation at the voice's register +2 st" — "" for the stock voice's own. */
+function pitchWords(cv?: Convert): string {
+ if (!cv?.pitch || cv.pitch === "target") return "";
+ const n = Number(cv.semitones) || 0;
+ const st = n ? ` ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : "";
+ return cv.pitch === "source" ? `follows your pitch${st}` : `your intonation at the voice's register${st}`;
+}
type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string };
type View = {
project: string; castFile: string | null; castError?: string; map: Record<string, string>;
@@ -527,7 +538,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<option value="">as: the post's author (else the narrator)</option>
{view.cast.map((c) => (
<option key={c.id} value={c.id}>
- as {c.name} ({pretty(c.convert?.voice ?? c.voice)})
+ as {c.name} ({pretty(c.convert?.voice ?? c.voice)}{pitchWords(c.convert) ? `, ${pitchWords(c.convert)}` : ""})
</option>
))}
</select>
@@ -580,6 +591,11 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<td className={cn(cell, "font-mono")}>{pretty(c.voice)}</td>
<td className={cn(cell, "text-[11px] text-text-2")}>
{c.convert ? `a recording → ${pretty(c.convert.voice ?? c.voice)}${c.convert.engine ? ` (${c.convert.engine})` : ""}` : ""}
+ {pitchWords(c.convert) && (
+ <span data-cast-pitch={c.id} title={`the pitch a converted read lands on: ${c.convert?.pitch}${c.convert?.semitones ? `, ${c.convert.semitones} semitones` : ""} — umtool cast set ${c.id} --convert-pitch target|source|contour --convert-semitones <n>`}>
+ {` · pitch: ${pitchWords(c.convert)}`}
+ </span>
+ )}
{c.speakers?.length ? ` · real voice: ${c.speakers.join(", ")}` : ""}
{c.note ? ` · ${c.note}` : ""}
</td>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -22,7 +22,7 @@ Inbox cannot disagree about what is wrong with one.
| `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) |
| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
-| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
+| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--convert-pitch target\|source\|contour] [--convert-semitones n] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write. A character's `convert` entry is what a recording of them is made into: the stock voice, the engine, and the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one; `set` lays the flags given over the entry). A followed pitch on an engine that has none, or semitones with nothing followed: **exit 1** |
| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
@@ -133,7 +133,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** |
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
-| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked |
+| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l]` · `<item> --derive <n> --op convert [--engine e] [--voice v] [--pitch …] [--semitones n]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1** |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
| `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell] [--bar "…" [--bar-style dark\|gold\|plain]]` · `set <n> [those flags; --bar off clears it]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) |
@@ -170,8 +170,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* |
| `still <project> ls` | the pictures in the project's shots/ | form · *project* |
| `cast ls` | the characters' voices across projects | form · *corpus* |
-| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
-| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
+| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour] [--convert-semitones N] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
+| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour] [--convert-semitones N] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
| `cast rm <id>` | a character out of the cast (an undo point) | form · *corpus* |
| `cast undo` | the cast as it was before its last write | form · *corpus* |
| `cast project <project>` | the project's characters, their voices and drift | form · *project* |
@@ -349,7 +349,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* |
| `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* |
| `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* |
-| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
+| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
| `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* |
| `posts voices <project> ls\|set\|remove [<handle>] [<voice>]` | the voice map a thread read uses | form · *draft* |
| `posts fit <project> [<items>…] [--all] [--linger N] [--dry-run]` | narrated posts' videos cut to their best part | form · queued · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1168,7 +1168,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n
| a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` |
| a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done |
| a THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — |
-| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>` | post bench, **run AI on take #n** (the op, an engine, a stock voice) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` | `op: "derive", from, op2, engine?, voice?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
+| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>`; a convert's **pitch** ([below](#the-pitch-a-converted-read-lands-on)) | post bench, **run AI on take #n** (the op, an engine, a stock voice; for a convert on `seed-vc`, **pitch** and **semitones**) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v] [--pitch target\|source\|contour] [--semitones n]` | `op: "derive", from, op2, engine?, voice?, pitch?, semitones?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
| delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) |
| `narration.pick` — the take that plays | post bench, the take's **Pick** | `--pick <n>` (1 = the first, as `--list` shows) | `patch: {pick}` (an index) |
| `narration.approved` — the picked take on this script, approved (a new script or pick takes it away) | post bench, **approved** | `--approve` · `--unapprove` | `patch: {approved: true \| null}` |
@@ -1320,7 +1320,8 @@ different ones to compare … and try to maintain consistent voices for differen
`castWrite` -- a token, an undo point a write, a broken file never overwritten): the CHARACTERS that recur across
projects -- `{id, name, handles, voice, convert?, speakers?, avatar?, note?, narrator?}`. `voice` is a STOCK voice
with its engine (`kokoro:am_michael`, `orpheus:zac`); `convert` the voice (and engine, openvoice | seed-vc) a
-recording of them is converted to (default: `voice`); `speakers` the names their REAL voice goes by in a project's
+recording of them is converted to (default: `voice`) and the **pitch** that converted read lands on (`pitch`,
+`semitones`: [below](#the-pitch-a-converted-read-lands-on)); `speakers` the names their REAL voice goes by in a project's
`speakers.json` -- a reference to compare a candidate with, never a target (the editor's convert op refuses a file;
the cast holds no path). One character may be the `narrator` (a recording's default character).
@@ -1349,12 +1350,12 @@ voice-convert) to the character's stock voice -- each a new take, the last picke
| Knob | In umtool | From a terminal | Route |
|---|---|---|---|
-| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [--convert-engine seed-vc] [--convert-voice …] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
+| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [--convert-engine seed-vc] [--convert-voice …] [--convert-pitch source\|contour\|target] [--convert-semitones n] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
| a project's characters -- each one's voice now and where it comes from, its reads, its drift, its real voice | **Voices**: the characters table | `umtool cast project <p> [--json]` | `GET /api/report/voices?project` |
| an audition | **Voices** → a character's **Audition**: the line, the candidates (engine, voice, Add), **Render** (a job: the editor's tts, then the closeness through the heavy slot), each played at one loudness, **▶ Play each in turn** (the real voice first) | `umtool cast audition <character\|@handle> --project <p> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json]` | `POST /api/report/voices {op: "audition", who, voices, text?, item?}` |
| the voice a character reads in -- this project, or everywhere | an audition's **Use for this project** / **Use everywhere** | `umtool cast use <p> <character\|@handle> <voice> [--everywhere]` (the project's own override goes with `--everywhere`) | `POST … {op: "use", who, voice, scope}` |
| the re-reads a voice change asks for | the confirm under the audition: the items, **Queue N re-reads** (steps of the queue: /jobs; each a new take, picked, awaiting approval) | `umtool cast reread <p> <character> [--dry-run]` | `POST … {op: "reread", who}` |
-| a recording made a character's read | **Voices** → *a recording*: the item, as whom, drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]` | `POST … multipart {op: "recording", item, as?, file}` |
+| a recording made a character's read | **Voices** → *a recording*: the item, as whom, drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--pitch …] [--semitones n]` | `POST … multipart {op: "recording", item, as?, file}` |
```sh
umtool cast add thequartering --name TheQuartering --voice kokoro:am_michael --handles thequartering --speakers Jeremy
@@ -1365,6 +1366,37 @@ umtool cast reread quartering-diet thequartering # each stale read m
umtool posts narrate quartering-diet <item> --recording my-read.wav --as thequartering
```
+### The pitch a converted read lands on
+
+A converter given no pitch speaks every read at the STOCK voice's own: measured 11 Nov, reads with a median pitch of
+128 to 237 Hz all came out at 196-199 Hz and a 152-321 Hz range came out as 165-240 Hz -- raising your voice for a
+character, and most of your intonation, was thrown away. A convert's **pitch** says where the result's pitch comes
+from (the editor's `voice-convert`: `pitch`, `semitones`):
+
+- **`target`** -- the stock voice's own pitch, as before. Either engine; the default until a character or
+ `settings.voice.convert.pitch` says otherwise.
+- **`source`** -- the pitch you read at, as you read it: raise your voice and the result rises, drop it and it drops.
+ For a read ACTED at the character's pitch.
+- **`contour`** -- your rises and falls, moved as a whole so their median sits on the stock voice's median: read in
+ your ordinary voice, and the character speaks in its own register with your intonation.
+- **`semitones`** (-12 to 12) then moves a followed pitch (`source`, `contour`) up or down. With `target` it is
+ refused: nothing is followed to move. A convert that names a followed pitch and no semitones takes
+ `settings.voice.convert.semitones` (0 unless set).
+
+`source` and `contour` are **seed-vc's**, on its f0-conditioned model -- optional files, `archilyzer voice setup
+--engine seed-vc --with f0` (1.49 GB); it takes about 1.7 times as long as seed-vc at the target's pitch. openvoice has one
+pitch and refuses another; a followed pitch without the f0 files is refused naming that command. A parted take's
+`contour` is measured once, on the whole take, and used for every part.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a character's convert pitch -- `convert.pitch`, `convert.semitones` in the cast: what every recording made that character's lands on | **Voices**: the cast row says it ("pitch: follows your pitch +2 st"), and the recording form's *as …* choice | `umtool cast set <id> --convert-engine seed-vc --convert-pitch source\|contour\|target [--convert-semitones n]` (the flags given are laid over the entry; `--no-convert` clears it) | `POST /api/report/voices {op: "cast-set", id, convertPitch?, convertSemitones?}` |
+| one read's pitch -- this conversion only, over the character's | post bench, **run AI on take #n** → *convert*, engine `seed-vc`: **pitch** (the stock voice's own pitch · follow my pitch · my intonation, at the voice's register) and **semitones**, starting from the post author's character in the cast (else the narrator), which the row names; a converted take's row says its pitch, and **Re-run** keeps it | `umtool posts narrate <p> <item> --recording <file> [--as <character>] --pitch source\|contour\|target [--semitones n]` · `--derive <n> --op convert --engine seed-vc [--voice v] --pitch … [--semitones n]` | `POST /api/report/post-narration {op: "derive", …, pitch?, semitones?}` · `GET …?project&id&convert=1` (the character's default) · the editor's `POST /api/ops/voice-convert {…, pitch?, semitones?}` |
+| the default for every conversion that names none | — | `settings.voice.convert.pitch`, `.semitones` ([SETTINGS.md](../../SETTINGS.md)) | — |
+
+A converted take's step keeps the pitch it was run at (`steps: [{op: "convert", engine, voice, pitch, semitones}]`),
+so `--list` and a re-run say it; the target's own pitch is not recorded.
+
## A caption (a chip explaining a phrase as it is read)
`fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape,
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -72,8 +72,8 @@ export const GROUPS = [
" project's characters and their drift, an audition of candidate voices (scored against the real voice)",
],
docs: [
- ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
- "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write"],
+ ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--convert-pitch target\\|source\\|contour] [--convert-semitones n] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
+ "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write. A character's `convert` entry is what a recording of them is made into: the stock voice, the engine, and the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one; `set` lays the flags given over the entry). A followed pitch on an engine that has none, or semitones with nothing followed: **exit 1**"],
["`cast project <project> [--json]` · `cast use <project> <character\\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]`",
"a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for"],
["`cast audition <character\\|@handle> --voices a,b,… [--project <p>] [--text \"…\" \\| --item <id> \\| --line <n> \\| --stock] [--no-score \\| --score-only] [--json] [--progress ndjson]`",
@@ -1026,8 +1026,8 @@ export const GROUPS = [
"**THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2**"],
["`posts voices <project> [ls] \\| set <handle\\|*> <voice> \\| remove <handle\\|*> [--json]`",
"**THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2**"],
- ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]`",
- "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked"],
+ ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l]` · `<item> --derive <n> --op convert [--engine e] [--voice v] [--pitch …] [--semitones n]`",
+ "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**"],
["`posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post\\|quoted\\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\\|above\\|side]` · `add clock [--rewind auto\\|on\\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]`",
"a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**)"],
["`posts clock <project> [on\\|off\\|default] [--zone <IANA zone>] [--json]`",
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -130,10 +130,13 @@ export const VERBS = Object.freeze([
form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }),
form("cast add", "corpus", "a character: name, stock voice, handles", [
arg("id"), opt("--name", { required: true }), opt("--voice", { required: true, help: "engine:voice" }), opt("--handles", { help: "a,b" }), opt("--speakers", { help: "Name,…" }),
- pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }), opt("--note"), bool("--narrator", "the recordings' default character"),
+ pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }),
+ pick("--convert-pitch", ["target", "source", "contour"], { help: "the pitch a converted read lands on" }), num("--convert-semitones", { help: "-12…12, moves a followed pitch" }),
+ opt("--note"), bool("--narrator", "the recordings' default character"),
]),
form("cast set", "corpus", "change a character", [
arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice"),
+ pick("--convert-pitch", ["target", "source", "contour"], { help: "the pitch a converted read lands on" }), num("--convert-semitones", { help: "-12…12, moves a followed pitch" }),
opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--narrator"), bool("--no-narrator"),
]),
form("cast rm", "corpus", "a character out of the cast (an undo point)", [arg("id")]),
@@ -460,7 +463,8 @@ function posts() {
item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"),
opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"),
bool("--thread", "with --take: a thread read"), opt("--parents"), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"),
- num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), dry(),
+ num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"),
+ pick("--pitch", ["target", "source", "contour"], { help: "a convert's pitch (--recording, --derive)" }), num("--semitones", { help: "-12…12, moves a followed pitch" }), dry(),
pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(),
], { ...Q, ...POST_ITEM }),
p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }),
diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs
@@ -122,6 +122,30 @@ test("umtool cast ls/add/set/rm/undo: the characters across projects", async ()
r = await cast(["ls", "--json"]);
assert.deepEqual(r.json().characters.map((c) => [c.id, c.voice, c.handles.join(",")]), [["hostman", "orpheus:zac", "hostman"], ["me", "kokoro:bm_george", "operator"]]);
assert.equal(r.json().characters[1].narrator, true);
+ // The pitch a converted read lands on: laid over the convert entry, what makes no sense refused.
+ r = await cast(["set", "me", "--convert-pitch", "contour", "--convert-semitones", "2", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "contour", semitones: 2 });
+ r = await cast(["set", "me", "--convert-voice", "kokoro:af_bella", "--json"]);
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "contour", semitones: 2, voice: "kokoro:af_bella" }, "the other keys kept");
+ r = await cast(["ls"]);
+ assert.match(r.text(), /convert: seed-vc -> kokoro:af_bella, pitch contour \+2 st/);
+ r = await cast(["set", "me", "--convert-pitch", "target", "--json"]);
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "target", voice: "kokoro:af_bella" }, "the target's own pitch drops the semitones");
+ for (const [args, re] of [
+ [["--convert-pitch", "high"], /--convert-pitch is one of target, source, contour/],
+ [["--convert-semitones", "13"], /--convert-semitones is a number from -12 to 12/],
+ [["--convert-semitones", "2"], /semitones moves a followed pitch/],
+ [["--convert-engine", "openvoice", "--convert-pitch", "source"], /pitch "source" is seed-vc's: openvoice lands every read on the target's own pitch/],
+ ]) {
+ r = await cast(["set", "me", ...args]);
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.deepEqual((await readCast(ROOT)).cast.characters[1].convert, { engine: "seed-vc", pitch: "target", voice: "kokoro:af_bella" }, "a refusal writes nothing");
+ r = await cast(["set", "me", "--no-convert"]);
+ r = await cast(["set", "me", "--convert-engine", "seed-vc"]);
+ assert.equal(r.code, 0, r.text());
r = await cast(["rm", "me"]);
assert.equal(r.code, 0);
r = await cast(["undo"]);
@@ -278,4 +302,36 @@ test("a recording made a character's read: kept, cleaned (when the editor can),
assert.equal(after.narration.takes[0].engine, "recorded", "the original kept");
assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:af_heart)");
await assert.rejects(importRecording(project, e, rec, { as: "nobody", ask: askOp }), /no such character/);
+ assert.equal("pitch" in picked.steps[0], false, "no pitch asked, none recorded");
+ // THE PITCH: the character's own (its convert entry) goes to the editor, a flag for this read beats it, and the
+ // step keeps what the editor says it ran.
+ const bodies = [];
+ const askPitch = async (route, body) => {
+ if (route.endsWith("voice-enhance")) return askOp(route, body);
+ bodies.push(body);
+ await wavOf(body.out, VOICE_A, 2);
+ return { jobId: `conv-${bodies.length + 1}`, result: { engine: body.engine ?? "openvoice", voice: body.voice, pitch: body.pitch ?? "target", ...(body.pitch && body.pitch !== "target" ? { semitones: body.semitones ?? 0 } : {}) } };
+ };
+ await castWrite(castFile(ROOT), (chars) => {
+ const g = chars.find((c) => c.id === "guest");
+ g.convert = { ...(g.convert ?? {}), engine: "seed-vc", pitch: "contour", semitones: 2 };
+ return { changed: "updated" };
+ }, { what: "set guest's convert pitch" });
+ const own = await importRecording(project, (await manifest()).timeline.find((x) => x.id === "p-3"), rec, { ask: askPitch });
+ assert.deepEqual([bodies[0].engine, bodies[0].pitch, bodies[0].semitones], ["seed-vc", "contour", 2]);
+ assert.equal(own.takes.at(-1).step, "converted to kokoro:af_heart (pitch: contour +2 st)");
+ let now = (await manifest()).timeline.find((x) => x.id === "p-3");
+ let step = now.narration.takes[now.narration.pick].steps[0];
+ assert.deepEqual([step.pitch, step.semitones], ["contour", 2]);
+ await importRecording(project, now, rec, { pitch: "source", semitones: -1, ask: askPitch });
+ assert.deepEqual([bodies[1].pitch, bodies[1].semitones], ["source", -1]);
+ // This read at the stock voice's own pitch: the character's semitones go with its pitch.
+ const flat = await importRecording(project, (await manifest()).timeline.find((x) => x.id === "p-3"), rec, { pitch: "target", ask: askPitch });
+ assert.equal(bodies[2].pitch, "target");
+ assert.equal("semitones" in bodies[2], false);
+ assert.equal(flat.takes.at(-1).step, "converted to kokoro:af_heart");
+ now = (await manifest()).timeline.find((x) => x.id === "p-3");
+ step = now.narration.takes[now.narration.pick].steps[0];
+ assert.equal("pitch" in step, false);
+ assert.equal(own.disclosure, "Narration: voice converted to a synthetic voice (seed-vc · kokoro:af_heart)", "the disclosure line is what it was");
});
diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs
@@ -4,7 +4,7 @@
//
// umtool cast [ls] [--json]
// umtool cast add <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e]
-// [--convert-voice <engine:voice>] [--avatar …] [--note "…"] [--narrator] [--json]
+// [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones n] [--avatar …] [--note "…"] [--narrator] [--json]
// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]
// umtool cast rm <id> [--json] · umtool cast undo [--json]
// umtool cast project <p> [--json]
@@ -15,7 +15,7 @@
//
// Plain ESM: the CLI runs under bare node.
import path from "node:path";
-import { CAST_CONVERT_ENGINES, characterOf, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast";
+import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, characterOf, convertPitchErrors, convertPitchLabel, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast";
import { handleKey, voiceRefOf } from "umtool-report-to-video/post-say";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { readManifest } from "../projects/report.mjs";
@@ -24,7 +24,8 @@ import { CastError, castFile, castForProject, castWrite, readCast, undoCast } fr
export const CAST_USAGE = [
"usage: umtool cast [ls] [--json]",
" umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine openvoice|seed-vc]",
- " [--convert-voice <engine:voice>] [--avatar …] [--note \"…\"] [--narrator] [--json]",
+ " [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones <n>]",
+ " [--avatar …] [--note \"…\"] [--narrator] [--json]",
" umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]",
" umtool cast rm <id> [--json]",
" umtool cast undo [--json]",
@@ -36,7 +37,10 @@ export const CAST_USAGE = [
"",
" THE CAST (<reports>/.umtool/cast.json, one writer, an undo point per write): the characters that recur across",
" projects -- an id, a name, their handles (X handles / channel slugs), the STOCK voice they read in (engine:voice),",
- " optionally the voice a recording of them is converted to (--convert-voice, its engine --convert-engine), the",
+ " optionally the voice a recording of them is converted to (--convert-voice, its engine --convert-engine) and the",
+ " PITCH that read lands on (--convert-pitch: target = the stock voice's own, the read's intonation flattened to it;",
+ " source = the pitch it was read at; contour = the read's rises and falls at the stock voice's register;",
+ " --convert-semitones -12…12 moves a followed one; source and contour are seed-vc's, with its f0 model), the",
" names their REAL voice goes by in a project's speakers.json (--speakers: a reference to compare with, never a",
" target), and one --narrator (a recording's default character). A project's narration/voices.json overrides it",
" (umtool posts voices); every read asks the same function: the read's own voice, the project's map, the cast, the",
@@ -53,7 +57,7 @@ export const CAST_USAGE = [
" each, picked, awaiting approval). Exit 0 done · 1 refused or failed · 2 usage.",
].join("\n");
-const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]);
+const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]);
const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean);
function parse(args) {
@@ -84,15 +88,33 @@ function fieldsOf(p) {
if (p.str("--speakers") !== null) f.speakers = splitList(p.str("--speakers"));
if (p.str("--avatar") !== null) f.avatar = p.str("--avatar");
if (p.str("--note") !== null) f.note = p.str("--note");
- if (p.str("--convert-engine") !== null || p.str("--convert-voice") !== null) {
+ if (["--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones"].some((k) => p.str(k) !== null)) {
const ce = p.str("--convert-engine");
if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")}`);
- f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}) };
+ const cp = p.str("--convert-pitch");
+ if (cp !== null && !CAST_CONVERT_PITCH.includes(cp)) throw new CastError(`--convert-pitch is one of ${CAST_CONVERT_PITCH.join(", ")}`);
+ const cs = p.str("--convert-semitones") === null ? null : Number(p.str("--convert-semitones"));
+ if (cs !== null && !(p.str("--convert-semitones").trim() !== "" && Number.isFinite(cs) && Math.abs(cs) <= CAST_SEMITONES_MAX)) throw new CastError(`--convert-semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`);
+ // Only the keys given: `set` lays them over the character's entry (convertOver), `add` takes them as they are.
+ f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}), ...(cp ? { pitch: cp } : {}), ...(cs !== null ? { semitones: cs } : {}) };
}
return f;
}
-const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
+/**
+ * A convert entry with the flags' keys laid over it, and what makes no sense together refused in a sentence: the
+ * target's own pitch drops the semitones (nothing is followed to move), 0 semitones is no entry.
+ */
+function convertOver(before, given) {
+ const cv = { ...(before ?? {}), ...given };
+ if (given.pitch === "target" && given.semitones === undefined) delete cv.semitones;
+ if (cv.semitones === 0) delete cv.semitones;
+ const wrong = convertPitchErrors(cv);
+ if (wrong.length) throw new CastError(`convert: ${wrong[0]} (--convert-engine seed-vc --convert-pitch source|contour)`);
+ return cv;
+}
+
+const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}${convertPitchLabel(c.convert) ? `, pitch ${convertPitchLabel(c.convert)}` : ""}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
async function projectOf(ref, reportsRoot) {
const r = await resolveProject(ref, reportsRoot);
@@ -164,13 +186,14 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
if (sub === "add") {
if (at >= 0) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …)`);
if (!f.name || !f.voice) throw new CastError('cast add takes --name "…" and --voice <engine:voice>');
- const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: f.convert } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) };
+ const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: convertOver(null, f.convert) } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) };
if (c.narrator) for (const x of chars) delete x.narrator;
chars.push(c);
return { changed: "added", character: c };
}
if (at < 0) throw new CastError(`no ${id} in the cast (umtool cast ls)`);
- const c = { ...chars[at], ...f };
+ // The convert flags are laid over the entry: --convert-pitch alone keeps its engine and voice.
+ const c = { ...chars[at], ...f, ...(f.convert ? { convert: convertOver(chars[at].convert, f.convert) } : {}) };
for (const h of p.all("--add-handle").map(handleKey)) if (h && !c.handles.includes(h)) c.handles = [...c.handles, h];
for (const h of p.all("--remove-handle").map(handleKey)) c.handles = c.handles.filter((x) => x !== h);
if (p.has("--no-convert")) delete c.convert;
diff --git a/umtool/lib/report/derivePitch.mjs b/umtool/lib/report/derivePitch.mjs
@@ -0,0 +1,58 @@
+// A CONVERT'S PITCH, between umtool and the editor's voice-convert (the pitch a converted read lands on: knobs.md,
+// "The pitch a converted read lands on"). The pure pieces the CLI's derive (postNarrationCli.mjs deriveTake) and the
+// app's (app/api/report/post-narration/route.ts, the post bench's "run AI on take") share, so they ask, record and
+// refuse alike:
+//
+// derivePitchOf what a derive is asked with (`pitch`, `semitones`), checked before any job
+// stepPitchOf what the new take's step keeps: the pitch as the editor RAN it, never the target's own
+// deriveRefusalOf an editor refusal read as "no engine for it" -- or passed through as it is, when it already
+// names the command that fixes it
+//
+// Dependency-free but for cast.mjs's constants.
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast";
+
+/**
+ * A derive's `pitch` / `semitones` as asked (a body's, a flag's): `{ ok: true, value: {pitch?, semitones?} }` with only
+ * what was given, or `{ ok: false, error }`. `semitones` may be a number or its string (a form field, a query). They
+ * are a convert's: asked of another op they are refused.
+ */
+export function derivePitchOf({ pitch, semitones } = {}, op = "convert") {
+ const none = (v) => v === undefined || v === null || v === "";
+ if (none(pitch) && none(semitones)) return { ok: true, value: {} };
+ if (op !== "convert") return { ok: false, error: `pitch and semitones are a convert's: ${op} keeps the read's own pitch` };
+ const value = {};
+ if (!none(pitch)) {
+ if (!CAST_CONVERT_PITCH.includes(pitch)) return { ok: false, error: `pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${JSON.stringify(pitch)})` };
+ value.pitch = pitch;
+ }
+ if (!none(semitones)) {
+ const n = typeof semitones === "number" ? semitones : typeof semitones === "string" && semitones.trim() !== "" ? Number(semitones) : NaN;
+ if (!Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) return { ok: false, error: `semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${JSON.stringify(semitones)})` };
+ value.semitones = n;
+ }
+ return { ok: true, value };
+}
+
+/**
+ * The pitch a derived take's step keeps: what the editor says it ran (its `@@voice-result`: its default when none was
+ * asked), else what was asked. The stock voice's own pitch is not a step's news (`{}`), and 0 semitones is none.
+ */
+export function stepPitchOf(asked = {}, said = {}) {
+ const pitch = typeof said?.pitch === "string" ? said.pitch : asked?.pitch;
+ if (!pitch || pitch === "target" || !CAST_CONVERT_PITCH.includes(pitch)) return {};
+ const n = typeof said?.semitones === "number" ? said.semitones : asked?.semitones;
+ return { pitch, ...(typeof n === "number" && Number.isFinite(n) && n !== 0 ? { semitones: n } : {}) };
+}
+
+/**
+ * An editor refusal of a derive, read: `null` (an ordinary error), or `{ installed: false, error }` -- the editor has
+ * no engine for the op (an older editor has no route; a newer one names the setup to run). A refusal that names an
+ * OPTIONAL group to fetch (`… --with f0`: the engine is there, its pitch-following model is not) is passed through in
+ * the editor's words: "no convert engine installed" would be false.
+ */
+export function deriveRefusalOf(op, status, message) {
+ const msg = String(message ?? "").replace(/^the editor refused it: /, "");
+ if (!(status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg))) return null;
+ if (/--with\b/.test(msg)) return { installed: false, error: msg };
+ return { installed: false, error: `the editor has no ${op} engine installed (not installed: ${msg})` };
+}
diff --git a/umtool/lib/report/derivePitch.test.mjs b/umtool/lib/report/derivePitch.test.mjs
@@ -0,0 +1,65 @@
+// lib/report/derivePitch.mjs: a convert's pitch between umtool and the editor -- what a derive is asked with, what the
+// new take's step keeps, and which editor refusals mean "no engine". The app's derive route
+// (app/api/report/post-narration/route.ts) and the CLI's (postNarrationCli.mjs deriveTake) both go through it.
+// Run: node --test umtool/lib/report/derivePitch.test.mjs
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { validatePostNarration } from "umtool-report-to-video/post-narration";
+import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "./derivePitch.mjs";
+
+test("a derive's pitch as asked: only what was given, a body's number or a query's string, a convert's alone", () => {
+ assert.deepEqual(derivePitchOf({}), { ok: true, value: {} });
+ assert.deepEqual(derivePitchOf({ pitch: null, semitones: "" }), { ok: true, value: {} }, "a query with neither");
+ assert.deepEqual(derivePitchOf({ pitch: "contour", semitones: 2 }), { ok: true, value: { pitch: "contour", semitones: 2 } });
+ assert.deepEqual(derivePitchOf({ pitch: "source", semitones: "-1.5" }), { ok: true, value: { pitch: "source", semitones: -1.5 } });
+ assert.deepEqual(derivePitchOf({ pitch: "target" }), { ok: true, value: { pitch: "target" } });
+ assert.deepEqual(derivePitchOf({ semitones: 0 }), { ok: true, value: { semitones: 0 } }, "0 is said, not dropped: the editor's default may be another");
+ for (const [given, re] of [
+ [{ pitch: "up" }, /^pitch is one of target, source, contour \(got "up"\)$/],
+ [{ pitch: 2 }, /pitch is one of/],
+ [{ pitch: "source", semitones: 13 }, /^semitones is a number from -12 to 12 \(got 13\)$/],
+ [{ pitch: "source", semitones: "two" }, /semitones is a number from -12 to 12 \(got "two"\)/],
+ [{ pitch: "source", semitones: true }, /semitones is a number/],
+ ]) {
+ const r = derivePitchOf(given);
+ assert.equal(r.ok, false, JSON.stringify(given));
+ assert.match(r.error, re);
+ }
+ const en = derivePitchOf({ pitch: "source" }, "enhance");
+ assert.equal(en.ok, false);
+ assert.match(en.error, /pitch and semitones are a convert's: enhance keeps the read's own pitch/);
+ assert.deepEqual(derivePitchOf({}, "enhance"), { ok: true, value: {} });
+});
+
+test("the step keeps the pitch the editor ran, else the one asked; never the target's own, never 0 semitones", () => {
+ assert.deepEqual(stepPitchOf({}, {}), {});
+ assert.deepEqual(stepPitchOf({ pitch: "target" }, {}), {});
+ assert.deepEqual(stepPitchOf({ pitch: "contour", semitones: 2 }, {}), { pitch: "contour", semitones: 2 }, "an editor that says nothing");
+ assert.deepEqual(stepPitchOf({ pitch: "source", semitones: 0 }, null), { pitch: "source" });
+ // The editor's default, when none was asked.
+ assert.deepEqual(stepPitchOf({}, { pitch: "contour", semitones: 2 }), { pitch: "contour", semitones: 2 });
+ // What it ran beats what was asked (its settings' semitones under an asked pitch).
+ assert.deepEqual(stepPitchOf({ pitch: "source" }, { pitch: "source", semitones: -1 }), { pitch: "source", semitones: -1 });
+ assert.deepEqual(stepPitchOf({ pitch: "contour", semitones: 2 }, { pitch: "target" }), {});
+ assert.deepEqual(stepPitchOf({}, { pitch: "sideways" }), {}, "not a pitch the manifest takes");
+ // Whatever it returns is a step the manifest's validator takes.
+ for (const p of [{ pitch: "contour", semitones: 2 }, { pitch: "source" }, {}]) {
+ const entry = { id: "p-1", narration: { script: "x", takes: [{ file: "narration/posts/1/take-2.convert-seed-vc.wav", engine: "derived", voice: "af_bella", seconds: 1, source: { kind: "take", from: "take-1.recorded-operator" }, steps: [{ op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", ...stepPitchOf(p, {}) }] }], pick: 0 } };
+ assert.deepEqual(validatePostNarration(entry).filter((e) => /steps/.test(e)), [], JSON.stringify(p));
+ }
+});
+
+test("an editor refusal: no engine, an ordinary error, or a missing optional model said in the editor's words", () => {
+ assert.deepEqual(deriveRefusalOf("enhance", 404, "HTTP 404"), { installed: false, error: "the editor has no enhance engine installed (not installed: HTTP 404)" });
+ assert.deepEqual(
+ deriveRefusalOf("convert", 400, "the editor refused it: OpenVoice v2 is not installed (/v/openvoice): missing the python venv — run `archilyzer voice setup --engine openvoice`"),
+ { installed: false, error: "the editor has no convert engine installed (not installed: OpenVoice v2 is not installed (/v/openvoice): missing the python venv — run `archilyzer voice setup --engine openvoice`)" },
+ );
+ // seed-vc IS installed; its pitch-following model is not: the editor's sentence, as it is.
+ const f0 = "pitch \"source\" needs Seed-VC (v1, 22 kHz speech)'s f0 model, which is not installed (/v/seed-vc: missing rmvpe.pt) — run `archilyzer voice setup --engine seed-vc --with f0`";
+ assert.deepEqual(deriveRefusalOf("convert", 400, `the editor refused it: ${f0}`), { installed: false, error: f0 });
+ assert.equal(/no convert engine/.test(deriveRefusalOf("convert", 400, f0).error), false);
+ // Not about an install: the caller answers it as the error it is.
+ assert.equal(deriveRefusalOf("convert", 400, "OpenVoice v2 (tone-colour converter) has no pitch control — it lands every read on the target's own pitch"), null);
+ assert.equal(deriveRefusalOf("convert", 400, "\"semitones\" moves a followed pitch"), null);
+});
diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { postsCommand } from "./postsCli.mjs";
-import { importPatches, makeTake, mixPatchOf } from "./postNarrationCli.mjs";
+import { importPatches, makeTake, mixPatchOf, pitchFlags } from "./postNarrationCli.mjs";
import { fitPostItem, rmsFrames, scanAttachment, scoreWindows } from "./postFit.mjs";
import { manifestToken, updatePostNarration } from "./manifest.mjs";
import { postItemPlan } from "umtool-report-to-video/post-item";
@@ -292,6 +292,7 @@ test("a DERIVED take: run through the editor's op into a new take, the original
});
assert.equal(asked.at(-1).route, "/api/ops/voice-enhance");
assert.equal("voice" in asked.at(-1).body, false);
+ assert.equal("pitch" in asked.at(-1).body, false);
assert.equal(e1.take.voice, "operator");
assert.deepEqual([e1.take.steps[0].op, e1.take.steps[0].engine, e1.take.steps[0].voice], ["enhance", "deepfilternet", undefined]);
// A convert that named no target: the stock voice the editor landed on.
@@ -302,7 +303,26 @@ test("a DERIVED take: run through the editor's op into a new take, the original
assert.equal("voice" in asked.at(-1).body, false);
assert.equal(c1.take.voice, "zac");
assert.deepEqual([c1.take.steps[0].engine, c1.take.steps[0].voice], ["openvoice", "zac"]);
- for (const k of [3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k);
+ // A convert's PITCH goes as asked, and the step keeps what the editor says it ran.
+ const c2 = await deriveTake(p, (await manifest(p)).timeline[0], {
+ from: 0, op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2,
+ ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-p", result: { op: "convert", engine: "seed-vc", voice: "af_bella", pitch: "contour", semitones: 2, f0: { targetHz: 197.5, sourceHz: 208.8, shiftSemitones: 1.04 } } }; },
+ });
+ assert.deepEqual([asked.at(-1).body.pitch, asked.at(-1).body.semitones], ["contour", 2]);
+ assert.deepEqual([c2.take.steps[0].pitch, c2.take.steps[0].semitones, c2.take.voice], ["contour", 2, "af_bella"]);
+ // Asked of an enhance, a pitch is not sent; the flags' values are checked in their own names.
+ const e2 = await deriveTake(p, (await manifest(p)).timeline[0], {
+ from: 0, op: "enhance", pitch: "source", semitones: 2,
+ ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-e2", result: { op: "enhance", engine: "deepfilternet" } }; },
+ });
+ assert.deepEqual(["pitch" in asked.at(-1).body, "semitones" in asked.at(-1).body, "pitch" in e2.take.steps[0]], [false, false, false]);
+ const flag = (o) => pitchFlags((k) => o[k] ?? null);
+ assert.deepEqual(flag({}), {});
+ assert.deepEqual(flag({ "--pitch": "source", "--semitones": "-2.5" }), { pitch: "source", semitones: -2.5 });
+ assert.throws(() => flag({ "--pitch": "up" }), /--pitch is one of target, source, contour \(got up\)/);
+ assert.throws(() => flag({ "--semitones": "20" }), /--semitones is a number from -12 to 12 \(got 20\)/);
+ assert.throws(() => flag({ "--semitones": "" }), /--semitones is a number/);
+ for (const k of [5, 4, 3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k);
// An op the editor has no engine for.
const { OpNotInstalled } = await import("umtool-report-to-video/narrate-via-editor");
await assert.rejects(
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -26,6 +26,8 @@ import { promisify } from "node:util";
import {
NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast";
+import { stepPitchOf } from "./derivePitch.mjs";
import { excerptSpansOf, postItemPlan, postReadText } from "umtool-report-to-video/post-item";
import { partRoles } from "umtool-report-to-video/post-thread";
import { spokenRead } from "umtool-report-to-video/post-redact";
@@ -45,6 +47,9 @@ export const NARRATE_USAGE = [
" [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full",
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
" umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]",
+ " [--pitch target|source|contour] [--semitones <n>]",
+ " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v]",
+ " [--pitch target|source|contour] [--semitones <n>]",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]",
" [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]",
" umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new",
@@ -71,6 +76,12 @@ export const NARRATE_USAGE = [
" narrator) -- each a new take, the last picked, the disclosure line said.",
" --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
+ " --pitch target|source|contour [--semitones <n>] (a convert, by --derive or --recording): the PITCH the converted",
+ " read lands on -- target: the stock voice's own (the read's intonation is flattened to it); source: the pitch it",
+ " was read at (raise your voice and it rises); contour: the read's rises and falls, moved as a whole to the stock",
+ " voice's register; --semitones (-12 to 12) then moves a followed pitch. Default: the character's own (umtool cast",
+ " set <id> --convert-pitch …), else the editor's (settings.voice.convert). source and contour are seed-vc's, with",
+ " its f0 model (archilyzer voice setup --engine seed-vc --with f0); the editor refuses what it cannot do.",
" A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,",
" pace=fast plays a post (or, with --cut, every post) back to back: lead 0.1, tail 0.15, ramp 0.3, linger 0.45 --",
" unless it sets one itself; pace=normal the cut's gaps.",
@@ -522,6 +533,7 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
// A RECORDING made a character's read: kept as a take (the original), cleaned, converted to its stock voice.
const r = await importRecording(project, e, str("--recording"), {
as: str("--as"), label: str("--label") ?? "operator", clean: !flags.has("--no-clean"), convert: !flags.has("--no-convert"), note: str("--note"),
+ ...pitchFlags(str),
emit: (_ev, f) => !json && f?.message && out(f.message),
});
if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2));
@@ -537,7 +549,9 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)");
const op = str("--op") ?? "";
try {
- const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), emit: (_ev, f) => !json && f?.message && out(f.message) });
+ const pitched = pitchFlags(str);
+ if (op !== "convert" && (pitched.pitch !== undefined || pitched.semitones !== undefined)) throw new NarrateError("--pitch and --semitones are a convert's (--op convert): an enhance keeps the read's own pitch");
+ const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), ...pitched, emit: (_ev, f) => !json && f?.message && out(f.message) });
if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2));
else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`);
return 0;
@@ -659,16 +673,34 @@ export async function fitCommand(project, refs, { all = false, linger = null, js
return 0;
}
+/** `--pitch` / `--semitones` as a convert takes them (only those given); a value the editor would refuse anyway is refused here, in the flag's name. */
+export function pitchFlags(str) {
+ const out = {};
+ const p = str("--pitch");
+ if (p !== null) {
+ if (!CAST_CONVERT_PITCH.includes(p)) throw new NarrateError(`--pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${p || "nothing"})`);
+ out.pitch = p;
+ }
+ const s = str("--semitones");
+ if (s !== null) {
+ const n = Number(s);
+ if (s.trim() === "" || !Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) throw new NarrateError(`--semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${s || "nothing"})`);
+ out.semitones = n;
+ }
+ return out;
+}
+
/**
* A DERIVED TAKE (post-narration.mjs: "run AI on recorded voice"): take
* `from` (an index) run through the editor's `op` (`enhance`, `convert`) into
* a NEW take -- source `{kind: "take", from: <its id>}`, its step recorded --
* the original untouched; a parted take part by part (its parts kept). The
* editor's op is a job (`POST /api/ops/voice-enhance|voice-convert` with
- * `{file, out, engine?, voice?, params?, parts?}`); one it has no engine for
- * throws OpNotInstalled.
+ * `{file, out, engine?, voice?, pitch?, semitones?, params?, parts?}`); one it has no engine for
+ * throws OpNotInstalled. A convert's `pitch` / `semitones` (the pitch the read lands on: the editor's voice-convert)
+ * go as asked and are kept on the take's step as the editor says it ran them.
*/
-export async function deriveTake(project, e, { from, op, engine = null, voice = null, params = null, emit = () => {}, editor = null, ask = null } = {}) {
+export async function deriveTake(project, e, { from, op, engine = null, voice = null, pitch = null, semitones = null, params = null, emit = () => {}, editor = null, ask = null } = {}) {
const takes = e.narration?.takes ?? [];
const t = takes[from];
if (!t) throw new NarrateError(`${e.id} has no take ${from + 1}`);
@@ -688,6 +720,7 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
const body = {
file: abs(t.file), out: abs(rel),
...(engine ? { engine } : {}), ...(target ? { voice: target } : {}), ...(params ? { params } : {}),
+ ...(op === "convert" && pitch ? { pitch } : {}), ...(op === "convert" && typeof semitones === "number" ? { semitones } : {}),
...(parts ? { parts: t.parts.map((p, k) => ({ file: abs(p.file), out: abs(parts[k].file) })) } : {}),
};
const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
@@ -697,11 +730,13 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
// The editor's defaults, when the ask named none: the engine it ran, the stock voice it landed on.
const ran = engine ?? (typeof said?.engine === "string" ? said.engine : null);
const landed = op === "convert" ? (target ?? (typeof said?.voice === "string" ? said.voice : null)) : null;
+ // The pitch it landed on, as the editor ran it (its default when none was asked); the target's own is not a step's news.
+ const pitched = op === "convert" ? stepPitchOf({ pitch, semitones }, said) : {};
const take = {
// A take's voice is the bare stock voice ("am_michael"); its step keeps the target as asked ("kokoro:am_michael").
file: rel, engine: "derived", voice: (landed ? String(landed).split(":").pop() : null) ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds,
source: { kind: "take", from: takeIdOf(t) },
- steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }],
+ steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...pitched, ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }],
script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId,
...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}),
};
@@ -715,16 +750,17 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
* as a RECORDED take (postRecord.mjs keepRecording: trimmed, levelled -- the original, never overwritten), then a
* derived take CLEANED by the editor's voice-enhance (skipped, and said, when it has no engine for it), then a
* derived take CONVERTED by its voice-convert to the character's STOCK voice (cast.mjs convertTargetOf: its convert
- * voice, else its voice) -- the character `as` names (an id, a handle), else the post's author's in the cast, else
+ * voice, else its voice) at the PITCH asked (`pitch`, `semitones`), else the character's own (its convert entry's),
+ * else the editor's -- the character `as` names (an id, a handle), else the post's author's in the cast, else
* the cast's narrator; none: kept as recorded (and cleaned). Each step a new take, the last one picked, with the
* disclosure line the cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character }`.
*/
-export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, note = null, emit = () => {}, editor = null, ask = null } = {}) {
+export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null } = {}) {
const abs = path.resolve(String(file ?? ""));
if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`);
const { keepRecording } = await import("./postRecord.mjs");
const { castForProject } = await import("./castStore.mjs");
- const { characterOf, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast");
+ const { characterOf, convertPitchLabel, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast");
const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration");
const castRead = await castForProject(project.dir);
const character = as ? findCharacter(castRead.cast, String(as).replace(/^@+/, "")) : characterOf(castRead.cast, e0.handle) ?? narratorOf(castRead.cast);
@@ -753,9 +789,13 @@ export async function importRecording(project, e0, file, { as = null, label = "o
if (!character) notes.push("not converted: no character to convert to (--as <character>, or the post's author or a narrator in the cast: umtool cast add …)");
else {
const target = convertTargetOf(character);
+ // The pitch asked for this read, else the character's; semitones asked of the target's own pitch are dropped
+ // with it (a character kept at "contour +2" read once with --pitch target).
+ const pitched = { pitch: pitch ?? target.pitch ?? null, semitones: semitones ?? (pitch === "target" ? null : target.semitones ?? null) };
try {
- const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, emit, editor, ask });
- takes.push({ step: `converted to ${target.voice}`, file: r.take.file });
+ const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, ...pitched, emit, editor, ask });
+ const how = convertPitchLabel(r.take.steps?.[0]);
+ takes.push({ step: `converted to ${target.voice}${how ? ` (pitch: ${how})` : ""}`, file: r.take.file });
e = await fresh();
} catch (err) {
if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err;
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -195,7 +195,7 @@ export const POSTS_USAGE = [
" none: the rule as it stands",
].join("\n");
-const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]);
+const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]);
/** The valued flags that may be given more than once (each value kept, in order). */
const MULTI = new Set(["--skip-parent", "--voice-for"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs
@@ -10,6 +10,8 @@
// "handles": ["thequartering"], // X handles / channel slugs (no @, lower case)
// "voice": "kokoro:am_michael", // <tts engine>:<stock voice>
// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael" }, // a recording made his (optional)
+// // + "pitch": "source" | "contour" | "target", "semitones": -12…12 -- the pitch a
+// // converted read lands on (seed-vc; the editor's voice-convert, CAST_CONVERT_PITCH)
// "speakers": ["Jeremy"], // his REAL voice's name in a project's speakers.json
// "avatar": "…", "note": "…", "narrator": true } ] }
//
@@ -37,6 +39,14 @@ export const CAST_KEYS = Object.freeze(["id", "name", "handles", "voice", "conve
/** The tts engines a cast voice may name (the editor's tts op), and the convert engines (its voice-convert op). */
export const CAST_TTS_ENGINES = TTS_ENGINE_IDS;
export const CAST_CONVERT_ENGINES = Object.freeze(["openvoice", "seed-vc"]);
+/**
+ * The pitch a converted read lands on (the editor's voice-convert, common/lib/voiceApps.ts VoicePitch): the stock
+ * voice's own (`target`), the pitch it was read at (`source`), or the read's rises and falls at the stock voice's
+ * register (`contour`); `semitones` moves a followed one. The engines that can follow a pitch.
+ */
+export const CAST_CONVERT_PITCH = Object.freeze(["target", "source", "contour"]);
+export const CAST_PITCH_ENGINES = Object.freeze(["seed-vc"]);
+export const CAST_SEMITONES_MAX = 12;
/** Which engine is heavy to run (the operator's rule: Orpheus pins ~8.5 GB; Kokoro first). */
export const ENGINE_WEIGHT = Object.freeze({ kokoro: "fast", "espeak-ng": "fast", orpheus: "heavy" });
@@ -84,8 +94,9 @@ export function validateCast(doc, where = "cast.json") {
if (!isQualifiedVoice(c.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(c.voice)})`);
if (c.convert !== undefined) {
const cv = c.convert;
- if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?}`);
+ if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice", "pitch", "semitones"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?, pitch?, semitones?}`);
else {
+ errors.push(...convertPitchErrors(cv).map((m) => `${w}.convert.${m}`));
if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.convert.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`);
if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.convert.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`);
}
@@ -130,9 +141,41 @@ export function castVoiceMap(cast) {
return out;
}
-/** A character's convert target -- what a recording is made into: its convert voice, else its voice. */
+/**
+ * What is wrong with a convert entry's pitch (`{engine?, pitch?, semitones?}`), as sentences that start at the key:
+ * the mode is one of CAST_CONVERT_PITCH, the semitones a number within CAST_SEMITONES_MAX, a followed pitch is an
+ * engine's that can follow one (CAST_PITCH_ENGINES; an entry with no engine takes the editor's default, which answers
+ * for itself), and semitones move a FOLLOWED pitch. The editor's op refuses the same things in its own words.
+ */
+export function convertPitchErrors(cv) {
+ const errors = [];
+ const { engine, pitch, semitones } = cv ?? {};
+ if (pitch !== undefined && !CAST_CONVERT_PITCH.includes(pitch)) errors.push(`pitch must be one of ${CAST_CONVERT_PITCH.join(", ")}`);
+ if (semitones !== undefined && !(typeof semitones === "number" && Number.isFinite(semitones) && Math.abs(semitones) <= CAST_SEMITONES_MAX)) errors.push(`semitones must be a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`);
+ if (errors.length) return errors;
+ const follows = pitch === "source" || pitch === "contour";
+ if (follows && engine !== undefined && !CAST_PITCH_ENGINES.includes(engine)) errors.push(`pitch "${pitch}" is ${CAST_PITCH_ENGINES.join(", ")}'s: ${engine} lands every read on the target's own pitch`);
+ if (semitones && !follows) errors.push(`semitones moves a followed pitch: it needs pitch source or contour`);
+ return errors;
+}
+
+/** How a convert entry's (or a step's) pitch is said: "contour +2 st", "source", "" for the target's own. */
+export function convertPitchLabel(cv) {
+ if (!cv?.pitch || cv.pitch === "target") return "";
+ const n = Number(cv.semitones) || 0;
+ return n ? `${cv.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : cv.pitch;
+}
+
+/**
+ * A character's convert target -- what a recording is made into: its convert voice, else its voice -- and, when the
+ * entry says one, the pitch the read lands on (`pitch`, `semitones`; absent: the editor's default).
+ */
export function convertTargetOf(c) {
- return { engine: c?.convert?.engine ?? null, voice: c?.convert?.voice ?? c?.voice ?? null };
+ const cv = c?.convert;
+ return {
+ engine: cv?.engine ?? null, voice: cv?.voice ?? c?.voice ?? null,
+ ...(cv?.pitch !== undefined ? { pitch: cv.pitch } : {}), ...(cv?.semitones !== undefined ? { semitones: cv.semitones } : {}),
+ };
}
/** The names a character's real voice may go by in a project's speakers.json (lower case, no punctuation). */
diff --git a/umtool/report-to-video/cast.test.mjs b/umtool/report-to-video/cast.test.mjs
@@ -4,7 +4,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
- castDrift, castVoiceMap, characterOf, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf,
+ castDrift, castVoiceMap, characterOf, convertPitchLabel, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf,
} from "./cast.mjs";
import { resolvePieceVoice, validateVoiceMap, voiceForPiece, voiceOverridesOf, voiceSourceOf } from "./post-say.mjs";
@@ -34,6 +34,16 @@ test("validateCast: the shape, ids, one owner a handle, stock voices only, one n
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, voice: "/tmp/jeremy.wav" }] }).some((e) => /STOCK voice with its engine/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, convert: { voice: "me.wav" } }] }).some((e) => /never a file/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, narrator: true }, S] }).some((e) => /one character at most is the narrator/.test(e)));
+ // The pitch a converted read lands on: a mode, semitones in range, and only what an engine can follow.
+ const conv = (convert) => validateCast({ ...emptyCast(), characters: [{ ...Q, convert }] });
+ assert.deepEqual(conv({ engine: "seed-vc", pitch: "contour", semitones: 2 }), []);
+ assert.deepEqual(conv({ pitch: "source" }), [], "no engine: the editor's default answers for itself");
+ assert.deepEqual(conv({ engine: "openvoice", pitch: "target" }), []);
+ assert.ok(conv({ pitch: "high" }).some((e) => /convert\.pitch must be one of target, source, contour/.test(e)));
+ assert.ok(conv({ pitch: "source", semitones: 13 }).some((e) => /convert\.semitones must be a number from -12 to 12/.test(e)));
+ assert.ok(conv({ engine: "openvoice", pitch: "contour" }).some((e) => /convert\.pitch "contour" is seed-vc's: openvoice lands every read on the target's own pitch/.test(e)));
+ assert.ok(conv({ engine: "seed-vc", semitones: 2 }).some((e) => /convert\.semitones moves a followed pitch/.test(e)));
+ assert.ok(conv({ engine: "seed-vc", speed: 2 }).some((e) => /convert must be \{engine\?, voice\?, pitch\?, semitones\?\}/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, handles: ["@TheQuartering"] }] }).some((e) => /lower case, no @/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, extra: 1 }] }).some((e) => /extra is not a character key/.test(e)));
});
@@ -47,6 +57,8 @@ test("a character by handle, id or name; the narrator; a recording's target; the
assert.deepEqual(castVoiceMap(cast), { thequartering: "kokoro:am_michael", madamsavvy: "orpheus:tara" });
assert.deepEqual(convertTargetOf(S), { engine: "seed-vc", voice: "orpheus:tara" });
assert.deepEqual(convertTargetOf({ ...Q, convert: { voice: "kokoro:am_onyx" } }), { engine: null, voice: "kokoro:am_onyx" });
+ assert.deepEqual(convertTargetOf({ ...S, convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }), { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 });
+ assert.deepEqual([convertPitchLabel(undefined), convertPitchLabel({ pitch: "target" }), convertPitchLabel({ pitch: "source" }), convertPitchLabel({ pitch: "contour", semitones: 2 }), convertPitchLabel({ pitch: "source", semitones: -1.5 })], ["", "", "source", "contour +2 st", "source −1.5 st"]);
const speakers = [{ name: "Jeremy" }, { name: "Melonie Mac" }];
assert.equal(speakerFor(Q, speakers)?.name, "Jeremy");
assert.equal(speakerFor({ id: "mm", name: "MelonieMac", handles: [] }, speakers)?.name, "Melonie Mac", "the name, its punctuation and case aside");
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -49,6 +49,8 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco
* { kind: "recorded", voice } a person's own read, recorded on the bench
* { kind: "take", from: <take id> } DERIVED: a new take made from another
* steps [{ op, engine?, params?, ranAt, job? }] the processing that made a derived take
+ * (a convert's also `voice`, the stock target, and -- when the read's pitch was FOLLOWED rather than
+ * flattened to the stock voice's -- `pitch: "source" | "contour"` and `semitones`, as the editor ran them)
*
* A derived take never overwrites the one it came from. Its ops are the
* editor's (each a job, like tts): `enhance` (denoise, level, de-reverb) and
@@ -190,7 +192,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz",
const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]);
const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]);
const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read"]);
-const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
+const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
// `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's;
// `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs).
// `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1).
@@ -661,6 +663,9 @@ export function validatePostNarration(e) {
if (!isObj(st) || !(POST_DERIVE_OPS.includes(st.op) || POST_LOCAL_OPS.includes(st.op))) errors.push(`${tw}.steps[${k}].op must be one of ${[...POST_DERIVE_OPS, ...POST_LOCAL_OPS].join(", ")}`);
else {
for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`);
+ // A convert's followed pitch, as the editor ran it.
+ if (st.pitch !== undefined && !["target", "source", "contour"].includes(st.pitch)) errors.push(`${tw}.steps[${k}].pitch must be target, source or contour`);
+ if (st.semitones !== undefined && !(fin(st.semitones) && Math.abs(st.semitones) <= 12)) errors.push(`${tw}.steps[${k}].semitones must be a number from -12 to 12`);
// A re-join's record: what it left out (a piece, "part <n>", "url").
if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`);
// A tempo step's record: each run of parts ("4-16", "21") and the tempo it reads at.