Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2a7883cf8aad9d26ad06e4330de2940b57eca989
parent 5b9035bdf2854ce02cb33f57be4d00e70a5aa7b5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 19:24:50 -0500

Merge lane/characters: a character is a preset -- a synthetic voice and speed, and for a recording its convert voice, pitch, clean-up, trim and a direction note; a video keeps characters of its own (anonymous ones never enter the cast), a post may name its character, and the Voices page edits them

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/app/api/report/post-narration/route.ts | 24++++++++++++++++--------
Mumtool/app/api/report/voices/route.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/components/projects/CharacterPresets.tsx | 379+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/VoicesPanel.tsx | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/docs/cli.md | 23++++++++++++++++-------
Mumtool/docs/knobs.md | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/e2e/voices.spec.ts | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/cli/groups.mjs | 26++++++++++++++++----------
Mumtool/lib/cli/verbs.mjs | 39++++++++++++++++++++++++++++++---------
Mumtool/lib/report/cast.test.mjs | 5+++--
Mumtool/lib/report/castAudition.mjs | 11+++++++++--
Mumtool/lib/report/castCli.mjs | 435++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/report/castProject.mjs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mumtool/lib/report/castStore.mjs | 128++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Aumtool/lib/report/characterLayers.mjs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/characters.test.mjs | 429+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/lintCli.mjs | 7+++++--
Mumtool/lib/report/manifest.mjs | 2+-
Mumtool/lib/report/postNarrationCli.mjs | 141++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/report/postRecord.mjs | 9++++++---
Mumtool/lib/report/postRevoice.mjs | 8++++++--
Mumtool/lib/report/postRevoice.test.mjs | 20++++++++++++++++++++
Mumtool/lib/report/postSay.mjs | 12+++++++++---
Mumtool/lib/report/postThreadRead.mjs | 82+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mumtool/lib/report/postsCli.mjs | 12++++++++++++
Mumtool/lib/report/readVoice.mjs | 24++++++++++++++----------
Mumtool/lib/report/recordSession.mjs | 4+++-
Mumtool/report-to-video/cast.mjs | 402+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Aumtool/report-to-video/characters.test.mjs | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-narration.mjs | 8++++++--
Mumtool/report-to-video/post-say.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
32 files changed, 2673 insertions(+), 365 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased] - **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published. +- **umtool: a character is a preset, and a video can have characters of its own.** The operator wanted "a preset of voice and other settings" per character, applied to that author's posts, anonymous characters with their own profile per video, a pool reused across videos, and different presets for synthetic and recorded voices. A cast character now carries two presets. `synthetic` is the stock voice and its speed. `recorded` is what a recording of them is made into: the stock voice it is converted to, the engine, the pitch and semitones, whether it is cleaned first, whether its edges are trimmed and how much room is kept, and a one-line direction for the person reading, which is never sent to a model. An existing `cast.json` (`voice`, `convert`) reads as these presets, and the first write makes it version 2; `umtool cast undo` puts the old file back. A video's own characters live in `<project>/narration/characters.json`, for people who must not enter the pool. An anonymous one goes by a shown name, "Anon 1", "Anon 2" by default, on the Voices page, in `umtool cast project` and in a recording's note, and is refused the pool. `narration/voices.json` keeps working and is not rewritten. A post item can name its own character (`umtool posts character <p> <item> <id>`, `--clear`). One read asks, first hit wins: the command's flags, the item's character, the video's character for the author, the cast's, the narrator's, the default. `umtool cast project <p>` prints the answer and its source for each author. A thread read ignored `--speed`: each part is now asked at its character's speed, and `--speed` sets every part. A recording made a read (`posts narrate --recording`) applies its character's clean and trim settings; `--clean`, `--no-clean`, `--trim` and `--no-trim` override them for one read. The Voices page edits both presets, keeps the video's own characters, and has "Add to the pool" and "Keep in this video only"; none of it needs an agent. New: `umtool cast set <id> --speed --enhance --trim --trim-pad --direction`, `umtool cast project <p> add|set|rm|undo|pool|keep`. A convert target is still always a stock synthetic voice, and the disclosure line is unchanged. Not built yet: the on-screen card is not anonymised (a cut still shows the post's author for an anonymous character), and the record page does not show the direction (umtool/docs/knobs.md, "A character is a preset"). - **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. diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -21,8 +21,8 @@ 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 { recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast"; +import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs"; import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs"; export const dynamic = "force-dynamic"; @@ -89,9 +89,12 @@ export async function GET(request: Request) { // 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 }); + // The chain a recording asks (cast.mjs characterForRead): the item's own character, this video's for the author, the + // cast's, the narrator -- and its recorded preset (what the record page will read: the direction, clean, trim). + const who = (await readLayers(r.project.dir)).characterForRead(e); + const c = who?.character ?? null; + const preset = c ? recordedPresetOf(c) : null; + return Response.json({ character: c ? { id: c.id, name: shownNameOf(c), layer: who.layer } : null, convert: preset ? preset.convert : null, ...(preset ? { recorded: { enhance: preset.enhance, trim: preset.trim, direction: preset.direction } } : {}) }, { 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 @@ -239,7 +242,8 @@ async function postHere(request: Request) { const k = postNarrationKnobs(e, (m.render ?? {}) as Record<string, unknown>); const script = String(body.script ?? e.narration?.script ?? "").trim(); if (!script) return Response.json({ error: `${id} has no script to read` }, { status: 400 }); - // The voice: the one asked for, the project's voice map, the CAST, the narrator's -- a single read's rule (readVoice.mjs). + // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the + // narrator's -- a single read's rule (readVoice.mjs). const said = await itemReadVoice(r.project, e, { render: (m.render ?? {}) as Record<string, unknown>, engine: typeof body.engine === "string" && body.engine ? body.engine : null, @@ -251,7 +255,10 @@ async function postHere(request: Request) { const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/")); await mkdir(dir, { recursive: true }); const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice); - const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed); + // Its speed: the one asked for, else the item's own (`narration.speed`), else its character's (the synthetic + // preset's that answered for the voice) -- makeTake's order. + const askedSpeed = body.speed === undefined || body.speed === null ? (e.narration as { speed?: number } | undefined)?.speed ?? (said as { speed?: number }).speed : Number(body.speed); + const speed = askedSpeed === undefined || askedSpeed === null || engine === "orpheus" ? undefined : Number(askedSpeed); // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's // filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.mjs); the script is kept as written. The bench cannot word-time a take as it is made, // so a beep falls back to skip here (the CLI's --take times it and beeps). @@ -394,7 +401,8 @@ async function record(request: Request) { } const script = form.get("script"); const note = form.get("note"); - const kept = await keepRecording(r.project, e, parts, { label, manifest: m, note: note ? String(note) : null, script: script === null ? null : String(script) }); + // Its character's recorded preset says whether its edges are trimmed, and the room kept (characterLayers.mjs). + const kept = await keepRecording(r.project, e, parts, { label, manifest: m, note: note ? String(note) : null, script: script === null ? null : String(script), trim: await recordedTrimFor(r.project.dir, e) }); return Response.json({ ok: true, take: kept.take, gain: kept.gain, target: kept.target, token: kept.result.token, entry: kept.result.entry }, { headers: noStore }); } catch (err) { return fail(err); diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts @@ -32,7 +32,15 @@ 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?, convertPitch?, convertSemitones?, narrator? } +// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, convertPitch?, convertSemitones?, narrator?, …the preset fields } +// POST { project, op: "character-set", scope: "cast" | "project", id, name?, voice?, speed?, convertEngine?, convertVoice?, convertPitch?, +// convertSemitones?, enhance?, trim?, trimPad?, direction?, handles?, anonymous?, shown? } a character's PRESETS (umtool cast set / +// cast project <p> set): "" or null for a field puts its default back +// POST { project, op: "character-add", id, name?, voice?, handles?, anonymous?, shown? } one of THIS VIDEO's own (cast project <p> add) +// POST { project, op: "character-rm", id } | { op: "characters-undo" } cast project <p> rm | undo +// POST { project, op: "character-pool", id } "Add to the pool": cast project <p> pool <id> +// POST { project, op: "character-keep", who, anonymous? } "Keep in this video only": cast project <p> keep <character|@handle> +// POST { project, op: "item-character", item, character: <id> | null } umtool posts character <p> <item> <id> | --clear // 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" }; @@ -50,6 +58,51 @@ async function cli(args: string[]) { return { code, json, error: code === 0 ? null : (json?.error as string | undefined) ?? (err.join("\n") || "refused") }; } +/** `umtool posts character …`, run here (its JSON, or its refusal in its words). */ +async function postsCli(args: string[]) { + const { postsCommand } = await import("@/lib/report/postsCli.mjs"); + const said: string[] = []; + const errs: string[] = []; + const code = await postsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (x: string) => said.push(x), err: (x: string) => errs.push(x) }); + let json: Record<string, unknown> | null = null; + try { + json = JSON.parse(said.join("\n") || "null"); + } catch { + json = null; + } + return { code, json, error: code === 0 ? null : (errs.join("\n") || said.join("\n") || "refused").replace(/^umtool posts: /, "") }; +} + +/** + * A character's preset fields as the CLI's flags (castCli.mjs fieldsOf: it refuses what makes no sense). A field + * that is "" or null puts its default back; one that is absent is left as it is. + */ +function presetArgs(b: Record<string, unknown>): string[] { + const args: string[] = []; + const has = (k: string) => b[k] !== undefined; + const blank = (k: string) => b[k] === null || b[k] === ""; + const val = (k: string) => String(b[k]).trim(); + if (has("name") && !blank("name")) args.push("--name", val("name")); + if (has("handles")) args.push("--handles", (Array.isArray(b.handles) ? b.handles.map(String) : String(b.handles ?? "").split(",")).map((h) => h.trim()).filter(Boolean).join(",")); + if (has("voice")) args.push(...(blank("voice") ? ["--no-voice"] : ["--voice", val("voice")])); + if (has("speed")) args.push(...(blank("speed") ? ["--no-speed"] : ["--speed", val("speed")])); + if (has("convertEngine")) args.push("--convert-engine", blank("convertEngine") ? "default" : val("convertEngine")); + if (has("convertVoice")) args.push("--convert-voice", blank("convertVoice") ? "default" : val("convertVoice")); + if (has("convertPitch")) args.push("--convert-pitch", blank("convertPitch") ? "default" : val("convertPitch")); + if (has("convertSemitones")) args.push("--convert-semitones", blank("convertSemitones") ? "0" : val("convertSemitones")); + const onOff = (k: string) => (blank(k) ? "default" : b[k] === true || b[k] === "on" ? "on" : b[k] === false || b[k] === "off" ? "off" : val(k)); + if (has("enhance")) args.push("--enhance", onOff("enhance")); + if (has("trim")) args.push("--trim", onOff("trim")); + if (has("trimPad")) args.push("--trim-pad", blank("trimPad") ? "default" : val("trimPad")); + if (has("direction")) args.push("--direction", blank("direction") ? "" : val("direction")); + if (b.anonymous === true || b.anonymous === "on") args.push("--anonymous"); + if (b.anonymous === false || b.anonymous === "off") args.push("--no-anonymous"); + if (has("shown") && !blank("shown")) args.push("--shown", val("shown")); + if (b.narrator === true || b.narrator === "on") args.push("--narrator"); + if (b.narrator === false || b.narrator === "off") args.push("--no-narrator"); + return args; +} + /** The checkout's heavy-slot CLI, when this umtool sits in the checkout (speakerCheck.mjs's rule). */ function queueLockScript() { const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs"); @@ -166,6 +219,8 @@ export async function POST(request: Request) { const r = await cli(["undo"]); return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers }); } + const answer = (r: { code: number; json: Record<string, unknown> | null; error: string | null }) => Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers }); + const idOk = (v: string) => /^[a-z0-9][a-z0-9_-]{0,47}$/.test(v); if (op === "cast-set") { const args = ["set", s("id")]; if (s("convertEngine")) args.push("--convert-engine", s("convertEngine")); @@ -175,8 +230,36 @@ export async function POST(request: Request) { 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")); - const r = await cli(args); - return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers }); + return answer(await cli(args)); + } + // A CHARACTER's PRESETS, the cast's or this video's own -- each the CLI's own command (castCli.mjs). + if (op === "character-set" || op === "character-add") { + const id = s("id"); + if (!idOk(id)) return Response.json({ error: "a character's id is lower case letters, digits, - and _" }, { status: 400 }); + const own = op === "character-add" || s("scope") === "project"; + const head = own ? ["project", project.id, op === "character-add" ? "add" : "set", id] : ["set", id]; + return answer(await cli([...head, ...presetArgs(b)])); + } + if (op === "character-rm") { + if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 }); + return answer(await cli(["project", project.id, "rm", s("id")])); + } + if (op === "characters-undo") return answer(await cli(["project", project.id, "undo"])); + if (op === "character-pool") { + if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 }); + return answer(await cli(["project", project.id, "pool", s("id")])); + } + if (op === "character-keep") { + const who = s("who"); + if (!/^@?[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(who)) return Response.json({ error: "keep takes a cast character's id, or an author (@handle)" }, { status: 400 }); + return answer(await cli(["project", project.id, "keep", who, ...(b.anonymous === true ? ["--anonymous"] : []), ...(s("shown") ? ["--shown", s("shown")] : [])])); + } + if (op === "item-character") { + const item = s("item"); + if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(item)) return Response.json({ error: "which post item?" }, { status: 400 }); + const id = s("character"); + if (id && !idOk(id)) return Response.json({ error: "which character?" }, { status: 400 }); + return answer(await postsCli(["character", project.id, item, id || "--clear"])); } if (op === "recording") { const file = form?.get("file"); @@ -195,7 +278,7 @@ export async function POST(request: Request) { const job = startJob(`cast-recording ${project.id}`, [{ label: `${item}: the recording kept, cleaned, converted`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000 }], { project: project.id }); return Response.json({ ok: true, job: jobView(job), file: path.relative(project.dir, abs) }, { headers }); } - return Response.json({ error: "op must be audition, use, reread, cast-rm, cast-undo, cast-set or recording" }, { status: 400 }); + return Response.json({ error: "op must be audition, use, reread, cast-rm, cast-undo, cast-set, character-set, character-add, character-rm, characters-undo, character-pool, character-keep, item-character or recording" }, { status: 400 }); } catch (e) { const status = (e as { status?: number }).status ?? 400; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); diff --git a/umtool/components/projects/CharacterPresets.tsx b/umtool/components/projects/CharacterPresets.tsx @@ -0,0 +1,379 @@ +"use client"; + +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// A CHARACTER IS A PRESET (components/projects/VoicesPanel.tsx; /api/report/voices; the CLI is `umtool cast set`, +// `umtool cast project <p> add|set|rm|undo|pool|keep`, `umtool posts character`). Works with the operator alone: +// every field is a form field, every write the CLI's own command -- nothing here needs an agent. +// +// PresetEditor one character's two presets: SYNTHETIC (the stock voice, its speed) and RECORDED (what a +// recording of them is made into: the stock voice it is converted to, the engine, the pitch +// and semitones, cleaned or not, its edges trimmed or not and the room kept, and a DIRECTION +// -- one line for the person reading, never sent to a model) -- the cast's or this video's own +// ProjectCharacters THIS VIDEO's OWN characters (narration/characters.json): people who must not enter the pool +// (anonymous ones go by "Anon 1" … here and in recording notes; the cut's card is not anonymised yet), add one, remove one, undo, "Add to the +// pool"; and the post items that name a character of their own +// --------------------------------------------------------------------------- + +export type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number }; +export type Synthetic = { voice?: string; speed?: number }; +export type Recorded = { convert?: Convert; enhance?: boolean; trim?: { on?: boolean; padMs?: number }; direction?: string }; +export type PresetCharacter = { + id: string; name: string; handles?: string[]; voice?: string; convert?: Convert; synthetic?: Synthetic; recorded?: Recorded; + speakers?: string[]; note?: string; narrator?: boolean; anonymous?: boolean; shown?: string; layer?: "cast" | "project"; +}; +export type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string }; +export type ItemCharacter = { id: string; handle: string | null; character: string; found: boolean; layer: "cast" | "project" | null; name?: string; voice: { spec: string; from: string; speed?: number } }; +type Post = { id: string; handle: string; author: string; text: string }; +type PostFn = (body: Record<string, unknown>) => Promise<Record<string, unknown> | null>; + +const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal"; +const pretty = (spec: string) => spec.replace(":", " · "); + +/** A recorded preset in words: "a recording → kokoro · am_michael (seed-vc), pitch contour +2 st · not cleaned · …". */ +export function recordedWords(c: PresetCharacter): string { + const rec = c.recorded; + if (!rec) return ""; + const bits: string[] = []; + const cv = rec.convert; + if (cv) { + const n = Number(cv.semitones) || 0; + const pitch = cv.pitch && cv.pitch !== "target" ? `, pitch ${cv.pitch}${n ? ` ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : ""}` : ""; + bits.push(`a recording → ${pretty(cv.voice ?? c.voice ?? "?")}${cv.engine ? ` (${cv.engine})` : ""}${pitch}`); + } + if (rec.enhance === false) bits.push("not cleaned"); + if (rec.trim?.on === false) bits.push("edges not trimmed"); + else if (typeof rec.trim?.padMs === "number") bits.push(`trim pad ${rec.trim.padMs} ms`); + if (rec.direction) bits.push(`direction: “${rec.direction}”`); + return bits.join(" · "); +} + +/** A stock voice picked as engine + voice; `none` (a label) offers "no voice of its own". */ +function VoicePick({ value, onChange, engines, none = null, name }: { value: string; onChange: (v: string) => void; engines: Engine[]; none?: string | null; name: string }) { + const at = value.indexOf(":"); + const eng = at > 0 ? value.slice(0, at) : ""; + const voice = at > 0 ? value.slice(at + 1) : ""; + const engine = engines.find((e) => e.id === eng) ?? null; + // A voice the editor's list does not carry (an older cast entry) stays selectable as it is. + const voices = engine ? (engine.voices.includes(voice) || !voice ? engine.voices : [voice, ...engine.voices]) : []; + return ( + <span className="inline-flex items-center gap-1"> + <select + data-preset-engine={name} + aria-label={`${name}: the engine`} + value={eng} + onChange={(e) => { + const next = engines.find((x) => x.id === e.target.value); + onChange(next ? `${next.id}:${next.defaultVoice || next.voices[0] || ""}` : ""); + }} + className={input} + > + {none !== null && <option value="">{none}</option>} + {none === null && !engine && <option value="">an engine…</option>} + {engines.map((e) => ( + <option key={e.id} value={e.id}> + {e.label} + </option> + ))} + </select> + {engine && ( + <select data-preset-voice={name} aria-label={`${name}: the voice`} value={voice} onChange={(e) => onChange(`${engine.id}:${e.target.value}`)} className={input}> + {voices.map((v) => ( + <option key={v} value={v}> + {v} + </option> + ))} + </select> + )} + </span> + ); +} + +type Form = { + name: string; shown: string; voice: string; speed: string; convertVoice: string; convertEngine: string; convertPitch: string; convertSemitones: string; + enhance: boolean; trim: boolean; trimPad: string; direction: string; +}; +const formOf = (c: PresetCharacter): Form => ({ + name: c.name ?? "", + shown: c.shown ?? "", + voice: c.synthetic?.voice ?? c.voice ?? "", + speed: typeof c.synthetic?.speed === "number" ? String(c.synthetic.speed) : "", + convertVoice: c.recorded?.convert?.voice ?? "", + convertEngine: c.recorded?.convert?.engine ?? "", + convertPitch: c.recorded?.convert?.pitch ?? "", + convertSemitones: typeof c.recorded?.convert?.semitones === "number" ? String(c.recorded.convert.semitones) : "", + enhance: c.recorded?.enhance !== false, + trim: c.recorded?.trim?.on !== false, + trimPad: typeof c.recorded?.trim?.padMs === "number" ? String(c.recorded.trim.padMs) : "", + direction: c.recorded?.direction ?? "", +}); + +/** + * ONE CHARACTER's PRESETS, editable: Save is `umtool cast set <id> …` (scope "cast": every project) or `umtool cast + * project <p> set <id> …` (scope "project": this video only). A field left empty is its default again. + */ +export function PresetEditor({ + c, scope, engines, convertEngines, busy, post, onSaved, onClose, +}: { + c: PresetCharacter; scope: "cast" | "project"; engines: Engine[]; convertEngines: string[]; busy: boolean; post: PostFn; onSaved: (what: string) => void; onClose: () => void; +}) { + // (The panel keys this editor by the character as it is stored: another one opened, or this one saved, is a new form.) + const [f, setF] = useState<Form>(() => formOf(c)); + const set = <K extends keyof Form>(k: K, v: Form[K]) => setF((x) => ({ ...x, [k]: v })); + const follows = f.convertPitch === "source" || f.convertPitch === "contour"; + const save = async () => { + const j = await post({ + op: "character-set", scope, id: c.id, + ...(f.name.trim() && f.name.trim() !== c.name ? { name: f.name.trim() } : {}), + ...(c.anonymous && f.shown.trim() && f.shown.trim() !== (c.shown ?? "") ? { shown: f.shown.trim() } : {}), + voice: f.voice, speed: f.voice ? f.speed : "", + convertVoice: f.convertVoice, convertEngine: f.convertEngine, convertPitch: f.convertPitch, convertSemitones: follows ? f.convertSemitones : "", + // On is the default: said only when it is off, so a preset nobody touched stays as short as it was. + enhance: f.enhance ? "" : "off", trim: f.trim ? (f.trimPad.trim() ? "on" : "") : "off", trimPad: f.trim ? f.trimPad.trim() : "", + direction: f.direction.trim(), + }); + if (j) onSaved(`${c.name}: its presets saved ${scope === "cast" ? "in the cast (every project)" : "for this video only"}`); + }; + const row = "flex flex-wrap items-center gap-x-3 gap-y-1.5"; + const lab = "inline-flex items-center gap-1.5"; + return ( + <section className="rounded-[4px] border border-seam-2 p-3" data-preset-editor={c.id} data-preset-scope={scope}> + <h2 className="micro mb-2"> + presets · {c.anonymous ? `${c.shown} (anonymous)` : c.name} + <span className="ml-2 normal-case tracking-normal text-muted">{scope === "cast" ? "the cast: the same in every project" : "this video only"}</span> + </h2> + <div className={row}> + <label className={lab}> + <span className="text-muted">name</span> + <input data-preset-name="" value={f.name} onChange={(e) => set("name", e.target.value)} maxLength={80} className={cn(input, "w-44")} /> + </label> + {c.anonymous && ( + <label className={lab} title="the name it goes by on this page, in `umtool cast project` and in a recording's note — the cut's on-screen card is not anonymised yet: it still shows the post's author"> + <span className="text-muted">shown as</span> + <input data-preset-shown="" value={f.shown} onChange={(e) => set("shown", e.target.value)} maxLength={80} className={cn(input, "w-32")} /> + </label> + )} + </div> + <h3 className="micro mb-1 mt-3">synthetic · a read the editor synthesizes</h3> + <div className={row}> + <span className={lab}> + <span className="text-muted">voice</span> + <VoicePick name="voice" value={f.voice} onChange={(v) => set("voice", v)} engines={engines} none={scope === "project" ? "none of its own (the cast's, the narrator's…)" : null} /> + </span> + <label className={lab} title="the tts op's speed, 0.5–2 (empty: 1). Orpheus has no speed: it is not asked one."> + <span className="text-muted">speed</span> + <input data-preset-speed="" type="number" min={0.5} max={2} step={0.05} value={f.speed} disabled={!f.voice} onChange={(e) => set("speed", e.target.value)} placeholder="1" className={cn(input, "w-16")} /> + {f.voice.startsWith("orpheus:") && f.speed && <span className="text-[11px] text-doubt-text">Orpheus has no speed</span>} + </label> + </div> + <h3 className="micro mb-1 mt-3">recorded · a recording of them, made their read</h3> + <div className={row}> + <span className={lab} title="always a STOCK synthetic voice: a file or a recording is never a target"> + <span className="text-muted">converted to</span> + <VoicePick name="convert" value={f.convertVoice} onChange={(v) => set("convertVoice", v)} engines={engines} none={f.voice ? `its own voice (${pretty(f.voice)})` : "its own voice"} /> + </span> + <label className={lab}> + <span className="text-muted">by</span> + <select data-preset-convert-engine="" value={f.convertEngine} onChange={(e) => set("convertEngine", e.target.value)} className={input}> + <option value="">the editor&apos;s default</option> + {convertEngines.map((e) => ( + <option key={e} value={e}> + {e} + </option> + ))} + </select> + </label> + <label className={lab} title="where the converted read's pitch comes from: the stock voice's own, the pitch you read at, or your rises and falls at the stock voice's register (source and contour are seed-vc's)"> + <span className="text-muted">pitch</span> + <select data-preset-pitch="" value={f.convertPitch} onChange={(e) => set("convertPitch", e.target.value)} className={input}> + <option value="">the editor&apos;s default</option> + <option value="target">target — the stock voice&apos;s own</option> + <option value="source">source — the pitch you read at</option> + <option value="contour">contour — your intonation, its register</option> + </select> + </label> + <label className={lab} title="moves a followed pitch (source, contour), −12…12"> + <span className="text-muted">semitones</span> + <input data-preset-semitones="" type="number" min={-12} max={12} step={0.5} value={follows ? f.convertSemitones : ""} disabled={!follows} onChange={(e) => set("convertSemitones", e.target.value)} placeholder="0" className={cn(input, "w-14")} /> + </label> + </div> + <div className={cn(row, "mt-1.5")}> + <label className="inline-flex items-center gap-1" title="the editor's voice-enhance (DeepFilterNet), before the convert"> + <input type="checkbox" data-preset-enhance="" checked={f.enhance} onChange={(e) => set("enhance", e.target.checked)} /> clean it first + </label> + <label className="inline-flex items-center gap-1" title="the silence (and a key click) before and after the words cut away"> + <input type="checkbox" data-preset-trim="" checked={f.trim} onChange={(e) => set("trim", e.target.checked)} /> trim its edges to speech + </label> + <label className={lab} title="the room kept either side of the words, milliseconds (empty: the recorder's own, 80 before and 150 after)"> + <span className="text-muted">pad</span> + <input data-preset-trim-pad="" type="number" min={0} max={2000} step={10} value={f.trim ? f.trimPad : ""} disabled={!f.trim} onChange={(e) => set("trimPad", e.target.value)} placeholder="default" className={cn(input, "w-20")} /> + <span className="text-muted">ms</span> + </label> + </div> + <label className="mt-1.5 flex flex-wrap items-center gap-1.5"> + <span className="text-muted">direction</span> + <input data-preset-direction="" value={f.direction} onChange={(e) => set("direction", e.target.value)} maxLength={200} placeholder="higher, brisk, amused" className={cn(input, "w-[26rem] max-w-full")} /> + <span className="text-[11px] text-muted">one line for the person reading — never sent to a model</span> + </label> + <div className="mt-2.5 flex flex-wrap gap-1.5"> + <button type="button" data-preset-save="" disabled={busy || !f.name.trim() || (scope === "cast" && !f.voice)} onClick={() => void save()} className={buttonVariants({ variant: "go", size: "sm" })}> + Save presets + </button> + <button type="button" data-preset-close="" onClick={onClose} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Close + </button> + </div> + </section> + ); +} + +/** THIS VIDEO's OWN characters, and the items that name a character of their own. */ +export function ProjectCharacters({ + own, cast, itemCharacters, posts, charactersError, busy, post, onChanged, onOpen, open, +}: { + own: PresetCharacter[]; cast: PresetCharacter[]; itemCharacters: ItemCharacter[]; posts: Post[]; charactersError?: string; busy: boolean; post: PostFn; + onChanged: (what: string) => void; onOpen: (id: string) => void; open: string | null; +}) { + const [add, setAdd] = useState({ id: "", name: "", handles: "", anonymous: false, shown: "" }); + const [item, setItem] = useState({ item: posts[0]?.id ?? "", character: "" }); + const cell = "border-t border-seam px-2 py-1 align-top"; + const idOk = /^[a-z0-9][a-z0-9_-]{0,47}$/.test(add.id); + const send = async (body: Record<string, unknown>, what: string) => { + const j = await post(body); + if (j) onChanged(what); + return j; + }; + return ( + <section data-project-characters={own.length}> + <h2 className="micro mb-1.5"> + this video&apos;s own characters · {own.length} + <span className="ml-2 normal-case tracking-normal text-muted">people who stay out of the pool — an anonymous one goes by its shown name here and in recording notes; the cut&apos;s on-screen card is not anonymised yet</span> + </h2> + {charactersError && <p className="m-0 mb-1 text-doubt-text" data-project-characters-error="">this video&apos;s characters are not read: {charactersError}</p>} + {own.length > 0 && ( + <table className="w-full border-collapse"> + <tbody> + {own.map((c) => ( + <tr key={c.id} data-project-character={c.id} className={cn(open === c.id && "bg-panel-2")}> + <td className={cell}> + <span className="font-medium">{c.anonymous ? c.shown : c.name}</span> + {c.anonymous && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-doubt-text" title={`anonymous: “${c.shown}” on this page, in cast project and in recording notes (your own label: ${c.name}) — the cut's on-screen card still shows the post's author`}>anonymous</span>} + <span className="ml-1.5 font-mono text-[11px] text-muted">{(c.handles ?? []).map((h) => `@${h}`).join(" ")}</span> + </td> + <td className={cn(cell, "font-mono")}> + {c.voice ? pretty(c.voice) : <span className="font-sans text-muted">no voice of its own</span>} + {typeof c.synthetic?.speed === "number" ? ` ×${c.synthetic.speed}` : ""} + </td> + <td className={cn(cell, "text-[11px] text-text-2")}>{recordedWords(c)}</td> + <td className={cn(cell, "whitespace-nowrap text-right")}> + <button type="button" data-project-character-preset={c.id} onClick={() => onOpen(c.id)} className={buttonVariants({ variant: open === c.id ? "pressed" : "outline", size: "sm" })}> + Presets + </button>{" "} + {!c.anonymous && ( + <button + type="button" + data-character-pool={c.id} + disabled={busy || !c.voice} + title={c.voice ? "into the cast: the same presets in every project" : "a cast character has a stock voice: give it one first"} + onClick={() => void send({ op: "character-pool", id: c.id }, `${c.name} is in the pool now, for every project`)} + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Add to the pool + </button> + )}{" "} + <button type="button" data-project-character-remove={c.id} disabled={busy} onClick={() => void send({ op: "character-rm", id: c.id }, `${c.anonymous ? c.shown : c.name} removed from this video's characters`)} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${c.anonymous ? c.shown : c.name} from this video's characters`}> + ✕ + </button> + </td> + </tr> + ))} + </tbody> + </table> + )} + <div className="mt-1.5 flex flex-wrap items-center gap-1.5" data-project-character-add=""> + <input data-project-character-id="" value={add.id} onChange={(e) => setAdd({ ...add, id: e.target.value.toLowerCase() })} placeholder="id (anon-1)" className={cn(input, "w-28")} aria-label="the new character's id" /> + <input data-project-character-name="" value={add.name} onChange={(e) => setAdd({ ...add, name: e.target.value })} placeholder={add.anonymous ? "your label for them (optional)" : "name"} className={cn(input, "w-44")} aria-label="the new character's name" /> + <input data-project-character-handles="" value={add.handles} onChange={(e) => setAdd({ ...add, handles: e.target.value })} placeholder="handles: a,b" className={cn(input, "w-40")} aria-label="the handles it covers" /> + <label className="inline-flex items-center gap-1"> + <input type="checkbox" data-project-character-anonymous="" checked={add.anonymous} onChange={(e) => setAdd({ ...add, anonymous: e.target.checked })} /> anonymous + </label> + {add.anonymous && <input data-project-character-shown="" value={add.shown} onChange={(e) => setAdd({ ...add, shown: e.target.value })} placeholder="shown as (Anon 1, Anon 2 …)" className={cn(input, "w-44")} aria-label="the name it is shown under" />} + <button + type="button" + data-project-character-add-go="" + disabled={busy || !idOk || (!add.anonymous && !add.name.trim())} + onClick={() => + void send({ op: "character-add", id: add.id, ...(add.name.trim() ? { name: add.name.trim() } : {}), ...(add.handles.trim() ? { handles: add.handles } : {}), ...(add.anonymous ? { anonymous: true, ...(add.shown.trim() ? { shown: add.shown.trim() } : {}) } : {}) }, `${add.id} is one of this video's characters`).then((j) => { + if (!j) return; + onOpen(add.id); + setAdd({ id: "", name: "", handles: "", anonymous: false, shown: "" }); + }) + } + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Add a character + </button> + <button type="button" data-project-characters-undo="" disabled={busy} onClick={() => void send({ op: "characters-undo" }, "undone: the last change to this video's characters")} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Undo the last change + </button> + </div> + + <h3 className="micro mb-1 mt-3"> + an item read as a character of its own · {itemCharacters.length} + <span className="ml-2 normal-case tracking-normal text-muted">its presets answer for that item before its author&apos;s handle does</span> + </h3> + {itemCharacters.length > 0 && ( + <ul className="m-0 mb-1.5 list-none p-0 text-[11.5px] text-text-2" data-item-characters={itemCharacters.length}> + {itemCharacters.map((it) => ( + <li key={it.id} data-item-character={it.id} data-item-character-found={it.found ? "yes" : "no"}> + <span className="font-mono">{it.id}</span> + {it.handle ? ` @${it.handle}` : ""} — read as <b>{it.name ?? it.character}</b> + {it.found ? ( + <> + {" "} + ({it.layer === "project" ? "this video's" : "the cast's"}): <span className="font-mono">{pretty(it.voice.spec)}</span> + {typeof it.voice.speed === "number" ? ` ×${it.voice.speed}` : ""} + </> + ) : ( + <span className="text-doubt-text"> — no such character: it reads as its author does ({pretty(it.voice.spec)})</span> + )}{" "} + <button type="button" data-item-character-clear={it.id} disabled={busy} onClick={() => void send({ op: "item-character", item: it.id, character: "" }, `${it.id}: read by its author's handle again`)} className="ink-link"> + clear + </button> + </li> + ))} + </ul> + )} + {posts.length > 0 && ( + <div className="flex flex-wrap items-center gap-1.5"> + <select data-item-character-item="" value={item.item} onChange={(e) => setItem({ ...item, item: e.target.value })} className={cn(input, "max-w-[22rem]")} aria-label="the post item"> + {posts.map((p) => ( + <option key={p.id} value={p.id}> + {p.id} @{p.handle}: {p.text} + </option> + ))} + </select> + <select data-item-character-pick="" value={item.character} onChange={(e) => setItem({ ...item, character: e.target.value })} className={input} aria-label="the character it is read as"> + <option value="">read as…</option> + {own.map((c) => ( + <option key={`p:${c.id}`} value={c.id}> + {c.anonymous ? c.shown : c.name} (this video) + </option> + ))} + {cast.filter((c) => !own.some((o) => o.id === c.id)).map((c) => ( + <option key={`c:${c.id}`} value={c.id}> + {c.name} (the cast) + </option> + ))} + </select> + <button type="button" data-item-character-set="" disabled={busy || !item.item || !item.character} onClick={() => void send({ op: "item-character", item: item.item, character: item.character }, `${item.item}: read as ${item.character}`)} className={buttonVariants({ variant: "outline", size: "sm" })}> + Set + </button> + </div> + )} + </section> + ); +} diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx @@ -4,14 +4,19 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { jobsHref, postBenchHref } from "@/lib/hrefs"; +import { PresetEditor, ProjectCharacters, recordedWords, type ItemCharacter, type PresetCharacter } from "./CharacterPresets"; // --------------------------------------------------------------------------- // THE VOICES PANEL (components/projects/VoicesPage.tsx; /api/report/voices; the CLI is `umtool cast`). Works with // the operator alone: nothing here needs an agent. // // the characters every author the project's reads use, the voice each reads in NOW and where it comes from -// (cast · project · narrator · default), how many items it reads, its picked reads in another -// voice (drift), its real voice (speakers.json) -- Audition opens the box below for it +// (the item's own character · this video's · the cast · narrator · default), how many items it +// reads, its picked reads in another voice (drift), its real voice (speakers.json) -- Audition +// opens the box below for it; Presets opens its two presets (CharacterPresets.tsx); an author +// with no character: "Add to the pool" / "Keep in this video only" +// this video's own the characters that live in this video only (anonymous ones under a shown name), and the items +// read as a character of their own // the audition a line (its own words in this project, a stock line, or typed), 2-6 candidate stock voices // (Kokoro fast, Orpheus heavy), Render: a job (the editor's tts; then the closeness to the real // voice through the heavy slot), each candidate played side by side at ONE loudness, with its @@ -22,11 +27,11 @@ import { jobsHref, postBenchHref } from "@/lib/hrefs"; // a recording a person's read of an item made a character's: kept, cleaned, converted to its stock voice // --------------------------------------------------------------------------- -type Voice = { engine: string; voice: string; spec: string; from: string }; +type Voice = { engine: string; voice: string; spec: string; from: string; speed?: number; character?: 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?: Convert; note?: string; narrator?: boolean } | null; + character: (PresetCharacter & { layer: "cast" | "project" }) | null; items: number; context: number; itemIds: string[]; contextIds: string[]; voice: Voice; contextVoice?: Voice; weight: string; reads: { id: string; role: string; spec: string; kind: string }[]; @@ -35,7 +40,7 @@ type Character = { // 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 }; +type CastChar = PresetCharacter & { voice: string }; /** 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 { @@ -50,6 +55,8 @@ type View = { narrator: { engine: string; voice: string; spec: string; from: string; character: { id: string; name: string; voice: string } | null; recorded: { id: string; kind: string; voice: string }[] }; characters: Character[]; overrides: { handle: string; character: string; cast: string; project: string }[]; cast: CastChar[]; engines: Engine[]; convertEngines: string[]; running: { id: string; state: string; kind: string } | null; + // This video's own characters (narration/characters.json) and the items that name a character of their own. + own?: PresetCharacter[]; itemCharacters?: ItemCharacter[]; charactersError?: string; }; type Candidate = { spec: string; engine: string; voice: string; weight: string; key: string; rel: string; cached: boolean; seconds: number | null; lufs: number | null; score: number | null }; type Audition = { character: { id: string; name: string; handles: string[]; voice: string | null }; text: string; from: string; speaker: string | null; reference: string | null; candidates: Candidate[] }; @@ -58,7 +65,7 @@ type Post = { id: string; handle: string; author: string; text: string }; const whoOf = (c: Character) => (c.character ? c.character.id : `@${c.handles[0]}`); const pretty = (spec: string) => spec.replace(":", " · "); -const FROM: Record<string, string> = { cast: "the cast", project: "this project", narrator: "the narrator's", default: "the default", override: "a read's own" }; +const FROM: Record<string, string> = { cast: "the cast", project: "this project", narrator: "the narrator's", default: "the default", override: "a read's own", item: "the item's own character" }; const fileUrl = (project: string, rel: string, v?: string | number | null) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}${v ? `&v=${v}` : ""}`; export default function VoicesPanel({ project, posts, initialWho = null }: { project: string; posts: Post[]; initialWho?: string | null }) { @@ -78,6 +85,8 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro const [queued, setQueued] = useState<string[] | null>(null); const [rec, setRec] = useState<{ item: string; as: string; clean: boolean; convert: boolean; file: File | null }>({ item: posts[0]?.id ?? "", as: "", clean: true, convert: true, file: null }); const [drag, setDrag] = useState(false); + // The character whose presets are open: the cast's, or one of this video's own. + const [preset, setPreset] = useState<{ scope: "cast" | "project"; id: string } | null>(null); const timer = useRef<ReturnType<typeof setTimeout> | null>(null); const audios = useRef<Map<string, HTMLAudioElement>>(new Map()); @@ -230,6 +239,23 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro }); }; + const changed = (what: string) => { + setStatus(what); + void load(); + void loadAudition(); + }; + // An author with no character: into the pool (the cast: the voice they read in now, everywhere) or this video only. + const poolAuthor = async (c: Character) => { + const j = await post({ op: "use", who: whoOf(c), voice: c.voice.spec, scope: "cast" }); + if (j) changed(`${c.name} is in the pool now (${pretty(c.voice.spec)}), for every project`); + }; + const keepHere = async (who: string, name: string) => { + const j = (await post({ op: "character-keep", who })) as { character?: { id: string } } | null; + if (!j) return; + changed(`${name} is a character of this video only`); + if (j.character?.id) setPreset({ scope: "project", id: j.character.id }); + }; + if (!view) return error ? <p role="alert" className="text-[12px] text-reject-text">{error}</p> : <p className="text-[12px] text-muted">reading the voices…</p>; const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal"; @@ -241,6 +267,8 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro const best = scored.length > 1 && scored[0] > scored[1] ? scored[0] : null; const missing = (audition?.candidates ?? []).filter((c) => !c.cached).length; const heavy = (audition?.candidates ?? []).some((c) => !c.cached && c.weight === "heavy"); + const own = view.own ?? []; + const presetOf = preset ? (preset.scope === "project" ? own.find((c) => c.id === preset.id) : view.cast.find((c) => c.id === preset.id)) ?? null : null; return ( <div className="space-y-5 text-[12.5px]" data-voices-panel={project}> @@ -249,7 +277,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro <h2 className="micro mb-1.5"> the characters · {view.characters.length} <span className="ml-2 normal-case tracking-normal text-muted"> - a voice comes from a read&apos;s own choice, this project&apos;s map, the cast (every project), the narrator&apos;s, or the default — in that order + a voice comes from a read&apos;s own choice, the item&apos;s own character, this video&apos;s characters and map, the cast (every project), the narrator&apos;s, or the default — in that order </span> </h2> {view.castError && <p className="m-0 mb-1 text-doubt-text" data-cast-error="">the cast is not read: {view.castError}</p>} @@ -272,10 +300,13 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro <td className={cell}> <span className="font-medium text-text">{c.name}</span> <span className="ml-1.5 font-mono text-[11px] text-muted">{c.handles.map((h) => `@${h}`).join(" ")}</span> - {c.character && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-signal-text" title="in the cast: the same voice in every project">cast</span>} + {c.character && c.character.layer !== "project" && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-signal-text" title="in the cast: the same voice in every project">cast</span>} + {c.character?.layer === "project" && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-text-2" data-voices-layer="project" title="a character of this video only">this video</span>} + {c.character?.anonymous && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-doubt-text" title={`anonymous: “${c.character.shown}” on this page, in cast project and in recording notes — the cut's on-screen card is not anonymised yet: it still shows the post's author`}>anonymous</span>} </td> <td className={cell}> <span className="font-mono text-[12px]" data-voice-now={c.voice.spec}>{pretty(c.voice.spec)}</span> + {typeof c.voice.speed === "number" && <span className="ml-1 font-mono text-[11px] text-text-2" data-voice-speed={c.voice.speed} title="its preset's speed">×{c.voice.speed}</span>} {c.weight === "heavy" && <span className="ml-1 text-[10.5px] text-doubt-text" title="Orpheus pins ~8.5 GB while it reads">heavy</span>} <div className="text-[11px] text-muted">from {FROM[c.voice.from] ?? c.voice.from}{c.contextVoice ? ` · as a context post: ${pretty(c.contextVoice.spec)} (${FROM[c.contextVoice.from] ?? c.contextVoice.from})` : ""}</div> </td> @@ -297,7 +328,27 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro <td className={cn(cell, "text-text-2")} data-voice-speaker={c.speaker ?? ""}> {c.speaker ?? <span className="text-muted" title="name it in speakers.json (the walk's Add to a voice) to score candidates against it">—</span>} </td> - <td className={cn(cell, "text-right")}> + <td className={cn(cell, "whitespace-nowrap text-right")}> + {c.character ? ( + <button + type="button" + data-voices-preset-open={k} + onClick={() => setPreset({ scope: c.character!.layer, id: c.character!.id })} + className={buttonVariants({ variant: preset?.id === c.character.id && preset.scope === c.character.layer ? "pressed" : "outline", size: "sm" })} + title="its two presets: the synthetic voice and speed, and what a recording of them is made into" + > + Presets + </button> + ) : ( + <> + <button type="button" data-character-pool-author={k} disabled={busy} onClick={() => void poolAuthor(c)} className={buttonVariants({ variant: "outline", size: "sm" })} title={`a cast character, reading in ${pretty(c.voice.spec)} in every project`}> + Add to the pool + </button>{" "} + <button type="button" data-character-keep={k} disabled={busy} onClick={() => void keepHere(k, c.name)} className={buttonVariants({ variant: "outline", size: "sm" })} title="a character of this video only — for someone who must not enter the pool"> + Keep in this video only + </button> + </> + )}{" "} <button type="button" data-voices-audition-open={k} @@ -342,6 +393,35 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro )} </section> + {/* --- one character's presets --------------------------------------------------- */} + {preset && presetOf && ( + <> + <PresetEditor key={`${preset.scope}:${preset.id}:${JSON.stringify([presetOf.name, presetOf.shown, presetOf.synthetic, presetOf.recorded])}`} c={presetOf} scope={preset.scope} engines={view.engines} convertEngines={view.convertEngines} busy={busy} post={post} onSaved={changed} onClose={() => setPreset(null)} /> + {preset.scope === "cast" && !own.some((c) => c.id === preset.id) && ( + <p className="m-0 -mt-3 text-[11.5px] text-text-2"> + <button type="button" data-character-keep={preset.id} disabled={busy} onClick={() => void keepHere(preset.id, presetOf.name)} className="ink-link"> + Keep in this video only + </button>{" "} + — a copy of {presetOf.name} for this video: change its presets here and the pool&apos;s stay as they are + </p> + )} + </> + )} + + {/* --- this video's own characters ------------------------------------------------ */} + <ProjectCharacters + own={own} + cast={view.cast} + itemCharacters={view.itemCharacters ?? []} + posts={posts} + charactersError={view.charactersError} + busy={busy} + post={post} + onChanged={changed} + onOpen={(id) => setPreset({ scope: "project", id })} + open={preset?.scope === "project" ? preset.id : null} + /> + {/* --- the audition ------------------------------------------------------------- */} {chosen && ( <section className="rounded-[4px] border border-seam-2 p-3" data-audition-panel={whoOf(chosen)}> @@ -466,7 +546,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro <button type="button" data-audition-use="project" disabled={busy} onClick={() => void use(c.spec, "project")} className={buttonVariants({ variant: "outline", size: "sm" })}> Use for this project </button> - <button type="button" data-audition-use="cast" disabled={busy} onClick={() => void use(c.spec, "cast")} className={buttonVariants({ variant: "outline", size: "sm" })} title="the cast: this character reads in it in every project"> + <button type="button" data-audition-use="cast" disabled={busy || !!chosen.character?.anonymous} onClick={() => void use(c.spec, "cast")} className={buttonVariants({ variant: "outline", size: "sm" })} title={chosen.character?.anonymous ? "an anonymous character stays in this video: it never enters the pool" : "the cast: this character reads in it in every project"}> Use everywhere </button> </div> @@ -535,8 +615,13 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro ))} </select> <select data-recording-as="" value={rec.as} onChange={(e) => setRec({ ...rec, as: e.target.value })} className={input}> - <option value="">as: the post&apos;s author (else the narrator)</option> - {view.cast.map((c) => ( + <option value="">as: the item&apos;s character, else the post&apos;s author (else the narrator)</option> + {own.filter((c) => c.voice || c.recorded).map((c) => ( + <option key={`own:${c.id}`} value={c.id}> + as {c.anonymous ? c.shown : c.name} (this video{c.recorded?.convert?.voice ?? c.voice ? `: ${pretty(c.recorded?.convert?.voice ?? c.voice ?? "")}` : ""}) + </option> + ))} + {view.cast.filter((c) => !own.some((o) => o.id === c.id)).map((c) => ( <option key={c.id} value={c.id}> as {c.name} ({pretty(c.convert?.voice ?? c.voice)}{pitchWords(c.convert) ? `, ${pitchWords(c.convert)}` : ""}) </option> @@ -588,7 +673,10 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro <span className="ml-1.5 font-mono text-[11px] text-muted">{(c.handles ?? []).map((h) => `@${h}`).join(" ")}</span> {c.narrator && <span className="ml-1.5 text-[11px] text-muted">the narrator</span>} </td> - <td className={cn(cell, "font-mono")}>{pretty(c.voice)}</td> + <td className={cn(cell, "font-mono")}> + {pretty(c.voice)} + {typeof c.synthetic?.speed === "number" ? ` ×${c.synthetic.speed}` : ""} + </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) && ( @@ -596,10 +684,14 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro {` · pitch: ${pitchWords(c.convert)}`} </span> )} + {recordedWords({ ...c, recorded: { ...c.recorded, convert: undefined } }) ? ` · ${recordedWords({ ...c, recorded: { ...c.recorded, convert: undefined } })}` : ""} {c.speakers?.length ? ` · real voice: ${c.speakers.join(", ")}` : ""} {c.note ? ` · ${c.note}` : ""} </td> - <td className={cn(cell, "text-right")}> + <td className={cn(cell, "whitespace-nowrap text-right")}> + <button type="button" data-cast-preset={c.id} onClick={() => setPreset({ scope: "cast", id: c.id })} className={buttonVariants({ variant: preset?.scope === "cast" && preset.id === c.id ? "pressed" : "outline", size: "sm" })}> + Presets + </button>{" "} <button type="button" data-cast-remove={c.id} disabled={busy} onClick={() => void post({ op: "cast-rm", id: c.id }).then((j) => j && load())} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${c.name} from the cast`}> ✕ </button> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -22,8 +22,9 @@ 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] [--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 [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--speed s] [--convert-engine e] [--convert-voice v] [--convert-pitch target\|source\|contour] [--convert-semitones n] [--enhance on\|off] [--trim on\|off] [--trim-pad ms] [--direction "…"] [--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, one writer, an undo point a write. **A character is a PRESET**, two of them ([knobs.md](knobs.md#a-character-is-a-preset)): `synthetic` -- the STOCK voice it reads in (`--voice`) and its speed (`--speed` 0.5–2; Orpheus has none) -- and `recorded` -- what a recording of them is made into: the stock voice (`--convert-voice`; a file or a recording is refused), the engine, 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), whether it is cleaned first (`--enhance`), its edges trimmed to speech (`--trim`, `--trim-pad` the ms kept either side) and a `--direction` (one line for the person reading, never sent to a model). `set` lays the flags given over the presets; `default` for one takes that key off; `--no-convert`, `--no-speed`. A version 1 file (`voice`, `convert` at a character's top) reads as these presets and the first write makes it version 2 (`undo` puts the old file back). A followed pitch on an engine that has none, semitones with nothing followed, a speed or a pad out of range: **exit 1** | +| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters: each one's voice now (and speed) and **where it comes from** -- the chain one read asks, first hit wins: the command's flags, the item's own character (`posts character`), this video's character for the author (then its voice map), the cast's, the narrator's, the default -- what a recording of them is made into, its stale reads; this video's own characters; the items that name their own. `use`: the voice for this project (its own character's when it has one for them, else the voice map) or everywhere, and the re-reads that asks for | +| `cast project <project> add <id> [--name "…"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown "…"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\|@handle> [--anonymous]` `[--json]` | **THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written | | `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)) | | `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) | @@ -130,10 +131,11 @@ Inbox cannot disagree about what is wrong with one. | `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | | `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--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= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. | -| `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 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] [--speed s] [--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 item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), 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 character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **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] [--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 narrate <project> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--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. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--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,11 +172,17 @@ 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] [--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 add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE] [--narrator]` | a character: name, stock voice, handles, its two presets | form · *corpus* | +| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--no-speed] [--narrator] [--no-narrator]` | change a character: its name, handles, presets | 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* | +| `cast project <project>` | the project's characters: each one's voice, where it comes from, its drift; this video's own | form · *project* | +| `cast project <project> add <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--anonymous] [--shown SHOWN] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE]` | a character of this video only (anonymous: shown under Anon 1 …) | form · *project* | +| `cast project <project> set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--shown SHOWN] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-voice] [--no-convert] [--no-speed] [--anonymous] [--no-anonymous]` | change a character of this video's | form · *project* | +| `cast project <project> rm <id>` | a character out of this video's (an undo point) | form · *project* | +| `cast project <project> undo` | this video's characters as they were before their last write | form · *project* | +| `cast project <project> pool <id>` | Add to the pool: this video's character into the cast | form · *corpus* | +| `cast project <project> keep <character> [--anonymous] [--shown SHOWN]` | Keep in this video only: a cast character copied here, or an author given one | form · *project* | | `cast audition <character> --voices VOICES [--project PROJECT] [--text TEXT] [--item ITEM] [--line N] [--stock] [--no-score] [--score-only]` | one line read by 2-6 candidate voices, scored against the real voice | form · queued · *project* | | `cast use <project> <character> <voice> [--everywhere]` | the voice a character reads in, here or everywhere | form · *draft* | | `cast reread <project> <character> [--dry-run]` | the items that say a character in another voice, read again | form · queued · *project* | @@ -351,6 +359,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `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] [--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 character <project> <item> [<character>] [--clear]` | the character one post item's own read is made with | 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* | | `posts fx <project> <item> ls\|add\|set\|remove [<what>] [--key value…] [--in-take IN-TAKE]` | a post item's word zooms, captions, clock, slams | form · *draft* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1275,16 +1275,21 @@ not the manifest: changing it never re-renders a card, it makes new takes. Beep still word-timed against its script as written (the replaced words are placed between the words heard). **The voice map** (`narration/voices.json`, `updateVoiceMap`): `{"<handle>": "<voice>", "*": "<voice>"}` -- the -project's override of THE CAST (below, "The cast"); the stock voice a read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on +project's override of THE CAST (below, "The cast"; a handle in it reads as one of this video's own characters with +only a synthetic voice, and the project's `narration/characters.json` answers before it); the stock voice a read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on Orpheus). The item's own author reads in the item's narrator voice (`narration.voice`, else the cut's) unless the map names them; `--voice-for <handle>=<voice>` overrides it for one read, `--voice` sets his post's. **A thread read** (`lib/report/postThreadRead.mjs`): `posts narrate <p> <item> --take --thread` reads the post it answers, the post it quotes, the posts its words link to and his words, in DATE order (`post-thread.mjs` `chronoPieces`), each piece cleaned to be spoken (a context post's paraphrase when it has one), each in its author's -voice. Each part (a paragraph; a long one split at a sentence end) is synthesized ONCE through the editor's tts op (a -job on its queue, paced; the GPU and the heavy slot are the editor's) into `narration/parts-cache/<sha1(voice|text)>.wav` -and reused by every read after -- a re-read after one word changed asks for that part alone. The transcription lane is +voice and **at its character's speed** (its synthetic preset's, [below](#a-character-is-a-preset); `--speed <s>`: every +part at that one, recorded on the take's `read`; his own words at the item's `narration.speed` when it has one -- the +flag, then the item's own, then the character's; Orpheus has no speed and is asked none). Each part (a paragraph; a long one split at a sentence end) is synthesized ONCE through +the editor's tts op (a job on its queue, paced; the GPU and the heavy slot are the editor's) into +`narration/parts-cache/<sha1(voice|text)>.wav` (a part at a speed: `…|x<speed>`, so the same words at another speed are +another part; `parts[i].speed` says it) and reused by every read after -- a re-read after one word changed asks for +that part alone. The transcription lane is held while parts are asked (only if it was not held; released after, on a failure, on Ctrl-C). The parts are 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`, kept with each part's ROLE stored, and PICKED -- one write, one undo point @@ -1297,7 +1302,7 @@ was not synthesized (the parts made stay cached: run it again), 2 a usage error; | what a voice would be asked to say (the lexicon, the redaction, the slur filter) | **Reads and voices** → **Try it** | `umtool posts say <p> try "tbh @grok atm" [--item <id>]` | — | | the picked reads that say an entry the old way, each with the command that re-reads it | **Reads and voices** names them | `umtool posts say <p> stale [--json]` | — | | the voice map | **Reads and voices**: the map, **Set** a handle (or `*`) and a voice, ✕ removes; the cut's authors with the voice each gets | `umtool posts voices <p> set kirscheverstahl tara` · `set '*' leo` · `remove <handle>` · `ls` (each author the cut carries, and the voice each gets) | — | -| a thread read -- `takes[i].read: {kind: "thread", parents, skip?, quoted?, linked?, seen?, voiceFor?, voice?}` | the post bench plays and picks it like any take | `umtool posts narrate <p> <item> --take --thread` (parent 0) · `--parents all` (every ancestor) · `--parents none` · `--skip-parent <id>` (repeat) · `--no-quoted` · `--no-linked` · `--read-seen` · `--voice-for Movail2=leah` · `--voice leo` · `--force` · `--dry-run` · `--json` | — | +| a thread read -- `takes[i].read: {kind: "thread", parents, skip?, quoted?, linked?, seen?, voiceFor?, voice?}` | the post bench plays and picks it like any take | `umtool posts narrate <p> <item> --take --thread` (parent 0) · `--parents all` (every ancestor) · `--parents none` · `--skip-parent <id>` (repeat) · `--no-quoted` · `--no-linked` · `--read-seen` · `--voice-for Movail2=leah` · `--voice leo` · `--speed 1.1` · `--force` · `--dry-run` · `--json` | — | Recipes (copy them; `<p>` is the project, `<item>` the post item's id or its post's id): @@ -1318,20 +1323,31 @@ different ones to compare … and try to maintain consistent voices for differen **The cast** (`report-to-video/cast.mjs`; `<reports>/.umtool/cast.json`, one writer `lib/report/castStore.mjs` `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`) 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). - -**Every read asks one function** (`post-say.mjs` `voiceSourceOf` / `resolvePieceVoice`): the read's own voice -(`--voice-for`, `--voice`, the bench's voice field), the project's voice map (`narration/voices.json` -- the -project's OVERRIDE LAYER; a value may name its engine too), **the cast**, the narrator's (the item's own author), -the map's `*`, the default. A single post's take (`posts narrate --take`, the bench's Re-take: `readVoice.mjs`) and -each piece of a thread read agree. A voice that names another engine than the read's is synthesized by it: a -thread read may join Orpheus and Kokoro parts (each part records its `engine`; the disclosure names both). Projects -without a cast read as before. +projects -- `{id, name, handles, synthetic, recorded, speakers?, avatar?, note?, narrator?}` (version 2). **A +character is a preset**, two of them ([below](#a-character-is-a-preset)): `synthetic.voice` is a STOCK voice with its +engine (`kokoro:am_michael`, `orpheus:zac`) and `synthetic.speed` its speed; `recorded.convert` the voice (and engine, +openvoice | seed-vc) a recording of them is converted to (default: the synthetic 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). **A version 1 file** kept the voice in `voice` and the convert entry in `convert` at the +character's top: those keys are READ as the presets (`upgradeCharacter`), a reader is handed a view that still says +`voice` and `convert` (`charactersOf`), and the first write makes the file version 2 -- whose undo point is the +version 1 text, so `umtool cast undo` puts the old file back as it was. **Before rolling umtool back**, undo the +cast change: `cast.json` becomes version 2 at the first write, and an older umtool build then reads the cast as empty +(and refuses to write it). + +**Every read asks one chain, first hit wins** (`post-say.mjs` `voiceSourceOf` / `resolvePieceVoice` for a synthesized +read; `cast.mjs` `characterForRead` for a recording): **the command's flags** (`--voice-for`, `--voice`, `--speed`, +the bench's voice field; `--as`, `--pitch`), **the item's own character** (`narration.character`), **this video's +character** for the author (`narration/characters.json`, then `narration/voices.json` -- the project's OVERRIDE +LAYER; a value may name its engine too), **the cast's**, **the narrator's** (the item's own author), the map's `*`, +the default. A layer answers for a preset it HAS: a project character with no synthetic voice leaves the voice to +the layers under it, and its recorded preset still answers for a recording. A single post's take (`posts narrate +--take`, the bench's Re-take: `readVoice.mjs`) and each piece of a thread read agree, and `umtool cast project <p>` +prints the answer and its source (`item`, `project`, `cast`, `narrator`, `default`) for every author. A voice that +names another engine than the read's is synthesized by it: a thread read may join Orpheus and Kokoro parts (each part +records its `engine`; the disclosure names both). Projects without a cast read as before. **The guard**: `umtool lint <p>` warns for each picked read that says a cast character in another voice than now (`umtool cast reread`), and notes each cast voice the project's map overrides on purpose. @@ -1346,16 +1362,23 @@ with an excerpt of the real voice (`ref-<speaker>.wav`) to listen to beside them **A recording made a character's read**: `posts narrate <p> <item> --recording <file> [--as <character>]` keeps it as a recorded take (the original), cleans it (the editor's voice-enhance, when installed) and converts it (its -voice-convert) to the character's stock voice -- each a new take, the last picked, the disclosure line said. +voice-convert) to the character's stock voice -- each a new take, the last picked, the disclosure line said. The +character is the chain's (`--as`, the item's own, this video's for the author, the cast's, the narrator), and its +**recorded preset** is applied: `enhance: false` skips the clean, `trim.on: false` keeps its edges as recorded, +`trim.padMs` is the room kept either side of the words (`--clean` / `--no-clean`, `--trim` / `--no-trim` say otherwise +for one read). | 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 …] [--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` | +| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, **Presets**, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** (or an author's **Add to the pool**) adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [the preset flags] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`, `--no-speed`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` | +| a character's presets -- `synthetic: {voice, speed}`, `recorded: {convert: {engine, voice, pitch, semitones}, enhance, trim: {on, padMs}, direction}` | **Voices** → a character's **Presets**: the voice and speed; converted to, by, pitch, semitones; clean it first; trim its edges and the pad; the direction; **Save presets** | `umtool cast set <id> [--voice kokoro:am_michael] [--speed 1.1] [--convert-engine seed-vc] [--convert-voice …] [--convert-pitch source\|contour\|target] [--convert-semitones n] [--enhance on\|off] [--trim on\|off] [--trim-pad 120] [--direction "higher, brisk, amused"]` (`default` for one takes it off) · this video's own: `umtool cast project <p> set <id> …` | `POST … {op: "character-set", scope: "cast" \| "project", id, voice?, speed?, convertEngine?, convertVoice?, convertPitch?, convertSemitones?, enhance?, trim?, trimPad?, direction?}` | +| a project's characters -- each one's voice now (and speed) and where it comes from, what a recording of them is made into, its reads, its drift, its real voice | **Voices**: the characters table | `umtool cast project <p> [--json]` | `GET /api/report/voices?project` | +| this video's own characters -- `<p>/narration/characters.json` | **Voices** → *this video's own characters*: **Add a character** (id, name, handles, anonymous and its shown name), **Presets**, ✕, **Undo the last change**; an author's **Keep in this video only**; a character's **Add to the pool** | `umtool cast project <p> add <id> --name … [--voice …] [--handles a,b] [--anonymous [--shown "Anon 1"]]` · `set <id> …` (`--no-voice`, `--no-anonymous`) · `rm <id>` · `undo` · `pool <id>` · `keep <character\|@handle> [--anonymous]` | `POST … {op: "character-add" \| "character-set" \| "character-rm" \| "characters-undo" \| "character-pool" \| "character-keep"}` | +| the character one post item's own read is made with -- `narration.character` | **Voices** → *an item read as a character of its own*: the item, **read as…**, **Set**; **clear** | `umtool posts character <p> <item> <character>` · `--clear` · none: print it | `POST … {op: "item-character", item, character}` | | 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] [--pitch …] [--semitones n]` | `POST … multipart {op: "recording", item, as?, file}` | +| a recording made a character's read | **Voices** → *a recording*: the item, as whom (this video's own, the cast's), drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--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 @@ -1364,8 +1387,55 @@ umtool cast audition thequartering --project quartering-diet --voices kokoro:am_ umtool cast use quartering-diet thequartering kokoro:am_michael --everywhere # then: umtool cast reread quartering-diet thequartering # each stale read made again (a take each, picked) umtool posts narrate quartering-diet <item> --recording my-read.wav --as thequartering +umtool cast set thequartering --speed 1.1 --convert-engine seed-vc --convert-pitch contour --direction "higher, brisk, amused" +umtool cast project quartering-diet add anon-1 --anonymous --handles somereplyguy --voice kokoro:am_puck # shown as "Anon 1" +umtool cast project quartering-diet keep @madamsavvy # a character of this video only, in the voice she reads in now +umtool posts character quartering-diet <item> anon-1 # this one item read as that character (--clear: by its handle) ``` +### A character is a preset + +The operator, 11 Nov 2026: "a preset of voice and other settings … different presets for synthetic and +human-filtered voices". A character carries two, picked by how the read is made: + +- **`synthetic`** -- a read the editor synthesizes: `voice` (`<engine>:<voice>`, a stock voice) and `speed` (0.5–2, + the tts op's; absent: 1). Speed is the only parameter the tts op takes beside the voice (Orpheus's emotion is in the + script, its `<sigh>` `<laugh>` tags; Orpheus has no speed and is asked none). It reaches a single take, the bench's + Re-take and every part of a thread read; `--speed` on the command wins, then the item's own `narration.speed`. +- **`recorded`** -- a recording of them made their read: `convert` `{engine, voice, pitch, semitones}` (the target is + ALWAYS a stock synthetic voice: validation refuses a file, a path or a recording, in the cast and in a project's + own characters), `enhance` (cleaned first by the editor's voice-enhance; absent: yes), `trim` `{on, padMs}` (its + edges trimmed to speech -- the silence, a key click -- and the milliseconds of room kept either side; absent: on, + 80 ms before and 150 after) and `direction` -- ONE LINE FOR THE PERSON READING ("higher, brisk, amused"), shown to + them, **never sent to a model** (at most 200 characters). + +The disclosure line a cut carries is unchanged: it is made from the takes (a synthetic voice, a voice converted to a +synthetic voice), never from a preset. + +### This video's own characters, and an item's own + +**A project's own characters** (`<project>/narration/characters.json`, format `umtool-project-characters`; the cast's +writer in `castStore.mjs` -- `projectCharactersWrite`: a token, an undo point a write in `characters.undo.json`, +atomic, a broken file never overwritten) are the cast's shape, for people who must **not enter the pool**: they live +in that video only. One may be **`anonymous: true`** with a **`shown`** name -- what the Voices page, `umtool cast +project` and a recording's note call them, never their own name. **The on-screen card is NOT anonymised yet**: a cut +still shows the post's author, so an anonymous character keeps someone out of the pool and off umtool's own surfaces, +not off the video. The default is the next unused of **"Anon 1", "Anon 2" …** (`cast.mjs` +`ANON_NAME_PATTERN`, the one place the pattern is written). A preset is optional here: a character with no synthetic +voice leaves the voice to the layers under it. It has no narrator (the narrator is the cast's). `narration/voices.json` +keeps working under it and is never rewritten by these commands. + +**Add to the pool** (`umtool cast project <p> pool <id>`) moves a project's character into the cast -- refused for an +anonymous one, and for an id the cast already has. **Keep in this video only** (`… keep <character|@handle>`) copies +a cast character into the project (its presets changed for this video alone; the pool's stay as they are), or gives +an author with no character one here, in the voice they read in now. + +**A post item's own character** (`narration.character`, `umtool posts character <p> <item> <id>`): the id of one of +the project's own characters, else of the cast's. Its presets answer for THAT item's own words before its author's +handle does -- a reply read as "Anon 2" while the same handle elsewhere reads as itself. An id nobody has is refused +by the command; one that stops existing later (the character removed) reads as its author does, and `umtool cast +project <p>` says so. + ### 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 diff --git a/umtool/e2e/voices.spec.ts b/umtool/e2e/voices.spec.ts @@ -19,6 +19,9 @@ import * as urls from "./urls"; // Use for this project -> the project's voice map; the lint's override note // a recording dropped on an item -> kept, converted to the character's stock voice // the cast: remove, undo +// a character's presets (CharacterPresets.tsx): Keep in this video only -> its voice, speed, clean, direction saved; +// an anonymous character of this video ("Anon 1"), never offered -- and refused -- the pool; an item read as a +// character of its own, and cleared // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -27,6 +30,8 @@ const P = "reports/voices-fixture"; const DIR = path.join(FIXTURE, "reports", "voices-fixture"); const MANIFEST = path.join(DIR, "video.manifest.json"); const CAST = path.join(FIXTURE, ".umtool", "cast.json"); +// This video's own characters (lib/report/castStore.mjs projectCharactersWrite). +const CHARACTERS = path.join(DIR, "narration", "characters.json"); const SHOTS = process.env.E2E_VOICES_SHOTS ?? null; const REC = path.join(FIXTURE, "voices-recording.wav"); @@ -50,7 +55,7 @@ test.beforeAll(() => { }); const reset = () => { copyFileSync(`${MANIFEST}.pristine`, MANIFEST); - for (const f of [CAST, CAST.replace(/\.json$/, ".undo.json"), path.join(DIR, "narration", "voices.json")]) rmSync(f, { force: true }); + for (const f of [CAST, CAST.replace(/\.json$/, ".undo.json"), path.join(DIR, "narration", "voices.json"), CHARACTERS, CHARACTERS.replace(/\.json$/, ".undo.json")]) rmSync(f, { force: true }); for (const d of ["auditions", "uploads", "parts-cache"]) rmSync(path.join(DIR, "narration", d), { recursive: true, force: true }); for (const id of ["1", "2", "3"]) { const dir = path.join(DIR, "narration", "posts", id); @@ -124,8 +129,10 @@ test("each character's voice and where it comes from; an audition side by side w const confirm = box.locator("[data-reread-confirm]"); await expect(confirm).toHaveAttribute("data-reread-confirm", "1"); await expect(confirm.locator('[data-reread-item="p-1"]')).toContainText("post orpheus · zac → kokoro · am_michael"); - const cast = JSON.parse(readFileSync(CAST, "utf8")) as { characters: { id: string; voice: string; handles: string[] }[] }; - expect(cast.characters).toEqual([{ id: "hostman", name: "Host Man", handles: ["hostman"], voice: "kokoro:am_michael" }]); + // The cast on disk is version 2: the voice is the character's synthetic preset. + const cast = JSON.parse(readFileSync(CAST, "utf8")) as { version: number; characters: { id: string; synthetic: { voice: string }; handles: string[] }[] }; + expect(cast.version).toBe(2); + expect(cast.characters).toEqual([{ id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "kokoro:am_michael" } }]); await expect(page.locator('[data-voices-character="hostman"]')).toHaveAttribute("data-voice-from", "cast"); await expect(page.locator('[data-voices-character="hostman"] [data-voice-drift]')).toHaveAttribute("data-voice-drift", "1"); await shot(page, "3-reread-confirm", confirm); @@ -202,6 +209,74 @@ test("a recording dropped on an item: kept as recorded, converted to the charact expect(conv.voice).toBe("orpheus:zac"); }); +test("a character's presets; this video's own characters -- an anonymous one is Anon 1 and never enters the pool; an item's own character", async ({ page }) => { + type Own = { id: string; name: string; anonymous?: boolean; shown?: string; handles?: string[]; synthetic?: { voice?: string; speed?: number }; recorded?: { enhance?: boolean; direction?: string } }; + const own = () => (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { format: string; characters: Own[] }).characters; + const itemCharacter = (id: string) => (entry(id).narration as { character?: string } | undefined)?.character ?? null; + await page.goto(urls.voicesHref(P)); + const host = page.locator('[data-voices-character="@hostman"]'); + await expect(host).toBeVisible({ timeout: 30_000 }); + // Keep in this video only: an author with no character gets one here, in the voice they read in now; its presets open. + await host.locator("[data-character-keep]").click(); + const ed = page.locator('[data-preset-editor="hostman"]'); + await expect(ed).toHaveAttribute("data-preset-scope", "project"); + expect(own().map((c) => [c.id, c.handles, c.synthetic?.voice])).toEqual([["hostman", ["hostman"], "orpheus:zac"]]); + const row = page.locator('[data-voices-character="hostman"]'); + await expect(row).toHaveAttribute("data-voice-from", "project"); + await expect(row.locator('[data-voices-layer="project"]')).toBeVisible(); + // Both presets, edited by hand: a Kokoro voice at 1.1, not cleaned, a direction for the reader. + await ed.locator('[data-preset-engine="voice"]').selectOption("kokoro"); + await ed.locator("[data-preset-speed]").fill("1.1"); + await ed.locator("[data-preset-enhance]").uncheck(); + await ed.locator("[data-preset-direction]").fill("higher, brisk, amused"); + await ed.locator("[data-preset-save]").click(); + await expect(page.locator("[data-voices-status]")).toContainText("its presets saved for this video only"); + const saved = own()[0]; + expect(saved.synthetic?.voice).toMatch(/^kokoro:/); + expect(saved.synthetic?.speed).toBe(1.1); + expect(saved.recorded).toEqual({ enhance: false, direction: "higher, brisk, amused" }); + await expect(row.locator("[data-voice-speed]")).toHaveAttribute("data-voice-speed", "1.1"); + await expect(page.locator('[data-project-character="hostman"]')).toContainText("not cleaned"); + await shot(page, "7-presets", ed); + // An anonymous character of this video's, for the guest: shown as Anon 1. + const mine = page.locator("[data-project-characters]"); + await mine.locator("[data-project-character-id]").fill("anon-a"); + await mine.locator("[data-project-character-handles]").fill("guest"); + await mine.locator("[data-project-character-anonymous]").check(); + await mine.locator("[data-project-character-add-go]").click(); + const anon = page.locator('[data-project-character="anon-a"]'); + await expect(anon).toContainText("Anon 1"); + await expect(anon).toContainText("anonymous"); + expect(own().find((c) => c.id === "anon-a")).toMatchObject({ anonymous: true, shown: "Anon 1", handles: ["guest"] }); + await expect(page.locator('[data-voices-character="anon-a"]')).toContainText("Anon 1"); + // It is never offered the pool -- and the route refuses it (the CLI's words), the cast untouched. + await expect(anon.locator("[data-character-pool]")).toHaveCount(0); + await expect(page.locator('[data-project-character="hostman"] [data-character-pool]')).toBeVisible(); + const refused = await page.evaluate(async (project) => { + const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-pool", id: "anon-a" }) }); + return { status: r.status, error: ((await r.json()) as { error?: string }).error ?? "" }; + }, P); + expect(refused.status).toBe(400); + expect(refused.error).toContain("anon-a is anonymous: it stays in this video"); + expect(existsSync(CAST)).toBe(false); + await shot(page, "8-own-characters", mine); + // An item read as a character of its own, then by its author's handle again. + await mine.locator("[data-item-character-item]").selectOption("p-3"); + await mine.locator("[data-item-character-pick]").selectOption("hostman"); + await mine.locator("[data-item-character-set]").click(); + const it = mine.locator('[data-item-character="p-3"]'); + await expect(it).toHaveAttribute("data-item-character-found", "yes"); + await expect(it).toContainText("this video's"); + expect(itemCharacter("p-3")).toBe("hostman"); + await it.locator("[data-item-character-clear]").click(); + await expect(it).toHaveCount(0); + expect(itemCharacter("p-3")).toBe(null); + // Undo: the last change to this video's characters (the anonymous one added) is taken back. + await mine.locator("[data-project-characters-undo]").click(); + await expect(anon).toHaveCount(0); + expect(own().map((c) => c.id)).toEqual(["hostman"]); +}); + test("the Cut tab's Reads and voices reaches the Voices page", async ({ page }) => { await page.goto(urls.projectHref(P, { tab: "cut" })); const { openPanel } = await import("./panels"); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -67,15 +67,19 @@ export const GROUPS = [ cmd: "cast", usage: [ " umtool cast [ls] | add <id> --name … --voice <engine:voice> [--handles a,b] | set <id> … | rm <id> | undo", - " | project <p> | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>", - " [--everywhere] | reread <p> <character> the CAST: characters' stock voices across projects (cast.json), a", - " project's characters and their drift, an audition of candidate voices (scored against the real voice)", + " | project <p> [add <id> … | set <id> … | rm <id> | undo | pool <id> | keep <character|@handle>]", + " | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>", + " [--everywhere] | reread <p> <character> the CAST: characters across projects (cast.json), each a", + " PRESET -- synthetic (voice, speed) and recorded (convert, clean, trim, a direction) -- a project's", + " characters, its OWN (characters.json: anonymous ones), their drift, an audition of candidate voices", ], docs: [ - ["`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 [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--speed s] [--convert-engine e] [--convert-voice v] [--convert-pitch target\\|source\\|contour] [--convert-semitones n] [--enhance on\\|off] [--trim on\\|off] [--trim-pad ms] [--direction \"…\"] [--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, one writer, an undo point a write. **A character is a PRESET**, two of them ([knobs.md](knobs.md#a-character-is-a-preset)): `synthetic` -- the STOCK voice it reads in (`--voice`) and its speed (`--speed` 0.5–2; Orpheus has none) -- and `recorded` -- what a recording of them is made into: the stock voice (`--convert-voice`; a file or a recording is refused), the engine, 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), whether it is cleaned first (`--enhance`), its edges trimmed to speech (`--trim`, `--trim-pad` the ms kept either side) and a `--direction` (one line for the person reading, never sent to a model). `set` lays the flags given over the presets; `default` for one takes that key off; `--no-convert`, `--no-speed`. A version 1 file (`voice`, `convert` at a character's top) reads as these presets and the first write makes it version 2 (`undo` puts the old file back). A followed pitch on an engine that has none, semitones with nothing followed, a speed or a pad out of range: **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"], + "a project's characters: each one's voice now (and speed) and **where it comes from** -- the chain one read asks, first hit wins: the command's flags, the item's own character (`posts character`), this video's character for the author (then its voice map), the cast's, the narrator's, the default -- what a recording of them is made into, its stale reads; this video's own characters; the items that name their own. `use`: the voice for this project (its own character's when it has one for them, else the voice map) or everywhere, and the re-reads that asks for"], + ["`cast project <project> add <id> [--name \"…\"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\\|@handle> [--anonymous]` `[--json]`", + "**THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written"], ["`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)"], ], @@ -1020,14 +1024,16 @@ export const GROUPS = [ "a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**)"], ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--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= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`", "a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."], - ["`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 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] [--speed s] [--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 item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), 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 character <project> <item> [<character> \\| --clear] [--json]`", + "**THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **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] [--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 narrate <project> <item> --recording <file> [--as <character>] [--no-clean\\|--clean] [--no-trim\\|--trim] [--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. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--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 @@ -87,6 +87,14 @@ const window_ = () => [num("--at", { help: "the window's start, s" }), num("--du // ---- the rows ------------------------------------------------------------------- const form = (verb, target, summary, args, extra = {}) => ({ verb, summary, target, ui: "form", args, ...extra }); +/** A character's preset flags (`umtool cast add|set`, `cast project <p> add|set`: castCli.mjs fieldsOf). */ +const presetArgs = () => [ + num("--speed", { help: "its voice's speed, 0.5–2 (Orpheus has none)" }), + pick("--convert-engine", ["openvoice", "seed-vc", "default"]), opt("--convert-voice", { help: "engine:voice -- a STOCK voice, never a file" }), + pick("--convert-pitch", ["target", "source", "contour", "default"], { help: "the pitch a converted read lands on" }), num("--convert-semitones", { help: "-12…12, moves a followed pitch" }), + pick("--enhance", ["on", "off", "default"], { help: "a recording is cleaned first" }), pick("--trim", ["on", "off", "default"], { help: "a recording's edges trimmed to speech" }), + opt("--trim-pad", { help: "ms kept either side, 0–2000 (or default)" }), opt("--direction", { help: "one line for the person reading (never sent to a model)" }), +]; /** A row's block menu (lane block-menus L8b): the block kinds that offer it, and what each fills in. */ const B = (blocks, fromBlock, more = {}) => ({ blocks, fromBlock, ...more }); const none = (verb, target, summary, reason, extra = {}) => ({ verb, summary, target, ui: "none", reason, args: [], ...extra }); @@ -128,20 +136,32 @@ export const VERBS = Object.freeze([ // ---- the cast ---- form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }), - form("cast add", "corpus", "a character: name, stock voice, handles", [ + form("cast add", "corpus", "a character: name, stock voice, handles, its two presets", [ 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" }), - 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"), + ...presetArgs(), 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 set", "corpus", "change a character: its name, handles, presets", [ + arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), ...presetArgs(), + opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--no-speed"), bool("--narrator"), bool("--no-narrator"), ]), form("cast rm", "corpus", "a character out of the cast (an undo point)", [arg("id")]), form("cast undo", "corpus", "the cast as it was before its last write", []), - form("cast project", "project", "the project's characters, their voices and drift", [project()]), + form("cast project", "project", "the project's characters: each one's voice, where it comes from, its drift; this video's own", [project()]), + // This video's OWN characters (<project>/narration/characters.json; castStore.mjs: one writer, an undo point a write). + form("cast project add", "project", "a character of this video only (anonymous: shown under Anon 1 …)", [ + project(), arg("id"), opt("--name", { help: "required unless --anonymous" }), opt("--voice", { help: "engine:voice (none: the layers under it)" }), opt("--handles", { help: "a,b" }), + bool("--anonymous", "goes by a shown name on umtool's pages; never enters the pool (the cut's card is not anonymised yet)"), opt("--shown", { help: "the shown name (default: the next Anon n)" }), ...presetArgs(), opt("--note"), + ], { shape: "cast project <project> add <id>" }), + form("cast project set", "project", "change a character of this video's", [ + project(), arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--shown"), ...presetArgs(), opt("--note"), opt("--add-handle"), opt("--remove-handle"), + bool("--no-voice", "no voice of its own: the layers under it"), bool("--no-convert"), bool("--no-speed"), bool("--anonymous"), bool("--no-anonymous"), + ], { shape: "cast project <project> set <id>" }), + form("cast project rm", "project", "a character out of this video's (an undo point)", [project(), arg("id")], { shape: "cast project <project> rm <id>" }), + form("cast project undo", "project", "this video's characters as they were before their last write", [project()], { shape: "cast project <project> undo" }), + form("cast project pool", "corpus", "Add to the pool: this video's character into the cast", [project(), arg("id")], { shape: "cast project <project> pool <id>" }), + form("cast project keep", "project", "Keep in this video only: a cast character copied here, or an author given one", [ + project(), arg("character", { allowAt: true, help: "a cast character's id, or @handle" }), bool("--anonymous"), opt("--shown"), + ], { shape: "cast project <project> keep <character>" }), form("cast audition", "project", "one line read by 2-6 candidate voices, scored against the real voice", [ arg("character", { allowAt: true, help: "a character id or @handle" }), opt("--voices", { required: true, help: "engine:voice,engine:voice,…" }), project({ name: "--project", required: false }), opt("--text", { type: "text" }), opt("--item"), num("--line"), bool("--stock"), bool("--no-score"), bool("--score-only"), @@ -468,6 +488,7 @@ function posts() { 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>" }), + p("character", "draft", "the character one post item's own read is made with", [item(), arg("character", { required: false, help: "a character's id (this video's own, else the cast's); none: print it" }), bool("--clear", "by its author's handle again")], POST_ITEM), p("voices", "draft", "the voice map a thread read uses", [pick("op", ["ls", "set", "remove"], { required: true }), arg("handle", { required: false, help: "a handle, or *" }), arg("voice", { required: false })], { shape: "posts voices <project> <op>" }), p("fit", "draft", "narrated posts' videos cut to their best part", [items(), bool("--all"), num("--linger"), dry()], { ...Q, ...POST_ITEMS }), p("fx", "draft", "a post item's word zooms, captions, clock, slams", [ diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs @@ -108,7 +108,8 @@ test("the store: one writer, a stale token refused, undo points, a broken file n test("umtool cast ls/add/set/rm/undo: the characters across projects", async () => { let r = await cast(["add", "hostman", "--name", "Host Man", "--voice", "orpheus:zac", "--handles", "@HostMan", "--speakers", "Host", "--json"]); assert.equal(r.code, 0, r.text()); - assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "orpheus:zac", speakers: ["Host"] }); + // A character as the CLI says it: version 2's presets, and the `voice` (and `convert`) they answer to. + assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "orpheus:zac" }, speakers: ["Host"], voice: "orpheus:zac" }); r = await cast(["add", "hostman", "--name", "Again", "--voice", "orpheus:zac"]); assert.equal(r.code, 1); assert.match(r.text(), /in the cast already/); @@ -226,7 +227,7 @@ test("cast project: each character's voice now and where it comes from, its drif // --everywhere for an author the cast does not know: a new character from the handle. r = await cast(["use", "voices", "@guest", "kokoro:af_heart", "--everywhere", "--json"]); assert.equal(r.code, 0, r.text()); - assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], voice: "kokoro:af_heart" }); + assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], synthetic: { voice: "kokoro:af_heart" }, voice: "kokoro:af_heart" }); // reread --dry-run lists; reread makes them (the stub editor is not here: the plan alone). r = await cast(["reread", "voices", "hostman", "--dry-run", "--json"]); assert.deepEqual(r.json().items.map((x) => x.argv.join(" ")), ["posts narrate voices p-1 --take"]); diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs @@ -104,18 +104,25 @@ export function characterLines(manifest, handles) { } /** - * The character `who` names for an audition: a cast character (its id, a handle, its name), else an AUTHOR of the + * The character `who` names for an audition: one of the project's own characters (its id, a handle), a cast character (its id, a handle, its name), else an AUTHOR of the * project by @handle (`{ id, name, handles, voice: null }`). Throws AuditionError naming what is missing. */ export async function auditionCharacter(cast, who, { project = null, manifest = null } = {}) { - const { characterOf, findCharacter } = await import("umtool-report-to-video/cast"); + const { characterOf, findCharacter, projectCharactersOf, shownNameOf } = await import("umtool-report-to-video/cast"); const w = String(who ?? "").trim(); if (!w) throw new AuditionError("an audition is of a character (its id, or @handle)"); + // This video's own characters first (narration/characters.json): by id, then by a handle -- named as it is shown. + const own = project ? projectCharactersOf((await (await import("./castStore.mjs")).readProjectCharacters(project.dir)).doc) : []; + const mine = (c) => ({ ...c, name: shownNameOf(c), handles: c.handles ?? [], voice: c.voice ?? null }); if (!w.startsWith("@")) { + const p = own.find((x) => x.id === w.toLowerCase()); + if (p) return mine(p); const c = findCharacter(cast, w); if (c) return c; } const h = handleKey(w); + const p = own.find((x) => (x.handles ?? []).includes(h)); + if (p) return mine(p); const c = characterOf(cast, h); if (c) return c; if (!project) throw new AuditionError(`${w} is not in the cast (umtool cast ls), and no --project names it`); diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs @@ -1,13 +1,17 @@ // `umtool cast` (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"): the CHARACTERS across projects -// and their voices, a project's characters, an AUDITION of candidate voices, and the voice a character reads in -- -// for a project (its voice map) or everywhere (the cast) -- with the re-reads that asks for. +// and their presets, a project's characters (the chain's answer for each author, and the project's OWN characters), +// an AUDITION of candidate voices, and the voice a character reads in -- for a project or everywhere (the cast) -- +// with the re-reads that asks for. // // umtool cast [ls] [--json] -// umtool cast add <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e] -// [--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 add <id> --name "…" --voice <engine:voice> [the preset flags] [--handles a,b] [--speakers Name,…] [--avatar …] [--note "…"] [--narrator] [--json] +// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json] // umtool cast rm <id> [--json] · umtool cast undo [--json] // umtool cast project <p> [--json] +// umtool cast project <p> add <id> [--name "…"] [--voice <engine:voice>] [the preset flags] [--handles a,b] [--anonymous [--shown "…"]] [--json] +// umtool cast project <p> set <id> [the same flags] [--no-voice] [--no-anonymous] … · rm <id> · undo +// umtool cast project <p> pool <id> its character into the cast ("Add to the pool") +// umtool cast project <p> keep <character|@handle> [--anonymous [--shown "…"]] a character of this video only // umtool cast audition <character|@handle> --voices a,b,… [--project <p>] [--text "…" | --item <id> | --line <n>] // [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson] // umtool cast use <p> <character|@handle> <voice> [--everywhere] [--json] @@ -15,49 +19,74 @@ // // Plain ESM: the CLI runs under bare node. import path from "node:path"; -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 { + ANON_NAME_PATTERN, CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, CAST_SPEED, DIRECTION_MAX, TRIM_PAD_MAX_MS, characterOf, characterView, convertPitchErrors, convertPitchLabel, + charactersOf, findCharacter, isQualifiedVoice, nextAnonName, projectCharactersOf, shownNameOf, upgradeCharacter, +} from "umtool-report-to-video/cast"; +import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; -import { CastError, castFile, castForProject, castWrite, readCast, undoCast } from "./castStore.mjs"; +import { CastError, castFile, castForProject, castWrite, projectCharactersWrite, readCast, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs"; + +const PRESET_FLAGS = "[--speed <s>] [--convert-engine openvoice|seed-vc] [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones <n>] [--enhance on|off|default] [--trim on|off|default] [--trim-pad <ms>|default] [--direction \"…\"]"; 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>] [--convert-pitch target|source|contour] [--convert-semitones <n>]", + " umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…]", + ` ${PRESET_FLAGS}`, " [--avatar …] [--note \"…\"] [--narrator] [--json]", - " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]", + " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json]", " umtool cast rm <id> [--json]", " umtool cast undo [--json]", " umtool cast project <project> [--json]", + " umtool cast project <project> add <id> [--name \"…\"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags] [--json]", + " umtool cast project <project> set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-voice] [--no-convert] [--no-speed] [--no-anonymous] [--json]", + " umtool cast project <project> rm <id> | undo | pool <id> | keep <character|@handle> [--anonymous [--shown \"…\"]] [--json]", " umtool cast audition <character|@handle> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--project <p>]", " [--text \"…\" | --item <id> | --line <n> | --stock] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]", " umtool cast use <project> <character|@handle> <engine:voice> [--everywhere] [--json]", " umtool cast reread <project> <character|@handle> [--dry-run] [--json]", "", " 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) 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", - " narrator's, the default.", - " project: every character the project's reads use, the voice each reads in now and where it comes from, its", - " picked reads in another voice (drift: re-read them), the cast voices the project overrides, its reference.", + " projects -- an id, a name, their handles (X handles / channel slugs) and TWO PRESETS, picked by how a read is made:", + " SYNTHETIC: the STOCK voice they read in (--voice engine:voice) and its speed (--speed 0.5-2; Orpheus has none).", + " RECORDED (a recording of them made their read): the voice it 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), whether it is cleaned first (--enhance on|off; default on), whether its edges are trimmed to speech", + " (--trim on|off; default on) and the room kept either side (--trim-pad <ms>), and a DIRECTION (--direction: one", + " line for the person reading -- \"higher, brisk, amused\" -- never sent to a model; \"\" removes it). A convert", + " target is always a STOCK synthetic voice: a file or a recording is refused. `default` for a convert flag, --enhance,", + " --trim or --trim-pad takes that key off (the default again). Also 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 version 1 file (voice, convert at a character's top) reads as these presets;", + " the first write after makes it version 2 (undo puts the old file back).", + " ONE READ's PRESET, first hit wins: the command's flags (--voice-for, --voice, --speed, --as, --pitch), the item's", + " own character (umtool posts character), this video's character for the author (project add; then its voice map,", + " umtool posts voices), the cast's, the narrator's, the default.", + " project: every character the project's reads use, the voice each reads in now and WHERE IT COMES FROM (item,", + " project, cast, narrator, default), its speed, its picked reads in another voice (drift: re-read them), the cast", + " voices the project overrides, its reference; this video's own characters; the items that name their own.", + " project <p> add|set|rm|undo: THIS VIDEO's OWN characters (<p>/narration/characters.json, one writer, an undo", + " point per write) -- the same shape, for people who must not enter the pool. --anonymous: it goes by a SHOWN NAME", + ` (--shown; default the next of "${ANON_NAME_PATTERN.replace("{n}", "1")}", "${ANON_NAME_PATTERN.replace("{n}", "2")}" …) on the Voices page, in cast project and in a recording's note, and never`, + " enters the pool. The cut's ON-SCREEN CARD IS NOT ANONYMISED YET: it still shows the post's author. --voice is optional", + " here: a character with none leaves the voice to the layers under it. pool <id>: it moves into the cast (an", + " anonymous one is refused). keep <character|@handle>: a cast character copied here (its presets changed for this", + " video only), or an author with no character given one here, in the voice they read in now.", " audition: one line (--text; --item: the character's line from that item; --line n: its n-th line; default its", " first, else a stock line) read by each candidate (2-6) through the editor's tts op (a job; Orpheus is heavy,", " Kokoro fast), kept at one loudness in <p>/narration/auditions/ (a re-audition is a cache hit), and with --project", " scored for closeness to the character's real voice (TitaNet-small, local; speakers.json). --no-score: synthesize", " only; --score-only: score what is kept.", - " use: the voice for this project (its voice map) or --everywhere (the cast; the project's own override of it is", - " removed); then the items whose picked reads say the character in another voice -- reread makes them (a new take", - " each, picked, awaiting approval). Exit 0 done · 1 refused or failed · 2 usage.", + " use: the voice for this project (its own character's when it has one for them, else its voice map) or", + " --everywhere (the cast; the project's own override of it is removed); then the items whose picked reads say the", + " character in another voice -- reread makes them (a new take 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", "--convert-pitch", "--convert-semitones", "--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", "--speed", "--enhance", "--trim", "--trim-pad", "--direction", "--shown"]); const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean); function parse(args) { @@ -75,6 +104,20 @@ function parse(args) { return { words, flags, str: (k) => flags.get(k)?.at(-1) ?? null, has: (k) => flags.has(k), all: (k) => flags.get(k) ?? [] }; } +/** `on` / `off` / `default` as true / false / null (null: the key removed -- the default again). */ +function onOff(flag, v) { + const x = String(v).trim().toLowerCase(); + if (x === "on" || x === "true" || x === "yes") return true; + if (x === "off" || x === "false" || x === "no") return false; + if (x === "default") return null; + throw new CastError(`${flag} is on, off or default (got ${v || "nothing"})`); +} +const numberOf = (flag, v, lo, hi, what) => { + const n = Number(v); + if (String(v).trim() === "" || !Number.isFinite(n) || n < lo || n > hi) throw new CastError(`${flag} is ${what} from ${lo} to ${hi} (got ${v || "nothing"})`); + return n; +}; + /** The fields `add`/`set` take from the flags (only those given). */ function fieldsOf(p) { const f = {}; @@ -84,20 +127,38 @@ function fieldsOf(p) { if (!isQualifiedVoice(v)) throw new CastError(`--voice is a STOCK voice with its engine: kokoro:am_michael, orpheus:zac (got ${v})`); f.voice = v; } + if (p.str("--speed") !== null) f.speed = numberOf("--speed", p.str("--speed"), CAST_SPEED[0], CAST_SPEED[1], "a number"); if (p.str("--handles") !== null) f.handles = splitList(p.str("--handles")).map(handleKey); 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 (["--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 ")}`); - 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(", ")}`); + // `default` for one of them takes that key off the entry (the editor's engine, the character's own voice, no pitch said). + const given = (k) => (p.str(k) !== null && p.str(k).trim().toLowerCase() !== "default" ? p.str(k).trim() : null); + const dropped = (k) => p.str(k) !== null && p.str(k).trim().toLowerCase() === "default"; + const ce = given("--convert-engine"); + if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")} (or default)`); + const cp = given("--convert-pitch"); + if (cp !== null && !CAST_CONVERT_PITCH.includes(cp)) throw new CastError(`--convert-pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (or default)`); 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}`); + const cvv = given("--convert-voice"); + if (cvv && !isQualifiedVoice(cvv)) throw new CastError(`--convert-voice is a STOCK voice with its engine, kokoro:am_michael -- never a file or a recording (got ${cvv})`); // 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 } : {}) }; + f.convert = { + ...(ce ? { engine: ce } : dropped("--convert-engine") ? { engine: null } : {}), ...(cvv ? { voice: cvv } : dropped("--convert-voice") ? { voice: null } : {}), + ...(cp ? { pitch: cp } : dropped("--convert-pitch") ? { pitch: null } : {}), ...(cs !== null ? { semitones: cs } : {}), + }; } + if (p.str("--enhance") !== null) f.enhance = onOff("--enhance", p.str("--enhance")); + if (p.str("--trim") !== null) f.trimOn = onOff("--trim", p.str("--trim")); + if (p.str("--trim-pad") !== null) f.trimPad = p.str("--trim-pad").trim().toLowerCase() === "default" ? null : numberOf("--trim-pad", p.str("--trim-pad"), 0, TRIM_PAD_MAX_MS, "a number of milliseconds"); + if (p.str("--direction") !== null) { + const d = p.str("--direction").replace(/\s+/g, " ").trim(); + if (d.length > DIRECTION_MAX) throw new CastError(`--direction is one line for the person reading (at most ${DIRECTION_MAX} characters)`); + f.direction = d; + } + if (p.str("--shown") !== null) f.shown = p.str("--shown").trim(); return f; } @@ -107,14 +168,116 @@ function fieldsOf(p) { */ function convertOver(before, given) { const cv = { ...(before ?? {}), ...given }; - if (given.pitch === "target" && given.semitones === undefined) delete cv.semitones; + for (const k of Object.keys(cv)) if (cv[k] === null) delete cv[k]; + if ((given.pitch === "target" || given.pitch === null) && 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}` : ""}`; +/** + * THE CHARACTER the flags make, pure: `before` (version 2's shape; null: a new one, `id`) with the fields given laid + * over its presets -- `layer` "cast" (it may be the narrator: the caller clears the others') or "project" (it may be + * anonymous, shown under `anon()`'s name when none is given; its voice may be removed). Refused in a sentence. + */ +export function characterFrom(before, id, f, p, { layer = "cast", anon = () => ANON_NAME_PATTERN.replace("{n}", "1") } = {}) { + const c = before ? JSON.parse(JSON.stringify(upgradeCharacter(before))) : { id, name: "", handles: [] }; + if (f.name !== undefined) c.name = f.name; + if (f.handles) c.handles = f.handles; + if (!Array.isArray(c.handles)) c.handles = []; + 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); + // The synthetic preset. + const syn = { ...(c.synthetic ?? {}) }; + if (f.voice) syn.voice = f.voice; + if (f.speed !== undefined) syn.speed = f.speed; + if (p.has("--no-speed") || syn.speed === 1) delete syn.speed; + if (p.has("--no-voice")) { + if (layer !== "project") throw new CastError("--no-voice is for a character of one video (umtool cast project <p> set …): a cast character has a stock voice"); + delete syn.voice; + delete syn.speed; + } + if (syn.speed !== undefined && !syn.voice) throw new CastError("--speed is its voice's: give the character a voice too (--voice <engine:voice>)"); + if (Object.keys(syn).length) c.synthetic = syn; + else delete c.synthetic; + // The recorded preset. + const rec = { ...(c.recorded ?? {}) }; + if (f.convert) rec.convert = convertOver(rec.convert, f.convert); + if (p.has("--no-convert")) delete rec.convert; + if (rec.convert && !Object.keys(rec.convert).length) delete rec.convert; + if (f.enhance !== undefined) { + if (f.enhance === null) delete rec.enhance; + else rec.enhance = f.enhance; + } + if (f.trimOn !== undefined || f.trimPad !== undefined) { + const t = { ...(rec.trim ?? {}) }; + if (f.trimOn === null) delete t.on; + else if (f.trimOn !== undefined) t.on = f.trimOn; + if (f.trimPad === null) delete t.padMs; + else if (f.trimPad !== undefined) t.padMs = f.trimPad; + if (f.trimOn === null && f.trimPad === undefined) delete t.padMs; + if (Object.keys(t).length) rec.trim = t; + else delete rec.trim; + } + if (f.direction !== undefined) { + if (f.direction) rec.direction = f.direction; + else delete rec.direction; + } + if (Object.keys(rec).length) c.recorded = rec; + else delete c.recorded; + if (f.speakers) c.speakers = f.speakers; + for (const k of ["avatar", "note"]) { + if (f[k] !== undefined) c[k] = f[k]; + if (c[k] === "") delete c[k]; + } + if (c.speakers && !c.speakers.length) delete c.speakers; + if (layer === "cast") { + if (p.has("--anonymous") || f.shown !== undefined) throw new CastError("an anonymous character is one video's, never the pool's: umtool cast project <p> add <id> --anonymous"); + if (p.has("--narrator")) c.narrator = true; + if (p.has("--no-narrator")) delete c.narrator; + } else { + if (p.has("--narrator")) throw new CastError("the narrator is a cast character (umtool cast set <id> --narrator)"); + if (p.has("--anonymous")) c.anonymous = true; + if (p.has("--no-anonymous")) { + delete c.anonymous; + delete c.shown; + } + if (f.shown !== undefined) { + if (!c.anonymous) throw new CastError("--shown is an anonymous character's shown name (--anonymous)"); + if (f.shown) c.shown = f.shown; + else delete c.shown; + } + if (c.anonymous && !c.shown) c.shown = anon(); + if (c.anonymous && !c.name) c.name = c.shown; + } + return upgradeCharacter(c); +} + +/** A character's recorded preset as words: "convert: seed-vc -> kokoro:am_michael, pitch contour +2 st; not cleaned; …". */ +function recordedWords(c) { + const rec = c.recorded; + if (!rec) return ""; + const cv = rec.convert; + const bits = []; + if (cv) bits.push(`convert: ${cv.engine ?? "default"} -> ${cv.voice ?? c.voice ?? "?"}${convertPitchLabel(cv) ? `, pitch ${convertPitchLabel(cv)}` : ""}`); + if (rec.enhance === false) bits.push("not cleaned"); + if (rec.trim?.on === false) bits.push("edges not trimmed"); + else if (typeof rec.trim?.padMs === "number") bits.push(`trim pad ${rec.trim.padMs} ms`); + if (rec.direction) bits.push(`direction: "${rec.direction}"`); + return bits.join("; "); +} + +/** A character as a line (a view: cast.mjs characterView). */ +const line = (c0) => { + const c = characterView(c0); + const speed = c.synthetic?.speed; + const voice = `${c.voice ?? "(no voice of its own)"}${typeof speed === "number" ? ` ×${speed}` : ""}`; + return `${c.id.padEnd(16)} ${voice.padEnd(20)} ${c.anonymous ? `${shownNameOf(c)} (anonymous; ${c.name})` : c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${recordedWords(c) ? ` ${recordedWords(c)}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`; +}; + +/** An id for a handle's new character ("kirsche.verstahl" -> "kirsche-verstahl"). */ +const idOfHandle = (h) => h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; async function projectOf(ref, reportsRoot) { const r = await resolveProject(ref, reportsRoot); @@ -131,19 +294,127 @@ export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {}) const { readSpeakers } = await import("./speakerCheck.mjs"); const { projectCharacters } = await import("./castProject.mjs"); const castRead = await castForProject(project.dir, reportsRoot); + const ownRead = await readProjectCharacters(project.dir); const map = await readVoiceMap(project.dir).catch(() => ({})); const speakers = await readSpeakers(project.dir).catch(() => []); - const view = projectCharacters(manifest, { map, cast: castRead.cast, speakers }); - return { manifest, map, castRead, speakers, view }; + const view = projectCharacters(manifest, { map, cast: castRead.cast, project: ownRead.doc, speakers }); + return { manifest, map, castRead, ownRead, speakers, view }; } -/** The handles `ref` names in a project: a character's (the cast's), or one @handle. */ -function handlesOf(ref, castRead, view) { - const c = findCharacter(castRead.cast, String(ref).replace(/^@+/, "")); - if (c && !String(ref).startsWith("@")) return { character: c, handles: [...(c.handles ?? [])] }; +/** The handles `ref` names in a project: a character's (the project's own, else the cast's), or one @handle. */ +function handlesOf(ref, castRead, view, ownRead = null) { + const bare = String(ref).replace(/^@+/, ""); + const at = String(ref).startsWith("@"); + const own = projectCharactersOf(ownRead?.doc); + const mine = at ? null : own.find((c) => c.id === bare.toLowerCase()) ?? null; + if (mine) return { character: mine, layer: "project", handles: [...(mine.handles ?? [])] }; + const c = findCharacter(castRead.cast, bare); + if (c && !at) return { character: c, layer: "cast", handles: [...(c.handles ?? [])] }; const h = handleKey(ref); const row = view?.characters?.find((r) => r.handles.includes(h)) ?? null; - return { character: characterOf(castRead.cast, h), handles: [h], row }; + const ownByHandle = own.find((x) => (x.handles ?? []).includes(h)) ?? null; + return { character: ownByHandle ?? characterOf(castRead.cast, h), layer: ownByHandle ? "project" : characterOf(castRead.cast, h) ? "cast" : null, handles: [h], row }; +} + +/** + * `umtool cast project <p> add|set|rm|undo|pool|keep …`: THIS VIDEO's OWN characters (castStore.mjs + * projectCharactersWrite: one writer, an undo point a write), and the two ways between them and the pool. + */ +async function projectCharactersCommand(project, op, rest, p, { reportsRoot, out, file }) { + const what = (w) => `${w} (${project.id})`; + if (op === "add" || op === "set") { + const [id] = rest; + if (!id) throw new CastError(`cast project ${op} takes the character's id`); + const f = fieldsOf(p); + const r = await projectCharactersWrite(project.dir, (chars) => { + const at = chars.findIndex((c) => c.id === id); + if (op === "add") { + if (at >= 0) throw new CastError(`${id} is one of ${project.id}'s characters already (umtool cast project ${project.id} set ${id} …)`); + if (!f.name && !p.has("--anonymous")) throw new CastError('cast project add takes --name "…" (or --anonymous: its shown name)'); + const c = characterFrom(null, id, f, p, { layer: "project", anon: () => nextAnonName(chars) }); + chars.push(c); + return { changed: "added", character: c }; + } + if (at < 0) throw new CastError(`no ${id} among ${project.id}'s characters (umtool cast project ${project.id})`); + const c = characterFrom(chars[at], id, f, p, { layer: "project", anon: () => nextAnonName(chars.filter((_, i) => i !== at)) }); + chars[at] = c; + return { changed: "updated", character: c }; + }, { what: what(`${op} ${id}`) }); + out({ ok: true, scope: "project", changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} in ${project.id}: ${line(r.character)}`); + return 0; + } + if (op === "rm" || op === "remove") { + const [id] = rest; + if (!id) throw new CastError("cast project rm takes the character's id"); + const r = await projectCharactersWrite(project.dir, (chars) => { + const at = chars.findIndex((c) => c.id === id); + if (at < 0) throw new CastError(`no ${id} among ${project.id}'s characters`); + const [gone] = chars.splice(at, 1); + return { removed: gone }; + }, { what: what(`rm ${id}`) }); + out({ ok: true, scope: "project", removed: characterView(r.removed), token: r.token }, `removed ${id} from ${project.id}'s characters (umtool cast project ${project.id} undo puts it back)`); + return 0; + } + if (op === "undo") { + const r = await undoProjectCharacters(project.dir); + out({ ok: true, scope: "project", undone: r.undone, at: r.at, left: r.left, token: r.token }, `undone: ${r.undone} (${r.left} undo point(s) left)`); + return 0; + } + if (op === "pool") { + // "Add to the pool": the project's character into the cast, then out of the project (the cast's answers here too). + const [id] = rest; + if (!id) throw new CastError("cast project pool takes the character's id"); + const own = await readProjectCharacters(project.dir); + if (own.error) throw new CastError(own.error); + const c = (own.doc.characters ?? []).map(upgradeCharacter).find((x) => x.id === id); + if (!c) throw new CastError(`no ${id} among ${project.id}'s characters`); + if (c.anonymous) throw new CastError(`${id} is anonymous: it stays in this video (umtool cast project ${project.id} set ${id} --no-anonymous first, if that is meant)`); + if (!c.synthetic?.voice) throw new CastError(`${id} has no stock voice: a cast character has one (umtool cast project ${project.id} set ${id} --voice <engine:voice>)`); + const castPath = (await castForProject(project.dir, reportsRoot)).file ?? file; + const w = await castWrite(castPath, (chars) => { + if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …; or umtool cast project ${project.id} rm ${id})`); + chars.push(c); + return { character: c }; + }, { what: `${id} into the pool (from ${project.id})` }); + await projectCharactersWrite(project.dir, (chars) => { + const at = chars.findIndex((x) => x.id === id); + if (at >= 0) chars.splice(at, 1); + return {}; + }, { what: what(`${id} into the pool`) }); + out({ ok: true, scope: "cast", changed: "pooled", character: characterView(w.character), token: w.token }, `${id} is in the pool now, for every project: ${line(w.character)}`); + return 0; + } + if (op === "keep") { + // "Keep in this video only": a cast character copied here, or an author with none given one here. + const [who] = rest; + if (!who) throw new CastError("cast project keep takes a cast character (its id) or an author (@handle)"); + const v = await projectView(project, { reportsRoot }); + if (v.ownRead.error) throw new CastError(v.ownRead.error); + const t = handlesOf(who, v.castRead, v.view, v.ownRead); + if (t.layer === "project") throw new CastError(`${t.character.id} is one of ${project.id}'s characters already (umtool cast project ${project.id} set ${t.character.id} …)`); + const f = fieldsOf(p); + const r = await projectCharactersWrite(project.dir, (chars) => { + let base; + if (t.character) { + // The cast's, as it is now -- never its narrator mark (the narrator is the cast's). + const { narrator: _n, ...copy } = upgradeCharacter((v.castRead.cast.characters ?? []).find((x) => x.id === t.character.id)); + base = copy; + } else { + const h = t.handles[0]; + if (!h || h === "*") throw new CastError(`${who}: no such character, and not a handle`); + const now = t.row?.voice ?? null; + const spec = now && now.engine ? voiceSpecOf({ engine: now.engine, voice: now.voice }) : null; + base = { id: idOfHandle(h), name: (t.row?.name || h).slice(0, 80), handles: [h], ...(isQualifiedVoice(spec) ? { synthetic: { voice: spec } } : {}) }; + } + if (chars.some((x) => x.id === base.id)) throw new CastError(`${base.id} is one of ${project.id}'s characters already`); + const c = characterFrom(base, base.id, f, p, { layer: "project", anon: () => nextAnonName(chars) }); + chars.push(c); + return { character: c }; + }, { what: what(`keep ${who}`) }); + out({ ok: true, scope: "project", changed: "kept", character: characterView(r.character), token: r.token }, `kept in ${project.id} only: ${line(r.character)}`); + return 0; + } + throw new CastError(`cast project <p>: nothing (the view), add, set, rm, undo, pool or keep (not ${op})`); } /** @@ -186,27 +457,20 @@ 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: convertOver(null, f.convert) } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) }; + const c = characterFrom(null, id, f, p, { layer: "cast" }); 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)`); - // 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; - if (p.has("--narrator")) { - for (const x of chars) delete x.narrator; - c.narrator = true; - } - if (p.has("--no-narrator")) delete c.narrator; - for (const k of ["note", "avatar"]) if (c[k] === "") delete c[k]; + // The flags are laid over the character's presets: --convert-pitch alone keeps its engine and voice. + const c = characterFrom(chars[at], id, f, p, { layer: "cast" }); + if (p.has("--narrator")) for (const x of chars) delete x.narrator; + if (p.has("--narrator")) c.narrator = true; chars[at] = c; return { changed: "updated", character: c }; }, { what: `${sub} ${id}` }); - out({ ok: true, changed: r.changed, character: r.character, token: r.token }, `${r.changed} ${line(r.character)}`); + out({ ok: true, changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} ${line(r.character)}`); return 0; } if (sub === "rm" || sub === "remove") { @@ -218,7 +482,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons const [gone] = chars.splice(at, 1); return { removed: gone }; }, { what: `rm ${id}` }); - out({ ok: true, removed: r.removed, token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`); + out({ ok: true, removed: characterView(r.removed), token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`); return 0; } if (sub === "undo") { @@ -227,20 +491,32 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons return 0; } if (sub === "project") { - const [ref] = rest; + const [ref, psub, ...prest] = rest; if (!ref) throw new CastError("cast project takes the project"); const project = await projectOf(ref, reportsRoot); - const { view, map, castRead } = await projectView(project, { reportsRoot }); + if (psub && psub !== "ls") return await projectCharactersCommand(project, psub, prest, p, { reportsRoot, out, file }); + const { view, map, castRead, ownRead } = await projectView(project, { reportsRoot }); if (json) { - log(JSON.stringify({ ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.error } : {}), map, ...view }, null, 2)); + log(JSON.stringify({ + ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.error } : {}), + charactersFile: ownRead.file, charactersToken: ownRead.token, ...(ownRead.error ? { charactersError: ownRead.error } : {}), map, ...view, + }, null, 2)); return 0; } - log(`${project.id}: ${view.characters.length} character(s); the narrator ${view.narrator.spec} (${view.narrator.from})${castRead.error ? `\n the cast is NOT read: ${castRead.error}` : ""}`); + const fromWords = (v) => `${v.from}${v.character && v.from !== "narrator" && v.from !== "default" ? `: ${v.character}` : ""}`; + const speedWords = (v) => (typeof v.speed === "number" ? ` ×${v.speed}` : ""); + log(`${project.id}: ${view.characters.length} character(s); the narrator ${view.narrator.spec} (${view.narrator.from})${castRead.error ? `\n the cast is NOT read: ${castRead.error}` : ""}${ownRead.error ? `\n this video's characters are NOT read: ${ownRead.error}` : ""}`); for (const c of view.characters) { - log(` ${(c.character ? c.character.id : c.key).padEnd(18)} ${c.voice.spec.padEnd(20)} (${c.voice.from}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}`); + log(` ${(c.character ? c.character.id : c.key).padEnd(18)} ${`${c.voice.spec}${speedWords(c.voice)}`.padEnd(20)} (${fromWords(c.voice)}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}${c.character?.anonymous ? ` shown as "${c.character.shown}"` : ""}`); + if (c.recorded && (c.character?.recorded || c.recorded.convert.voice)) log(` a recording of them: ${c.recorded.convert.voice ? `converted to ${c.recorded.convert.voice}${c.recorded.convert.engine ? ` (${c.recorded.convert.engine})` : ""}${convertPitchLabel(c.recorded.convert) ? `, pitch ${convertPitchLabel(c.recorded.convert)}` : ""}` : "not converted (no stock voice)"}; ${c.recorded.enhance ? "cleaned" : "not cleaned"}; ${c.recorded.trim.on ? `edges trimmed${c.recorded.trim.padMs !== null ? ` (pad ${c.recorded.trim.padMs} ms)` : ""}` : "edges not trimmed"}${c.recorded.direction ? `; direction: "${c.recorded.direction}"` : ""}`); if (c.drift.length) log(` ${c.drift.length} read(s) in another voice: ${c.drift.map((d) => `${d.id} ${d.reads} (now ${d.want})`).join(", ")} -- umtool cast reread ${project.id} ${c.character?.id ?? `@${c.handles[0]}`}`); } for (const o of view.overrides) log(` note: @${o.handle} (${o.character}) reads in ${o.project} here -- the cast says ${o.cast} (an override on purpose)`); + if (view.own.length) { + log(` this video's own characters (${ownRead.file}):`); + for (const c of view.own) log(` ${line(c)}`); + } + for (const it of view.itemCharacters) log(` item ${it.id} is read as ${it.character}${it.found ? ` (${it.layer === "project" ? "this video's" : "the cast's"}): ${it.voice.spec}${speedWords(it.voice)} (${fromWords(it.voice)})` : ` -- NO SUCH CHARACTER: it reads as its author does, ${it.voice.spec} (${fromWords(it.voice)}); umtool posts character ${project.id} ${it.id} --clear`}`); return 0; } if (sub === "use") { @@ -248,27 +524,35 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons if (!ref || !who || !voice) throw new CastError("cast use takes the project, the character (or @handle) and the voice: cast use quartering-diet thequartering kokoro:am_michael"); const project = await projectOf(ref, reportsRoot); const before = await projectView(project, { reportsRoot }); - const t = handlesOf(who, before.castRead, before.view); + if (before.ownRead.error) throw new CastError(before.ownRead.error); + const t = handlesOf(who, before.castRead, before.view, before.ownRead); if (!t.handles.length) throw new CastError(`${who} has no handles to give a voice (umtool cast set ${who} --add-handle <h>)`); if (!voiceRefOf(voice)) throw new CastError(`${voice} is not a stock voice (tara, kokoro:am_michael): a file or a recording is never a voice`); const { updateVoiceMap } = await import("./postSay.mjs"); const removed = []; let scope = "project"; + const cast = before.castRead.cast; + // This video's own characters that answer for these handles (their presets come before the cast's). + const ownFor = projectCharactersOf(before.ownRead.doc).filter((c) => (c.handles ?? []).some((h) => t.handles.includes(h))); if (p.has("--everywhere")) { + const anon = ownFor.find((c) => c.anonymous); + if (anon) throw new CastError(`${anon.id} is anonymous: it stays in this video, never the pool (umtool cast use ${project.id} ${anon.id} ${voice} sets its voice here)`); if (!isQualifiedVoice(voice)) throw new CastError(`--everywhere takes a voice with its engine (kokoro:am_michael), so every project reads it the same`); scope = "cast"; const castPath = before.castRead.file ?? file; + // The cast's character: the one named, else the one a handle belongs to (a project's own character is not it). + const target = t.layer === "cast" ? t.character : t.handles.map((h) => characterOf(cast, h)).find(Boolean) ?? null; await castWrite(castPath, (chars) => { - const c = t.character ? chars.find((x) => x.id === t.character.id) : null; - if (c) c.voice = voice; + const c = target ? chars.find((x) => x.id === target.id) : null; + if (c) c.synthetic = { ...(c.synthetic ?? {}), voice }; else { const h = t.handles[0]; - const id = h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; + const id = idOfHandle(h); if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already, without @${h}: umtool cast set ${id} --add-handle ${h}`); - chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], voice }); + chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], synthetic: { voice } }); } return {}; - }, { what: `${t.character?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` }); + }, { what: `${target?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` }); // Its voice everywhere -- here too: the project's own override of it goes. for (const h of t.handles) { if (h in before.map) { @@ -276,16 +560,29 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons removed.push(h); } } + // (A character of this video's own for the handle still answers first: said below, never removed unasked.) } else { - for (const h of t.handles) await updateVoiceMap(project.dir, { set: { handle: h, voice } }); + // This video's own character for a handle takes it (its preset answers before the voice map); else the map. + const own = projectCharactersOf(before.ownRead.doc); + const mineOf = (h) => own.find((c) => (c.handles ?? []).includes(h) && c.voice) ?? null; + const ids = [...new Set(t.handles.map((h) => mineOf(h)?.id).filter(Boolean))]; + if (ids.length) { + if (!isQualifiedVoice(voice)) throw new CastError(`${ids.join(", ")} is this video's own character: its voice names its engine (kokoro:am_michael)`); + await projectCharactersWrite(project.dir, (chars) => { + for (const c of chars) if (ids.includes(c.id)) c.synthetic = { ...(c.synthetic ?? {}), voice }; + return {}; + }, { what: `${ids.join(", ")} read${ids.length === 1 ? "s" : ""} in ${voice} (${project.id})` }); + } + for (const h of t.handles) if (!mineOf(h)) await updateVoiceMap(project.dir, { set: { handle: h, voice } }); } const after = await projectView(project, { reportsRoot }); const { rereadPlan } = await import("./castProject.mjs"); const plan = rereadPlan(project.id, after.manifest, after.view.characters.flatMap((c) => c.drift), t.handles); out( - { ok: true, scope, handles: t.handles, voice, removed, reread: plan.items.map((x) => ({ id: x.id, take: x.take, thread: x.thread, reads: x.reads, argv: x.argv })), skipped: plan.skipped }, + { ok: true, scope, handles: t.handles, voice, removed, ...(scope === "cast" && ownFor.some((c) => c.voice) ? { shadowedBy: ownFor.filter((c) => c.voice).map((c) => c.id) } : {}), reread: plan.items.map((x) => ({ id: x.id, take: x.take, thread: x.thread, reads: x.reads, argv: x.argv })), skipped: plan.skipped }, [ - `${t.handles.map((h) => `@${h}`).join(", ")} read${t.handles.length === 1 ? "s" : ""} in ${voice} ${scope === "cast" ? "everywhere (the cast)" : `in ${project.id} (its voice map)`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`, + `${t.handles.map((h) => `@${h}`).join(", ")} read${t.handles.length === 1 ? "s" : ""} in ${voice} ${scope === "cast" ? "everywhere (the cast)" : `in ${project.id}`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`, + ...(scope === "cast" ? ownFor.filter((c) => c.voice).map((c) => ` here, this video's own character ${c.id} still answers first (${c.voice}): umtool cast project ${project.id} rm ${c.id} follows the cast`) : []), plan.items.length ? ` ${plan.items.length} item(s) read them in another voice -- umtool cast reread ${project.id} ${who}:` : " no picked read says them in another voice", ...plan.items.map((x) => ` ${x.id} ${x.reads.map((r) => `${r.role} ${r.reads} -> ${r.want}`).join(", ")}`), ].join("\n"), @@ -297,7 +594,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons if (!ref || !who) throw new CastError("cast reread takes the project and the character (or @handle)"); const project = await projectOf(ref, reportsRoot); const v = await projectView(project, { reportsRoot }); - const t = handlesOf(who, v.castRead, v.view); + const t = handlesOf(who, v.castRead, v.view, v.ownRead); const { rereadPlan } = await import("./castProject.mjs"); const plan = rereadPlan(project.id, v.manifest, v.view.characters.flatMap((c) => c.drift), t.handles); if (p.has("--dry-run") || !plan.items.length) { diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -1,39 +1,52 @@ // A PROJECT's CAST (the Voices panel; `umtool cast project <p>`): every character the project's reads use -- the // post items' authors, the authors of the posts they answer, quote and link, and the narrator -- with the voice each -// reads in NOW and where it comes from (the project's map, the cast, the narrator's, the default), how many items it +// reads in NOW and where it comes from (the item's own character, the project's own characters and its map, the +// cast, the narrator's, the default: post-say.mjs voiceSourceOf, the chain every read asks), how many items it // reads, what its picked reads are actually in (stale ones: DRIFT), its real-voice reference (speakers.json) and its // lines to audition; and THE RE-READS a voice change asks for, as the commands that make them. // // Plain ESM. import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; import { handleKey, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; -import { castDrift, castVoiceMap, characterOf, charactersOf, convertTargetOf, narratorOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT } from "umtool-report-to-video/cast"; +import { + castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, recordedPresetOf, + shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT, +} from "umtool-report-to-video/cast"; import { characterLines } from "./castAudition.mjs"; const str = (v) => (typeof v === "string" ? v : ""); /** * The voice a piece of a picked read would be said in NOW, as the read that made it would ask (its own --voice-for - * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from }`. A read - * converted from a recording is compared with its character's convert target (the cast's), else not at all. + * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from, speed?, + * character? }`. A read converted from a recording is compared with its character's convert target (the chain's: + * cast.mjs characterForRead), else not at all. `project` is the project's own characters (characters.json's document). */ -export function resolverFor({ map = {}, cast = null, render = {} }) { - const castMap = castVoiceMap(cast); +export function resolverFor({ map = {}, cast = null, project = null, render = {} }) { + const castMap = castPresetMap(cast); + const layer = projectPresetMap(project, map); return (e, role, handle, take, read = null) => { if (read?.kind === "converted") { - const c = characterOf(cast, handle); - const ref = c ? voiceRefOf(convertTargetOf(c).voice) : null; - return ref ? { ...ref, from: "cast" } : null; + const who = characterForRead(e, { project, cast }); + const ref = who?.character && who.layer !== "narrator" ? voiceRefOf(convertTargetOf(who.character).voice) : null; + return ref ? { ...ref, from: who.layer } : null; } const k = postNarrationKnobs(e, render); const tr = take?.read?.kind === "thread" ? take.read : null; return resolvePieceVoice({ handle, role }, { - map, cast: castMap, overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null, + map: layer, cast: castMap, item: itemPresetOf(e, { project, cast }), overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null, narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine, }); }; } +/** A character as a row carries it: its id, name, presets (and the `voice` / `convert` they answer to), what it is. */ +const rowCharacter = (c, layer) => ({ + id: c.id, name: c.name, layer, ...(c.voice ? { voice: c.voice } : {}), ...(c.convert ? { convert: c.convert } : {}), + ...(c.synthetic ? { synthetic: c.synthetic } : {}), ...(c.recorded ? { recorded: c.recorded } : {}), + ...(c.note ? { note: c.note } : {}), ...(c.narrator ? { narrator: true } : {}), ...(c.anonymous ? { anonymous: true, shown: shownNameOf(c) } : {}), +}); + /** The post items' authors and context authors: `Map<handle, { handle, name, items: id[], context: id[] }>`. */ export function authorsOf(manifest) { const out = new Map(); @@ -57,21 +70,28 @@ export function authorsOf(manifest) { } /** - * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides }` -- each character - * `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from}, - * contextVoice?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines, weight }`, the most-read first. + * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides, own, itemCharacters }` -- each + * character `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from, + * speed?, character?}, contextVoice?, recorded?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines, + * weight }`, the most-read first. A handle's character is the project's own (characters.json) before the cast's; + * `character.layer` says which. `own` is every character the project holds, in the cut or not; `itemCharacters` the + * post items that name their own (`narration.character`), each with the character it names (`found: false`: no such + * one -- the read falls to the layers under it). */ -export function projectCharacters(manifest, { map = {}, cast = null, speakers = [] } = {}) { +export function projectCharacters(manifest, { map = {}, cast = null, project = null, speakers = [] } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs({}, render); - const resolve = resolverFor({ map, cast, render }); - const castMap = castVoiceMap(cast); + const resolve = resolverFor({ map, cast, project, render }); + const castMap = castPresetMap(cast); + const layer = projectPresetMap(project, map); + const pchars = projectCharactersOf(project); const drift = voiceDrift(manifest, resolve); const groups = new Map(); for (const a of authorsOf(manifest).values()) { - const c = characterOf(cast, a.handle); + const own = pchars.find((c) => (c.handles ?? []).includes(a.handle)) ?? null; + const c = own ?? characterOf(cast, a.handle); const key = c ? c.id : `@${a.handle}`; - const g = groups.get(key) ?? { key, character: c, name: c?.name ?? a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] }; + const g = groups.get(key) ?? { key, character: c, layer: c ? (own ? "project" : "cast") : null, name: c ? shownNameOf(c) : a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] }; g.handles.push(a.handle); for (const id of a.items) if (!g.itemIds.includes(id)) g.itemIds.push(id); for (const id of a.context) if (!g.contextIds.includes(id)) g.contextIds.push(id); @@ -82,19 +102,23 @@ export function projectCharacters(manifest, { map = {}, cast = null, speakers = for (const e of tl) if (e?.type === "post") for (const r of takeReads(e)) reads.push({ id: e.id, ...r }); const rows = [...groups.values()].map((g) => { const h = g.handles[0]; - const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id)) ?? null; - const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id)) ?? null; + // The handle's own voice: an item that names its own character answers for itself (itemCharacters), not for the handle. + const plain = (e) => !e?.narration?.character; + const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id) && plain(e)) ?? null; + const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id) && plain(e)) ?? null; const own = first ? resolve(first, "post", h, null) : null; - const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map, cast: castMap, narrator: k.voice, engine: k.engine }); + const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map: layer, cast: castMap, narrator: k.voice, engine: k.engine }); const now = own ?? ctx; const mine = new Set(g.handles); const sp = speakerFor(g.character ?? { name: g.name, handles: g.handles, id: h }, speakers); return { key: g.key, name: g.name, handles: g.handles, - character: g.character ? { id: g.character.id, name: g.character.name, voice: g.character.voice, ...(g.character.convert ? { convert: g.character.convert } : {}), ...(g.character.note ? { note: g.character.note } : {}), ...(g.character.narrator ? { narrator: true } : {}) } : null, + character: g.character ? rowCharacter(g.character, g.layer) : null, items: g.itemIds.length, context: g.contextIds.length, itemIds: g.itemIds, contextIds: g.contextIds, voice: { ...now, spec: voiceSpecOf(now) }, ...(own && ctx && voiceSpecOf(own) !== voiceSpecOf(ctx) ? { contextVoice: { ...ctx, spec: voiceSpecOf(ctx) } } : {}), + // What a recording of them is made into (the recorded preset, its defaults filled) -- a character's only. + ...(g.character ? { recorded: recordedPresetOf(g.character) } : {}), weight: ENGINE_WEIGHT[now.engine] ?? "fast", reads: reads.filter((r) => r.handle && mine.has(handleKey(r.handle))).map((r) => ({ id: r.id, role: r.role, spec: voiceSpecOf({ engine: r.engine, voice: r.voice }), kind: r.kind })), drift: drift.filter((d) => mine.has(d.handle)), @@ -105,11 +129,18 @@ export function projectCharacters(manifest, { map = {}, cast = null, speakers = rows.sort((a, b) => b.items + b.context - (a.items + a.context) || a.name.localeCompare(b.name)); const nar = narratorOf(cast); const recorded = reads.filter((r) => r.kind === "recorded" || r.kind === "converted"); + const itemCharacters = tl.filter((e) => e?.type === "post" && e.narration?.character).map((e) => { + const it = itemCharacterOf(e, { project, cast }); + const v = resolve(e, "post", e.handle ?? null, null); + return { id: e.id, handle: handleKey(e.handle) || null, character: it.id, found: !!it.character, layer: it.layer, ...(it.character ? { name: shownNameOf(it.character) } : {}), voice: { ...v, spec: voiceSpecOf(v) } }; + }); return { narrator: { engine: k.engine, voice: k.voice, spec: `${k.engine}:${k.voice}`, from: render?.postNarration?.voice ? "project" : "default", character: nar ? { id: nar.id, name: nar.name, voice: nar.voice } : null, recorded: recorded.map((r) => ({ id: r.id, kind: r.kind, voice: r.voice })) }, characters: rows, ...castDrift(manifest, { cast, map, resolve }), cast: charactersOf(cast).length, + own: pchars.map((c) => rowCharacter(c, "project")).map((c, i) => ({ ...c, handles: pchars[i].handles ?? [] })), + itemCharacters, }; } @@ -125,6 +156,7 @@ export function threadArgvOf(read, { handles = [], author = null } = {}) { if (read.seen === true) a.push("--read-seen"); for (const [h, v] of Object.entries(read.voiceFor ?? {})) if (!drop.has(handleKey(h))) a.push("--voice-for", `${h}=${v}`); if (read.voice && !(author && drop.has(handleKey(author)))) a.push("--voice", String(read.voice)); + if (typeof read.speed === "number") a.push("--speed", String(read.speed)); return a; } diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -2,6 +2,12 @@ // // <REPORTS_ROOT>/.umtool/cast.json the characters, for every project // <REPORTS_ROOT>/.umtool/cast.undo.json the undo points: the file as it was before each write (the last 50) +// <project>/narration/characters.json THE PROJECT's OWN characters (cast.mjs PROJECT_CHARACTERS_FILE): the +// <project>/narration/characters.undo.json same writer, the same rules, its own undo points +// +// A version 1 cast (`voice` / `convert` at a character's top) is READ as version 2 (cast.mjs upgradeCast) and +// written as version 2 by the first write after -- whose undo point is the version 1 text, so `undo` puts the old +// file back as it was, and it reads the same. // // Every write is serialised in-process, re-reads the file inside the lock, checks the caller's token (the sha1 of // the file it read: a write over a newer file is refused), refuses a cast cast.mjs refuses (whole), keeps an undo @@ -15,7 +21,10 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; -import { CAST_FORMAT, CAST_VERSION, emptyCast, validateCast } from "umtool-report-to-video/cast"; +import { + CAST_FORMAT, CAST_VERSION, PROJECT_CHARACTERS_FILE, PROJECT_CHARACTERS_FORMAT, PROJECT_CHARACTERS_VERSION, characterView, emptyCast, emptyProjectCharacters, foldWritten, upgradeCharacter, + validateCast, validateProjectCharacters, +} from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; @@ -52,27 +61,53 @@ export async function castFileFor(dir, reportsRoot = REPORTS_ROOT) { const sha = (text) => createHash("sha1").update(text).digest("hex").slice(0, 16); -/** - * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with - * no file). A file that does not parse or is refused reads as the empty cast with `error`. - */ -export async function readCastFile(file) { +/** The two files this store writes: what each is called, how it is refused, read and written. */ +const CAST_KIND = Object.freeze({ + what: "the cast", validate: validateCast, empty: emptyCast, + doc: (characters) => ({ format: CAST_FORMAT, version: CAST_VERSION, characters }), +}); +const PROJECT_KIND = Object.freeze({ + what: "the project's characters", validate: validateProjectCharacters, empty: emptyProjectCharacters, + doc: (characters) => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters }), +}); + +async function readKind(kind, file) { let text; try { text = await readFile(file, "utf8"); } catch (e) { - if (e?.code === "ENOENT") return { cast: emptyCast(), token: null, file, exists: false, text: null }; - return { cast: emptyCast(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` }; + if (e?.code === "ENOENT") return { cast: kind.empty(), token: null, file, exists: false, text: null }; + return { cast: kind.empty(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` }; } let doc; try { doc = JSON.parse(text); } catch (e) { - return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` }; + return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` }; } - const errors = validateCast(doc, path.basename(file)); - if (errors.length) return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; - return { cast: doc, token: sha(text), file, exists: true, text }; + const errors = kind.validate(doc, path.basename(file)); + if (errors.length) return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; + // As a reader is handed it: each character version 2's shape, with the `voice` / `convert` its presets answer to. + return { cast: { ...kind.doc(doc.characters.map(characterView)) }, token: sha(text), file, exists: true, text }; +} + +/** + * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with + * no file), `cast` as VERSION 2 whatever the file's, each character a VIEW (cast.mjs characterView). A file that does not parse or is refused + * reads as the empty cast with `error`. + */ +export const readCastFile = (file) => readKind(CAST_KIND, file); + +/** A project's own characters file. */ +export const projectCharactersFile = (dir) => path.join(/* turbopackIgnore: true */ dir, ...PROJECT_CHARACTERS_FILE.split("/")); + +/** + * A project's OWN characters as its file holds them: `{ doc, token, file, exists, error? }` (readCastFile's shape, + * the document under `doc`). No file: none. A file that does not parse or is refused reads as none, with `error`. + */ +export async function readProjectCharacters(dir) { + const { cast, ...rest } = await readKind(PROJECT_KIND, projectCharactersFile(dir)); + return { doc: cast, ...rest }; } /** The cast under a reports root. */ @@ -110,23 +145,19 @@ function withCastLock(fn) { return run; } -/** - * ONE WRITE of the cast: `mutate(characters)` (a copy; it throws CastError to refuse) returns what the caller - * wants back. Refused when the file changed since the caller's `token` (409), when it does not parse, or when the - * result is refused (cast.mjs validateCast). Returns `{ ...result, cast, token, undo: <points left> }`. - * @param {string} file - * @param {(chars: any[]) => any} mutate - * @param {{ token?: string | null, what?: string }} [o] - */ -export function castWrite(file, mutate, { token = null, what = "an edit" } = {}) { +function writeKind(kind, file, mutate, { token = null, what = "an edit" } = {}) { return withCastLock(async () => { - const read = await readCastFile(file); + const read = await readKind(kind, file); if (read.error && read.exists) throw new CastError(`${read.error} -- fix the file first; nothing written`, 409); - if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read (${token} -> ${read.token}): read it again`, 409); - const chars = JSON.parse(JSON.stringify(read.cast.characters ?? [])); + if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read (${token} -> ${read.token}): read it again`, 409); + // The mutation is handed version 2's characters (no `voice` / `convert` beside the presets), and what is written + // is version 2's shape: a `voice` / `convert` it sets the old way is the newer word unless it changed the preset + // itself (cast.mjs foldWritten, against the character as it was handed). + const chars = JSON.parse(JSON.stringify((read.cast.characters ?? []).map(upgradeCharacter))); + const was = new Map(chars.map((c) => [c?.id, JSON.parse(JSON.stringify(c))])); const result = mutate(chars) ?? {}; - const doc = { format: CAST_FORMAT, version: CAST_VERSION, characters: chars }; - const errors = validateCast(doc); + const doc = kind.doc(chars.map((c) => foldWritten(c, was.get(c?.id) ?? null))); + const errors = kind.validate(doc, path.basename(file)); if (errors.length) throw new CastError(`refused: ${errors.join("; ")}`); const points = [...(await readCastUndo(file)), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }].slice(-CAST_UNDO_KEEP); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); @@ -136,18 +167,49 @@ export function castWrite(file, mutate, { token = null, what = "an edit" } = {}) }); } -/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */ -export function undoCast(file, { token = null } = {}) { +function undoKind(kind, file, { token = null } = {}) { return withCastLock(async () => { - const read = await readCastFile(file); - if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read: read it again`, 409); + const read = await readKind(kind, file); + if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read: read it again`, 409); const points = await readCastUndo(file); const last = points.pop(); - if (!last) throw new CastError("nothing to undo on the cast"); - if (last.text === null) await writeAtomic(file, `${JSON.stringify(emptyCast(), null, 1)}\n`); + if (!last) throw new CastError(`nothing to undo on ${kind.what}`); + if (last.text === null) await writeAtomic(file, `${JSON.stringify(kind.empty(), null, 1)}\n`); else await writeAtomic(file, last.text); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); - const now = await readCastFile(file); + const now = await readKind(kind, file); return { undone: last.what, at: last.at, left: points.length, cast: now.cast, token: now.token }; }); } + +/** + * ONE WRITE of the cast: `mutate(characters)` (a copy, as version 2 holds them; it throws CastError to refuse) + * returns what the caller wants back. Refused when the file changed since the caller's `token` (409), when it does + * not parse, or when the result is refused (cast.mjs validateCast). Written as VERSION 2. Returns `{ ...result, + * cast, token, undo: <points left> }`. + * @param {string} file + * @param {(chars: any[]) => any} mutate + * @param {{ token?: string | null, what?: string }} [o] + */ +export const castWrite = (file, mutate, o) => writeKind(CAST_KIND, file, mutate, o); + +/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */ +export const undoCast = (file, o) => undoKind(CAST_KIND, file, o); + +/** + * ONE WRITE of a project's own characters (`<dir>/narration/characters.json`): castWrite's rules -- a token, an undo + * point, atomic, refused whole (cast.mjs validateProjectCharacters). Returns `{ ...result, doc, token, undo }`. + * @param {string} dir the project's folder + * @param {(chars: any[]) => any} mutate + * @param {{ token?: string | null, what?: string }} [o] + */ +export async function projectCharactersWrite(dir, mutate, o) { + const { cast, ...rest } = await writeKind(PROJECT_KIND, projectCharactersFile(dir), mutate, o); + return { ...rest, doc: cast }; +} + +/** A project's own characters as they were before their last write. */ +export async function undoProjectCharacters(dir, o) { + const { cast, ...rest } = await undoKind(PROJECT_KIND, projectCharactersFile(dir), o); + return { ...rest, doc: cast }; +} diff --git a/umtool/lib/report/characterLayers.mjs b/umtool/lib/report/characterLayers.mjs @@ -0,0 +1,49 @@ +// THE LAYERS ONE READ ASKS, read from a project's folder (cast.mjs, post-say.mjs voiceSourceOf; knobs.md, "A +// character is a preset"): the project's own characters (`narration/characters.json`) over its voice map +// (`narration/voices.json`), the CAST it reads (castStore.mjs castForProject), and the character a post item names +// for itself (`narration.character`). Every reader -- a single post's take (readVoice.mjs), a thread read +// (postThreadRead.mjs), a recording made a read (postNarrationCli.mjs importRecording), the bench's routes, `umtool +// cast project` -- loads them here, so they ask the same files. +// +// A broken characters.json or cast.json reads as none (its `error` kept: `umtool cast project` says it); a broken +// voice map reads as none too unless `strictMap` (a thread read refuses one, as before). +// +// Plain ESM. +import { castPresetMap, characterForRead, itemCharacterOf, itemPresetOf, projectPresetMap, recordedPresetOf } from "umtool-report-to-video/cast"; +import { castForProject, readProjectCharacters } from "./castStore.mjs"; + +/** + * The trim a recording of post item `e` is kept with (postRecord.mjs keepRecording's `trim`): its character's recorded + * preset's (cast.mjs characterForRead, recordedPresetOf) -- `{ on, padMs }` -- or null: no character, the recorder's own. + */ +export async function recordedTrimFor(dir, e) { + const who = (await readLayers(dir).catch(() => null))?.characterForRead(e) ?? null; + return who?.character ? recordedPresetOf(who.character).trim : null; +} + +/** + * @param {string} dir the project's folder + * @param {{ reportsRoot?: string, strictMap?: boolean }} [o] + * @returns {Promise<{ castRead: any, projectRead: any, voiceMap: Record<string, string>, cast: any, project: any, + * map: Record<string, any>, castMap: Record<string, any>, itemOf: (e: any) => any, itemCharacterOf: (e: any) => any, + * characterForRead: (e: any, as?: string | null) => any }>} + */ +export async function readLayers(dir, { reportsRoot = undefined, strictMap = false } = {}) { + const { readVoiceMap } = await import("./postSay.mjs"); + const castRead = await castForProject(dir, ...(reportsRoot ? [reportsRoot] : [])); + const projectRead = await readProjectCharacters(dir); + const voiceMap = strictMap ? await readVoiceMap(dir) : await readVoiceMap(dir).catch(() => ({})); + const layers = { project: projectRead.doc, cast: castRead.cast }; + return { + castRead, projectRead, voiceMap, ...layers, + /** voiceSourceOf's `map`: the project's characters over its voice map. */ + map: projectPresetMap(projectRead.doc, voiceMap), + /** voiceSourceOf's `cast`. */ + castMap: castPresetMap(castRead.cast), + /** voiceSourceOf's `item` for post item `e`. */ + itemOf: (e) => itemPresetOf(e, layers), + itemCharacterOf: (e) => itemCharacterOf(e, layers), + /** The character a recording of `e` is made into (cast.mjs characterForRead). */ + characterForRead: (e, as = null) => characterForRead(e, { ...layers, as }), + }; +} diff --git a/umtool/lib/report/characters.test.mjs b/umtool/lib/report/characters.test.mjs @@ -0,0 +1,429 @@ +// A character is a preset, on disk (castStore.mjs, castCli.mjs, characterLayers.mjs, postThreadRead.mjs, +// postNarrationCli.mjs): a version 1 cast read as version 2 and written as it (undo puts the old file back), the +// preset flags of `umtool cast set`, a project's OWN characters (one writer, an undo point a write, anonymous ones +// "Anon 1", "Anon 2"), "Add to the pool" / "Keep in this video only", a post item's own character, the chain's answer +// and its source in `umtool cast project`, a preset's SPEED on a single take and on a thread read's parts (and the +// flag over it), and a recording made a read with its character's recorded preset. No editor: the tts and voice ops +// are stubs; every project is a temp dir. +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { CastError, castFile, castWrite, projectCharactersFile, projectCharactersWrite, readCast, readCastFile, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs"; +import { castCommand } from "./castCli.mjs"; +import { readLayers, recordedTrimFor } from "./characterLayers.mjs"; +import { importRecording, makeTake } from "./postNarrationCli.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { partKey, readParts, threadReadPlan, threadTake, upToDate } from "./postThreadRead.mjs"; +import { itemReadVoice } from "./readVoice.mjs"; +import { threadArgvOf } from "./castProject.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-characters-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const wavOf = async (file, voice, seconds = 1.5, silence = 0.3) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: silence, after: silence }))); +}; +const run = (command, key) => async (args, extra = {}) => { + const lines = []; + const code = await command(args, { [key]: ROOT, log: (s) => lines.push(s), out: (s) => lines.push(s), err: (s) => lines.push(s), ...extra }); + return { code, lines, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; +const cast = run(castCommand, "reportsRoot"); +const posts = run(postsCommand, "root"); +const stubAsk = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out, body.voice === "am_michael" ? VOICE_A : VOICE_B, 1.2); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice } }; +}; + +// THE PROJECT: @hostman's post (p-1), his answer to @guest (p-2: a thread), @guest's own post (p-3), a stranger's (p-4). +const DIR = path.join(ROOT, "chars"); +{ + const post = (id, handle, author, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o }); + await mkdir(DIR, { recursive: true }); + await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: "chars", title: "Characters", provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, postNarration: { engine: "kokoro", voice: "af_heart" } }, + timeline: [ + post("1", "hostman", "Host Man", { narration: { script: "Host's first line, read aloud." } }), + post("2", "hostman", "Host Man", { parents: [{ id: "20", handle: "guest", author: "The Guest", date: "2026-10-30T09:00:00.000Z", text: "the guest asks a question" }], narration: { script: "Host answers the guest." } }), + post("3", "guest", "The Guest", { narration: { script: "The guest's own line." } }), + post("4", "stranger", "A Stranger", { narration: { script: "A stranger says a thing." } }), + ], + }, null, 2)); +} +const project = { id: "chars", dir: DIR }; +const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8")); +const item = async (id) => (await manifest()).timeline.find((e) => e.id === id); + +test("the store: a version 1 cast reads as version 2, the first write makes it version 2, undo puts the old file back", async () => { + const file = castFile(ROOT); + const v1 = `${JSON.stringify({ format: "umtool-cast", version: 1, characters: [ + { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "kokoro:am_michael", speakers: ["Host"] }, + { id: "me", name: "Me", handles: ["operator"], voice: "kokoro:bm_george", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, narrator: true }, + ] }, null, 1)}\n`; + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, v1); + const r = await readCastFile(file); + assert.equal(r.error, undefined); + assert.equal(r.cast.version, 2, "in memory: version 2"); + assert.deepEqual(r.cast.characters[1], { + id: "me", name: "Me", handles: ["operator"], synthetic: { voice: "kokoro:bm_george" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true, + voice: "kokoro:bm_george", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, + }, "its presets, and the voice / convert they answer to"); + assert.equal(await readFile(file, "utf8"), v1, "reading writes nothing"); + // A write: version 2 on disk, the presets alone (no voice / convert beside them). + const w = await castWrite(file, (chars) => { + assert.equal(chars[0].voice, undefined, "the mutation is handed version 2's characters"); + chars[0].synthetic.speed = 1.1; + }, { token: r.token, what: "hostman at 1.1" }); + const disk = JSON.parse(await readFile(file, "utf8")); + assert.equal(disk.version, 2); + assert.deepEqual(disk.characters[0], { id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "kokoro:am_michael", speed: 1.1 }, speakers: ["Host"] }); + assert.deepEqual(disk.characters[1], { id: "me", name: "Me", handles: ["operator"], synthetic: { voice: "kokoro:bm_george" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true }); + assert.equal(w.undo, 1); + // A view written back with its PRESET changed: the preset wins over the view's own alias (which still says the old voice). + const view = (await readCastFile(file)).cast.characters[0]; + await castWrite(file, (chars) => { chars[0] = { ...view, synthetic: { ...view.synthetic, voice: "kokoro:am_onyx" } }; }, { what: "a view, its preset changed" }); + assert.deepEqual(JSON.parse(await readFile(file, "utf8")).characters[0].synthetic, { voice: "kokoro:am_onyx", speed: 1.1 }); + // …and the old way of setting one (`c.voice = …`) is still the newer word; neither leaves an alias on disk. + await castWrite(file, (chars) => { chars[0].voice = "kokoro:am_michael"; }, { what: "the old way" }); + assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk); + await undoCast(file); + await undoCast(file); + // A refusal writes nothing: a convert target that is a file. + await assert.rejects(castWrite(file, (chars) => { chars[0].recorded = { convert: { voice: "narration/me.wav" } }; }), /never a file or a recording/); + assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk); + // Undo: the version 1 text, byte for byte -- and it reads the same. + const u = await undoCast(file); + assert.equal(u.undone, "hostman at 1.1"); + assert.equal(await readFile(file, "utf8"), v1); + assert.equal((await readCast(ROOT)).cast.characters[0].voice, "kokoro:am_michael"); +}); + +test("umtool cast set: the preset fields -- speed, clean, trim and its pad, the direction; default takes one off", async () => { + let r = await cast(["set", "hostman", "--speed", "1.15", "--enhance", "off", "--trim", "on", "--trim-pad", "120", "--direction", "higher, brisk, amused", "--convert-engine", "seed-vc", "--convert-pitch", "source", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character.synthetic, { voice: "kokoro:am_michael", speed: 1.15 }); + assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc", pitch: "source" }, enhance: false, trim: { on: true, padMs: 120 }, direction: "higher, brisk, amused" }); + assert.equal(r.json().character.voice, "kokoro:am_michael", "the view still says its voice"); + assert.equal(JSON.parse(await readFile(castFile(ROOT), "utf8")).version, 2, "the write made the file version 2"); + r = await cast(["ls"]); + assert.match(r.text(), /hostman\s+kokoro:am_michael ×1\.15\s+Host Man @hostman convert: seed-vc -> kokoro:am_michael, pitch source; not cleaned; trim pad 120 ms; direction: "higher, brisk, amused"/); + // `default` takes a key off; --no-speed the speed; "" the direction. + r = await cast(["set", "hostman", "--enhance", "default", "--trim", "default", "--convert-pitch", "default", "--no-speed", "--direction", "", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character.synthetic, { voice: "kokoro:am_michael" }); + assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc" } }); + for (const [args, re] of [ + [["--speed", "3"], /--speed is a number from 0\.5 to 2/], + [["--enhance", "maybe"], /--enhance is on, off or default/], + [["--trim-pad", "9000"], /--trim-pad is a number of milliseconds from 0 to 2000/], + [["--direction", "x".repeat(201)], /--direction is one line for the person reading \(at most 200/], + [["--convert-voice", "me.wav"], /--convert-voice is a STOCK voice with its engine.*never a file or a recording/], + [["--anonymous"], /an anonymous character is one video's, never the pool's/], + [["--no-voice"], /a cast character has a stock voice/], + ]) { + r = await cast(["set", "hostman", ...args]); + assert.equal(r.code, 1, args.join(" ")); + assert.match(r.text(), re); + } + assert.deepEqual((await readCast(ROOT)).cast.characters[0].recorded, { convert: { engine: "seed-vc" } }, "a refusal writes nothing"); + r = await cast(["set", "hostman", "--speed", "1.15"]); + assert.equal(r.code, 0, r.text()); +}); + +test("a project's own characters: one writer, an undo point a write, anonymous ones Anon 1, Anon 2; voices.json left alone", async () => { + await mkdir(path.join(DIR, "narration"), { recursive: true }); + const voices = path.join(DIR, "narration", "voices.json"); + const mapText = `${JSON.stringify({ stranger: "kokoro:am_onyx" }, null, 1)}\n`; + await writeFile(voices, mapText); + assert.equal((await readProjectCharacters(DIR)).exists, false); + let r = await cast(["project", "chars", "add", "anon-a", "--anonymous", "--handles", "@Guest", "--voice", "kokoro:am_puck", "--speed", "0.9", "--direction", "flat, tired", "--enhance", "off", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character, { + id: "anon-a", name: "Anon 1", anonymous: true, shown: "Anon 1", handles: ["guest"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 }, recorded: { enhance: false, direction: "flat, tired" }, voice: "kokoro:am_puck", + }); + r = await cast(["project", "chars", "add", "anon-b", "--anonymous", "--name", "the second one", "--json"]); + assert.deepEqual([r.json().character.shown, r.json().character.name, r.json().character.synthetic], ["Anon 2", "the second one", undefined], "the next shown name; no voice of its own"); + const file = projectCharactersFile(DIR); + assert.equal(file, path.join(DIR, "narration", "characters.json")); + const disk = JSON.parse(await readFile(file, "utf8")); + assert.deepEqual([disk.format, disk.version, disk.characters.length], ["umtool-project-characters", 1, 2]); + assert.equal(disk.characters[0].voice, undefined, "the presets alone on disk"); + assert.ok(existsSync(file.replace(/\.json$/, ".undo.json"))); + // Refusals, in the layer's words -- nothing written. + for (const [args, re] of [ + [["add", "anon-a", "--name", "Again"], /is one of chars's characters already/], + [["add", "plain"], /takes --name "…" \(or --anonymous/], + [["add", "plain", "--name", "Plain", "--shown", "X"], /--shown is an anonymous character's shown name/], + [["add", "plain", "--name", "Plain", "--narrator"], /the narrator is a cast character/], + [["add", "plain", "--name", "Plain", "--voice", "/tmp/me.wav"], /--voice is a STOCK voice with its engine/], + [["add", "plain", "--name", "Plain", "--convert-voice", "seedvc:/home/me.wav"], /never a file or a recording/], + [["add", "plain", "--name", "Plain", "--handles", "guest"], /@guest is anon-a's already/], + [["set", "nobody", "--speed", "1"], /no nobody among chars's characters/], + [["pool", "anon-a"], /anon-a is anonymous: it stays in this video/], + [["pool", "anon-b"], /anonymous/], + [["frobnicate"], /nothing \(the view\), add, set, rm, undo, pool or keep/], + ]) { + r = await cast(["project", "chars", ...args]); + assert.equal(r.code, 1, args.join(" ")); + assert.match(r.text(), re); + } + assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk); + // The store itself: a stale token refused, a broken file never overwritten. + const read = await readProjectCharacters(DIR); + await assert.rejects(projectCharactersWrite(DIR, () => {}, { token: "stale" }), (e) => e instanceof CastError && e.status === 409); + await projectCharactersWrite(DIR, (chars) => { chars[1].shown = "The Second"; }, { token: read.token, what: "rename" }); + assert.equal((await readProjectCharacters(DIR)).doc.characters[1].shown, "The Second"); + const u = await undoProjectCharacters(DIR); + assert.equal(u.undone, "rename"); + assert.equal((await readProjectCharacters(DIR)).doc.characters[1].shown, "Anon 2"); + // set, rm, undo through the CLI. + r = await cast(["project", "chars", "set", "anon-b", "--shown", "Witness", "--voice", "kokoro:af_bella", "--json"]); + assert.deepEqual([r.json().character.shown, r.json().character.voice], ["Witness", "kokoro:af_bella"]); + r = await cast(["project", "chars", "set", "anon-b", "--no-voice", "--json"]); + assert.equal(r.json().character.synthetic, undefined); + r = await cast(["project", "chars", "rm", "anon-b"]); + assert.equal(r.code, 0, r.text()); + assert.equal((await readProjectCharacters(DIR)).doc.characters.length, 1); + r = await cast(["project", "chars", "undo"]); + assert.match(r.text(), /undone: rm anon-b \(chars\)/); + assert.equal((await readProjectCharacters(DIR)).doc.characters.length, 2); + await cast(["project", "chars", "rm", "anon-b"]); + assert.equal(await readFile(voices, "utf8"), mapText, "voices.json is not rewritten"); + // A broken file: read as none, said, never overwritten. + const good = await readFile(file, "utf8"); + await writeFile(file, "{ nope"); + assert.match((await readProjectCharacters(DIR)).error, /not JSON/); + r = await cast(["project", "chars", "add", "x", "--name", "X"]); + assert.equal(r.code, 1); + assert.match(r.text(), /fix the file first/); + assert.equal(await readFile(file, "utf8"), "{ nope"); + r = await cast(["project", "chars"]); + assert.match(r.text(), /this video's characters are NOT read/); + await writeFile(file, good); +}); + +test("cast project: the chain's answer and its source for each author; a post item's own character", async () => { + let r = await cast(["project", "chars", "--json"]); + assert.equal(r.code, 0, r.text()); + let v = r.json(); + const row = (key) => v.characters.find((c) => c.key === key); + // hostman: the cast's character, its speed with it. guest: this video's anonymous character, over nothing. + assert.deepEqual([row("hostman").voice.spec, row("hostman").voice.from, row("hostman").voice.speed, row("hostman").character.layer], ["kokoro:am_michael", "cast", 1.15, "cast"]); + assert.deepEqual([row("anon-a").voice.spec, row("anon-a").voice.from, row("anon-a").voice.speed, row("anon-a").voice.character], ["kokoro:am_puck", "project", 0.9, "anon-a"]); + assert.deepEqual([row("anon-a").name, row("anon-a").character.anonymous, row("anon-a").character.shown, row("anon-a").character.layer], ["Anon 1", true, "Anon 1", "project"], "shown under its shown name"); + assert.deepEqual(row("anon-a").recorded, { convert: { engine: null, voice: "kokoro:am_puck" }, enhance: false, trim: { on: true, padMs: null }, direction: "flat, tired" }); + // stranger: the voice map -- a project character with only a synthetic voice. + assert.deepEqual([row("@stranger").voice.spec, row("@stranger").voice.from, row("@stranger").character], ["kokoro:am_onyx", "project", null]); + assert.deepEqual(v.own.map((c) => [c.id, c.handles]), [["anon-a", ["guest"]]]); + assert.deepEqual(v.itemCharacters, []); + assert.equal(v.charactersFile, projectCharactersFile(DIR)); + r = await cast(["project", "chars"]); + assert.match(r.text(), /hostman\s+kokoro:am_michael ×1\.15\s+\(cast: hostman\)/); + assert.match(r.text(), /anon-a\s+kokoro:am_puck ×0\.9\s+\(project: anon-a\).*shown as "Anon 1"/); + assert.match(r.text(), /a recording of them: converted to kokoro:am_puck; not cleaned; edges trimmed; direction: "flat, tired"/); + assert.match(r.text(), /@stranger\s+kokoro:am_onyx\s+\(project\)/); + + // `posts voices ls` answers through the same layers: this video's own character, the map, the cast. + r = await posts(["voices", "chars", "ls", "--json"]); + assert.equal(r.code, 0, r.text()); + const author = (h) => r.json().authors.find((a) => a.handle === h); + assert.deepEqual([author("guest").voice, author("guest").from, author("guest").own, author("guest").speed], ["kokoro:am_puck", "project", "anon-a", 0.9]); + assert.deepEqual([author("stranger").voice, author("stranger").from, author("stranger").own, author("stranger").mapped], ["kokoro:am_onyx", "project", undefined, true]); + assert.deepEqual([author("hostman").voice, author("hostman").from, author("hostman").character], ["kokoro:am_michael", "cast", "hostman"]); + r = await posts(["voices", "chars", "ls"]); + assert.match(r.text(), /@guest kokoro:am_puck ×0\.9 \(this video's character: anon-a\)/); + + // A POST ITEM's OWN CHARACTER: p-4 (the stranger's) read as the cast's `me`. + r = await posts(["character", "chars", "p-4", "ghost"]); + assert.equal(r.code, 2); + assert.match(r.text(), /no character ghost among chars's own or in the cast/); + r = await posts(["character", "chars", "p-4", "me", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual([r.json().character, r.json().layer, r.json().changed, r.json().voice.spec, r.json().voice.from], ["me", "cast", "set", "kokoro:bm_george", "item"]); + assert.equal((await item("p-4")).narration.character, "me"); + r = await posts(["character", "chars", "p-4"]); + assert.match(r.text(), /p-4: read as me \(Me; the cast's\): kokoro:bm_george \(item: me\)/); + r = await cast(["project", "chars", "--json"]); + v = r.json(); + assert.deepEqual(v.itemCharacters.map((x) => [x.id, x.character, x.found, x.layer, x.voice.spec, x.voice.from]), [["p-4", "me", true, "cast", "kokoro:bm_george", "item"]]); + assert.deepEqual([row("@stranger").voice.spec, row("@stranger").voice.from], ["kokoro:am_onyx", "project"], "the handle's own answer is still the map's"); + // The single take asks the same chain (readVoice.mjs), and a thread read's plan. + assert.deepEqual(await itemReadVoice(project, await item("p-4"), { render: (await manifest()).render }), { engine: "kokoro", voice: "bm_george", from: "item", character: "me" }); + // The project's own first: an id both layers have. + await projectCharactersWrite(DIR, (chars) => { chars.push({ id: "me", name: "Me, here", handles: [], synthetic: { voice: "kokoro:am_echo", speed: 1.3 } }); }); + assert.deepEqual(await itemReadVoice(project, await item("p-4"), { render: (await manifest()).render }), { engine: "kokoro", voice: "am_echo", from: "item", speed: 1.3, character: "me" }); + await undoProjectCharacters(DIR); + // --clear: by its author's handle again. + r = await posts(["character", "chars", "p-4", "--clear", "--json"]); + assert.deepEqual([r.json().character, r.json().changed, r.json().voice.from], [null, "cleared", "project"]); + assert.equal((await item("p-4")).narration.character, undefined); + r = await posts(["character", "chars", "p-4", "me", "--clear"]); + assert.equal(r.code, 2); +}); + +test("a preset's speed on a single take: the flag, then the character's, then the item's own", async () => { + const m = await manifest(); + const asked = []; + // hostman (the cast: kokoro am_michael ×1.15): his take is asked at 1.15, and says so. + let t = await makeTake(project, await item("p-1"), { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).speed], ["kokoro", "am_michael", 1.15]); + assert.equal(t.take.speed, 1.15); + // The flag over it. + t = await makeTake(project, await item("p-1"), { render: m.render, speed: 0.8, ask: stubAsk(asked), redaction: null }); + assert.equal(asked.at(-1).speed, 0.8); + // The item's own speed (narration.speed: set on this one item) beats its character's; the flag beats both. + const own = { ...(await item("p-1")), narration: { ...(await item("p-1")).narration, speed: 0.7 } }; + t = await makeTake(project, own, { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.equal(asked.at(-1).speed, 0.7); + t = await makeTake(project, own, { render: m.render, speed: 1.4, ask: stubAsk(asked), redaction: null }); + assert.equal(asked.at(-1).speed, 1.4); + // The stranger (the voice map: no preset): no speed asked. + t = await makeTake(project, await item("p-4"), { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.deepEqual([asked.at(-1).voice, "speed" in asked.at(-1)], ["am_onyx", false]); + assert.equal(t.take.speed, undefined); +}); + +test("a thread read: each part at its character's speed, the flag over them all, Orpheus none -- and another speed is another part", async () => { + const m = await manifest(); + const e2 = await item("p-2"); + const L = await readLayers(DIR); + const plan = threadReadPlan(m, e2, { map: L.map, cast: L.castMap, item: L.itemOf(e2) }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice, p.from, p.speed ?? null, p.character ?? null]), [["parent:0", "am_puck", "project", 0.9, "anon-a"], ["post", "am_michael", "cast", 1.15, "hostman"]]); + const parts = readParts(plan); + assert.deepEqual(parts.map((p) => p.speed), [0.9, 1.15]); + assert.equal(parts[1].key, partKey("kokoro", "am_michael", parts[1].text, 1.15)); + assert.notEqual(parts[1].key, partKey("kokoro", "am_michael", parts[1].text), "the same words at another speed are another part"); + assert.equal(partKey("kokoro", "am_michael", "hi", 1), partKey("kokoro", "am_michael", "hi"), "at 1: the key as before"); + // --speed: every part at that one. + assert.deepEqual(threadReadPlan(m, e2, { map: L.map, cast: L.castMap, speed: 1.4 }).pieces.map((p) => p.speed), [1.4, 1.4]); + // Orpheus has no speed: a piece in it is asked none, whatever the flag says. + assert.deepEqual(threadReadPlan(m, e2, { map: { guest: "orpheus:tara" }, cast: L.castMap, speed: 1.4 }).pieces.map((p) => [p.engine, p.speed ?? null]), [["orpheus", null], ["kokoro", 1.4]]); + // His own words at the item's own speed (narration.speed), as a single take -- over his character's; the others' untouched. + assert.deepEqual(threadReadPlan(m, { ...e2, narration: { ...e2.narration, speed: 0.75 } }, { map: {}, cast: {} }).pieces.map((p) => [p.role, p.speed ?? null]), [["parent:0", null], ["post", 0.75]]); + assert.deepEqual(threadReadPlan(m, { ...e2, narration: { ...e2.narration, speed: 0.75 } }, { map: L.map, cast: L.castMap }).pieces.map((p) => [p.role, p.speed ?? null]), [["parent:0", 0.9], ["post", 0.75]]); + + // Made: the editor is asked each part at its speed, the take's parts keep it, and the same read again is up to date. + const asked = []; + const r = await threadTake(project, e2, { manifest: m, red: null, ask: stubAsk(asked), lanes: null }); + assert.deepEqual(asked.map((b) => [b.voice, b.speed]), [["am_puck", 0.9], ["am_michael", 1.15]]); + assert.deepEqual(r.take.parts.map((p) => [p.role, p.voice, p.speed]), [["parent:0", "am_puck", 0.9], ["post", "am_michael", 1.15]]); + assert.equal(r.take.read.speed, undefined, "a preset's speed is the character's, not the read's"); + const after = await item("p-2"); + const again = await threadTake(project, after, { red: null, ask: stubAsk(asked), lanes: null }); + assert.equal(again.upToDate, true); + assert.equal(asked.length, 2); + // The flag: not up to date; the parts asked again at it (new cache keys), the read records it, and a re-read keeps it. + assert.equal(upToDate(after, threadReadPlan(await manifest(), after, { map: L.map, cast: L.castMap, speed: 1.4 })), false); + const fast = await threadTake(project, after, { red: null, speed: 1.4, ask: stubAsk(asked), lanes: null }); + assert.deepEqual(asked.slice(2).map((b) => b.speed), [1.4, 1.4]); + assert.equal(fast.take.read.speed, 1.4); + assert.deepEqual(threadArgvOf(fast.take.read), ["--speed", "1.4"]); + // Through the CLI: --speed reaches a thread read (it was ignored), and a bad one is refused in the flag's name. + let c = await posts(["narrate", "chars", "p-2", "--take", "--thread", "--speed", "1.4", "--dry-run", "--json"]); + assert.equal(c.code, 0, c.text()); + assert.deepEqual(c.json().pieces.map((p) => p.speed), [1.4, 1.4]); + assert.equal(c.json().upToDate, true); + c = await posts(["narrate", "chars", "p-2", "--take", "--thread", "--speed", "9", "--dry-run"]); + assert.equal(c.code, 2); + assert.match(c.text(), /--speed is a number from 0\.5 to 2/); +}); + +test("\"Add to the pool\" and \"Keep in this video only\"", async () => { + // Keep an author with no character here: a character of this video, in the voice they read in now. + let r = await cast(["project", "chars", "keep", "@stranger", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character, { id: "stranger", name: "A Stranger", handles: ["stranger"], synthetic: { voice: "kokoro:am_onyx" }, voice: "kokoro:am_onyx" }); + // Keep a cast character here: a copy, without its narrator mark; changing it leaves the pool's as it is. + r = await cast(["project", "chars", "keep", "me", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.equal(r.json().character.narrator, undefined); + assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }); + r = await cast(["project", "chars", "set", "me", "--convert-semitones", "-3", "--json"]); + assert.equal(r.json().character.recorded.convert.semitones, -3); + assert.equal((await readCast(ROOT)).cast.characters.find((c) => c.id === "me").recorded.convert.semitones, 2, "the pool's is untouched"); + r = await cast(["project", "chars", "keep", "me"]); + assert.equal(r.code, 1); + assert.match(r.text(), /me is one of chars's characters already/); + // `use` for this project: this video's own character takes it (its preset answers before the voice map). + r = await cast(["use", "chars", "@stranger", "kokoro:am_fenrir", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.equal((await readProjectCharacters(DIR)).doc.characters.find((c) => c.id === "stranger").voice, "kokoro:am_fenrir"); + assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { stranger: "kokoro:am_onyx" }, "the map is left as it was"); + // An anonymous character never reaches the pool through `use --everywhere` either. + r = await cast(["use", "chars", "anon-a", "kokoro:am_onyx", "--everywhere"]); + assert.equal(r.code, 1); + assert.match(r.text(), /anon-a is anonymous: it stays in this video, never the pool/); + r = await cast(["use", "chars", "@guest", "kokoro:am_onyx", "--everywhere"]); + assert.equal(r.code, 1, "by its handle too"); + assert.equal((await readCast(ROOT)).cast.characters.some((c) => (c.handles ?? []).includes("guest")), false); + // Add to the pool: into the cast, out of the project; one the cast has already is refused. + r = await cast(["project", "chars", "pool", "me"]); + assert.equal(r.code, 1); + assert.match(r.text(), /me is in the cast already/); + r = await cast(["project", "chars", "pool", "stranger", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual([r.json().scope, r.json().changed], ["cast", "pooled"]); + assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "stranger").synthetic, { voice: "kokoro:am_fenrir" }); + assert.equal((await readProjectCharacters(DIR)).doc.characters.some((c) => c.id === "stranger"), false); + r = await cast(["undo"]); + assert.match(r.text(), /undone: stranger into the pool \(from chars\)/); + await cast(["project", "chars", "rm", "me"]); +}); + +test("a recording made a read with its character's recorded preset: clean off, trim off, the direction; the flags over them", async () => { + const rec = path.join(ROOT, "my-read.wav"); + await wavOf(rec, VOICE_B, 2, 0.6); + const ops = []; + const askOp = async (route, body) => { + ops.push(route.split("/").at(-1)); + await wavOf(body.out, VOICE_A, 2); + return { jobId: `op-${ops.length}`, result: { engine: body.engine ?? "openvoice", voice: body.voice } }; + }; + // p-3 is @guest's: this video's anonymous character (enhance off, direction) -- not cleaned, converted to its voice. + let r = await importRecording(project, await item("p-3"), rec, { ask: askOp }); + assert.deepEqual(r.character, { id: "anon-a", name: "Anon 1", voice: "kokoro:am_puck", layer: "project" }, "named as it is shown"); + assert.equal(r.direction, "flat, tired"); + assert.deepEqual(ops, ["voice-convert"]); + assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "converted to kokoro:am_puck"]); + assert.match(r.notes[0], /not cleaned: anon-a's recorded preset says so/); + assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:am_puck)", "the disclosure line is what it was"); + const kept = (await item("p-3")).narration.takes[0]; + assert.match(kept.note, /recorded for Anon 1/); + const trimmed = kept.seconds; + assert.ok(trimmed < 2.6, `its edges trimmed (${trimmed} s of 3.2)`); + // The command over the preset: clean it this once. + ops.length = 0; + r = await importRecording(project, await item("p-3"), rec, { clean: true, ask: askOp }); + assert.deepEqual(ops, ["voice-enhance", "voice-convert"]); + // The preset says trim off: kept as recorded, edges and all; a pad is the room kept. + await cast(["project", "chars", "set", "anon-a", "--trim", "off"]); + r = await importRecording(project, await item("p-3"), rec, { convert: false, ask: askOp }); + const whole = (await item("p-3")).narration.takes.find((t) => t.file === r.takes[0].file).seconds; + assert.ok(whole > 3, `not trimmed (${whole} s)`); + await cast(["project", "chars", "set", "anon-a", "--trim", "on", "--trim-pad", "400"]); + r = await importRecording(project, await item("p-3"), rec, { convert: false, ask: askOp }); + const padded = (await item("p-3")).narration.takes.find((t) => t.file === r.takes[0].file).seconds; + assert.ok(padded > trimmed + 0.3 && padded < whole, `the pad kept (${padded} s between ${trimmed} and ${whole})`); + // The record page's two paths ask the same preset (characterLayers.mjs recordedTrimFor): the room kept; none with no character. + assert.deepEqual(await recordedTrimFor(DIR, await item("p-3")), { on: true, padMs: 400 }); + assert.deepEqual(await recordedTrimFor(DIR, await item("p-1")), { on: true, padMs: null }, "the cast's character: trimmed, the recorder's own room"); + assert.deepEqual(await recordedTrimFor(DIR, { id: "x", handle: "nobody-at-all" }), { on: true, padMs: null }, "nobody's: the narrator's"); + // --as: a character of this video's by id, the cast's by id; the item's own character before its author's. + r = await importRecording(project, await item("p-1"), rec, { as: "anon-a", convert: false, ask: askOp }); + assert.equal(r.character.layer, "flag"); + await assert.rejects(importRecording(project, await item("p-1"), rec, { as: "ghost", ask: askOp }), /--as ghost: no such character in this video's characters or the cast/); + await posts(["character", "chars", "p-3", "me"]); + ops.length = 0; + r = await importRecording(project, await item("p-3"), rec, { ask: askOp }); + assert.deepEqual([r.character.id, r.character.layer], ["me", "item"]); + assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "cleaned", "converted to kokoro:bm_george (pitch: contour +2 st)"]); + await posts(["character", "chars", "p-3", "--clear"]); +}); diff --git a/umtool/lib/report/lintCli.mjs b/umtool/lib/report/lintCli.mjs @@ -72,9 +72,12 @@ export async function castProblems(manifest, project, reportsRoot = REPORTS_ROOT const { readVoiceMap } = await import("./postSay.mjs"); const { resolverFor } = await import("./castProject.mjs"); const map = await readVoiceMap(project.dir).catch(() => ({})); - const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, render: manifest?.render ?? {} }) }); + // This video's own characters answer before the cast's (cast.mjs: the chain every read asks). + const { readProjectCharacters } = await import("./castStore.mjs"); + const own = (await readProjectCharacters(project.dir)).doc; + const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, project: own, render: manifest?.render ?? {} }) }); return { - warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? "the project's voice map" : d.from === "cast" ? "the cast" : d.from}): umtool cast reread ${project.id} ${d.character}`), + warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? (d.handle in map ? "the project's voice map" : "this video's own character") : d.from === "cast" ? "the cast" : d.from === "item" ? "the item's own character" : d.from}): umtool cast reread ${project.id} ${d.character}`), notes: overrides.map((o) => `@${o.handle} (${o.character}) reads in ${o.project} in this project -- the cast says ${o.cast} (an override on purpose; umtool posts voices ${project.id} remove ${o.handle} follows the cast)`), }; } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -3307,7 +3307,7 @@ export function handlesWithoutAvatar(m, handles) { // ---- a post item's narration (report-to-video/post-narration.mjs) ---------- /** The narration keys a write may set on one post item (post-narration.mjs; knobs.md, "A narrated post item"). */ -export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]); +export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "character", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]); /** * One post item's narration, changed in place (`m` the manifest inside a diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -24,7 +24,7 @@ import { mkdir, readFile, readdir, rename, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { - NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, + NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, 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"; @@ -46,12 +46,12 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", " [--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]", + " umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] [--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]", + " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--force] [--dry-run]", " umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new", " read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)", " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", @@ -72,8 +72,13 @@ export const NARRATE_USAGE = [ " --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).", " --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label operator]: a person's RECORDING of the", " item made a character's read -- kept as a recorded take (the original), cleaned (the editor's voice-enhance), then", - " converted to the character's STOCK voice (umtool cast: its convert voice; default the post's author's, else the", - " narrator) -- each a new take, the last picked, the disclosure line said.", + " converted to the character's STOCK voice (umtool cast: its convert voice) -- each a new take, the last picked, the", + " disclosure line said. The character: --as (this video's own, else the cast's), else the item's own (umtool posts", + " character), this video's for the post's author, the cast's, the narrator. Its RECORDED PRESET says whether the", + " read is cleaned and its edges trimmed to speech (and the room kept): --clean | --no-clean and --trim | --no-trim", + " say otherwise for this read.", + " --speed <s> (--take, --take --thread): the speed the read is asked at (0.5-2; Orpheus has none) -- default the", + " item's own, else its character's (the synthetic preset's: umtool cast set <id> --speed). A thread read: every part.", " --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", @@ -330,12 +335,15 @@ export async function makeTake(project, e, { script = null, note = null, engine const k = postNarrationKnobs(e, render); const words = String(script ?? e.narration?.script ?? "").trim(); if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`); - // The voice his own read is said in: the one asked for, the project's voice map, the CAST, the narrator's (readVoice.mjs). + // The voice his own read is said in: the one asked for, the item's own character, the project's characters and voice + // map, the CAST, the narrator's (readVoice.mjs). const { itemReadVoice } = await import("./readVoice.mjs"); const said0 = await itemReadVoice(project, e, { render, engine, voice }); const eng = said0.engine; const vox = said0.voice; - const spd = speed ?? e.narration?.speed ?? null; + // Its speed: the one asked for (--speed), else the item's own (`narration.speed`: set on this one item), else its + // character's (the synthetic preset's that answered for the voice). + const spd = speed ?? e.narration?.speed ?? said0.speed ?? null; const pid = postIdOf(e); const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); await mkdir(dir, { recursive: true }); @@ -532,7 +540,10 @@ export async function narrateCommand(project, words, flags, { json = false, dryR if (str("--recording") !== null) { // 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"), + // --no-clean / --clean and --no-trim / --trim win over the character's recorded preset; neither: the preset's. + as: str("--as"), label: str("--label") ?? "operator", clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined, + ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}), + convert: !flags.has("--no-convert"), note: str("--note"), ...pitchFlags(str), emit: (_ev, f) => !json && f?.message && out(f.message), }); @@ -585,15 +596,14 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return threadCommand(project, e, { manifest, json, out, overrides, parents, skip: multi("--skip-parent").flatMap((x) => x.split(",")).map((x) => x.trim()).filter(Boolean), quoted: !flags.has("--no-quoted"), linked: !flags.has("--no-linked"), readSeen: flags.has("--read-seen"), - voice: str("--voice"), engine: str("--engine"), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, + voice: str("--voice"), engine: str("--engine"), speed: speedFlag(str), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, }); } if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { - const speedRaw = str("--speed"); const r = await makeTake(project, e, { script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"), - speed: speedRaw === null ? null : Number(speedRaw), render, emit: (_ev, f) => !json && f?.message && out(f.message), + speed: speedFlag(str), render, emit: (_ev, f) => !json && f?.message && out(f.message), }); if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, narration: r.result.narration, token: r.result.token }, null, 2)); else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}`); @@ -622,6 +632,58 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return 0; } +export const CHARACTER_USAGE = [ + "usage: umtool posts character <project> <item> [<character> | --clear] [--json]", + " THE CHARACTER ONE POST ITEM's OWN READ IS MADE WITH (its `narration.character`): the id of one of this video's", + " own characters (umtool cast project <p>), else of the cast's (umtool cast ls) -- its presets answer for this", + " item's read before its author's handle does: the synthetic one for a new take or a thread read (voice, speed),", + " the recorded one for a recording made its read (--recording). No character: the one it names, and what its read", + " resolves to now. --clear: by its author's handle again. One undoable write; no take is made or changed (a picked", + " read in another voice is DRIFT: umtool cast project <p>).", +].join("\n"); + +/** `umtool posts character <p> <item> [<id> | --clear]` -- a post item's own character (cast.mjs itemCharacterOf). */ +export async function characterCommand(project, rest, { flags = new Map(), json = false, out = (s) => console.log(s) } = {}) { + const [ref, id] = rest; + const manifest = await readManifest(project.dir); + if (!manifest) throw new NarrateError(`${project.id} has no manifest`); + const e0 = findPostItem(manifest, ref); + if (!e0) throw new NarrateError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + const clear = flags.has("--clear"); + if (clear && id) throw new NarrateError("posts character: a character's id, or --clear -- not both"); + const { readLayers } = await import("./characterLayers.mjs"); + const { characterById, shownNameOf } = await import("umtool-report-to-video/cast"); + const { itemReadVoice } = await import("./readVoice.mjs"); + const { voiceSpecOf } = await import("umtool-report-to-video/post-say"); + const layers = await readLayers(project.dir); + let e = e0; + let changed = null; + if (clear || id) { + let want = null; + if (id) { + const hit = characterById(id, layers); + if (!hit) throw new NarrateError(`no character ${id} among ${project.id}'s own or in the cast (umtool cast project ${project.id}; umtool cast ls)${layers.projectRead.error ? ` -- and this video's characters are not read: ${layers.projectRead.error}` : ""}`); + want = hit.character.id; + } + if ((e0.narration?.character ?? null) !== want) { + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e0.id, { character: want }, { token: await manifestToken(project.dir) })); + e = result.entry; + changed = want ? "set" : "cleared"; + } + } + const it = layers.itemCharacterOf(e); + const v = await itemReadVoice(project, e, { render: manifest.render ?? {}, map: layers.map, cast: layers.castMap, item: layers.itemOf(e) }); + const voice = { ...v, spec: voiceSpecOf(v) }; + if (json) out(JSON.stringify({ ok: true, id: e.id, character: it?.id ?? null, found: it ? !!it.character : null, layer: it?.layer ?? null, changed, voice }, null, 2)); + else { + const how = `${voice.spec}${typeof voice.speed === "number" ? ` ×${voice.speed}` : ""} (${voice.from}${voice.character && voice.from !== "narrator" ? `: ${voice.character}` : ""})`; + if (!it) out(`${e.id}: no character of its own${changed ? " now" : ""} -- read by its author's handle: ${how}`); + else if (!it.character) out(`${e.id}: names ${it.id}, which is NOT a character of this video's or the cast's -- it reads as its author does: ${how} (umtool posts character ${project.id} ${e.id} --clear)`); + else out(`${e.id}: read as ${it.id} (${shownNameOf(it.character)}; ${it.layer === "project" ? "this video's own" : "the cast's"}): ${how}`); + } + return 0; +} + export const FIT_USAGE = [ "usage: umtool posts fit <project> [--all | <item> …] [--linger <s>] [--dry-run] [--json]", " NARRATED POSTS, NO LINGERING: each post read in full, then over `linger` (1.8 s) after the words; a video", @@ -673,6 +735,16 @@ export async function fitCommand(project, refs, { all = false, linger = null, js return 0; } +/** `--speed` as a read takes it (null: not given); a value the tts op would refuse is refused here, in the flag's name. */ +function speedFlag(str) { + const raw = str("--speed"); + if (raw === null) return null; + const n = Number(raw); + const [lo, hi] = POST_NARRATION_LIMITS.speed; + if (String(raw).trim() === "" || !Number.isFinite(n) || n < lo || n > hi) throw new NarrateError(`--speed is a number from ${lo} to ${hi} (got ${raw || "nothing"})`); + return n; +} + /** `--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 = {}; @@ -751,30 +823,40 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = * 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) 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 }`. + * else the editor's. + * + * THE CHARACTER, and its RECORDED PRESET (cast.mjs characterForRead, recordedPresetOf): the one `as` names (an id, a + * handle, a name -- the project's own characters first), else the item's own (`narration.character`), else the + * project's for the post's author, else the cast's, else the cast's narrator; none: kept as recorded (and cleaned). + * What the command says wins over the preset: `clean` (undefined: the preset's `enhance`, on unless it says off), + * `trim` (undefined: the preset's -- its edges trimmed to speech unless `trim.on` is false, `trim.padMs` the room + * kept either side), `pitch` / `semitones`. 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, direction }`. */ -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 } = {}) { +export async function importRecording(project, e0, file, { as = null, label = "operator", clean = undefined, convert = true, trim = undefined, 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, convertPitchLabel, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast"); + const { readLayers } = await import("./characterLayers.mjs"); + const { convertPitchLabel, recordedPresetOf, shownNameOf } = 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); - if (as && !character) throw new NarrateError(`--as ${as}: no such character in the cast (umtool cast ls)`); + const layers = await readLayers(project.dir); + const who = layers.characterForRead(e0, as); + const character = who?.character ?? null; + if (as && !character) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`); + const preset = character ? recordedPresetOf(character) : null; + const doClean = clean ?? preset?.enhance ?? true; + const doTrim = trim ?? (preset ? preset.trim : undefined); const notes = []; const takes = []; const fresh = async () => findPostItem(await readManifest(project.dir), e0.id); - const kept = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${character.name}` : ""}` }); + const kept = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${shownNameOf(character)}` : ""}`, ...(doTrim ? { trim: doTrim } : {}) }); takes.push({ step: "recorded", file: kept.take.file }); - emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB)` }); + emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB${doTrim?.on === false ? ", its edges not trimmed" : ""})` }); let e = await fresh(); const indexOf = (rel) => (e?.narration?.takes ?? []).findIndex((t) => t.file === rel); let from = indexOf(kept.take.file); - if (clean) { + if (doClean) { try { const r = await deriveTake(project, e, { from, op: "enhance", emit, editor, ask }); takes.push({ step: "cleaned", file: r.take.file }); @@ -784,11 +866,12 @@ export async function importRecording(project, e0, file, { as = null, label = "o if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err; notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`); } - } + } else if (clean === undefined) notes.push(`not cleaned: ${character.id}'s recorded preset says so (enhance off)`); if (convert) { - 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 …)"); + const target = character ? preset.convert : null; + if (!character) notes.push("not converted: no character to convert to (--as <character>, the item's own, or the post's author or a narrator in the cast: umtool cast add …)"); + else if (!target.voice) notes.push(`not converted: ${character.id} has no stock voice to convert to (umtool cast ${who.layer === "cast" || who.layer === "narrator" ? "" : `project ${project.id} `}set ${character.id} --convert-voice <engine:voice>)`); 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) }; @@ -803,7 +886,11 @@ export async function importRecording(project, e0, file, { as = null, label = "o } } } - return { takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null, character: character ? { id: character.id, name: character.name, voice: character.voice } : null }; + return { + takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null, + character: character ? { id: character.id, name: shownNameOf(character), voice: character.voice ?? null, layer: who.layer } : null, + ...(preset?.direction ? { direction: preset.direction } : {}), + }; } /** diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -61,9 +61,12 @@ export function targetLufsOf(manifest) { * @param {{ id: string, dir: string }} project * @param {Record<string, any>} entry * @param {Array<{ file: string, text?: string, para?: number }>} parts - * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null }} [o] + * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null, trim?: { on?: boolean, padMs?: number | null } | null }} [o] */ -export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null } = {}) { +export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null } = {}) { + // A character's recorded preset (cast.mjs recordedPresetOf): its edges left as recorded (`trim.on` false), or the + // room kept either side of the words (`trim.padMs`); none: trimmed, RECORD_ROOM. + const room = trim && Number.isFinite(trim.padMs) ? { head: trim.padMs / 1000, tail: trim.padMs / 1000 } : RECORD_ROOM; if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`); if (!parts.length) throw new Error("nothing was recorded"); const pid = postIdOf(entry); @@ -83,7 +86,7 @@ export async function keepRecording(project, entry, parts, { label = "operator", await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.file, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", raw]); const { seconds } = await measureTake(raw); const sil = await detectSilence(raw, { silenceMinDur: 0.15 }).catch(() => []); - const span = trimSpan(sil, seconds ?? 0); + const span = trim?.on === false ? { from: 0, to: r3(seconds ?? 0) } : trimSpan(sil, seconds ?? 0, room); const out = path.join(partsDir, `p${String(k + 1).padStart(2, "0")}.wav`); await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", raw, "-af", `atrim=${span.from}:${span.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", out]); await rm(raw, { force: true }); diff --git a/umtool/lib/report/postRevoice.mjs b/umtool/lib/report/postRevoice.mjs @@ -210,12 +210,16 @@ export function revoicePlan(entry, { match, occurrence = 1, say, voice = null, x to: { lo: r3(Math.min(Math.max(to, b.end), Math.max(to - REVOICE_REACH_WIDE, b.end))), hi: r3(Math.min(total, to + REVOICE_REACH_WIDE, next ? next.end : total)) }, }; const v = voice ?? voiceOf(entry, take, parts[part], render); + const partSpeed = parts[part]?.speed ?? (parts.length ? null : take.speed ?? null); + const speed = typeof partSpeed === "number" && Number.isFinite(partSpeed) && partSpeed !== 1 && engine !== "orpheus" ? partSpeed : null; const spoken = red ? spokenOf(say, entry, red) : { text: say, lexicon: [] }; const fixedAt = (Array.isArray(entry.fx) ? entry.fx : []).filter((fx) => fin(fx?.at)).length; return { take, picked, recut, target, first, last, phrase: words.slice(first, last + 1).map((w) => w.w).join(" "), nominal: { from: r3(from), to: r3(Math.min(total, to)) }, windows, wide, - say, said: spoken.text, lexicon: spoken.lexicon, voice: v, engine, key: partKey(engine, v, spoken.text), part, xfade, fixedAt, + // The speed the part it sits in was synthesized at (its character's preset's, or the read's --speed): the phrase + // put in is asked at it too, so it does not sound slower or faster than the words around it. + say, said: spoken.text, lexicon: spoken.lexicon, voice: v, engine, ...(speed !== null ? { speed } : {}), key: partKey(engine, v, spoken.text, speed), part, xfade, fixedAt, }; } @@ -390,7 +394,7 @@ export async function revoiceTake(project, e, o) { const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; emit("note", { message: `re-voicing "${plan.phrase}" as "${plan.said}" (${plan.engine} · ${plan.voice}): asking the editor…` }); try { - ({ jobId = null } = (await askTts({ text: plan.said, engine: plan.engine, voice: plan.voice, out: wav }, { ...(editor ? { editor } : {}), emit })) ?? {}); + ({ jobId = null } = (await askTts({ text: plan.said, engine: plan.engine, voice: plan.voice, out: wav, ...(typeof plan.speed === "number" ? { speed: plan.speed } : {}) }, { ...(editor ? { editor } : {}), emit })) ?? {}); } catch (err) { throw new RevoiceError(`"${plan.said}" (${plan.voice}) was not synthesized: ${err instanceof Error ? err.message : err}`); } diff --git a/umtool/lib/report/postRevoice.test.mjs b/umtool/lib/report/postRevoice.test.mjs @@ -53,6 +53,26 @@ function tones(seconds, spans, { amp = 0.2, freq = 220 } = {}) { return x; } +test("a re-voice is asked at the speed its part was synthesized at (a character's preset's, the read's --speed); Orpheus has none", async () => { + const { partKey } = await import("./postThreadRead.mjs"); + const fast = (engine) => { + const e = item(); + const t = e.narration.takes[0]; + t.engine = engine; + t.parts[0].speed = 1.2; + return e; + }; + const p = revoicePlan(fast("kokoro"), ASK); + assert.equal(p.speed, 1.2); + assert.equal(p.key, partKey("kokoro", p.voice, p.said, 1.2), "another speed is another cached part"); + assert.notEqual(p.key, partKey("kokoro", p.voice, p.said)); + // The second part has no speed of its own: asked as before. + const q = revoicePlan(fast("kokoro"), { match: "4", occurrence: 2, say: "four" }); + assert.equal(q.speed, undefined); + assert.equal(q.key, partKey("kokoro", q.voice, q.said)); + assert.equal(revoicePlan(fast("orpheus"), ASK).speed, undefined); +}); + test("THE ASK: the phrase and #n, --say, --voice (auto: the piece's own), --xfade 0-0.2 (default 0.03); the refusals are usage errors", () => { assert.deepEqual(parseRevoice({ phrase: "20 10 4 0", say: " 20... 10... " }), { match: "20 10 4 0", occurrence: 1, say: "20... 10...", voice: null, xfade: 0.03, cut: null }); assert.deepEqual(parseRevoice({ phrase: "4#2", say: "four", voice: "auto", xfade: "0.05" }), { match: "4", occurrence: 2, say: "four", voice: null, xfade: 0.05, cut: null }); diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -293,6 +293,9 @@ export async function voicesCommand(project, rest, { json = false, out = (s) => const k = postNarrationKnobs({}, manifest.render ?? {}); const castRead = await castForProject(project.dir); const cast = castVoiceMap(castRead.cast); + // The layers a read asks (characterLayers.mjs): this video's own characters over this map, then the cast -- so the + // table says what a read would say, and why. + const L = await (await import("./characterLayers.mjs")).readLayers(project.dir); // Every author a thread read could voice: the items' own, their parents', quoted and linked posts'. const authors = new Map(); const count = (h, own) => { @@ -312,9 +315,11 @@ export async function voicesCommand(project, rest, { json = false, out = (s) => } // Each author's voice as a context post, and WHERE it comes from: the project's map, the cast, the default. const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => { - const v = voiceSourceOf({ handle: a.handle, role: "parent:0" }, { map, cast, narrator: k.voice, engine: k.engine }); + const v = voiceSourceOf({ handle: a.handle, role: "parent:0" }, { map: L.map, cast: L.castMap, narrator: k.voice, engine: k.engine }); const c = characterOf(castRead.cast, a.handle); - return { ...a, voice: v.spec, from: v.from, mapped: a.handle in map, ...(c ? { character: c.id, castVoice: c.voice } : {}) }; + // `own`: this video's own character that answers for the handle (narration/characters.json), before the map. + const own = v.from === "project" && v.character ? v.character : null; + return { ...a, voice: v.spec, from: v.from, ...(typeof v.speed === "number" ? { speed: v.speed } : {}), mapped: a.handle in map, ...(own ? { own } : {}), ...(c ? { character: c.id, castVoice: c.voice } : {}) }; }); if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, cast: { file: castRead.file, characters: Object.keys(cast).length, ...(castRead.error ? { error: castRead.error } : {}) }, authors: rows }, null, 2)); else { @@ -322,7 +327,8 @@ export async function voicesCommand(project, rest, { json = false, out = (s) => for (const [h, v] of Object.entries(map)) out(` ${h === VOICE_MAP_OTHER ? "* (everyone else)" : `@${h}`} -> ${v}${cast[h] && cast[h] !== v ? ` (the cast says ${cast[h]}: overridden here)` : ""}`); if (castRead.error) out(` the cast is not read: ${castRead.error}`); if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped or cast):"); - for (const r of rows) out(` @${r.handle} ${r.voice} (${r.from === "project" ? "project" : r.from === "cast" ? `cast: ${r.character}` : "default"}) -- ${r.items} item(s), ${r.context} context post(s)`); + if (L.projectRead.error) out(` this video's own characters are not read: ${L.projectRead.error}`); + for (const r of rows) out(` @${r.handle} ${r.voice}${r.speed !== undefined ? ` ×${r.speed}` : ""} (${r.from === "project" ? (r.own ? `this video's character: ${r.own}${r.mapped ? "; the map's entry is under it" : ""}` : "project") : r.from === "cast" ? `cast: ${r.character}` : "default"}) -- ${r.items} item(s), ${r.context} context post(s)`); } return 0; } diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -56,7 +56,7 @@ import { chronoPieces } from "umtool-report-to-video/post-thread"; import { cardText, parentsOf } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { spokenRead } from "umtool-report-to-video/post-redact"; -import { resolvePieceVoice } from "umtool-report-to-video/post-say"; +import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -81,11 +81,12 @@ export class ThreadReadError extends Error { export const THREAD_READ_USAGE = [ " umtool 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]", + " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s]", " [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]", " A THREAD READ: the post it answers (--parents all: every ancestor; none: no parent), the post it quotes, the posts", " its words link to and his words, in DATE order, each in its author's voice (the project's voice map, umtool posts", - " voices; --voice-for handle=voice for this read), the redaction, the slur filter and the pronunciation lexicon", + " voices; --voice-for handle=voice for this read) and at its character's SPEED (its synthetic preset's; --speed s:", + " every part at that one; Orpheus has no speed), the redaction, the slur filter and the pronunciation lexicon", " (umtool 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 (its tts op, a job) into narration/parts-cache/ and reused by", " every read after; the take (take-<n>.<engine>-thread.wav + take-<n>.parts.json) is saved with its parts' roles and", @@ -94,15 +95,21 @@ export const THREAD_READ_USAGE = [ " could not be synthesized (the parts already made stay cached: run it again).", ].join("\n"); -/** The project's cast as a voice map (castStore.mjs: the cast the project reads; `{}` with none, or a broken one). */ +/** + * The project's cast as a preset layer (castStore.mjs: the cast the project reads; `{}` with none, or a broken one): + * `{ handle: { voice, speed?, character } }` (cast.mjs castPresetMap), voiceSourceOf's `cast`. + */ export async function projectCastMap(dir) { const { castForProject } = await import("./castStore.mjs"); - const { castVoiceMap } = await import("umtool-report-to-video/cast"); - return castVoiceMap((await castForProject(dir)).cast); + const { castPresetMap } = await import("umtool-report-to-video/cast"); + return castPresetMap((await castForProject(dir)).cast); } -/** A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`). */ -export const partKey = (engine, voice, text) => createHash("sha1").update(engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`).digest("hex"); +/** + * A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when + * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before). + */ +export const partKey = (engine, voice, text, speed = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}`).digest("hex"); /** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */ export function parentsSelector(v) { @@ -135,14 +142,16 @@ export function seenIds(manifest, e) { * * @param {Record<string, any>} manifest * @param {Record<string, any>} e the post item - * `cast` is the cast as a voice map (cast.mjs castVoiceMap: `{ handle: "engine:voice" }`). Each piece's `engine` is - * its voice's (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf). - * The read's `engine` is his piece's. + * `map`, `cast` and `item` are voiceSourceOf's layers (cast.mjs projectPresetMap, castPresetMap, itemPresetOf: an entry + * a voice as written, or a character's preset `{ voice, speed?, character }`). Each piece's `engine` is its voice's + * (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf); `speed` + * the speed it is asked at (readSpeedOf: the command's `speed`, else the item's own for his words, else its + * character's preset's -- none for Orpheus, which has none, or at 1). The read's `engine` is his piece's. * - * @param {{ red?: any, map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, parents?: string, - * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null }} [o] + * @param {{ red?: any, map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, parents?: string, + * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o] */ -export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) { +export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; @@ -200,8 +209,9 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, o skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" }); continue; } - const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, overrides, self: str(e.handle), voice, narrator, engine: eng }); - pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); + const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, item, overrides, self: str(e.handle), voice, narrator, engine: eng }); + const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: p.role === "post" ? e.narration?.speed ?? null : null, engine: v.engine }); + pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); } if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()]; @@ -218,12 +228,12 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, o export function readParts(plan) { return plan.pieces.flatMap((pc, piece) => { const eng = pc.engine ?? plan.engine; - return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, text: q.text, key: partKey(eng, pc.voice, q.text) })); + return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null) })); }); } -/** Each piece's `engine:voice`, in order, once each -- what a read sounds like, for "is it up to date". */ -const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}`))].join("+"); +/** Each piece's `engine:voice` (and its speed, when it has one), in order, once each -- what a read sounds like, for "is it up to date". */ +const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}${typeof p.speed === "number" && p.speed !== 1 ? `x${p.speed}` : ""}`))].join("+"); /** * THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece, @@ -237,7 +247,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p. const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; t += gap; const s = Number(seconds[i]); - const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; t += s; return row; }); @@ -245,11 +255,13 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p. } /** The `read` record of a take: how it was asked for (only what differs from the defaults). */ -export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null }) { +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null }) { return { kind: "thread", parents: parentsSelector(parents), ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), ...(readSeen ? { seen: true } : {}), ...(Object.keys(overrides ?? {}).length ? { voiceFor: { ...overrides } } : {}), ...(voice ? { voice } : {}), + // The speed the command asked for the whole read (`--speed`); a character's own is its preset's, not the read's. + ...(typeof speed === "number" && Number.isFinite(speed) ? { speed } : {}), }; } @@ -257,9 +269,9 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = export function upToDate(e, plan) { const t = pickedTake(e); if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false; - // A take whose parts say their voices: each piece in the same engine and voice. + // A take whose parts say their voices: each piece in the same engine and voice, at the same speed. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; - if (!parts.length) return true; + if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number"); return voiceSig(parts, t.engine ?? "orpheus") === voiceSig(plan.pieces, plan.engine); } @@ -281,16 +293,20 @@ async function durationOf(file) { */ export async function threadTake(project, e, opts = {}) { const { - manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, - readSeen = false, voice = null, engine = null, note = null, force = false, hold = true, dryRun = false, + manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, + readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, } = opts; const manifest = m0 ?? (await readManifest(project.dir)); if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); const red = red0 !== undefined ? red0 : await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest); - const map = map0 !== undefined ? map0 : await (await import("./postSay.mjs")).readVoiceMap(project.dir); - const cast = cast0 !== undefined ? cast0 : await projectCastMap(project.dir); - const plan = threadReadPlan(manifest, e, { red, map, cast, overrides, parents, skip, quoted, linked, readSeen, voice, engine }); + // The layers (characterLayers.mjs): the project's characters over its voice map (a broken map refuses the read), the + // cast, the item's own character -- each the caller's when it hands one in. + const L = map0 !== undefined && cast0 !== undefined && item0 !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir, { strictMap: map0 === undefined }); + const map = map0 !== undefined ? map0 : L.map; + const cast = cast0 !== undefined ? cast0 : L.castMap; + const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null; + const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed }); const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => path.join(cacheDir, `${p.key}.wav`); @@ -353,7 +369,7 @@ export async function threadTake(project, e, opts = {}) { emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.engine === plan.engine ? p.voice : `${p.engine}:${p.voice}`}): asking the editor…` }); await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); try { - const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit }); + const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p), ...(typeof p.speed === "number" ? { speed: p.speed } : {}) }, { ...(editor ? { editor } : {}), emit }); if (jobId) jobs.push(jobId); } catch (err) { throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`); @@ -397,7 +413,7 @@ export async function threadTake(project, e, opts = {}) { parts: meta, ...(plan.slurs ? { slurs: plan.slurs } : {}), ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), - read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice }), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed }), }; const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); @@ -429,19 +445,19 @@ export async function threadCommand(project, e, o) { } throw err; } - const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); + const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.character ? { character: p.character } : {}), words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); const guard = r.take ? await guardOf(project, e.id) : null; if (json) { out(JSON.stringify({ ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped, - parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, key: p.key, cached: p.cached, text: p.text })), + parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, ...(p.speed !== undefined ? { speed: p.speed } : {}), key: p.key, cached: p.cached, text: p.text })), fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane, ...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}), }, null, 2)); return 0; } out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`); - for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); + for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : p.from === "item" ? `(the item's character: ${p.character}) ` : p.from === "project" && p.character ? `(this video's character: ${p.character}) ` : ""}${p.speed !== undefined ? `×${p.speed} ` : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`); if (r.upToDate) { out(` up to date: the picked take already reads this, in these voices (--force makes it again)`); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -80,6 +80,9 @@ const SAY_LINES = [ " masked slur and a redacted word are never replaced. stale: the picked reads that still say one the old way.", " umtool posts voices <project> [ls] | set <handle|*> <voice> | remove <handle|*> [--json]", " THE VOICE MAP (narration/voices.json): the voice a thread read gives each author (* everyone else; default leo).", + " umtool posts character <project> <item> [<character> | --clear] [--json]", + " THE CHARACTER ONE ITEM's OWN READ IS MADE WITH: one of this video's own (umtool cast project <p>) or the cast's;", + " its presets answer before its author's handle does. --clear: by its handle again (posts character --help).", ]; export const POSTS_USAGE = [ @@ -523,6 +526,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; }); } + if (verb === "character") { + // A post item's own character (postNarrationCli.mjs characterCommand; cast.mjs). + const { CHARACTER_USAGE, characterCommand } = await import("./postNarrationCli.mjs"); + if (!projectArg || flags.has("--help") || words.length < 3) { + err(CHARACTER_USAGE); + return 2; + } + return await characterCommand(await projectOf(projectArg, root), words.slice(2), { flags, json, out }); + } if (verb === "narrate") { const { NARRATE_USAGE, narrateCommand } = await import("./postNarrationCli.mjs"); if (!projectArg || flags.has("--help")) { diff --git a/umtool/lib/report/readVoice.mjs b/umtool/lib/report/readVoice.mjs @@ -1,22 +1,24 @@ // THE VOICE A POST ITEM's OWN READ IS SAID IN (a single post's take: `umtool posts narrate <p> <item> --take`, the // bench's Re-take), through the SAME function a thread read asks for his piece (post-say.mjs resolvePieceVoice): the -// read's own voice (--voice, the bench's voice field), the project's voice map, the CAST, the narrator's (the item's -// own `narration.voice`, else the cut's). So a post read alone and the same post read with its thread agree. +// read's own voice (--voice, the bench's voice field), the item's own character (`narration.character`), the +// project's characters and voice map, the CAST, the narrator's (the item's own `narration.voice`, else the cut's). So +// a post read alone and the same post read with its thread agree. // // Plain ESM. import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; import { resolvePieceVoice, voiceRefOf } from "umtool-report-to-video/post-say"; /** - * `{ engine, voice, from }` for post item `e`'s own read -- `from` "override", "project", "cast", "narrator". - * `map` and `cast` are read from the project when not given (a broken voice map reads as none here: the read is not - * refused for it; `umtool posts voices` says what is wrong with it). + * `{ engine, voice, from, speed?, character? }` for post item `e`'s own read -- `from` "override", "item", "project", + * "cast", "narrator"; `speed` and `character` the preset's that answered (a character's `synthetic.speed`, its id). + * `map`, `cast` and `item` (voiceSourceOf's layers) are read from the project when not given (characterLayers.mjs; a + * broken voice map reads as none here: the read is not refused for it; `umtool posts voices` says what is wrong). * * @param {{ dir: string }} project * @param {Record<string, any>} e - * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, string>, cast?: Record<string, string> }} [o] + * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, any>, cast?: Record<string, any>, item?: any }} [o] */ -export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined } = {}) { +export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined, item = undefined } = {}) { const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; const narrator = e.narration?.voice ?? k.voice; @@ -24,9 +26,11 @@ export async function itemReadVoice(project, e, { render = {}, engine = null, vo const ref = voiceRefOf(voice, eng) ?? { engine: eng, voice: String(voice) }; return { engine: engine ?? ref.engine ?? eng, voice: ref.voice, from: "override" }; } - const m = map !== undefined ? map : await (await import("./postSay.mjs")).readVoiceMap(project.dir).catch(() => ({})); - const c = cast !== undefined ? cast : await (await import("./postThreadRead.mjs")).projectCastMap(project.dir).catch(() => ({})); - const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, self: e.handle ?? null, narrator, engine: eng }); + const L = map !== undefined && cast !== undefined && item !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir).catch(() => null); + const m = map !== undefined ? map : L?.map ?? {}; + const c = cast !== undefined ? cast : L?.castMap ?? {}; + const it = item !== undefined ? item : L?.itemOf(e) ?? null; + const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, item: it, self: e.handle ?? null, narrator, engine: eng }); // An engine asked for outright that the resolved voice is not of: the narrator's voice in it. if (engine && r.engine !== engine) return { engine, voice: narrator, from: "narrator" }; return r; diff --git a/umtool/lib/report/recordSession.mjs b/umtool/lib/report/recordSession.mjs @@ -117,7 +117,9 @@ export async function finishSession(project, entry, { label = "operator", manife const p = doc.parts[String(n)]; parts.push({ file: path.join(dir, p.file), text: p.text, para: p.para }); } - const kept = await keepRecording(project, entry, parts, { label, manifest, script }); + // Its character's recorded preset says whether its edges are trimmed, and the room kept (characterLayers.mjs). + const { recordedTrimFor } = await import("./characterLayers.mjs"); + const kept = await keepRecording(project, entry, parts, { label, manifest, script, trim: await recordedTrimFor(project.dir, entry) }); await rm(dir, { recursive: true, force: true }); return kept; } diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -1,26 +1,52 @@ // THE CAST (operator, 6 Nov 2026: "I'd like to be able to pick different voices // for different characters, and in UI alone be able to try rendering different // ones to compare … and try to maintain consistent voices for different -// repeating characters"): the CHARACTERS that recur across projects, each with -// the stock voice it reads in, stored ONCE for every project -// (`<REPORTS_ROOT>/.umtool/cast.json`, lib/report/castStore.mjs its one writer). +// repeating characters"): the CHARACTERS that recur across projects, stored +// ONCE for every project (`<REPORTS_ROOT>/.umtool/cast.json`, +// lib/report/castStore.mjs its one writer). // -// { "format": "umtool-cast", "version": 1, +// A CHARACTER IS A PRESET (operator, 11 Nov 2026: "a preset of voice and other +// settings … different presets for synthetic and human-filtered voices"): two +// of them, picked by how the read is made -- +// +// { "format": "umtool-cast", "version": 2, // "characters": [ { "id": "thequartering", "name": "TheQuartering", // "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) +// "synthetic": { "voice": "kokoro:am_michael", // <tts engine>:<stock voice> +// "speed": 1.1 }, // the tts op's speed, 0.5-2 (absent: 1) +// "recorded": { // a RECORDING made his read +// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael", +// "pitch": "contour", "semitones": 2 }, // CAST_CONVERT_PITCH, the editor's voice-convert +// "enhance": true, // cleaned first (DeepFilterNet); absent: yes +// "trim": { "on": true, "padMs": 120 }, // its edges trimmed to speech, the room kept (absent: on, RECORD_ROOM) +// "direction": "higher, brisk, amused" }, // one line for the PERSON reading -- never sent to a model // "speakers": ["Jeremy"], // his REAL voice's name in a project's speakers.json // "avatar": "…", "note": "…", "narrator": true } ] } // +// VERSION 1 kept the stock voice in `voice` and the convert entry in `convert` +// at the character's top: those keys are READ AS THE PRESETS (upgradeCharacter: +// `voice` is `synthetic.voice`, `convert` is `recorded.convert`), in a file of +// either version, and the writer writes version 2. A +// reader is handed a VIEW (charactersOf, characterView): the presets AND the +// `voice` / `convert` they answer to, so what read version 1 reads version 2. +// +// A PROJECT's OWN CHARACTERS (`<project>/narration/characters.json`, +// PROJECT_CHARACTERS_FORMAT; the same store) are the same shape, with no +// narrator and with `anonymous: true` + `shown` ("Anon 1") for a person who +// must not enter the pool: they live in that video only. (The shown name is +// what umtool's own surfaces call them; the cut's card is not anonymised yet.) +// // A project's `narration/voices.json` (post-say.mjs) stays the project's -// OVERRIDE LAYER. The voice a piece of a read is said in, in order: the read's -// own override (--voice-for, --voice), the project's map, the CAST, the -// narrator's (the item's own author), the map's "*", the engine's default -- -// post-say.mjs voiceForPiece, which every read goes through (a single post's -// take, each piece of a thread read), so they agree. +// OVERRIDE LAYER (a handle in it reads as a project character with only a +// synthetic voice). The preset one read is made with, FIRST HIT WINS: the +// command's flags (--voice-for, --voice, --speed, --as, --pitch …), the item's +// own character (`narration.character`), the project's character for the +// handle (characters.json, then voices.json), the CAST's, the narrator's (the +// item's own author), the map's "*", the engine's default -- post-say.mjs +// voiceSourceOf for a synthesized read (a single post's take, each piece of a +// thread read: they agree), characterForRead below for a recording. A layer +// answers for a preset it HAS: a project character with no synthetic voice +// leaves the voice to the layers under it. // // A voice is ALWAYS a stock synthetic one (`<engine>:<voice>`): a character's // REAL voice (`speakers`) is a reference to compare a candidate with @@ -33,9 +59,32 @@ import { CONTEXT_VOICE_DEFAULTS, TTS_ENGINE_IDS, handleKey, voiceRefOf, voiceSpe export { voiceRefOf, voiceSpecOf }; export const CAST_FORMAT = "umtool-cast"; -export const CAST_VERSION = 1; +export const CAST_VERSION = 2; +/** The versions a reader takes (1: `voice` / `convert` at the character's top). */ +export const CAST_VERSIONS_READ = Object.freeze([1, 2]); export const CAST_MAX = 300; -export const CAST_KEYS = Object.freeze(["id", "name", "handles", "voice", "convert", "speakers", "avatar", "note", "narrator"]); +export const CAST_KEYS = Object.freeze(["id", "name", "handles", "synthetic", "recorded", "speakers", "avatar", "note", "narrator"]); +/** Version 1's keys, read as the presets (upgradeCharacter). */ +export const CAST_LEGACY_KEYS = Object.freeze(["voice", "convert"]); +/** A character's two presets: how a SYNTHESIZED read is made, and how a RECORDED one is. */ +export const SYNTHETIC_KEYS = Object.freeze(["voice", "speed"]); +export const RECORDED_KEYS = Object.freeze(["convert", "enhance", "trim", "direction"]); +export const TRIM_KEYS = Object.freeze(["on", "padMs"]); +/** The tts op's speed (the editor's: 0.5-2), the room a trim may keep, a direction's length. */ +export const CAST_SPEED = Object.freeze([0.5, 2]); +export const TRIM_PAD_MAX_MS = 2000; +export const DIRECTION_MAX = 200; + +/** A project's own characters: the file (relative to the project's folder), its format, its extra keys. */ +export const PROJECT_CHARACTERS_FILE = "narration/characters.json"; +export const PROJECT_CHARACTERS_FORMAT = "umtool-project-characters"; +export const PROJECT_CHARACTERS_VERSION = 1; +export const PROJECT_CHARACTER_KEYS = Object.freeze([...CAST_KEYS.filter((k) => k !== "narrator"), "anonymous", "shown"]); +/** + * The name an anonymous character is shown under when none is given: "Anon 1", "Anon 2" … (`{n}` the first number + * the project does not use). THE ONE PLACE the pattern is written. + */ +export const ANON_NAME_PATTERN = "Anon {n}"; /** 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"]); @@ -61,58 +110,201 @@ export const isQualifiedVoice = (spec) => !!voiceRefOf(spec) && str(spec).includ /** The empty cast. */ export const emptyCast = () => ({ format: CAST_FORMAT, version: CAST_VERSION, characters: [] }); +/** A project with no characters of its own. */ +export const emptyProjectCharacters = () => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters: [] }); -/** Every reason a cast document is refused (empty: it is fine). */ -export function validateCast(doc, where = "cast.json") { - if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`]; +const KEY_ORDER = ["id", "name", "anonymous", "shown", "handles", "synthetic", "recorded", "speakers", "avatar", "note", "narrator"]; + +/** + * A character as VERSION 2 holds it, from either version (pure, a copy): `voice` read as `synthetic.voice`, `convert` + * as `recorded.convert`, and the keys in one order. Where a preset says the key too, THE PRESET WINS: a top-level + * `voice` / `convert` beside it is a view's alias (characterView), which may be stale -- a view whose + * `synthetic.voice` was changed folds to the new value. (A writer's mutation that SETS `c.voice` the old way is told + * apart by what the character was before: foldWritten.) Anything else is left as it is (validateCast says what is wrong). + */ +export function upgradeCharacter(c) { + if (!isObj(c)) return c; + const { voice, convert, synthetic, recorded, ...rest } = c; + const syn = synthetic !== undefined && !isObj(synthetic) ? synthetic : { ...(voice !== undefined ? { voice } : {}), ...(synthetic ?? {}) }; + const rec = recorded !== undefined && !isObj(recorded) ? recorded : { ...(convert !== undefined ? { convert } : {}), ...(recorded ?? {}) }; + const all = { ...rest, ...(!isObj(syn) || Object.keys(syn).length ? { synthetic: syn } : {}), ...(!isObj(rec) || Object.keys(rec).length ? { recorded: rec } : {}) }; + const out = {}; + for (const k of KEY_ORDER) if (k in all) out[k] = all[k]; + for (const k of Object.keys(all)) if (!(k in out)) out[k] = all[k]; + return out; +} + +/** + * A character AS A WRITE LEAVES IT, folded to version 2 (pure): `c` what the mutation left, `before` the character it + * was handed (version 2's, no aliases; null: a new one). A top-level `voice` / `convert` on it was put there by the + * mutation -- the old way of setting one (`c.voice = …`) -- and is the newer word WHEN THE PRESET IS AS IT WAS; a + * preset the mutation changed itself wins (the top-level key is then a stale alias: a view written back). + */ +export function foldWritten(c, before = null) { + if (!isObj(c)) return c; + const out = { ...c }; + const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); + if (out.voice !== undefined && isObj(out.synthetic) && out.synthetic.voice !== undefined && before && same(before.synthetic?.voice, out.synthetic.voice)) out.synthetic = { ...out.synthetic, voice: out.voice }; + if (out.convert !== undefined && isObj(out.recorded) && out.recorded.convert !== undefined && before && same(before.recorded?.convert, out.recorded.convert)) out.recorded = { ...out.recorded, convert: out.convert }; + return upgradeCharacter(out); +} + +/** A cast document as version 2 holds it (upgradeCharacter each); a document that is not one is returned as it is. */ +export function upgradeCast(doc) { + if (!isObj(doc) || !Array.isArray(doc.characters) || doc.format !== CAST_FORMAT || !CAST_VERSIONS_READ.includes(doc.version)) return doc; + return { ...doc, version: CAST_VERSION, characters: doc.characters.map(upgradeCharacter) }; +} + +/** A character's stock voice (`synthetic.voice`; version 1's `voice`), its speed, its convert entry -- of either shape. */ +export const characterVoice = (c) => (isObj(c?.synthetic) && c.synthetic.voice !== undefined ? c.synthetic.voice : c?.voice) ?? null; +export const characterSpeed = (c) => (isObj(c?.synthetic) && typeof c.synthetic.speed === "number" ? c.synthetic.speed : null); +export const characterConvert = (c) => (isObj(c?.recorded) && c.recorded.convert !== undefined ? c.recorded.convert : c?.convert); + +/** + * A character as a READER is handed it: version 2's shape, AND the `voice` / `convert` its presets answer to (what + * version 1's readers ask). Never written: the writer's characters are upgradeCharacter's. + */ +export function characterView(c) { + if (!isObj(c)) return c; + const u = upgradeCharacter(c); + const voice = characterVoice(u); + const convert = characterConvert(u); + return { ...u, ...(voice !== null ? { voice } : {}), ...(convert !== undefined ? { convert } : {}) }; +} + +/** What is wrong with a convert entry (`{engine?, voice?, pitch?, semitones?}`), as sentences that start at `w`. */ +function convertErrors(cv, w) { + if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice", "pitch", "semitones"].includes(k))) return [`${w} must be {engine?, voice?, pitch?, semitones?}`]; + const errors = convertPitchErrors(cv).map((m) => `${w}.${m}`); + if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`); + if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`); + return errors; +} + +/** + * What is wrong with ONE character (upgraded: upgradeCharacter), as sentences that start at `w`. `layer` "cast" (a + * stock voice is required; it may be the narrator) or "project" (a preset is optional -- the layers under it answer + * -- and it may be `anonymous`, with the name it is `shown` under). Both layers refuse a voice, or a convert target, + * that is not a STOCK synthetic one. + */ +export function characterErrors(c, w, { layer = "cast" } = {}) { + const keys = layer === "project" ? PROJECT_CHARACTER_KEYS : CAST_KEYS; + if (!isObj(c)) return [`${w} must be {id, name, handles, synthetic, …}`]; + const errors = []; + for (const k of Object.keys(c)) if (!keys.includes(k)) errors.push(`${w}.${k} is not a character key (${keys.join(", ")})`); + if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`); + if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`); + if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`); + else { + if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`); + for (const h of c.handles ?? []) if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`); + } + const syn = c.synthetic; + if (syn === undefined) { + if (layer === "cast") errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(undefined)})`); + } else if (!isObj(syn) || Object.keys(syn).some((k) => !SYNTHETIC_KEYS.includes(k))) errors.push(`${w}.synthetic must be {voice, speed?}`); + else { + if (!isQualifiedVoice(syn.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(syn.voice)})`); + if (syn.speed !== undefined && !(typeof syn.speed === "number" && Number.isFinite(syn.speed) && syn.speed >= CAST_SPEED[0] && syn.speed <= CAST_SPEED[1])) errors.push(`${w}.synthetic.speed must be a number from ${CAST_SPEED[0]} to ${CAST_SPEED[1]}`); + } + const rec = c.recorded; + if (rec !== undefined) { + if (!isObj(rec) || Object.keys(rec).some((k) => !RECORDED_KEYS.includes(k))) errors.push(`${w}.recorded must be {convert?, enhance?, trim?, direction?}`); + else { + if (rec.convert !== undefined) errors.push(...convertErrors(rec.convert, `${w}.recorded.convert`)); + if (rec.enhance !== undefined && typeof rec.enhance !== "boolean") errors.push(`${w}.recorded.enhance must be true or false`); + if (rec.trim !== undefined) { + const t = rec.trim; + if (!isObj(t) || Object.keys(t).some((k) => !TRIM_KEYS.includes(k)) || (t.on !== undefined && typeof t.on !== "boolean")) errors.push(`${w}.recorded.trim must be {on?: true | false, padMs?}`); + else if (t.padMs !== undefined && !(typeof t.padMs === "number" && Number.isFinite(t.padMs) && t.padMs >= 0 && t.padMs <= TRIM_PAD_MAX_MS)) errors.push(`${w}.recorded.trim.padMs must be a number of milliseconds from 0 to ${TRIM_PAD_MAX_MS}`); + } + if (rec.direction !== undefined && (typeof rec.direction !== "string" || !rec.direction.trim() || rec.direction.length > DIRECTION_MAX || /[\r\n]/.test(rec.direction))) errors.push(`${w}.recorded.direction must be one line for the person reading (at most ${DIRECTION_MAX} characters)`); + } + } + if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`); + for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`); + if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`); + if (layer === "project") { + if (c.anonymous !== undefined && c.anonymous !== true) errors.push(`${w}.anonymous must be true or absent`); + if (c.shown !== undefined && (typeof c.shown !== "string" || !c.shown.trim() || c.shown.length > 80)) errors.push(`${w}.shown must be the name it is shown under (1-80 characters)`); + if (c.shown !== undefined && c.anonymous !== true) errors.push(`${w}.shown is an anonymous character's shown name (anonymous: true)`); + } + return errors; +} + +/** A list of characters refused: each one's reasons, an id twice, a handle two characters hold. */ +function listErrors(list, where, layer) { const errors = []; - if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`); - if (doc.version !== CAST_VERSION) errors.push(`${where}: version must be ${CAST_VERSION}`); - const list = doc.characters; - if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; - if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); const ids = new Set(); const owner = new Map(); - let narrators = 0; - list.forEach((c, i) => { + list.forEach((c0, i) => { const w = `${where}.characters[${i}]`; - if (!isObj(c)) return errors.push(`${w} must be {id, name, handles, voice, …}`); - for (const k of Object.keys(c)) if (!CAST_KEYS.includes(k)) errors.push(`${w}.${k} is not a character key (${CAST_KEYS.join(", ")})`); - if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`); - else if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`); - ids.add(c.id); - if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`); - if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`); - else { - if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`); - for (const h of c.handles ?? []) { - if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`); - else if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`); - else owner.set(h, c.id); - } + const c = upgradeCharacter(c0); + errors.push(...characterErrors(c, w, { layer })); + if (!isObj(c)) return; + if (CHARACTER_ID_RE.test(str(c.id))) { + if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`); + ids.add(c.id); } - 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", "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)`); - } + for (const h of Array.isArray(c.handles) ? c.handles : []) { + if (typeof h !== "string" || h !== handleKey(h)) continue; + if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`); + else owner.set(h, c.id); } - if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`); - for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`); - if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`); - if (c.narrator === true) narrators += 1; }); - if (narrators > 1) errors.push(`${where}: one character at most is the narrator`); return errors; } -/** The cast's characters (the invalid ones dropped, never fatal for a reader). */ +/** Every reason a cast document is refused (empty: it is fine). A version 1 document is read as version 2. */ +export function validateCast(doc, where = "cast.json") { + if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`]; + const errors = []; + if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`); + if (!CAST_VERSIONS_READ.includes(doc.version)) errors.push(`${where}: version must be ${CAST_VERSION} (or ${CAST_VERSIONS_READ.filter((v) => v !== CAST_VERSION).join(", ")}, read as it)`); + const list = doc.characters; + if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; + if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); + errors.push(...listErrors(list, where, "cast")); + if (list.filter((c) => isObj(c) && c.narrator === true).length > 1) errors.push(`${where}: one character at most is the narrator`); + return errors; +} + +/** Every reason a project's characters document is refused (empty: it is fine). */ +export function validateProjectCharacters(doc, where = "characters.json") { + if (!isObj(doc)) return [`${where} must be {"format": "${PROJECT_CHARACTERS_FORMAT}", "version": ${PROJECT_CHARACTERS_VERSION}, "characters": [...]}`]; + const errors = []; + if (doc.format !== PROJECT_CHARACTERS_FORMAT) errors.push(`${where}: format must be "${PROJECT_CHARACTERS_FORMAT}"`); + if (doc.version !== PROJECT_CHARACTERS_VERSION) errors.push(`${where}: version must be ${PROJECT_CHARACTERS_VERSION}`); + const list = doc.characters; + if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; + if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); + errors.push(...listErrors(list, where, "project")); + return errors; +} + +/** The cast's characters, as views (characterView) -- the invalid ones dropped, never fatal for a reader. */ export function charactersOf(cast) { - return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(c.voice)); + return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(characterVoice(c))).map(characterView); +} + +/** A project's own characters, as views -- one needs an id and a name; its presets are optional. */ +export function projectCharactersOf(doc) { + return (Array.isArray(doc?.characters) ? doc.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && str(c.name).trim()).map(characterView); +} + +/** + * The name a character goes by where umtool names it (the Voices page, `umtool cast project`, a recording's note): an + * anonymous one's `shown` name, never its own. The cut's on-screen card does NOT ask this yet: it shows the post's author. + */ +export const shownNameOf = (c) => (c?.anonymous === true ? str(c.shown).trim() || ANON_NAME_PATTERN.replace("{n}", "1") : str(c?.name)); + +/** The next unused shown name of ANON_NAME_PATTERN among a project's characters ("Anon 3"). */ +export function nextAnonName(characters) { + const used = new Set((Array.isArray(characters) ? characters : []).flatMap((c) => [str(c?.shown).trim().toLowerCase(), str(c?.name).trim().toLowerCase()])); + for (let n = 1; ; n += 1) { + const name = ANON_NAME_PATTERN.replace("{n}", String(n)); + if (!used.has(name.toLowerCase())) return name; + } } /** The character a handle belongs to, or null. */ @@ -141,6 +333,102 @@ export function castVoiceMap(cast) { return out; } +/** A character's SYNTHETIC preset as a layer's entry (post-say.mjs voiceSourceOf): `{ voice, speed?, character }`, or null when it has no stock voice. */ +export function presetEntryOf(c) { + const voice = characterVoice(c); + if (!isQualifiedVoice(voice)) return null; + const speed = characterSpeed(c); + return { voice, ...(speed !== null && speed !== 1 ? { speed } : {}), character: c.id }; +} + +/** The cast as a preset layer: `{ "<handle>": { voice, speed?, character } }` -- castVoiceMap with each character's speed and id. */ +export function castPresetMap(cast) { + const out = {}; + for (const c of charactersOf(cast)) for (const h of c.handles ?? []) out[h] = presetEntryOf(c); + return out; +} + +/** + * THE PROJECT's LAYER, pure: its voice map (`narration/voices.json`: a handle in it reads as a project character with + * only a synthetic voice; "*" kept) under its own characters (`narration/characters.json`: each handle of one that + * HAS a synthetic voice) -- `{ "<handle>": "<voice>" | { voice, speed?, character } }`, voiceSourceOf's `map`. + */ +export function projectPresetMap(doc, voiceMap = {}) { + const out = { ...(isObj(voiceMap) ? voiceMap : {}) }; + for (const c of projectCharactersOf(doc)) { + const entry = presetEntryOf(c); + if (entry) for (const h of c.handles ?? []) out[h] = entry; + } + return out; +} + +/** The character an id names, the project's own first: `{ character, layer: "project" | "cast" }`, or null. */ +export function characterById(id, { project = null, cast = null } = {}) { + const k = str(id).trim().toLowerCase(); + if (!k) return null; + const p = projectCharactersOf(project).find((c) => c.id === k); + if (p) return { character: p, layer: "project" }; + const c = charactersOf(cast).find((x) => x.id === k); + return c ? { character: c, layer: "cast" } : null; +} + +/** The character a post item names for its own read (`narration.character`): `{ id, character, layer }` (character null: no such one), or null. */ +export function itemCharacterOf(e, layers = {}) { + const id = str(e?.narration?.character).trim(); + if (!id) return null; + const hit = characterById(id, layers); + return { id, character: hit?.character ?? null, layer: hit?.layer ?? null }; +} + +/** The item's own character as a layer's entry (voiceSourceOf's `item`), or null: none named, no such one, or one with no synthetic voice. */ +export function itemPresetOf(e, layers = {}) { + const it = itemCharacterOf(e, layers); + return it?.character ? presetEntryOf(it.character) : null; +} + +/** Can a character be a RECORDED read's (it has a recorded preset, or a stock voice to convert to)? */ +const readsRecorded = (c) => !!c && (isObj(c.recorded) || isQualifiedVoice(characterVoice(c))); + +/** + * THE CHARACTER A RECORDING OF POST ITEM `e` IS MADE INTO, pure -- the chain a synthesized read asks, for the + * recorded preset: `as` (the command's --as: an id, a handle or a name, the project's own first), the item's own + * character, the project's character for its author, the cast's, the cast's narrator. `{ character, layer: "flag" | + * "item" | "project" | "cast" | "narrator" }`, or null: no one to convert to. `as` that names no one is `{ character: + * null, layer: "flag" }`. + */ +export function characterForRead(e, { project = null, cast = null, as = null } = {}) { + const pchars = projectCharactersOf(project); + if (str(as).trim()) { + const r = str(as).trim().replace(/^@+/, ""); + const low = r.toLowerCase(); + const p = pchars.find((c) => c.id === low) ?? (str(as).trim().startsWith("@") ? null : pchars.find((c) => str(c.name).toLowerCase() === low)) ?? pchars.find((c) => (c.handles ?? []).includes(handleKey(r)) && readsRecorded(c)); + return { character: p ?? findCharacter(cast, r), layer: "flag" }; + } + const it = itemCharacterOf(e, { project, cast }); + if (readsRecorded(it?.character)) return { character: it.character, layer: "item" }; + const h = handleKey(e?.handle); + const p = h ? pchars.find((c) => (c.handles ?? []).includes(h)) : null; + if (readsRecorded(p)) return { character: p, layer: "project" }; + const c = characterOf(cast, h); + if (c) return { character: c, layer: "cast" }; + const n = narratorOf(cast); + return n ? { character: n, layer: "narrator" } : null; +} + +/** + * A character's RECORDED preset, its defaults filled: `{ convert: convertTargetOf, enhance (true unless it says + * false), trim: { on (true unless false), padMs (null: the recorder's own room) }, direction (null: none) }`. + */ +export function recordedPresetOf(c) { + const rec = isObj(c?.recorded) ? c.recorded : {}; + return { + convert: convertTargetOf(c), + enhance: rec.enhance !== false, + trim: { on: rec.trim?.on !== false, padMs: typeof rec.trim?.padMs === "number" ? rec.trim.padMs : null }, + direction: typeof rec.direction === "string" && rec.direction.trim() ? rec.direction.trim() : null, + }; +} + /** * 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 @@ -171,9 +459,9 @@ export function convertPitchLabel(cv) { * entry says one, the pitch the read lands on (`pitch`, `semitones`; absent: the editor's default). */ export function convertTargetOf(c) { - const cv = c?.convert; + const cv = characterConvert(c); return { - engine: cv?.engine ?? null, voice: cv?.voice ?? c?.voice ?? null, + engine: cv?.engine ?? null, voice: cv?.voice ?? characterVoice(c) ?? null, ...(cv?.pitch !== undefined ? { pitch: cv.pitch } : {}), ...(cv?.semitones !== undefined ? { semitones: cv.semitones } : {}), }; } diff --git a/umtool/report-to-video/characters.test.mjs b/umtool/report-to-video/characters.test.mjs @@ -0,0 +1,204 @@ +// A character is a preset (cast.mjs): version 1's `voice` / `convert` read as the synthetic and recorded presets and +// back (a view), what each layer refuses, a project's own characters (anonymous ones, "Anon 1"), the chain one read +// asks -- the command's flags, the item's own character, the project's, the cast's, the narrator's, the default +// (post-say.mjs voiceSourceOf for a synthesized read; characterForRead for a recording) -- and the speed a part is +// asked at. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + ANON_NAME_PATTERN, CAST_VERSION, PROJECT_CHARACTERS_FILE, castPresetMap, castVoiceMap, characterById, characterForRead, characterView, charactersOf, convertTargetOf, emptyCast, foldWritten, + emptyProjectCharacters, itemCharacterOf, itemPresetOf, nextAnonName, projectCharactersOf, projectPresetMap, recordedPresetOf, shownNameOf, upgradeCast, upgradeCharacter, validateCast, + validateProjectCharacters, +} from "./cast.mjs"; +import { readSpeedOf, resolvePieceVoice, voiceSourceOf } from "./post-say.mjs"; + +// Version 1, as the files on disk are today. +const V1 = { + format: "umtool-cast", version: 1, + characters: [ + { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], voice: "kokoro:am_michael", speakers: ["Jeremy"], note: "the host" }, + { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], voice: "orpheus:tara", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, narrator: true }, + ], +}; + +test("migration on read: version 1's voice and convert are the synthetic and recorded presets, the version bumps", () => { + assert.deepEqual(validateCast(V1), [], "a version 1 file is fine as it is"); + const up = upgradeCast(V1); + assert.equal(up.version, CAST_VERSION); + assert.equal(CAST_VERSION, 2); + assert.deepEqual(up.characters[0], { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, speakers: ["Jeremy"], note: "the host" }); + assert.deepEqual(up.characters[1], { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], synthetic: { voice: "orpheus:tara" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true }); + assert.deepEqual(validateCast(up), []); + assert.deepEqual(upgradeCast(up), up, "upgrading version 2 changes nothing"); + assert.equal(V1.characters[0].synthetic, undefined, "a copy: the document read is not touched"); + // Not a cast, or a version nobody reads: left as it is, and refused in words. + assert.equal(upgradeCast({ format: "x", version: 1, characters: [] }).version, 1); + assert.match(validateCast({ ...V1, version: 3 })[0], /version must be 2 \(or 1, read as it\)/); +}); + +test("migration the other way: a reader is handed the presets AND the voice / convert they answer to", () => { + const v2 = upgradeCast(V1); + const views = charactersOf(v2); + assert.equal(views[0].voice, "kokoro:am_michael"); + assert.deepEqual(views[0].synthetic, { voice: "kokoro:am_michael" }); + assert.deepEqual(views[1].convert, { engine: "seed-vc", pitch: "contour", semitones: 2 }); + assert.deepEqual(charactersOf(V1), views, "either version reads the same"); + assert.deepEqual(castVoiceMap(V1), castVoiceMap(v2)); + assert.deepEqual(convertTargetOf(V1.characters[1]), convertTargetOf(v2.characters[1])); + assert.deepEqual(convertTargetOf(v2.characters[1]), { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 }); + // A view written back is the same character: its `voice` says what its preset says. + assert.deepEqual(upgradeCharacter(views[1]), v2.characters[1]); + assert.deepEqual(characterView(views[1]), views[1]); + // A VIEW WHOSE PRESET WAS CHANGED folds to the new value: the preset wins over its own (now stale) alias. + const edited = { ...views[0], synthetic: { ...views[0].synthetic, voice: "kokoro:am_onyx", speed: 1.1 } }; + assert.equal(edited.voice, "kokoro:am_michael", "the alias still says the old voice"); + assert.deepEqual(upgradeCharacter(edited).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 }); + assert.equal(characterView(edited).voice, "kokoro:am_onyx", "and a view of it says the new one"); + assert.deepEqual(upgradeCharacter({ ...views[1], recorded: { convert: { engine: "openvoice" } } }).recorded, { convert: { engine: "openvoice" } }); + // A WRITE's mutation that sets `c.voice` the old way, on the character it was handed (no alias): the newer word. + const handed = v2.characters[0]; + assert.deepEqual(foldWritten({ ...handed, voice: "kokoro:am_onyx" }, handed).synthetic, { voice: "kokoro:am_onyx" }); + assert.deepEqual(foldWritten({ ...v2.characters[1], convert: { engine: "openvoice" } }, v2.characters[1]).recorded, { convert: { engine: "openvoice" } }); + assert.deepEqual(foldWritten({ ...handed, synthetic: { voice: "kokoro:am_michael", speed: 1.1 }, voice: "kokoro:am_onyx" }, handed).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 }, "its speed kept"); + // …but a mutation that changed the preset itself wins over a stale alias beside it (a view written back). + assert.deepEqual(foldWritten(edited, handed).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 }); + assert.deepEqual(foldWritten({ id: "new", name: "New", handles: [], voice: "kokoro:am_echo" }, null).synthetic, { voice: "kokoro:am_echo" }, "a new character the old way"); + assert.equal(foldWritten(handed, handed).voice, undefined, "no alias is written"); +}); + +test("validation: the presets' shape, in the cast -- a voice and a convert target are STOCK voices, never a file", () => { + const one = (c) => validateCast({ ...emptyCast(), characters: [{ id: "q", name: "Q", handles: ["q"], synthetic: { voice: "kokoro:am_michael" }, ...c }] }); + assert.deepEqual(one({}), []); + assert.deepEqual(one({ synthetic: { voice: "kokoro:am_michael", speed: 1.15 }, recorded: { convert: { engine: "seed-vc", voice: "kokoro:am_onyx", pitch: "source" }, enhance: false, trim: { on: true, padMs: 120 }, direction: "higher, brisk, amused" } }), []); + assert.ok(one({ synthetic: undefined }).some((e) => /voice must be a STOCK voice with its engine/.test(e)), "a cast character has a stock voice"); + assert.ok(one({ synthetic: { voice: "/home/me/jeremy.wav" } }).some((e) => /STOCK voice with its engine/.test(e))); + assert.ok(one({ synthetic: { voice: "kokoro:am_michael", speed: 3 } }).some((e) => /synthetic\.speed must be a number from 0\.5 to 2/.test(e))); + assert.ok(one({ synthetic: { voice: "kokoro:am_michael", emotion: "on" } }).some((e) => /synthetic must be \{voice, speed\?\}/.test(e))); + assert.ok(one({ recorded: { convert: { voice: "me.wav" } } }).some((e) => /recorded\.convert\.voice must be a STOCK voice.*never a file or a recording/.test(e))); + assert.ok(one({ recorded: { convert: { voice: "seedvc:/home/me.wav" } } }).some((e) => /never a file or a recording/.test(e))); + assert.ok(one({ recorded: { convert: { engine: "openvoice", pitch: "contour" } } }).some((e) => /pitch "contour" is seed-vc's/.test(e))); + assert.ok(one({ recorded: { enhance: "yes" } }).some((e) => /recorded\.enhance must be true or false/.test(e))); + assert.ok(one({ recorded: { trim: { on: "off" } } }).some((e) => /recorded\.trim must be \{on\?: true \| false, padMs\?\}/.test(e))); + assert.ok(one({ recorded: { trim: { padMs: 5000 } } }).some((e) => /trim\.padMs must be a number of milliseconds from 0 to 2000/.test(e))); + assert.ok(one({ recorded: { direction: "two\nlines" } }).some((e) => /direction must be one line for the person reading/.test(e))); + assert.ok(one({ recorded: { direction: "x".repeat(201) } }).some((e) => /at most 200/.test(e))); + assert.ok(one({ recorded: { model: "x" } }).some((e) => /recorded must be \{convert\?, enhance\?, trim\?, direction\?\}/.test(e))); + assert.ok(one({ anonymous: true }).some((e) => /anonymous is not a character key/.test(e)), "an anonymous character is never the pool's"); +}); + +test("a project's own characters: the same shape, a preset optional, anonymous ones under a shown name, no narrator", () => { + const doc = (chars) => ({ ...emptyProjectCharacters(), characters: chars }); + assert.equal(PROJECT_CHARACTERS_FILE, "narration/characters.json"); + assert.deepEqual(validateProjectCharacters(doc([])), []); + const anon = { id: "anon-1", name: "the reply guy", anonymous: true, shown: "Anon 1", handles: ["replyguy99"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 } }; + const bare = { id: "witness", name: "A witness", handles: ["w1"] }; + assert.deepEqual(validateProjectCharacters(doc([anon, bare])), [], "a character with no preset leaves the voice to the layers under it"); + assert.match(validateProjectCharacters({ format: "umtool-cast", version: 2, characters: [] })[0], /format must be "umtool-project-characters"/); + assert.ok(validateProjectCharacters(doc([{ ...anon, narrator: true }])).some((e) => /narrator is not a character key/.test(e))); + assert.ok(validateProjectCharacters(doc([{ ...bare, shown: "Anon 2" }])).some((e) => /shown is an anonymous character's shown name/.test(e))); + assert.ok(validateProjectCharacters(doc([{ ...anon, anonymous: false }])).some((e) => /anonymous must be true or absent/.test(e))); + assert.ok(validateProjectCharacters(doc([anon, { ...bare, handles: ["replyguy99"] }])).some((e) => /@replyguy99 is anon-1's already/.test(e))); + assert.ok(validateProjectCharacters(doc([anon, { ...bare, id: "anon-1" }])).some((e) => /two characters are "anon-1"/.test(e))); + // Both layers refuse a convert target that is not a stock synthetic voice. + assert.ok(validateProjectCharacters(doc([{ ...bare, recorded: { convert: { voice: "narration/me.wav" } } }])).some((e) => /never a file or a recording/.test(e))); + assert.ok(validateProjectCharacters(doc([{ ...bare, synthetic: { voice: "operator" } }])).some((e) => /STOCK voice with its engine/.test(e))); + // The shown name: an anonymous character's, never its own; the next unused one of the pattern. + assert.equal(ANON_NAME_PATTERN, "Anon {n}"); + assert.equal(shownNameOf(anon), "Anon 1"); + assert.equal(shownNameOf(bare), "A witness"); + assert.equal(nextAnonName([]), "Anon 1"); + assert.equal(nextAnonName([anon, bare]), "Anon 2"); + assert.equal(nextAnonName([anon, { id: "b", name: "x", anonymous: true, shown: "anon 2" }]), "Anon 3", "any case"); + assert.deepEqual(projectCharactersOf(doc([anon, bare])).map((c) => [c.id, c.voice ?? null]), [["anon-1", "kokoro:am_puck"], ["witness", null]]); +}); + +// The layers of one project: the cast (V1), the project's own characters, its voice map. +const cast = upgradeCast(V1); +const own = { + ...emptyProjectCharacters(), + characters: [ + { id: "anon-1", name: "the reply guy", anonymous: true, shown: "Anon 1", handles: ["replyguy99"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 }, recorded: { enhance: false, direction: "flat, tired" } }, + { id: "savvy-here", name: "Savvy, this video", handles: ["madamsavvy"], synthetic: { voice: "kokoro:af_bella", speed: 1.2 } }, + { id: "witness", name: "A witness", handles: ["thequartering"] }, + { id: "guest-star", name: "Guest star", handles: [], synthetic: { voice: "kokoro:bm_george", speed: 1.1 }, recorded: { convert: { voice: "kokoro:bm_lewis" }, trim: { on: false } } }, + ], +}; +const voiceMap = { madamsavvy: "leah", someone: "dan", "*": "zoe" }; + +test("the layers as voiceSourceOf takes them: the project's characters over its voice map, the cast with its speeds", () => { + const map = projectPresetMap(own, voiceMap); + assert.deepEqual(map, { + madamsavvy: { voice: "kokoro:af_bella", speed: 1.2, character: "savvy-here" }, someone: "dan", "*": "zoe", + replyguy99: { voice: "kokoro:am_puck", speed: 0.9, character: "anon-1" }, + }, "a character with a voice wins its handle; one with none (witness) leaves it; voices.json is kept for the rest"); + assert.deepEqual(projectPresetMap(null, voiceMap), voiceMap, "no characters.json: the voice map as it is"); + assert.deepEqual(castPresetMap(cast), { thequartering: { voice: "kokoro:am_michael", character: "thequartering" }, madamsavvy: { voice: "orpheus:tara", character: "savvy" } }); + assert.deepEqual(characterById("savvy", { project: own, cast })?.layer, "cast"); + assert.deepEqual(characterById("anon-1", { project: own, cast })?.layer, "project"); + assert.equal(characterById("nobody", { project: own, cast }), null); +}); + +test("the chain for a synthesized read, first hit wins: flags, the item's character, the project's, the cast's, the narrator's, the default", () => { + const e = { id: "p-1", handle: "MadamSavvy", narration: { character: "guest-star" } }; + const layers = { project: own, cast }; + const full = { map: projectPresetMap(own, voiceMap), cast: castPresetMap(cast), item: itemPresetOf(e, layers), self: e.handle, narrator: "zac", engine: "orpheus" }; + const her = { handle: "MadamSavvy", role: "post" }; + // 1. the command's flags. + assert.deepEqual(voiceSourceOf(her, { ...full, overrides: { madamsavvy: "leo" }, voice: "dan" }), { spec: "leo", from: "override" }); + assert.deepEqual(voiceSourceOf(her, { ...full, voice: "dan" }), { spec: "dan", from: "override" }); + // 2. the item's own character. + assert.deepEqual(voiceSourceOf(her, full), { spec: "kokoro:bm_george", from: "item", speed: 1.1, character: "guest-star" }); + assert.deepEqual(resolvePieceVoice(her, full), { engine: "kokoro", voice: "bm_george", from: "item", speed: 1.1, character: "guest-star" }); + // 3. the project's character for the handle -- over its own voice map, which is next. + assert.deepEqual(voiceSourceOf(her, { ...full, item: null }), { spec: "kokoro:af_bella", from: "project", speed: 1.2, character: "savvy-here" }); + assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: voiceMap }), { spec: "leah", from: "project" }, "voices.json alone: a project character with only a synthetic voice"); + // 4. the cast's. + assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: {} }), { spec: "orpheus:tara", from: "cast", character: "savvy" }); + // 5. the narrator's (the item's own author), 6. the map's "*", the default. + assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: {}, cast: {} }), { spec: "zac", from: "narrator" }); + assert.deepEqual(voiceSourceOf({ handle: "stranger", role: "parent:0" }, full), { spec: "zoe", from: "project" }); + assert.deepEqual(voiceSourceOf({ handle: "stranger", role: "parent:0" }, { ...full, map: {} }), { spec: "leo", from: "default" }); + // The item's character is its OWN words' -- another author's piece of the same read asks its own layers. + assert.deepEqual(voiceSourceOf({ handle: "replyguy99", role: "parent:0" }, full), { spec: "kokoro:am_puck", from: "project", speed: 0.9, character: "anon-1" }); + assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "quoted" }, full), { spec: "kokoro:am_michael", from: "cast", character: "thequartering" }, "a project character with no voice leaves it to the cast"); + // An item naming a character nobody has, or one with no voice: the layers under it. + assert.deepEqual(itemCharacterOf({ narration: { character: "ghost" } }, layers), { id: "ghost", character: null, layer: null }); + assert.equal(itemPresetOf({ narration: { character: "ghost" } }, layers), null); + assert.equal(itemPresetOf({ narration: { character: "witness" } }, layers), null); + assert.equal(itemPresetOf({ narration: {} }, layers), null); +}); + +test("the speed a part is asked at: the flag, the item's own, the preset's -- none for Orpheus, or at 1", () => { + assert.equal(readSpeedOf({ flag: 1.3, preset: 1.1, own: 0.9, engine: "kokoro" }), 1.3); + assert.equal(readSpeedOf({ preset: 1.1, own: 0.9, engine: "kokoro" }), 0.9, "set on the one item: it beats its character's"); + assert.equal(readSpeedOf({ preset: 1.1, engine: "kokoro" }), 1.1); + assert.equal(readSpeedOf({ own: 0.9, engine: "kokoro" }), 0.9); + assert.equal(readSpeedOf({ engine: "kokoro" }), null); + assert.equal(readSpeedOf({ flag: 1.3, engine: "orpheus" }), null, "Orpheus has no speed"); + assert.equal(readSpeedOf({ flag: 1, preset: 1.2, engine: "kokoro" }), null, "the flag wins, and 1 is no speed"); +}); + +test("the chain for a recording: --as, the item's character, the project's for the author, the cast's, the narrator", () => { + const layers = { project: own, cast }; + const e = { id: "p-1", handle: "MadamSavvy", narration: { character: "guest-star" } }; + assert.deepEqual([characterForRead(e, { ...layers, as: "anon-1" }).character.id, characterForRead(e, { ...layers, as: "anon-1" }).layer], ["anon-1", "flag"]); + assert.equal(characterForRead(e, { ...layers, as: "@replyguy99" }).character.id, "anon-1", "by a handle"); + assert.equal(characterForRead(e, { ...layers, as: "TheQuartering" }).character.id, "thequartering", "the cast's, when the project has none of that name"); + assert.deepEqual(characterForRead(e, { ...layers, as: "nobody" }), { character: null, layer: "flag" }); + assert.deepEqual([characterForRead(e, layers).character.id, characterForRead(e, layers).layer], ["guest-star", "item"]); + const plain = { id: "p-2", handle: "MadamSavvy" }; + assert.deepEqual([characterForRead(plain, layers).character.id, characterForRead(plain, layers).layer], ["savvy-here", "project"]); + assert.deepEqual([characterForRead(plain, { cast }).character.id, characterForRead(plain, { cast }).layer], ["savvy", "cast"]); + // A project character with neither a voice nor a recorded preset names someone: it is not what a recording is made into. + assert.deepEqual([characterForRead({ handle: "TheQuartering" }, layers).character.id, characterForRead({ handle: "TheQuartering" }, layers).layer], ["thequartering", "cast"]); + assert.deepEqual([characterForRead({ handle: "stranger" }, layers).character.id, characterForRead({ handle: "stranger" }, layers).layer], ["savvy", "narrator"]); + assert.equal(characterForRead({ handle: "stranger" }, { cast: { ...cast, characters: [cast.characters[0]] } }), null, "nobody to convert to"); +}); + +test("a recorded preset, its defaults filled: cleaned and trimmed unless it says not, the convert target a stock voice", () => { + const [anon, , , star] = projectCharactersOf(own); + assert.deepEqual(recordedPresetOf(anon), { convert: { engine: null, voice: "kokoro:am_puck" }, enhance: false, trim: { on: true, padMs: null }, direction: "flat, tired" }); + assert.deepEqual(recordedPresetOf(star), { convert: { engine: null, voice: "kokoro:bm_lewis" }, enhance: true, trim: { on: false, padMs: null }, direction: null }); + assert.deepEqual(recordedPresetOf(charactersOf(cast)[1]), { convert: { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 }, enhance: true, trim: { on: true, padMs: null }, direction: null }); + assert.deepEqual(recordedPresetOf({ id: "x", name: "X", recorded: { trim: { padMs: 120 } } }).trim, { on: true, padMs: 120 }); +}); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -190,13 +190,15 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", // `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on. // `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim. 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"]); +// `character`: the character THIS item's own read is made with (cast.mjs: the project's own, else the cast's) -- absent: by its author's handle. +const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "character", "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", "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). -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo"]); +// `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1). +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -607,6 +609,7 @@ export function validatePostNarration(e) { if (n.script !== undefined) errors.push(...scriptErrors(n.script, `${w}.script`)); for (const k of ["excerpt", "approved", "off"]) if (n[k] !== undefined && typeof n[k] !== "boolean") errors.push(`${w}.${k} must be true or false`); if (n.speed !== undefined && !numIn(n.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${w}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); + if (n.character !== undefined && !(typeof n.character === "string" && /^[a-z0-9][a-z0-9_-]{0,47}$/.test(n.character))) errors.push(`${w}.character must be a character's id (umtool posts character)`); if (n.window !== undefined) { const x = n.window; if (!isObj(x) || !Number.isInteger(x.media) || !fin(x.start) || !fin(x.end) || x.end <= x.start || (x.score !== undefined && !fin(x.score)) || (x.reason !== undefined && typeof x.reason !== "string")) { @@ -702,6 +705,7 @@ export function validatePostNarration(e) { if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`); if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`); if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); + if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs @@ -40,9 +40,10 @@ // "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS for // the engine). The map is the project's OVERRIDE LAYER over THE CAST // (cast.mjs: the characters that recur across projects, each with its voice): -// the read's own override, the map, the cast, the narrator's (the item's own -// author), the map's "*", the default -- voiceForPiece, the one function every -// read goes through. +// the read's own override, the item's own character, the map (and the +// project's own characters: cast.mjs projectPresetMap), the cast, the +// narrator's (the item's own author), the map's "*", the default -- +// voiceSourceOf, the one function every read goes through. // // PURE and dependency-free. @@ -259,27 +260,49 @@ export function voiceRefOf(spec, engine = null) { /** `{engine, voice}` as `engine:voice` (bare when there is no engine). */ export const voiceSpecOf = (r) => (r?.engine ? `${r.engine}:${r.voice}` : str(r?.voice)); +/** A layer's entry as `{ voice, speed?, character? }`: a voice as written ("tara"), or a character's preset; null when it names no voice. */ +function entryOf(v) { + if (typeof v === "string") return v ? { voice: v } : null; + return isObj(v) && typeof v.voice === "string" && v.voice ? v : null; +} +const hit = (entry, from) => ({ + spec: entry.voice, from, + ...(typeof entry.speed === "number" && Number.isFinite(entry.speed) ? { speed: entry.speed } : {}), + ...(typeof entry.character === "string" && entry.character ? { character: entry.character } : {}), +}); + /** - * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from }` -- `spec` as written - * (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "project" (the map), "cast" (the - * cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default". In order: - * the run's own `overrides` (`--voice-for`), the item's `voice` for its own post (`--voice`), the map's for the - * author, the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the - * narrator's. + * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from, speed?, character? }` -- + * `spec` as written (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "item" (the item's + * own character: `narration.character`), "project" (the project's character for the author, or its voice map), + * "cast" (the cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default"; + * `speed` the preset's (a character's `synthetic.speed`) and `character` its id, when the layer that answered is a + * character's. FIRST HIT WINS, in order: the run's own `overrides` (`--voice-for`), the item's `voice` for its own + * post (`--voice`), the item's own character for its author's words (`item`), the project's for the author (`map`), + * the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the narrator's. + * + * A layer's entry (`map[h]`, `cast[h]`, `item`) is a voice as written or a character's synthetic preset + * `{ voice, speed?, character }` (cast.mjs presetEntryOf, projectPresetMap, castPresetMap). * * @param {{ handle?: string | null, role: string }} piece - * @param {{ map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, + * @param {{ map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, * self?: string | null, voice?: string | null, narrator: string, engine?: string }} o */ -export function voiceSourceOf(piece, { map = {}, cast = {}, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { +export function voiceSourceOf(piece, { map = {}, cast = {}, item = null, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { const h = handleKey(piece?.handle); const mine = piece?.role === "post" || (!!h && h === handleKey(self)); if (h && overrides[h]) return { spec: overrides[h], from: "override" }; if (piece?.role === "post" && voice) return { spec: voice, from: "override" }; - if (h && h !== VOICE_MAP_OTHER && map[h]) return { spec: map[h], from: "project" }; - if (h && h !== VOICE_MAP_OTHER && cast?.[h]) return { spec: cast[h], from: "cast" }; + const own = mine ? entryOf(item) : null; + if (own) return hit(own, "item"); + const named = h && h !== VOICE_MAP_OTHER; + const p = named ? entryOf(map?.[h]) : null; + if (p) return hit(p, "project"); + const c = named ? entryOf(cast?.[h]) : null; + if (c) return hit(c, "cast"); if (mine) return { spec: narrator, from: "narrator" }; - if (map[VOICE_MAP_OTHER]) return { spec: map[VOICE_MAP_OTHER], from: "project" }; + const other = entryOf(map?.[VOICE_MAP_OTHER]); + if (other) return { spec: other.voice, from: "project" }; return { spec: CONTEXT_VOICE_DEFAULTS[engine] ?? narrator, from: "default" }; } @@ -289,13 +312,24 @@ export function voiceForPiece(piece, o) { } /** - * The voice one piece is said in, RESOLVED: `{ engine, voice, from }` -- a bare voice in the read's `engine`, one that - * names its own engine in that one. The thread read and a single post's take both ask this. + * The voice one piece is said in, RESOLVED: `{ engine, voice, from, speed?, character? }` -- a bare voice in the + * read's `engine`, one that names its own engine in that one; `speed` and `character` as voiceSourceOf says them. + * The thread read and a single post's take both ask this. */ export function resolvePieceVoice(piece, o) { - const { spec, from } = voiceSourceOf(piece, o); + const { spec, from, speed, character } = voiceSourceOf(piece, o); const ref = voiceRefOf(spec, o.engine ?? "orpheus") ?? { engine: o.engine ?? "orpheus", voice: String(spec) }; - return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from }; + return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from, ...(speed !== undefined ? { speed } : {}), ...(character ? { character } : {}) }; +} + +/** + * THE SPEED A PART IS ASKED AT, pure: the command's (`flag`), else the item's own (`own`: `narration.speed`, for its + * own words -- set on that one item, it beats a character's), else the preset's (`preset`: the character's that + * answered for the voice) -- and none (null) for an engine that has no speed (Orpheus), or at 1. + */ +export function readSpeedOf({ flag = null, preset = null, own = null, engine = null } = {}) { + const v = [flag, own, preset].find((x) => typeof x === "number" && Number.isFinite(x)); + return v === undefined || engine === "orpheus" || v === 1 ? null : v; } /** `--voice-for h=v` words as `{ handle: voice }` (handles keyed as the map keys them); throws naming a bad one. */