commit 9f5cdbd16573bc534cfafcf37655c9d162ccded7
parent 208a2c4c9afde59f880d7d249913e23af9e3702d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 14:17:19 -0500
Merge lane/character-tuning: a character carries its Orpheus tuning (Orpheus re-tune S2) -- the synthetic preset gains a tuning (temperature, top_p, repeat penalty, takes), offered as three named starting points, Steady, Default and Lively, with the numbers always shown (`umtool cast set|add` and `cast project <p> set|add` take --tuning <name>, the number flags, --chunk-takes and --no-tuning); Try it in the preset reads a line this character says with those numbers, Another reading the next one, each try listed with its numbers and played at one loudness (`umtool cast try`), Keep these settings saves them; a character's tuning is the default of its Orpheus reads on post takes, thread reads and screen lines, a line's own numbers beat it one value at a time, and every take records whether its tuning was the character's or the line's; the bench's Tune starts from what a plain press would use now, says so, sends as the line's own only what was changed, has Keep this tuning for the character and a way back to the character's; reads made with other settings are counted and listed as stale (`umtool cast stale`), never re-made; a character with no tuning asks exactly what it asked before (pinned against main's code); cards have no character
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
36 files changed, 3058 insertions(+), 97 deletions(-)
diff --git a/common/lib/ttsTuning.d.mts b/common/lib/ttsTuning.d.mts
@@ -20,3 +20,11 @@ export function parseTtsTuning(
): { ok: true; value: TtsTuning } | { ok: false; error: string };
export function ttsReadingError(value: unknown, name?: string): string | null;
export function ttsReadingSeedBase(base: number, reading?: number): number;
+
+// A character's tuning (lane character-tuning): its fields and the named starting points.
+export type TtsTuningName = "steady" | "default" | "lively";
+export const CHARACTER_TUNING_FIELDS: readonly ("temperature" | "top_p" | "repeat_penalty" | "takes")[];
+export const ORPHEUS_TUNING_NAMED_FIELDS: readonly ("temperature" | "top_p" | "repeat_penalty")[];
+export const ORPHEUS_TUNING_NAMED: Readonly<Record<TtsTuningName, Readonly<{ temperature: number; top_p: number; repeat_penalty: number }>>>;
+export const ORPHEUS_TUNING_NAMES: readonly TtsTuningName[];
+export function ttsTuningNameOf(tuning: unknown): TtsTuningName | "custom";
diff --git a/common/lib/ttsTuning.mjs b/common/lib/ttsTuning.mjs
@@ -123,3 +123,45 @@ export function ttsReadingError(value, name = '"reading"') {
export function ttsReadingSeedBase(base, reading = 0) {
return base + TTS_READING_SEED_STEP * (reading || 0);
}
+
+// ---------------------------------------------------------------------------
+// A CHARACTER's TUNING (lane character-tuning, S2 of the re-tune plan): the fields a character's synthetic preset
+// may carry, and three NAMED STARTING POINTS the operator picks from by ear -- the numbers always shown under them.
+// The names cover the sampler only; `takes` is a field of its own.
+// ---------------------------------------------------------------------------
+
+/** The tuning fields a character's synthetic preset may carry (umtool cast set --temperature …). */
+export const CHARACTER_TUNING_FIELDS = Object.freeze(["temperature", "top_p", "repeat_penalty", "takes"]);
+
+/** The sampler fields a named starting point sets. */
+export const ORPHEUS_TUNING_NAMED_FIELDS = Object.freeze(["temperature", "top_p", "repeat_penalty"]);
+
+/**
+ * The named starting points: Steady (cooler and narrower -- steadier pitch and pace; the repeat penalty held, since a
+ * cooler sampler loops more readily), Default (ORPHEUS_SAMPLER), Lively (warmer and wider -- more varied intonation,
+ * a touch quicker; kept under 0.8, where words start to slur).
+ */
+export const ORPHEUS_TUNING_NAMED = Object.freeze({
+ steady: Object.freeze({ temperature: 0.4, top_p: 0.8, repeat_penalty: 1.2 }),
+ default: Object.freeze({ temperature: ORPHEUS_TUNING_DEFAULTS.temperature, top_p: ORPHEUS_TUNING_DEFAULTS.top_p, repeat_penalty: ORPHEUS_TUNING_DEFAULTS.repeat_penalty }),
+ lively: Object.freeze({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 }),
+});
+export const ORPHEUS_TUNING_NAMES = Object.freeze(Object.keys(ORPHEUS_TUNING_NAMED));
+
+/**
+ * The named starting point a tuning's sampler is ("steady" | "default" | "lively"), or "custom": its temperature,
+ * top_p and repeat_penalty (a missing one is the default) equal to one, and top_k and min_p the defaults. `takes` is
+ * not looked at.
+ */
+export function ttsTuningNameOf(tuning) {
+ const t = isObj(tuning) ? tuning : {};
+ const v = (k) => {
+ const q = quantizeTtsTuningValue(k, t[k]);
+ return typeof q === "number" && Number.isFinite(q) ? q : ORPHEUS_TUNING_DEFAULTS[k];
+ };
+ if (v("top_k") !== ORPHEUS_TUNING_DEFAULTS.top_k || v("min_p") !== ORPHEUS_TUNING_DEFAULTS.min_p) return "custom";
+ for (const name of ORPHEUS_TUNING_NAMES) {
+ if (ORPHEUS_TUNING_NAMED_FIELDS.every((k) => v(k) === ORPHEUS_TUNING_NAMED[name][k])) return name;
+ }
+ return "custom";
+}
diff --git a/common/lib/ttsTuning.test.ts b/common/lib/ttsTuning.test.ts
@@ -8,8 +8,11 @@ import assert from "node:assert/strict";
// range, at its edges and past them, refused in a sentence naming the field.
import {
+ CHARACTER_TUNING_FIELDS,
ORPHEUS_DEFAULT_TAKES,
ORPHEUS_TUNING_DEFAULTS,
+ ORPHEUS_TUNING_NAMED,
+ ORPHEUS_TUNING_NAMES,
TTS_READING_MAX,
TTS_TUNING_FIELDS,
TTS_TUNING_RANGES,
@@ -18,6 +21,7 @@ import {
quantizeTtsTuningValue,
ttsReadingError,
ttsReadingSeedBase,
+ ttsTuningNameOf,
ttsTuningValueError,
} from "./ttsTuning.mjs";
@@ -115,3 +119,30 @@ test("the normaliser drops what equals its default, quantised; takes only agains
assert.deepEqual(Object.keys(normalizeTtsTuning({ top_k: 40, temperature: 0.7, seed: 4 })), ["temperature", "top_k"]);
assert.deepEqual(normalizeTtsTuning(null), {});
});
+
+test("a character's tuning: its fields, and the three named starting points (lane character-tuning)", () => {
+ assert.deepEqual([...CHARACTER_TUNING_FIELDS], ["temperature", "top_p", "repeat_penalty", "takes"]);
+ assert.deepEqual([...ORPHEUS_TUNING_NAMES], ["steady", "default", "lively"]);
+ // Default IS the sampler's defaults; every named value is in range and quantised.
+ assert.deepEqual({ ...ORPHEUS_TUNING_NAMED.default }, { temperature: ORPHEUS_TUNING_DEFAULTS.temperature, top_p: ORPHEUS_TUNING_DEFAULTS.top_p, repeat_penalty: ORPHEUS_TUNING_DEFAULTS.repeat_penalty });
+ assert.deepEqual(normalizeTtsTuning(ORPHEUS_TUNING_NAMED.default), {});
+ for (const name of ORPHEUS_TUNING_NAMES) {
+ const parsed = parseTtsTuning({ ...ORPHEUS_TUNING_NAMED[name] });
+ assert.deepEqual(parsed, { ok: true, value: { ...ORPHEUS_TUNING_NAMED[name] } }, name);
+ }
+ // Steady is cooler than Default, Lively warmer.
+ assert.ok(ORPHEUS_TUNING_NAMED.steady.temperature < ORPHEUS_TUNING_NAMED.default.temperature);
+ assert.ok(ORPHEUS_TUNING_NAMED.lively.temperature > ORPHEUS_TUNING_NAMED.default.temperature);
+});
+
+test("ttsTuningNameOf: a tuning's sampler named, else custom; takes is not looked at", () => {
+ assert.equal(ttsTuningNameOf(null), "default");
+ assert.equal(ttsTuningNameOf({}), "default");
+ assert.equal(ttsTuningNameOf({ takes: 5 }), "default");
+ assert.equal(ttsTuningNameOf({ ...ORPHEUS_TUNING_NAMED.lively }), "lively");
+ assert.equal(ttsTuningNameOf({ ...ORPHEUS_TUNING_NAMED.steady, takes: 2 }), "steady");
+ assert.equal(ttsTuningNameOf({ temperature: 0.4, top_p: 0.8 }), "steady", "a missing field is its default (repeat_penalty 1.2)");
+ assert.equal(ttsTuningNameOf({ ...ORPHEUS_TUNING_NAMED.lively, temperature: 0.8 }), "custom");
+ assert.equal(ttsTuningNameOf({ top_k: 40 }), "custom");
+ assert.equal(ttsTuningNameOf({ temperature: 0.7500000001, top_p: 0.92, repeat_penalty: 1.25 }), "lively", "quantised first");
+});
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -32,6 +32,32 @@
- `pnpm ops get cookies [fresh]` gives the same rows as JSON.
- The dashboard's cookie banners, /settings' X and archive sections and /review's X run console link to it. The
alert sentences and job log lines now say "on /cookies" where they said "on /settings".
+- **umtool: a character carries an Orpheus tuning, tried and kept from its preset on the Voices page.** The synthetic
+ preset gains `tuning` (temperature, top_p, repeat penalty, takes), the default of every Orpheus read the character
+ answers for; a read's own tuning beats it, and a character without one reads exactly as before.
+ - Three named starting points fill the numbers: **Steady** (0.4 / 0.8 / 1.2), **Default** (the sampler's own) and
+ **Lively** (0.75 / 0.92 / 1.25). The numbers are always shown and editable ("custom").
+ - **Read it** reads a line this character says in the project (or any typed line) as a job through the editor's tts;
+ **Another reading** reads it again at the next reading. The tries are listed at one loudness with their numbers
+ and reading. They are scratch: no take, nothing in the draft.
+ - **Keep these settings** runs `umtool cast set` (or `cast project <p> set`): `--tuning steady|default|lively`,
+ `--temperature`, `--top-p`, `--repeat-penalty`, `--chunk-takes`, `--no-tuning`. `--json` says every value the reads
+ are asked with, the editor's takes when the character names none.
+ - The reads made with other settings than the character's tuning now are counted and listed on the preset and the
+ characters table, and by `umtool cast stale <p> [<character>]`. They are never re-made by themselves.
+ - `umtool cast try <p> <character>` is the Read it twin (`--reading N`, `--another`, `--list`, `--clear`,
+ `--scope cast|project`).
+ - Every Orpheus read the character's preset answers for asks its tuning: a post's take (the CLI and the bench's Read
+ again), a thread read's pieces and its screen lines. A line's own numbers (flags, the bench's Tune) beat it field
+ by field. The take, and each thread part, records where its tuning came from: `tuningAsked` `"preset"` (the
+ character's: stale when that changes) or `true` (its own). A character with no tuning asks, keys and records
+ exactly as before (pinned against main).
+ - On the bench, the Tune starts from what a plain press reads now: the character's tuning, or the line's own when
+ its last read was its own. A press asks as the line's own only what differs from the character's, so a plain Read
+ again of a character's line asks the character's tuning as it is then, and Defaults asks the defaults as the
+ line's own. **Keep this tuning for <character>** keeps the numbers as the character's (the cast's, or this video's
+ own) and says what that leaves made with other settings. `cast reread` of a take whose tuning was the character's
+ asks the character's tuning as it is then.
- **An Orpheus line can be read again differently: the tts op takes a `tuning` and a `reading`.** `pnpm ops tts`
(`POST /api/ops/tts`) takes `tuning` (any of temperature 0.1–1.5, top_p 0.05–1, top_k 0–200, min_p 0–0.5,
repeat_penalty 1–2, takes 1–6) and `reading` (0–99,999; reading r reads with seed base 1234 + 9973 × r). A value out
diff --git a/plans/orpheus-retune.md b/plans/orpheus-retune.md
@@ -1,8 +1,8 @@
# Orpheus re-tune and re-run, by the operator alone
Status: **planned 15 Nov 2026; S1 done (merged 2dff0a631, shipped 16 Nov 2026); S3 done (`lane/line-rerun`,
-merged 17 Nov 2026; S3b, re-read one sentence, is a follow-up after S4); S2 in progress
-(`lane/character-tuning`).** Written to be picked up cold (after a usage reset). S4 is not started.
+merged 17 Nov 2026; S3b, re-read one sentence, is a follow-up after S4); S2 done (`lane/character-tuning`,
+merged 17 Nov 2026).** Written to be picked up cold (after a usage reset). S4 is not started.
## The ask (operator, 15 Nov 2026)
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -22,7 +22,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 { recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
+import { tuningAskOf } from "umtool-report-to-video/post-say";
+import { characterById, recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs";
import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
import { getJob, runningJob, startJob as startUmtoolJob, type Job } from "@/lib/jobs";
@@ -93,6 +94,10 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// screens, else `posts narrate <p> <item> --take --thread` asked as the
// playing read was -- every synthesized piece's next reading, unpicked
// GET ?project&id&screenJob=<job> either job: its state, its result, and -- ended -- the entry as it is
+// GET ?project&id&reads=all the CHARACTER whose synthetic preset reads each piece of the item now
+// (the playing read's overrides kept), and its tuning: {pieces: {<role>:
+// {character: {id, name, layer: "cast" | "project"} | null, tuning}}} --
+// a Tune's baseline and its "Keep for <character>" (lane character-tuning)
// GET ?project&id&pending=1 the post's read being made or made and not kept: {jobId, file,
// script, note} -- the bench follows `?job` with them to land its take
@@ -138,6 +143,31 @@ export async function GET(request: Request) {
}
return Response.json({ ok: true, prompts }, { headers: noStore });
}
+ if (id && q.get("reads") !== null) {
+ // THE CHARACTER EACH PIECE OF THIS ITEM's READ IS MADE WITH NOW, and its tuning (lane character-tuning): the plan a
+ // read would make (postThreadRead.mjs, a dry run -- the playing thread read's own options and voice overrides
+ // kept, so a piece its read gives another voice on purpose has no character), each synthesized piece's
+ // `{ character: {id, name, layer} | null, tuning }` -- `tuning` the character's (null: the defaults). One call per
+ // item: the bench's panels share it.
+ const e = postsOf(m).find((x) => x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ const L = await readLayers(r.project.dir).catch(() => null);
+ const takes = (e.narration?.takes ?? []) as Array<{ read?: Record<string, unknown> }>;
+ const pick = Number.isInteger(e.narration?.pick) ? Number(e.narration?.pick) : 0;
+ const rd = (takes[pick]?.read?.kind === "thread" ? takes[pick].read : null) as { parents?: string; skip?: string[]; quoted?: boolean; linked?: boolean; seen?: boolean; voiceFor?: Record<string, string>; voice?: string; screens?: boolean } | null;
+ const { threadTake } = await import("@/lib/report/postThreadRead.mjs");
+ const plan = await threadTake(r.project, e, {
+ manifest: m, dryRun: true, parents: rd?.parents ?? "0", skip: rd?.skip ?? [], quoted: rd?.quoted !== false, linked: rd?.linked !== false, readSeen: rd?.seen === true,
+ overrides: rd?.voiceFor ?? {}, voice: rd?.voice ?? null, screens: rd?.screens !== false,
+ }).then((x: { plan?: { pieces?: Array<{ role: string; character?: string; take?: unknown; tuning?: Record<string, number>; tuningAsked?: unknown }> } }) => x.plan ?? null, () => null);
+ const pieces: Record<string, { character: { id: string; name: string; layer: string } | null; tuning: Record<string, number> | null }> = {};
+ for (const pc of plan?.pieces ?? []) {
+ if (pc.take || pieces[pc.role]) continue;
+ const hit = pc.character && L ? characterById(pc.character, { project: L.project, cast: L.cast }) : null;
+ pieces[pc.role] = { character: hit ? { id: hit.character.id, name: shownNameOf(hit.character), layer: hit.layer } : null, tuning: hit && pc.tuningAsked === "preset" && pc.tuning ? pc.tuning : null };
+ }
+ return Response.json({ pieces }, { headers: noStore });
+ }
if (id && q.get("pending") !== null) {
// THE READ OF THIS POST BEING MADE, or made and not yet kept (review 2, finding 2): its marker's job, file and
// words -- a bench that lost it follows the same `?job` GET to land its take. `{ pending: null }` when there is none.
@@ -232,10 +262,12 @@ export async function GET(request: Request) {
const { slurs, lexicon } = spoken;
// What the POST asked (its speed and where it came from), kept beside the file until the take is made.
const askFile = `${abs}.ask.json`;
- const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset"; keepPick?: boolean } | null;
+ const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset"; keepPick?: boolean; tuningAsked?: true | "preset" } | null;
await rm(askFile, { force: true });
const take = {
...(typeof ask?.speed === "number" ? { speed: ask.speed } : {}), ...(ask?.speedAsked !== undefined ? { speedAsked: ask.speedAsked } : {}),
+ // Where its tuning came from (lane character-tuning): its line's own, or its character's.
+ ...(ask?.tuningAsked === true || ask?.tuningAsked === "preset" ? { tuningAsked: ask.tuningAsked } : {}),
// What it said, when an anonymous handle made that differ from the script (post-anon.mjs; the lint reads it).
...(spoken.anonymised ? { said: spoken.text } : {}),
...(slurs ? { slurs } : {}),
@@ -417,9 +449,14 @@ async function postHere(request: Request) {
// Its speed and where it came from, for the take the GET makes when the job is done (a sidecar, removed then).
// A re-read (`keepPick`, the bench's Read again) joins the list unpicked: said here too.
const keepPick = body.keepPick === true;
+ // Its tuning: the line's own (the Tune), else -- Orpheus only -- its character's (the synthetic preset's that
+ // answered for the voice: lane character-tuning); a character with no tuning asks as it always did.
+ // Field by field, as makeTake and every thread piece: the line's own values over the character's (tuningAskOf).
+ const ta = tuningAskOf({ own: tuned?.ok ? tuned.value : null, preset: (said as { tuning?: Record<string, number> }).tuning ?? null, engine });
+ const tuning = ta.tuning;
+ const tuningAsked = ta.asked;
askFile = `${out}.ask.json`;
- if (speed || keepPick) await writeFile(`${out}.ask.json`, JSON.stringify({ ...(speed ? { speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" } : {}), ...(keepPick ? { keepPick: true } : {}) }));
- const tuning = tuned?.ok && Object.keys(tuned.value).length ? tuned.value : null;
+ if (speed || keepPick || tuningAsked) await writeFile(`${out}.ask.json`, JSON.stringify({ ...(speed ? { speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" } : {}), ...(keepPick ? { keepPick: true } : {}), ...(tuningAsked ? { tuningAsked } : {}) }));
const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) });
// The marker names its job, its file and what the take keeps (its words, its note): a bench that lost the job
// finds it again here and lands its take (GET ?pending).
diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts
@@ -14,6 +14,7 @@ import { addStep } from "@/lib/queue/store.mjs";
import { kickQueue, queueDir } from "@/lib/queue/runner";
import { REPORTS_ROOT } from "@/lib/projects/core.mjs";
import { CAST_CONVERT_ENGINES, ENGINE_WEIGHT, charactersOf } from "umtool-report-to-video/cast";
+import { ORPHEUS_TUNING_DEFAULTS, ttsReadingError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
import { readPolicy } from "@/lib/articles/generation";
import { castAssignRouteOf } from "@/lib/report/castAssignModel.mjs";
@@ -28,6 +29,13 @@ export const dynamic = "force-dynamic";
// engines and their stock voices, the job running
// GET ?project&who&voices=a,b[&text|&item] an audition as it is kept (auditionView: nothing asked)
// GET ?job=<id>[&since&sinceEvent] that job
+// GET ?project&stale=<who> the reads made with other settings than its tuning now (cast stale)
+// GET ?project&tries=<who>[&scope=cast|project] a character's TRIES (umtool cast try <p> <who> --list): its tuning,
+// the line the page prefills, the tries kept (newest first)
+// POST { project, op: "try", who, scope?, text, tuning: { temperature, top_p, repeat_penalty, takes? }, reading | another: true }
+// a JOB: one line read in the character's voice (of that layer) with
+// that tuning and reading -- or the next after the highest kept
+// (umtool cast try: the editor's tts; scratch, no take, no draft)
// POST { project, op: "audition", who, voices: [..], text?, item? } a JOB: the editor's tts for the candidates not
// kept, then (with a reference) their closeness to the real voice
// through the heavy slot
@@ -36,7 +44,8 @@ export const dynamic = "force-dynamic";
// 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?, …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 /
+// convertSemitones?, enhance?, trim?, trimPad?, direction?, handles?, anonymous?, shown?,
+// tuning?: { temperature?, top_p?, repeat_penalty?, takes? } | null } 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
@@ -108,9 +117,45 @@ function presetArgs(b: Record<string, unknown>): string[] {
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");
+ if (has("tuning")) args.push(...tuningArgs(b.tuning));
return args;
}
+/** The tuning fields a character keeps, and the CLI flag of each (castCli.mjs CHARACTER_TUNING_FLAGS). */
+const TUNING_FIELD_FLAGS: Record<string, string> = { temperature: "--temperature", top_p: "--top-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" };
+
+/**
+ * A tuning as the CLI's flags, EXACTLY these numbers: each field given, the others `default` (off); null, "" or "none"
+ * is --no-tuning. A field a character does not keep (top_k, min_p) is refused unless it is Orpheus's default.
+ */
+function tuningArgs(t: unknown): string[] {
+ if (t === null || t === "" || t === "none") return ["--no-tuning"];
+ if (!t || typeof t !== "object" || Array.isArray(t)) throw new TuningAskError("a tuning is { temperature, top_p, repeat_penalty, takes }");
+ const o = t as Record<string, unknown>;
+ for (const k of Object.keys(o)) {
+ if (k in TUNING_FIELD_FLAGS) {
+ const v = o[k];
+ if (v !== undefined && v !== null && v !== "" && !(typeof v === "number" && Number.isFinite(v))) throw new TuningAskError(`tuning.${k} is a number (got ${JSON.stringify(v)})`);
+ continue;
+ }
+ const dflt = (ORPHEUS_TUNING_DEFAULTS as Record<string, number>)[k];
+ if (dflt !== undefined && (o[k] === null || o[k] === undefined || Number(o[k]) === dflt)) continue;
+ throw new TuningAskError(`a character keeps temperature, top_p, repeat penalty and takes (not ${k})`);
+ }
+ const args: string[] = [];
+ for (const [k, flag] of Object.entries(TUNING_FIELD_FLAGS)) {
+ const v = o[k];
+ args.push(flag, v === undefined || v === null || v === "" ? "default" : String(v));
+ }
+ return args;
+}
+class TuningAskError extends Error {}
+
+/** A character as an argv word: its id, or an @handle -- never a flag. */
+const whoOk = (v: string) => /^[a-z0-9][a-z0-9_-]{0,47}$/.test(v) || /^@[a-z0-9_.-]{1,64}$/i.test(v);
+/** The layer a try's character is looked up in: "cast", "project", or none (this video's own first). */
+const scopeArgs = (v: unknown): string[] => (v === "cast" || v === "project" ? ["--scope", v] : []);
+
/** 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");
@@ -119,7 +164,7 @@ function queueLockScript() {
const mine = (project: string) => {
const r = runningJob();
- return r && r.project === project && (r.kind.startsWith("cast-audition ") || r.kind.startsWith("cast-recording ") || r.kind.startsWith("cast-assign ")) ? jobView(r) : null;
+ return r && r.project === project && (r.kind.startsWith("cast-audition ") || r.kind.startsWith("cast-recording ") || r.kind.startsWith("cast-assign ") || r.kind.startsWith("cast-try ")) ? jobView(r) : null;
};
export async function GET(request: Request) {
@@ -133,7 +178,20 @@ export async function GET(request: Request) {
const project = await projectRef(String(url.searchParams.get("project") ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
const who = url.searchParams.get("who");
+ const tries = url.searchParams.get("tries");
try {
+ // The reads a character's tuning leaves stale (umtool cast stale <p> <who>): the bench's Keep for <character> says them.
+ const staleOf = url.searchParams.get("stale");
+ if (staleOf) {
+ if (!whoOk(staleOf)) return Response.json({ error: "a character's id, or @handle" }, { status: 400 });
+ const r = await cli(["stale", project.id, staleOf]);
+ return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ }
+ if (tries) {
+ if (!whoOk(tries)) return Response.json({ error: "a character's id, or @handle" }, { status: 400 });
+ const r = await cli(["try", project.id, tries, ...scopeArgs(url.searchParams.get("scope")), "--list"]);
+ return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ }
if (who) {
const castRead = await castForProject(project.dir);
const voices = String(url.searchParams.get("voices") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, AUDITION_MAX);
@@ -198,6 +256,32 @@ export async function POST(request: Request) {
const job = startJob(plan.kind, plan.steps, { project: project.id });
return Response.json({ ok: true, job: jobView(job), audition: view }, { headers });
}
+ if (op === "try") {
+ // ONE LINE read in the character's voice with a tuning and a reading: the CLI's own command as a job (scratch).
+ const who = s("who");
+ const text = s("text");
+ if (!who || !whoOk(who)) return Response.json({ error: "a try is of a character: its id, or @handle" }, { status: 400 });
+ if (!text) return Response.json({ error: "type the line to read" }, { status: 400 });
+ // Another reading: the CLI counts the next one from what it keeps (the line as it is said, not as typed).
+ const another = b.another === true;
+ const reading = another || b.reading === undefined || b.reading === null || b.reading === "" ? 0 : b.reading;
+ const readingError = ttsReadingError(reading);
+ if (readingError) return Response.json({ error: readingError }, { status: 400 });
+ let tuning: string[];
+ try {
+ tuning = b.tuning === undefined ? [] : tuningArgs(b.tuning).filter((a) => a !== "--no-tuning");
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+ // With no tuning given, the try reads with the character's own; "none" reads with the defaults.
+ if (b.tuning === null || b.tuning === "none") tuning = ["--tuning", "default", "--chunk-takes", "default"];
+ const running = runningJob();
+ if (running) return Response.json({ error: `another job is running (${running.kind}): Read it is open again when it ends`, busy: true, running: jobView(running) }, { status: 409 });
+ const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+ const argv = [process.execPath, cliPath, "cast", "try", project.id, who, ...scopeArgs(b.scope), "--text", text, ...tuning, ...(another ? ["--another"] : ["--reading", String(reading)]), "--progress", "ndjson"];
+ const job = startJob(`cast-try ${project.id}`, [{ label: `${who}: the line read (the editor's tts), ${another ? "another reading" : `reading ${reading}`}`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, ndjson: true, timeoutMs: 45 * 60 * 1000 }], { project: project.id });
+ return Response.json({ ok: true, job: jobView(job) }, { headers });
+ }
if (op === "use") {
const scope = s("scope") === "cast" ? "cast" : "project";
const r = await cli(["use", project.id, s("who"), s("voice"), ...(scope === "cast" ? ["--everywhere"] : [])]);
@@ -248,7 +332,14 @@ export async function POST(request: Request) {
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)]));
+ let args: string[];
+ try {
+ args = presetArgs(b);
+ } catch (e) {
+ if (e instanceof TuningAskError) return Response.json({ error: e.message }, { status: 400 });
+ throw e;
+ }
+ return answer(await cli([...head, ...args]));
}
if (op === "character-rm") {
if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 });
diff --git a/umtool/components/projects/CharacterPresets.tsx b/umtool/components/projects/CharacterPresets.tsx
@@ -3,13 +3,15 @@
import { useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+import { CharacterTuning, type StaleRead, type TuningFields } from "./CharacterTuning";
// ---------------------------------------------------------------------------
// 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
+// PresetEditor one character's two presets: SYNTHETIC (the stock voice, its speed, its Orpheus tuning and a
+// line to try it on: CharacterTuning.tsx) 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
@@ -19,7 +21,7 @@ import { cn } from "@/lib/utils";
// ---------------------------------------------------------------------------
export type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number };
-export type Synthetic = { voice?: string; speed?: number };
+export type Synthetic = { voice?: string; speed?: number; tuning?: TuningFields };
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;
@@ -116,11 +118,16 @@ const formOf = (c: PresetCharacter): Form => ({
* 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, scope, engines, convertEngines, busy, post, onSaved, onClose, project = null, stale = [],
}: {
c: PresetCharacter; scope: "cast" | "project"; engines: Engine[]; convertEngines: string[]; busy: boolean; post: PostFn; onSaved: (what: string) => void; onClose: () => void;
+ /** The project the page is of: its tuning tried on this project's lines (none: no tuning row). */
+ project?: string | null;
+ /** The reads by this character made with other settings than its tuning now (cast.mjs tuningStale). */
+ stale?: StaleRead[];
}) {
- // (The panel keys this editor by the character as it is stored: another one opened, or this one saved, is a new form.)
+ // (The panel keys this editor by the character as it is stored: another one opened, or this one saved, is a new form.
+ // Its Orpheus tuning is left out of the key: Keep these settings must not throw away unsaved edits above it.)
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";
@@ -169,6 +176,9 @@ export function PresetEditor({
{f.voice.startsWith("orpheus:") && f.speed && <span className="text-[11px] text-doubt-text">Orpheus has no speed</span>}
</label>
</div>
+ {project && (c.synthetic?.voice ?? c.voice) && (
+ <CharacterTuning project={project} id={c.id} name={c.anonymous ? c.shown ?? c.name : c.name} voice={String(c.synthetic?.voice ?? c.voice)} scope={scope} busy={busy} post={post} onKept={onSaved} stale={stale} />
+ )}
<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">
diff --git a/umtool/components/projects/CharacterTuning.tsx b/umtool/components/projects/CharacterTuning.tsx
@@ -0,0 +1,330 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { postBenchHref } from "@/lib/hrefs";
+import { ORPHEUS_TUNING_NAMED, ORPHEUS_TUNING_NAMES, TTS_TUNING_RANGES, ttsTuningNameOf, type TtsTuningName } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+
+// ---------------------------------------------------------------------------
+// A CHARACTER's ORPHEUS TUNING, in its preset (lane character-tuning; components/projects/CharacterPresets.tsx; the
+// CLI is `umtool cast set <id> --tuning … --temperature …`, `umtool cast try <p> <id> …`, `umtool cast stale <p>`).
+// Works with the operator alone: every button a form and a job, every write the CLI's own command.
+//
+// the tuning Steady / Default / Lively fill the numbers, which are always shown and editable ("custom")
+// try it a line (its own in this project, or typed), Read it -> a job (the editor's tts) -> plays when
+// done; Another reading -> the same line and numbers, the next reading; the list of tries, each at
+// one loudness (-20 LUFS), with its numbers and reading; scratch (no take, nothing in the draft)
+// keep Keep these settings -> umtool cast set (the cast) / cast project <p> set (this video)
+// stale the reads by this character made with other settings than its tuning now (listed, never re-made)
+// ---------------------------------------------------------------------------
+
+export type TuningFields = { temperature?: number; top_p?: number; repeat_penalty?: number; takes?: number };
+export type StaleRead = { id: string; role: string; character: string; reading: number; made: Record<string, number>; want: Record<string, number> };
+type TuningView = { tuning: TuningFields | null; name: string; effective: Record<string, number>; takesFrom: "character" | "setting" };
+type TryRow = { key: string; character: string; layer?: string | null; voice: string; text: string; tuning: TuningFields; reading: number; rel: string; seconds: number | null; lufs: number | null; at: string };
+type Tries = { character: { id: string; name: string; layer: string | null; voice: string | null; tuning: TuningView }; line: { text: string; from: string }; settingTakes: number; tries: TryRow[] };
+type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; kind?: string; events?: { ev?: string; phase?: string; key?: string; reading?: number }[] };
+type PostFn = (body: Record<string, unknown>) => Promise<Record<string, unknown> | null>;
+
+const FIELDS = [
+ { k: "temperature", label: "temperature", step: 0.05 },
+ { k: "top_p", label: "top_p", step: 0.01 },
+ { k: "repeat_penalty", label: "repeat penalty", step: 0.05 },
+ { k: "takes", label: "takes", step: 1 },
+] as const;
+type Form = Record<(typeof FIELDS)[number]["k"], string>;
+const NAME_LABEL: Record<string, string> = { steady: "Steady", default: "Default", lively: "Lively", custom: "custom" };
+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 fileUrl = (project: string, rel: string, v?: string) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}${v ? `&v=${v}` : ""}`;
+
+const formOf = (t: TuningFields | null | undefined, eff?: Record<string, number>): Form => ({
+ temperature: String(t?.temperature ?? eff?.temperature ?? ORPHEUS_TUNING_NAMED.default.temperature),
+ top_p: String(t?.top_p ?? eff?.top_p ?? ORPHEUS_TUNING_NAMED.default.top_p),
+ repeat_penalty: String(t?.repeat_penalty ?? eff?.repeat_penalty ?? ORPHEUS_TUNING_NAMED.default.repeat_penalty),
+ takes: typeof t?.takes === "number" ? String(t.takes) : "",
+});
+/** The form's numbers, or the field that is out of its range. */
+function numbersOf(f: Form): { ok: true; t: TuningFields } | { ok: false; field: string } {
+ const t: TuningFields = {};
+ for (const { k } of FIELDS) {
+ const raw = f[k].trim();
+ if (!raw && k === "takes") continue;
+ const n = Number(raw);
+ const r = TTS_TUNING_RANGES[k];
+ if (!raw || !Number.isFinite(n) || n < r.min || n > r.max || (r.integer && !Number.isInteger(n))) return { ok: false, field: k };
+ t[k] = Math.round(n * 1000) / 1000;
+ }
+ return { ok: true, t };
+}
+/** The form's numbers the same as the tuning KEPT: the sampler's three (unsaid: the default) and takes as stored (none: none). */
+const sameAsStored = (a: TuningFields, stored: TuningFields) =>
+ (["temperature", "top_p", "repeat_penalty"] as const).every((k) => (a[k] ?? ORPHEUS_TUNING_NAMED.default[k]) === (stored[k] ?? ORPHEUS_TUNING_NAMED.default[k])) && (a.takes ?? null) === (stored.takes ?? null);
+const numbersWords = (t: TuningFields, settingTakes: number) =>
+ `temperature ${t.temperature ?? ORPHEUS_TUNING_NAMED.default.temperature} · top_p ${t.top_p ?? ORPHEUS_TUNING_NAMED.default.top_p} · repeat penalty ${t.repeat_penalty ?? ORPHEUS_TUNING_NAMED.default.repeat_penalty} · takes ${t.takes ?? settingTakes}`;
+
+export function CharacterTuning({
+ project, id, name, voice, scope, busy, post, onKept, stale,
+}: {
+ project: string; id: string; name: string; voice: string; scope: "cast" | "project"; busy: boolean; post: PostFn; onKept: (what: string) => void; stale: StaleRead[];
+}) {
+ const orpheus = voice.startsWith("orpheus:");
+ const [data, setData] = useState<Tries | null>(null);
+ const [form, setForm] = useState<Form | null>(null);
+ const [text, setText] = useState<string | null>(null);
+ const [job, setJob] = useState<JobPoll | null>(null);
+ const [blocked, setBlocked] = useState<string | null>(null);
+ const [renderWait, setRenderWait] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [status, setStatus] = useState<string | null>(null);
+ const [notes, setNotes] = useState<string[]>([]);
+ // A press sent and not answered yet: a second press waits (no second job, no second follow).
+ const [pending, setPending] = useState(false);
+ // The same, read synchronously: two clicks inside one render both see `pending` false.
+ const pendingRef = useRef(false);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const audios = useRef<Map<string, HTMLAudioElement>>(new Map());
+ // The try a finished job made: it plays when the list is read again, and only it.
+ const playKey = useRef<string | null>(null);
+
+ const load = useCallback(async () => {
+ let r: Response;
+ let j: (Tries & { error?: string }) | null = null;
+ try {
+ r = await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&tries=${encodeURIComponent(id)}&scope=${scope}`, { cache: "no-store" });
+ j = (await r.json().catch(() => null)) as (Tries & { error?: string }) | null;
+ } catch (e) {
+ playKey.current = null;
+ setError(`the tries could not be read: ${e instanceof Error ? e.message : String(e)}`);
+ return;
+ }
+ if (!r.ok || !j) {
+ playKey.current = null;
+ setError(j?.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setData(j);
+ setForm((f) => f ?? formOf(j.character.tuning.tuning, j.character.tuning.effective));
+ setText((t) => t ?? j.line.text);
+ }, [project, id, scope]);
+ useEffect(() => {
+ void load();
+ return () => {
+ if (timer.current) clearTimeout(timer.current);
+ };
+ }, [load]);
+ // A new try plays when its job ends: the row of the key that job made, once the list is read again.
+ useEffect(() => {
+ const k = playKey.current;
+ if (!k) return;
+ playKey.current = null;
+ void audios.current.get(k)?.play().catch(() => undefined);
+ }, [data]);
+
+ const settingTakes = data?.settingTakes ?? 3;
+ const nums = form ? numbersOf(form) : null;
+ const tuning = nums?.ok ? nums.t : null;
+ const named = tuning ? ttsTuningNameOf(tuning) : "custom";
+ const kept = data?.character.tuning.tuning ?? {};
+ const isKept = !!tuning && sameAsStored(tuning, kept);
+ const running = job?.state === "running";
+ const off = busy || running || pending || !!blocked || !orpheus;
+
+ /**
+ * Follow a job to its end; while it runs, say when render mode holds the machine. An answer that is not the job's
+ * (umtool restarted: no such job) or a poll that cannot reach umtool ends it as failed -- never as made.
+ */
+ const follow = useCallback((jobId: string, then: (j: JobPoll) => void) => {
+ if (timer.current) clearTimeout(timer.current);
+ const tick = async () => {
+ let j: JobPoll;
+ try {
+ const r = await fetch(`/api/report/voices?job=${encodeURIComponent(jobId)}`, { cache: "no-store" });
+ const body = (await r.json().catch(() => null)) as (JobPoll & { error?: string }) | null;
+ j = r.ok && body && typeof body.state === "string" ? body : { id: jobId, state: "failed", error: body?.error ?? `HTTP ${r.status}` };
+ } catch (e) {
+ j = { id: jobId, state: "failed", error: `the job could not be followed: ${e instanceof Error ? e.message : String(e)}` };
+ }
+ const rm = (await fetch("/api/render-mode", { cache: "no-store" }).then((x) => x.json()).catch(() => null)) as { held?: boolean; what?: string | null } | null;
+ setRenderWait(j.state === "running" && rm?.held ? `Waiting for the render (${rm.what ?? "render mode is on"}): the read is made when it lets go.` : null);
+ if (j.state === "running") {
+ timer.current = setTimeout(() => void tick(), 1000);
+ return;
+ }
+ then(j);
+ };
+ void tick();
+ }, []);
+
+ const read = async (ask: { reading: number } | { another: true }) => {
+ if (!tuning || !text?.trim() || pendingRef.current) return;
+ pendingRef.current = true;
+ setPending(true);
+ setError(null);
+ setStatus(null);
+ try {
+ let r: Response;
+ let j: { job?: JobPoll; error?: string; running?: JobPoll };
+ try {
+ r = await fetch("/api/report/voices", {
+ method: "POST", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, op: "try", who: id, scope, text: text.trim(), tuning: { ...tuning, takes: tuning.takes ?? null }, ...ask }),
+ });
+ j = (await r.json().catch(() => ({}))) as typeof j;
+ } catch (e) {
+ setError(`umtool could not be reached: ${e instanceof Error ? e.message : String(e)}`);
+ return;
+ }
+ if (r.status === 409 && j.running) {
+ // Another job holds umtool's runner: said here, the buttons open again when it ends.
+ setBlocked(`Another job is running (${j.running.kind ?? "a job"}): Read it is open again when it ends.`);
+ follow(j.running.id, () => setBlocked(null));
+ return;
+ }
+ if (!r.ok || !j.job) {
+ setError(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setJob(j.job);
+ follow(j.job.id, (done) => {
+ setJob(done);
+ const made = (done.events ?? []).find((ev) => ev?.ev === "cast-try" && ev.phase === "done" && typeof ev.key === "string");
+ if (done.state !== "done" || !made) setError(`the read failed: ${done.error ?? "see the job's log on /jobs"}`);
+ else {
+ playKey.current = made.key ?? null;
+ setStatus(`reading ${made.reading ?? 0} made`);
+ }
+ void load();
+ });
+ } finally {
+ pendingRef.current = false;
+ setPending(false);
+ }
+ };
+ const keep = async () => {
+ if (!tuning) return;
+ setNotes([]);
+ const j = (await post({ op: "character-set", scope, id, tuning: { ...tuning, takes: tuning.takes ?? null } })) as { notes?: string[]; tuning?: TuningView } | null;
+ if (j) {
+ onKept(`${name}: Orpheus tuning kept (${NAME_LABEL[named]}) ${scope === "cast" ? "in the cast (every project)" : "for this video only"}`);
+ // What the CLI said beside it (takes 3 not kept, a voice that ignores it), and the takes field as it is stored.
+ setNotes(Array.isArray(j.notes) ? j.notes : []);
+ const storedTakes = j.tuning?.tuning?.takes;
+ setForm((f) => (f ? { ...f, takes: typeof storedTakes === "number" ? String(storedTakes) : "" } : f));
+ void load();
+ }
+ };
+ const pick = (n: TtsTuningName) => setForm((f) => ({ ...(f ?? formOf(null)), temperature: String(ORPHEUS_TUNING_NAMED[n].temperature), top_p: String(ORPHEUS_TUNING_NAMED[n].top_p), repeat_penalty: String(ORPHEUS_TUNING_NAMED[n].repeat_penalty) }));
+ const staleIds = useMemo(() => [...new Set(stale.map((s) => s.id))], [stale]);
+
+ return (
+ <div className="mt-2" data-tuning={id} data-tuning-name={named} data-tuning-kept={isKept ? "yes" : "no"}>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <span className="text-muted">Orpheus tuning</span>
+ <span role="radiogroup" aria-label={`${name}'s Orpheus tuning: a starting point`} className="inline-flex gap-1">
+ {ORPHEUS_TUNING_NAMES.map((n) => {
+ const t = ORPHEUS_TUNING_NAMED[n];
+ return (
+ <button
+ key={n} type="button" role="radio" aria-checked={named === n} data-tuning-pick={n} disabled={!orpheus}
+ aria-label={`Orpheus tuning: ${NAME_LABEL[n]} (temperature ${t.temperature}, top_p ${t.top_p}, repeat penalty ${t.repeat_penalty})`}
+ onClick={() => pick(n)} className={buttonVariants({ variant: named === n ? "pressed" : "outline", size: "sm" })}
+ >
+ {NAME_LABEL[n]}
+ </button>
+ );
+ })}
+ </span>
+ {named === "custom" && <span className="rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-text-2" data-tuning-custom="">custom</span>}
+ {!orpheus && <span className="text-[11px] text-doubt-text" data-tuning-ignored="">{voice.split(":")[0] || "this voice"} ignores a tuning</span>}
+ </div>
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ {FIELDS.map(({ k, label, step }) => {
+ const r = TTS_TUNING_RANGES[k];
+ return (
+ <label key={k} className="inline-flex items-center gap-1.5" title={`${r.min}–${r.max}${k === "takes" ? `; empty: the editor's setting (${settingTakes})` : ""}`}>
+ <span className="text-muted">{label}</span>
+ <input
+ data-tuning-field={k} type="number" min={r.min} max={r.max} step={step} disabled={!orpheus || !form}
+ aria-label={`Orpheus tuning: ${label}`} placeholder={k === "takes" ? String(settingTakes) : undefined}
+ value={form?.[k] ?? ""} onChange={(e) => setForm((f) => ({ ...(f ?? formOf(null)), [k]: e.target.value }))}
+ aria-invalid={nums && !nums.ok && nums.field === k ? true : undefined}
+ className={cn(input, "w-16", nums && !nums.ok && nums.field === k && "border-reject-text")}
+ />
+ </label>
+ );
+ })}
+ <span className="text-[11px] text-muted" data-tuning-effective="">
+ {data ? (data.character.tuning.tuning ? `kept: ${NAME_LABEL[data.character.tuning.name] ?? data.character.tuning.name} · ${numbersWords(data.character.tuning.effective, settingTakes)}` : `kept: none (Default · takes ${settingTakes})`) : ""}
+ </span>
+ </div>
+
+ <div className="mt-2 flex flex-wrap items-start gap-1.5">
+ <textarea
+ data-tuning-text="" aria-label="the line to try" value={text ?? ""} onChange={(e) => setText(e.target.value)} rows={2} maxLength={400}
+ className={cn(input, "min-w-[18rem] flex-1")} disabled={!orpheus}
+ />
+ <button type="button" data-tuning-read="" aria-label="Read the line with these settings" disabled={off || !tuning || !text?.trim()} onClick={() => void read({ reading: 0 })} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Read it
+ </button>
+ <button type="button" data-tuning-another="" aria-label="Read the same line again, the next reading" disabled={off || !tuning || !text?.trim()} onClick={() => void read({ another: true })} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Another reading
+ </button>
+ <button type="button" data-tuning-keep="" aria-label={`Keep these settings for ${name} (${scope === "cast" ? "the cast" : "this video"})`} disabled={busy || running || pending || !tuning || isKept || !orpheus} onClick={() => void keep()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Keep these settings
+ </button>
+ </div>
+ {running && <p className="m-0 mt-1 text-[11.5px] text-text-2" data-tuning-running="">reading… (the editor's tts)</p>}
+ {renderWait && <p className="m-0 mt-1 text-[11.5px] text-doubt-text" data-tuning-render-wait="">{renderWait}</p>}
+ {blocked && <p className="m-0 mt-1 text-[11.5px] text-doubt-text" data-tuning-blocked="">{blocked}</p>}
+ {status && <p className="m-0 mt-1 text-[11.5px] text-text-2" data-tuning-status="">{status}</p>}
+ {notes.map((n) => (
+ <p key={n} className="m-0 mt-1 text-[11.5px] text-doubt-text" data-tuning-note="">
+ note: {n}
+ </p>
+ ))}
+ {error && <p role="alert" className="m-0 mt-1 text-[11.5px] text-reject-text" data-tuning-error="">{error}</p>}
+
+ {data && data.tries.length > 0 && (
+ <table className="mt-2 w-full border-collapse text-[11.5px]" data-tuning-tries={data.tries.length}>
+ <tbody>
+ {data.tries.map((t) => (
+ <tr key={t.key} data-tuning-try={t.reading} data-tuning-try-key={t.key} className="align-top">
+ <td className="border-t border-seam px-1.5 py-1 text-text-2">{t.text.length > 70 ? `${t.text.slice(0, 70)}…` : t.text}</td>
+ <td className="border-t border-seam px-1.5 py-1 font-mono text-[11px]" data-tuning-try-numbers="">
+ {NAME_LABEL[ttsTuningNameOf(t.tuning)] ?? "custom"} · {numbersWords(t.tuning ?? {}, settingTakes)}
+ </td>
+ <td className="border-t border-seam px-1.5 py-1 whitespace-nowrap">reading {t.reading}</td>
+ <td className="border-t border-seam px-1.5 py-1 w-[16rem]">
+ <audio ref={(a) => { if (a) audios.current.set(t.key, a); else audios.current.delete(t.key); }} controls preload="none" src={fileUrl(project, t.rel, t.key)} className="w-full" aria-label={`play reading ${t.reading}`} data-tuning-try-audio="" />
+ {t.lufs !== null && <span className="text-[10.5px] text-muted" title="every try is brought to one loudness, so they compare by ear, not by level">{t.lufs.toFixed(1)} LUFS</span>}
+ </td>
+ <td className="border-t border-seam px-1.5 py-1 whitespace-nowrap">
+ <button type="button" className="ink-link" data-tuning-try-use={t.key} aria-label={`Use reading ${t.reading}'s numbers`} onClick={() => { setForm(formOf(t.tuning)); setText(t.text); }}>
+ use these numbers
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+
+ <p className="m-0 mt-2 text-[11.5px]" data-tuning-stale={staleIds.length}>
+ {staleIds.length ? (
+ <span className="text-doubt-text">
+ {staleIds.length} read{staleIds.length === 1 ? "" : "s"} by this character {staleIds.length === 1 ? "was" : "were"} made with other settings:{" "}
+ {staleIds.map((x, i) => (
+ <span key={x}>
+ {i ? ", " : ""}
+ <a href={postBenchHref(project, x)} className="ink-link font-mono" data-tuning-stale-item={x}>{x}</a>
+ </span>
+ ))}
+ </span>
+ ) : (
+ <span className="text-muted">no read by this character was made with other settings</span>
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -17,6 +17,7 @@ import type { PostPlan } from "./review/PostItemPlayer";
import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
import PostAttachmentLane from "./PostAttachmentLane";
import ReadAgain, { madeWithText, playNow, useAutoPlay, type KeepForCharacter, type Tuning } from "./read/ReadAgain";
+import { useKeepForCharacter } from "./read/keepForCharacter";
import { LEGACY_EDIT_TEXT, legacyReadOf } from "umtool-report-to-video/post-item";
// ---------------------------------------------------------------------------
@@ -286,11 +287,12 @@ export default function PostNarrationPanel({
if (saved) await readAgain(script, tuning);
};
// How this text was last made (its last synthesized take's tuning, else the playing take's): Tune starts there.
- const madeWith = useMemo(() => {
+ const madeTake = useMemo(() => {
const synth = takes.filter((t) => takeSourceOf(t).kind === "tts" && t.read?.kind !== "thread" && t.tuning);
const same = synth.filter((t) => (t.script ?? "").replace(/\s+/g, " ").trim() === (n.script ?? "").replace(/\s+/g, " ").trim());
- return (same.at(-1) ?? (picked?.tuning ? picked : null) ?? synth.at(-1))?.tuning ?? null;
+ return (same.at(-1) ?? (picked?.tuning ? picked : null) ?? synth.at(-1)) ?? null;
}, [takes, n.script, picked]);
+ const madeWith = madeTake?.tuning ?? null;
const legacy = legacyReadOf(entry);
useEffect(() => {
if (!job || job.state !== "running") return;
@@ -357,8 +359,9 @@ export default function PostNarrationPanel({
// What a convert of THIS post defaults to: its author's character in the cast (else the narrator) -- the engine, the
// stock voice and the pitch every recording made that character's lands on (`umtool cast set <id> --convert-pitch …`).
const [castConvert, setCastConvert] = useState<{ name: string; engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null>(null);
- // The character this item's read is made with (the convert's answer): S2 keeps a Tune for it.
- const [character, setCharacter] = useState<{ id: string; name: string; layer?: string } | null>(null);
+ // The character whose SYNTHETIC preset reads his words now (lane character-tuning): a Tune is kept for it, and its
+ // tuning is where the Tune starts -- unless his last read was his own.
+ const readsAs = useKeepForCharacter(project, entry.id, "post", madeTake ? { tuning: madeTake.tuning ?? null, tuningAsked: (madeTake as { tuningAsked?: unknown }).tuningAsked } : null);
useEffect(() => {
let live = true;
setCastConvert(null);
@@ -366,7 +369,6 @@ export default function PostNarrationPanel({
.then((r) => (r.ok ? r.json() : null))
.then((j: { character?: { id?: string; name: string; layer?: string } | null; convert?: { engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null } | null) => {
if (live && j?.character && j.convert) setCastConvert({ name: j.character.name, ...j.convert });
- if (live && j?.character) setCharacter(j.character as { id: string; name: string; layer?: string });
})
.catch(() => {});
return () => {
@@ -819,8 +821,13 @@ export default function PostNarrationPanel({
onReadAgain={(t) => void press(() => readAgain(n.script ?? "", t))}
onReadEdited={(t) => void press(() => readEdited(t))}
madeWith={madeWith}
- character={character}
- keepForCharacter={keepForCharacter}
+ baseline={readsAs.baseline}
+ madeOwn={readsAs.madeOwn}
+ refreshBaseline={readsAs.refresh}
+ baselineError={readsAs.error}
+ onRetryBaseline={readsAs.retry}
+ character={readsAs.character ?? null}
+ keepForCharacter={keepForCharacter ?? readsAs.keepForCharacter}
autoplay={autoplay}
onAutoplay={setAutoplay}
/>
diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx
@@ -2,6 +2,8 @@
import { useEffect, useMemo, useRef, useState } from "react";
import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
+import { useKeepForCharacter } from "./read/keepForCharacter";
+import { threadTuneMadeOf } from "@/lib/report/tuneAsk.mjs";
import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread";
import { followKnobs } from "umtool-report-to-video/read-follow";
import { pickedTake } from "umtool-report-to-video/post-narration";
@@ -71,7 +73,11 @@ export default function PostThreadPanel({
};
// READ THE THREAD AGAIN (lane line-rerun): every synthesized piece's next reading, a new take unpicked, played as
// it lands -- `posts screen … read` / `posts narrate … --take --thread` as a umtool job (op thread-read).
- const playing = pickedTake(entry) as { read?: { kind?: string }; parts?: Array<{ reading?: number; tuning?: Tuning }> } | null;
+ const playing = pickedTake(entry) as { read?: { kind?: string }; parts?: Array<{ role?: string; take?: string; reading?: number; tuning?: Tuning; tuningAsked?: true | "preset" }> } | null;
+ // HIS piece (review 2 #4): the thread's Tune starts from how his words were last read and keeps for his character --
+ // never another piece's (a parent's, a screen speaker's).
+ const postPart = threadTuneMadeOf(playing?.parts) as { tuning: Tuning | null; tuningAsked?: unknown } | null;
+ const readsAs = useKeepForCharacter(project, entry.id, "post", postPart);
const [autoplay, setAutoplay] = useAutoPlay();
const [again, setAgain] = useState<{ state: string; waiting?: string | null; error?: string | null; said?: string | null } | null>(null);
const poll = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -169,7 +175,14 @@ export default function PostThreadPanel({
busy={again?.state === "running"}
waiting={again?.state === "running" ? again.waiting ?? null : null}
onReadAgain={(t) => void readThreadAgain(t)}
- madeWith={playing.parts?.find((p) => p.tuning)?.tuning ?? null}
+ madeWith={postPart?.tuning ?? null}
+ baseline={readsAs.baseline}
+ madeOwn={readsAs.madeOwn}
+ refreshBaseline={readsAs.refresh}
+ baselineError={readsAs.error}
+ onRetryBaseline={readsAs.retry}
+ character={readsAs.character}
+ keepForCharacter={readsAs.keepForCharacter}
error={again?.state === "failed" ? again.error ?? "failed" : null}
note={again?.said ?? null}
autoplay={autoplay}
diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useMic, ls } from "./useMic";
import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
+import { useKeepForCharacter } from "./read/keepForCharacter";
// ---------------------------------------------------------------------------
// A SCREEN LINE IN THE OPERATOR's VOICE, on the post bench's screens section (lib/report/screenLineRecord.mjs; the
@@ -175,7 +176,7 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str
}
follow({ id: j.job.id, what: "read", state: j.job.state });
};
- return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead, readLine, pickTake, landed, autoplay, setAutoplay, project };
+ return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead, readLine, pickTake, landed, autoplay, setAutoplay, project, id };
}
export type ScreenVoice = ReturnType<typeof useScreenVoice>;
@@ -184,7 +185,7 @@ export type ScreenVoice = ReturnType<typeof useScreenVoice>;
export type LineTakeOption = { id: string; label: string; current: boolean };
/** One synthesized reading of a line: the take it is in (index), its part's file, words, reading and tuning. */
-export type LineReading = { take: number; picked: boolean; file: string | null; text: string; reading: number; tuning: Tuning | null };
+export type LineReading = { take: number; picked: boolean; file: string | null; text: string; reading: number; tuning: Tuning | null; tuningAsked?: true | "preset" };
/** The readings of a line (`role`) in an item's takes: each take whose parts read it, synthesized. */
export function lineReadings(entry: Record<string, unknown>, role: string): LineReading[] {
@@ -192,13 +193,17 @@ export function lineReadings(entry: Record<string, unknown>, role: string): Line
const pick = Number.isInteger(n.pick) ? (n.pick as number) : 0;
return (n.takes ?? []).flatMap((t, i) => {
const p = (t.parts ?? []).find((x) => x.role === role && !(x as { take?: string }).take);
- return p ? [{ take: i, picked: i === pick, file: p.file ?? null, text: String(p.text ?? ""), reading: Number.isInteger(p.reading) ? (p.reading as number) : 0, tuning: p.tuning ?? null }] : [];
+ const asked = (p as { tuningAsked?: unknown } | undefined)?.tuningAsked;
+ return p ? [{ take: i, picked: i === pick, file: p.file ?? null, text: String(p.text ?? ""), reading: Number.isInteger(p.reading) ? (p.reading as number) : 0, tuning: p.tuning ?? null, ...(asked === true || asked === "preset" ? { tuningAsked: asked } : {}) }] : [];
});
}
/** ONE READ LINE's voice cell: Record / Stop / play back / Redo / Keep, and the take chosen for it. */
export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoose, readings = [], edited = false }: { role: string; n: number; voice: ScreenVoice; dirty: boolean; options: LineTakeOption[]; chosen: string | undefined; onChoose: (id: string | undefined) => void; readings?: LineReading[]; edited?: boolean }) {
const mine = voice.at === role && voice.phase === "recording";
+ // The character whose synthetic preset reads this line (its speaker's; lane character-tuning): a Tune is kept for it.
+ const playedLine = readings.find((x) => x.picked) ?? null;
+ const readsAs = useKeepForCharacter(voice.project, voice.id, role, playedLine ? { tuning: playedLine.tuning, tuningAsked: playedLine.tuningAsked } : null);
const t = voice.takes[role];
const busy = voice.job?.state === "running";
const other = voice.phase === "recording" && voice.at !== role;
@@ -243,7 +248,14 @@ export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoo
edited={!dirty && edited}
onReadAgain={(t) => void voice.readLine(role, t)}
onReadEdited={(t) => void voice.readLine(role, t)}
- madeWith={readings.find((x) => x.picked)?.tuning ?? null}
+ madeWith={playedLine?.tuning ?? null}
+ baseline={readsAs.baseline}
+ madeOwn={readsAs.madeOwn}
+ refreshBaseline={readsAs.refresh}
+ baselineError={readsAs.error}
+ onRetryBaseline={readsAs.retry}
+ character={readsAs.character}
+ keepForCharacter={readsAs.keepForCharacter}
autoplay={voice.autoplay}
onAutoplay={voice.setAutoplay}
/>
diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx
@@ -5,6 +5,7 @@ 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";
+import type { StaleRead } from "./CharacterTuning";
import { ProposedCharacters, type Proposal } from "./ProposedCharacters";
// ---------------------------------------------------------------------------
@@ -39,6 +40,8 @@ type Character = {
voice: Voice; contextVoice?: Voice; weight: string;
reads: { id: string; role: string; spec: string; kind: string }[];
drift: Drift[]; speaker: string | null; lines: { item: string; text: string; own: boolean }[];
+ // Its reads made with other settings than its Orpheus tuning now (stale: listed, never re-made).
+ stale?: StaleRead[];
};
// 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`).
@@ -57,6 +60,7 @@ type View = {
project: string; castFile: string | null; castError?: string; map: Record<string, string>;
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 }[];
+ tuningStale?: StaleRead[];
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;
@@ -340,6 +344,11 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
) : (
<span className="text-muted" data-voice-drift="0">none yet</span>
)}
+ {c.stale && c.stale.length > 0 && (
+ <div className="text-[11px] text-doubt-text" data-voice-stale={new Set(c.stale.map((d) => d.id)).size} title={c.stale.map((d) => `${d.id} ${d.role}: made with temperature ${d.made.temperature}, top_p ${d.made.top_p}, repeat penalty ${d.made.repeat_penalty}, takes ${d.made.takes}`).join("\n")}>
+ {new Set(c.stale.map((d) => d.id)).size} made with other settings
+ </div>
+ )}
</td>
<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>}
@@ -415,7 +424,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
{/* --- 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)} />
+ <PresetEditor key={`${preset.scope}:${preset.id}:${JSON.stringify([presetOf.name, presetOf.shown, { ...presetOf.synthetic, tuning: undefined }, presetOf.recorded])}`} c={presetOf} scope={preset.scope} engines={view.engines} convertEngines={view.convertEngines} busy={busy} post={post} onSaved={changed} onClose={() => setPreset(null)} project={project} stale={(view.tuningStale ?? []).filter((d) => d.character === preset.id)} />
{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">
diff --git a/umtool/components/projects/read/ReadAgain.tsx b/umtool/components/projects/read/ReadAgain.tsx
@@ -1,10 +1,11 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ls } from "../useMic";
-import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS, TTS_TUNING_FIELDS, TTS_TUNING_RANGES } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS, TTS_TUNING_FIELDS, TTS_TUNING_RANGES, ttsTuningNameOf } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { asksSampler, characterTuneOf, keepAskOf, madeOwnOf as tuneMadeOwnOf, sameBaseline, tuneAskOf, tuneStartOf, unknownBaselineAskOf } from "@/lib/report/tuneAsk.mjs";
// ---------------------------------------------------------------------------
// READ AGAIN (lane line-rerun, S3 of the Orpheus re-tune plan): one line's
@@ -26,6 +27,18 @@ export type Tuning = Partial<Record<"temperature" | "top_p" | "top_k" | "min_p"
/** S2's seam: keep these numbers for the character (its command: `umtool cast set <id> --temperature …`). */
export type KeepForCharacter = (tuning: Tuning) => Promise<string | null>;
+/**
+ * THE TUNE's BASELINE (lane character-tuning, review 2): what a plain press reads this piece with NOW -- its
+ * character's tuning (null: the defaults; no character: the defaults), unless its last read was the line's own
+ * (`madeOwn`): then those numbers, and they stay the line's own. A press sends as the line's own only what differs
+ * from the character's (all of it when the last read was the line's own); nothing changed on a character's line sends
+ * none of the sampler, so the character's is asked as it is then.
+ */
+export type TuneBaseline = { character: { name: string; tuning: Tuning | null } | null; madeOwn: boolean };
+/** Was a read the line's own? (lib/report/tuneAsk.mjs: the one rule.) */
+export const madeOwnOf = (tuning: Tuning | null | undefined, tuningAsked: unknown): boolean => tuneMadeOwnOf(tuning, tuningAsked);
+const NAMED: Record<string, string> = { steady: "Steady", default: "Default", lively: "Lively", custom: "custom" };
+
const AUTOPLAY_KEY = "umtool.reads.autoplay";
const LABEL: Record<string, string> = { temperature: "temperature", top_p: "top p", top_k: "top k", min_p: "min p", repeat_penalty: "repeat penalty", takes: "takes" };
// `takes` has no default here: empty is the editor's settings' own (tts.orpheus.takes), never a guessed 3.
@@ -81,7 +94,7 @@ export function madeWithText(t: { reading?: number | null; tuning?: Tuning | nul
}
export default function ReadAgain({
- what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay,
+ what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, baseline = undefined, madeOwn = false, refreshBaseline, baselineError = null, onRetryBaseline, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay,
}: {
/** What is read, in the controls' names: "" (the post), "line 2", "the thread", "the card". */
what?: string;
@@ -94,8 +107,21 @@ export default function ReadAgain({
onReadAgain: (tuning: Tuning | null) => void;
/** Absent: no edited text here (a thread read). */
onReadEdited?: (tuning: Tuning | null) => void;
- /** How the line was last made: the Tune numbers start from it. */
+ /** How the line was last made: the Tune numbers start from it (with no `baseline`, S3's rule). */
madeWith?: Tuning | null;
+ /**
+ * What a plain press reads it with now (lane character-tuning): the Tune starts there, and a press sends only what
+ * differs. null: not known yet -- the presses wait for it (a press before would ask the last read's numbers as the
+ * line's own); absent: S3's rule (the last read's numbers).
+ */
+ baseline?: TuneBaseline | null;
+ /** Its last read was the line's own (known before the baseline is: an untouched press while it is read). */
+ madeOwn?: boolean;
+ /** The baseline as it is NOW: a press asking a sampler value of its own checks it first (review 3 #1). */
+ refreshBaseline?: () => Promise<TuneBaseline | null>;
+ /** Why the baseline could not be read, and a retry: said in place. */
+ baselineError?: string | null;
+ onRetryBaseline?: () => void;
/** The character this line is read by, when known: S2 keeps a tuning for it. */
character?: { id: string; name: string; layer?: string } | null;
keepForCharacter?: KeepForCharacter;
@@ -106,11 +132,78 @@ export default function ReadAgain({
autoplay: boolean;
onAutoplay: (on: boolean) => void;
}) {
- const start = (): Record<string, string> => Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, madeWith?.[k as keyof Tuning] !== undefined ? String(madeWith[k as keyof Tuning]) : k in DEFAULTS ? String(DEFAULTS[k]) : ""]));
+ // The numbers a plain press would read with now: the line's own last numbers, else its character's, else the
+ // defaults; the takes the last read's (lib/report/tuneAsk.mjs).
+ // "Use <character>'s" (review 3 #3): the line back to its character -- the baseline as if its last read were the
+ // character's, until a new read lands.
+ const [fromCharacter, setFromCharacter] = useState(false);
+ const eff: TuneBaseline | null | undefined = baseline && fromCharacter ? (characterTuneOf(madeWith, baseline).baseline as TuneBaseline) : baseline;
+ const start = (): Record<string, string> => tuneStartOf({ madeWith, baseline: eff }) as Record<string, string>;
const [draft, setDraft] = useState<Record<string, string>>(start);
const [kept, setKept] = useState<string | null>(null);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- useEffect(() => setDraft(start()), [JSON.stringify(madeWith)]);
+ const [keeping, setKeeping] = useState(false);
+ const keepingRef = useRef(false);
+ // The takes field typed by the operator (a Keep pins takes only then: the draft's are the last read's recorded).
+ const [takesTyped, setTakesTyped] = useState(false);
+ // A field edited: the draft is the operator's -- a baseline read again does not replace it (it is said instead).
+ const [dirty, setDirty] = useState(false);
+ const [notice, setNotice] = useState<string | null>(null);
+ const pressing = useRef(false);
+ useEffect(() => setFromCharacter(false), [JSON.stringify(madeWith)]);
+ useEffect(() => {
+ if (dirty) return;
+ setDraft(start());
+ setTakesTyped(false);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [JSON.stringify(madeWith), JSON.stringify(eff)]);
+ const edit = (next: Record<string, string>) => {
+ setDraft(next);
+ setDirty(true);
+ setNotice(null);
+ };
+ /**
+ * What a press asks as the line's own: with no character, S3's rule (what differs from the defaults); with one,
+ * what differs from the character's tuning -- all of the sampler when the last read was the line's own -- and the
+ * takes when given (S3's rule).
+ */
+ const ask = (): Tuning | null => (eff?.character ? (tuneAskOf(draft, eff) as Tuning | null) : tuningAsked(draft));
+ // The baseline is not known (being read, or its read failed): an untouched press asks nothing of its own; an edited
+ // one waits for it (review 3 #2).
+ const loading = baseline === null;
+ const waits = loading && dirty;
+ const words = (b: TuneBaseline | null | undefined) => (!b ? "unknown" : b.madeOwn ? "this line's own" : b.character ? `${b.character.name}: ${NAMED[ttsTuningNameOf(b.character.tuning ?? {})] ?? "custom"}` : "defaults");
+ /**
+ * A PRESS (review 3 #1): with the baseline unknown, the untouched ask; else the ask -- and one that names a sampler
+ * value of its own is sent only if the baseline is still the one the draft was made against (read again first). If
+ * it changed under the draft, nothing is sent: the new baseline is said, and the next press reads what is shown.
+ */
+ const press = async (send: (t: Tuning | null) => void) => {
+ if (pressing.current) return;
+ if (loading) {
+ const u = unknownBaselineAskOf(draft, { madeOwn, dirty });
+ if (!u.waits) {
+ send(u.ask as Tuning | null);
+ setDirty(false);
+ }
+ return;
+ }
+ const a = ask();
+ if (baseline && refreshBaseline && asksSampler(a)) {
+ pressing.current = true;
+ const fresh = await refreshBaseline().catch(() => null);
+ pressing.current = false;
+ if (fresh && !sameBaseline({ ...fresh, madeOwn: baseline.madeOwn }, baseline)) {
+ setNotice(`it starts from ${words({ ...fresh, madeOwn: false })} now (it changed): press again to read with the numbers shown`);
+ return;
+ }
+ }
+ setNotice(null);
+ setDirty(false);
+ send(a);
+ };
+ /** What a Keep keeps: the sampler as it stands, top k and min p when not their defaults, the takes only when typed. */
+ const keepAsk = (): Tuning => keepAskOf(draft, { takesTyped }) as Tuning;
+ const baseWords = !eff ? null : words(eff);
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const bad = TTS_TUNING_FIELDS.some((k: string) => {
const r = (TTS_TUNING_RANGES as Record<string, { min: number; max: number; integer: boolean }>)[k];
@@ -121,11 +214,11 @@ export default function ReadAgain({
});
return (
<div className="flex flex-wrap items-center gap-1.5" data-read-again={what || "post"}>
- <button type="button" className={btn} disabled={busy || bad || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again` : "Read again"} data-read-again-button="">
+ <button type="button" className={btn} disabled={busy || bad || waits || !canReadAgain} onClick={() => void press(onReadAgain)} aria-label={what ? `Read ${what} again` : "Read again"} data-read-again-button="">
Read again
</button>
{onReadEdited && (
- <button type="button" className={btn} disabled={busy || bad || !edited} onClick={() => onReadEdited(tuningAsked(draft))} aria-label={what ? `Read ${what} as edited` : "Read the edited text"} data-read-edited-button="">
+ <button type="button" className={btn} disabled={busy || bad || waits || !edited} onClick={() => void press(onReadEdited)} aria-label={what ? `Read ${what} as edited` : "Read the edited text"} data-read-edited-button="">
Read edited text
</button>
)}
@@ -135,24 +228,67 @@ export default function ReadAgain({
</summary>
<div className="absolute z-10 mt-1 w-64 space-y-1 rounded border border-seam bg-[var(--color-panel)] p-2 shadow">
<span className="micro">this line only</span>
+ {baseWords && (
+ <span className="block text-text-2" data-read-tune-baseline="">
+ from {baseWords}
+ </span>
+ )}
{TTS_TUNING_FIELDS.map((k: string) => {
const r = (TTS_TUNING_RANGES as Record<string, { min: number; max: number; integer: boolean }>)[k];
return (
<label key={k} className="flex items-center justify-between gap-2">
<span>{LABEL[k]}</span>
- <input type="number" min={r.min} max={r.max} step={r.integer ? 1 : 0.01} value={draft[k]} placeholder={k === "takes" ? "settings" : undefined} onChange={(e) => setDraft({ ...draft, [k]: e.target.value })} className="w-20 rounded border border-seam bg-ground px-1 py-0.5" aria-label={`${LABEL[k]}, this line only`} data-read-tune-field={k} />
+ <input type="number" min={r.min} max={r.max} step={r.integer ? 1 : 0.01} value={draft[k]} placeholder={k === "takes" ? "settings" : undefined} onChange={(e) => {
+ edit({ ...draft, [k]: e.target.value });
+ if (k === "takes") setTakesTyped(true);
+ }} className="w-20 rounded border border-seam bg-ground px-1 py-0.5" aria-label={`${LABEL[k]}, this line only`} data-read-tune-field={k} />
</label>
);
})}
<div className="flex flex-wrap gap-1.5 pt-1">
- <button type="button" className={btn} disabled={busy || bad || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again with this tuning` : "Read again with this tuning"} data-read-tune-read="">
+ <button type="button" className={btn} disabled={busy || bad || waits || !canReadAgain} onClick={() => void press(onReadAgain)} aria-label={what ? `Read ${what} again with this tuning` : "Read again with this tuning"} data-read-tune-read="">
Read with these
</button>
- <button type="button" className={btn} onClick={() => setDraft(Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, k in DEFAULTS ? String(DEFAULTS[k]) : ""])))} aria-label="Tuning back to the defaults" data-read-tune-defaults="">
+ <button type="button" className={btn} onClick={() => edit(Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, k in DEFAULTS ? String(DEFAULTS[k]) : ""])))} aria-label="Tuning back to the defaults" data-read-tune-defaults="">
Defaults
</button>
+ {baseline?.character && baseline.madeOwn && !fromCharacter && (
+ <button
+ type="button"
+ className={btn}
+ onClick={() => {
+ // Back to the character: its numbers, and the next press asks nothing of the line's own ("preset").
+ setFromCharacter(true);
+ setDraft(characterTuneOf(madeWith, baseline).draft as Record<string, string>);
+ setDirty(false);
+ setNotice(null);
+ }}
+ aria-label={`Use ${baseline.character.name}'s tuning for this line`}
+ data-read-tune-character=""
+ >
+ Use {baseline.character.name}'s
+ </button>
+ )}
{keepForCharacter && character && (
- <button type="button" className={btn} disabled={bad} onClick={() => void keepForCharacter(tuningAsked(draft) ?? {}).then(setKept)} aria-label={`Keep this tuning for ${character.name}`} data-read-tune-keep="">
+ <button
+ type="button"
+ className={btn}
+ disabled={bad || keeping}
+ onClick={() => {
+ // One keep at a time: a second press while it is written is no second write.
+ if (keepingRef.current) return;
+ keepingRef.current = true;
+ setKeeping(true);
+ void keepForCharacter(keepAsk())
+ .then(setKept)
+ .finally(() => {
+ keepingRef.current = false;
+ setKeeping(false);
+ });
+ }}
+ aria-label={`Keep this tuning for ${character.name}`}
+ data-read-tune-keep=""
+ >
Keep for {character.name}
</button>
)}
@@ -165,6 +301,17 @@ export default function ReadAgain({
play when ready
</label>
{busy && <span className="text-text-2" data-read-busy="">{waiting ?? "reading…"}</span>}
+ {notice && <span className="text-[var(--color-warn,#c80)]" data-read-tune-notice="">{notice}</span>}
+ {baselineError && (
+ <span className="text-[var(--color-warn,#c80)]" data-read-baseline-error="">
+ the character's tuning could not be read ({baselineError}){waits ? ": an edited press waits for it" : ""}{" "}
+ {onRetryBaseline && (
+ <button type="button" className="ink-link" onClick={onRetryBaseline} aria-label="Read the character's tuning again" data-read-baseline-retry="">
+ retry
+ </button>
+ )}
+ </span>
+ )}
{!busy && note && <span className="text-text-2" data-read-note="">{note}</span>}
{error && <span className="text-[var(--color-blocking,#c33)]" data-read-error="">{error}</span>}
</div>
diff --git a/umtool/components/projects/read/keepForCharacter.ts b/umtool/components/projects/read/keepForCharacter.ts
@@ -0,0 +1,142 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import type { KeepForCharacter, TuneBaseline, Tuning } from "./ReadAgain";
+import { madeOwnOf } from "@/lib/report/tuneAsk.mjs";
+
+// ---------------------------------------------------------------------------
+// A PIECE's CHARACTER ON THE BENCH (lane character-tuning; ReadAgain.tsx's seam): who reads each piece of an item now
+// and with what tuning -- ONE call per item (GET /api/report/post-narration?reads=all, the playing read's voice
+// overrides kept), shared by every panel that mounts a Read again for it, read again after a Keep. It gives each
+// Tune its BASELINE (what a plain press reads the piece with now) and its "Keep for <character>": the numbers kept as
+// the character's through its command (`umtool cast set <id> …` for a cast character, `cast project <p> set <id> …`
+// for this video's own: /api/report/voices op "character-set"), then what that leaves stale (`umtool cast stale`).
+// ---------------------------------------------------------------------------
+
+export type ReadCharacter = { id: string; name: string; layer: "cast" | "project" };
+type Piece = { character: ReadCharacter | null; tuning: Tuning | null };
+type Pieces = Record<string, Piece>;
+
+type Slot = { data: Pieces | null; error: string | null; loading: Promise<Pieces | null> | null; subs: Set<() => void> };
+const store = new Map<string, Slot>();
+const keyOf = (project: string, id: string) => `${project}\u0000${id}`;
+
+function slot(project: string, id: string) {
+ const k = keyOf(project, id);
+ let s = store.get(k);
+ if (!s) {
+ s = { data: null, error: null, loading: null, subs: new Set() };
+ store.set(k, s);
+ }
+ return s;
+}
+
+/**
+ * Read an item's pieces again (on every mount, after a Keep, before a press that asks a sampler value of its own):
+ * every panel of it is told. The value kept meanwhile is the last one read; a read that fails leaves it as it was and
+ * says why (`error`) -- never "no characters". Returns the pieces as they are now (null: not known).
+ */
+export function refreshReads(project: string, id: string): Promise<Pieces | null> {
+ const s = slot(project, id);
+ if (s.loading) return s.loading;
+ const tell = () => {
+ for (const f of s.subs) f();
+ };
+ s.loading = (async () => {
+ type Answer = { pieces?: Record<string, { character?: ReadCharacter | null; tuning?: Tuning | null }>; error?: string };
+ let r = null as Response | null;
+ let j = null as Answer | null;
+ try {
+ r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&reads=all`, { cache: "no-store" });
+ j = (await r.json().catch(() => null)) as Answer | null;
+ } catch (e) {
+ s.error = `umtool could not be reached (${e instanceof Error ? e.message : String(e)})`;
+ }
+ if (r?.ok && j && typeof j.pieces === "object" && j.pieces) {
+ const pieces: Pieces = {};
+ for (const [role, p] of Object.entries(j.pieces)) {
+ const c = p?.character;
+ pieces[role] = { character: c && (c.layer === "cast" || c.layer === "project") ? c : null, tuning: p?.tuning ?? null };
+ }
+ s.data = pieces;
+ s.error = null;
+ } else if (r) s.error = j?.error ?? `HTTP ${r.status}`;
+ s.loading = null;
+ tell();
+ return s.data;
+ })();
+ tell();
+ return s.loading;
+}
+
+/** An item's pieces as the bench reads them (null until known), why they could not be read, and a retry. */
+export function useReads(project: string | null | undefined, id: string): { pieces: Pieces | null; error: string | null; retry: () => void } {
+ const [, setTick] = useState(0);
+ useEffect(() => {
+ if (!project) return;
+ const s = slot(project, id);
+ const f = () => setTick((n) => n + 1);
+ s.subs.add(f);
+ // Read again on EVERY mount (review 3 #1): a character changed on the Voices page or in another tab is seen; the
+ // value kept meanwhile is the last one read.
+ void refreshReads(project, id);
+ return () => {
+ s.subs.delete(f);
+ };
+ }, [project, id]);
+ const s = project ? store.get(keyOf(project, id)) : undefined;
+ return { pieces: s?.data ?? null, error: s?.error ?? null, retry: () => void (project ? refreshReads(project, id) : null) };
+}
+
+const words = (t: Tuning) => Object.entries(t).map(([k, v]) => `${k.replace("_", " ")} ${v}`).join(", ") || "the defaults";
+
+/**
+ * The seam's function for one character: keep `tuning` as its own -- exactly these numbers (a sampler value left out
+ * is its default; takes left out is the editor's setting) -- and say what was kept and what that leaves stale, this
+ * item first. A refusal is said in the command's words ("not kept: …").
+ */
+export function keepTuningFor(project: string, item: string, c: ReadCharacter): KeepForCharacter {
+ return async (t) => {
+ const tuning = { temperature: t.temperature ?? null, top_p: t.top_p ?? null, repeat_penalty: t.repeat_penalty ?? null, takes: t.takes ?? null, ...(t.top_k !== undefined ? { top_k: t.top_k } : {}), ...(t.min_p !== undefined ? { min_p: t.min_p } : {}) };
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-set", scope: c.layer, id: c.id, tuning }) }).catch(() => null);
+ const j = (await r?.json().catch(() => null)) as { error?: string; notes?: string[] } | null;
+ if (!r?.ok) return `not kept: ${j?.error ?? (r ? `HTTP ${r.status}` : "umtool could not be reached")}`;
+ // Every panel of this item reads its baseline again: the character's tuning is the new one now.
+ void refreshReads(project, item);
+ const where = c.layer === "cast" ? "the cast: every project" : "this video only";
+ const s = (await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&stale=${encodeURIComponent(c.id)}`, { cache: "no-store" }).then((x) => (x.ok ? x.json() : null)).catch(() => null)) as { count?: number; items?: string[] } | null;
+ const items = s?.items ?? [];
+ const stale = !s ? "" : items.length ? ` · ${items.includes(item) ? "this read was" : `${items.length} read${items.length === 1 ? " was" : "s were"}`} made with other settings${items.includes(item) && items.length > 1 ? ` (and ${items.length - 1} more: ${items.filter((x) => x !== item).join(", ")})` : items.includes(item) ? "" : `: ${items.join(", ")}`}` : " · every read of theirs is made with these";
+ return `kept for ${c.name} (${where}): ${words(t)}${(j?.notes ?? []).map((n) => ` · ${n}`).join("")}${stale}`;
+ };
+}
+
+/**
+ * One piece of one item (`role`): its character and keeper (none: no button), and its Tune's baseline from how it was
+ * last made (`made`: its recorded tuning and `tuningAsked`) -- null until the item's pieces are known.
+ */
+export function useKeepForCharacter(project: string | null | undefined, id: string, role = "post", made: { tuning?: Tuning | null; tuningAsked?: unknown } | null = null): {
+ character: ReadCharacter | null; keepForCharacter: KeepForCharacter | undefined; baseline: TuneBaseline | null; madeOwn: boolean;
+ error: string | null; retry: () => void; refresh: () => Promise<TuneBaseline | null>;
+} {
+ const { pieces, error, retry } = useReads(project, id);
+ const piece = pieces?.[role] ?? null;
+ const character = piece?.character ?? null;
+ const keepForCharacter = useMemo(() => (project && character ? keepTuningFor(project, id, character) : undefined), [project, id, character]);
+ const madeOwn = madeOwnOf(made?.tuning ?? null, made?.tuningAsked);
+ const tuningKey = JSON.stringify(piece?.tuning ?? null);
+ const baseline = useMemo<TuneBaseline | null>(
+ () => (pieces ? { character: character ? { name: character.name, tuning: piece?.tuning ?? null } : null, madeOwn } : null),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [pieces, character?.id, character?.name, tuningKey, madeOwn],
+ );
+ // The baseline as it is NOW (read again): a press that asks a sampler value of its own checks it first.
+ const refresh = async (): Promise<TuneBaseline | null> => {
+ if (!project) return null;
+ const p = await refreshReads(project, id);
+ if (!p) return null;
+ const c = p[role]?.character ?? null;
+ return { character: c ? { name: c.name, tuning: p[role]?.tuning ?? null } : null, madeOwn };
+ };
+ return { character, keepForCharacter, baseline, madeOwn, error, retry, refresh };
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -27,6 +27,8 @@ Inbox cannot disagree about what is wrong with one.
| `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; **anonymity belongs to the handle, project-wide**: every card, popup post, promise panel, chat replay and synthesized read draws or says them under the shown name; what cannot be fixed is refused or warned -- the coverage table in [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own). `--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 assign <project> [--model] [--dry-run] [--json]` · `--accept <id>` · `--accept-all` · `--reject <id>` · `--reject-all` · `--change <id> [--voice <engine:voice>] [--speed s] [--name "…"] [--direction "…"] [--anonymous [--shown "…"] \| --no-anonymous]` | **AUTO-ASSIGNMENT BY RULE** ([knobs.md](knobs.md#proposed-characters-cast-assign)): every post item's author gets a character -- the item's own, this video's, its voice map's or the cast's; an author with none a **PROPOSED** character of this video: an id from the handle, their name, a STOCK Kokoro voice -- the next, in one fixed rotation (a male and a female voice in turn), that this project does not use yet; a gender hint only from the profile's own stated pronouns when the capture carries them. Proposals are kept apart in `<project>/narration/characters.json` (`proposed`; the same writer, an undo point: `cast project <p> undo`) and are **applied to nothing** -- no item, no picked read -- until a person accepts. `--accept <id>` / `--accept-all`: this video's character, named (`narration.character`) on that author's items that name none -- no take made or changed (a picked read in another voice shows as drift); `--change <id>`: its voice (a stock one only), speed, name, direction or anonymity -- the row is then a person's, never re-sent to a model or overwritten; `--reject <id>` / `--reject-all`: dropped. An author an anonymous character covers is never proposed for and never sent to a model. A proposal whose author has a character now is dropped by the next run. `--dry-run` writes nothing. **`--model`** (on request only): the generation task `cast-assign`, routed by `settings.generation` like the other tasks, is asked per author (display name, bio, post text -- untrusted) for `{character, voice, speed, direction}`; each field is checked (a stock voice, a speed 0.5–2, one plain line, control characters stripped) and laid over the rule's row, which stays when the answer fails. Refused: **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) |
+| `cast set <id> [--tuning steady\|default\|lively] [--temperature t] [--top-p p] [--repeat-penalty r] [--chunk-takes n] [--no-tuning]` (and `cast add`, `cast project <p> add\|set`) | **A CHARACTER's ORPHEUS TUNING** ([knobs.md](knobs.md#a-characters-orpheus-tuning)): on its synthetic preset -- a named starting point (Steady, Default, Lively: temperature, top_p and repeat penalty together) and the numbers over it; `default` takes one off; a value equal to its default is not kept (takes 3 too: its reads then take the editor's `tts.orpheus.takes`). The default of every Orpheus read the character's preset answers for; a read's own tuning flags beat it; Kokoro and eSpeak NG ignore it. `--json` says `tuning` with every value its reads are asked with (`effective`). Out of range: **exit 1** |
+| `cast try <project> <character\|@handle> [--text "…" \| --item <id> \| --line <n>] [the tuning flags] [--reading N \| --another] [--scope cast\|project] [--list \| --clear] [--json] [--progress ndjson]` · `cast stale <project> [<character>] [--json]` | **TRY IT**: one line read in the character's own voice with a tuning (its own, or the flags over it) and a reading, through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` and kept in a short list (`tries.json`, the newest 12 per character; `--list`, `--clear`) -- SCRATCH: no take on any post, nothing in the draft. **STALE**: the picked Orpheus reads of a character made with other settings than its tuning now (a read whose line asked its own tuning, or a recorded one, never is; takes compared only when the character names them) -- listed, never re-made |
| `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> [--take T] [--clips a,b] [--pad S] [--json]` · `quote-check <project> [--take T] --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; the editor's work files go to `<project>/.quote-check/`, never under `out/` (a link onto a media drive the editor will not write in); `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them; `--take T` judges the take's own clips into `takes/T/quote-check.json`, which the take's render, `check --take T` and `window --take T --align` read with the project's rows (either current row refuses: `--take` only ever adds a refusal) ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) |
@@ -177,18 +179,20 @@ 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] [--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 add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--speed N] [--tuning steady\|default\|lively] [--temperature TEMPERATURE] [--top-p TOP-P] [--repeat-penalty REPEAT-PENALTY] [--chunk-takes CHUNK-TAKES] [--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] [--tuning steady\|default\|lively] [--temperature TEMPERATURE] [--top-p TOP-P] [--repeat-penalty REPEAT-PENALTY] [--chunk-takes CHUNK-TAKES] [--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] [--no-tuning] [--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: 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> add <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--anonymous] [--shown SHOWN] [--speed N] [--tuning steady\|default\|lively] [--temperature TEMPERATURE] [--top-p TOP-P] [--repeat-penalty REPEAT-PENALTY] [--chunk-takes CHUNK-TAKES] [--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] [--tuning steady\|default\|lively] [--temperature TEMPERATURE] [--top-p TOP-P] [--repeat-penalty REPEAT-PENALTY] [--chunk-takes CHUNK-TAKES] [--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] [--no-tuning] [--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 try <project> <character> [--text TEXT] [--item ITEM] [--line N] [--tuning steady\|default\|lively] [--temperature TEMPERATURE] [--top-p TOP-P] [--repeat-penalty REPEAT-PENALTY] [--chunk-takes CHUNK-TAKES] [--reading N] [--another] [--scope cast\|project] [--list] [--clear] [--no-hold]` | one line read in a character's voice with a tuning and a reading (scratch) | form · queued · *project* |
+| `cast stale <project> [<character>]` | the reads made with other settings than a character's tuning now (listed, never re-made) | form · *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* |
| `cast assign <project> [--model] [--dry-run] [--accept ACCEPT] [--accept-all] [--reject REJECT] [--reject-all] [--change CHANGE] [--voice VOICE] [--speed N] [--name NAME] [--direction DIRECTION] [--anonymous] [--shown SHOWN] [--no-anonymous]` | a proposed character for each author with none (by rule; --model on request); accept, change, reject | form · *project* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1832,6 +1832,73 @@ human-filtered voices". A character carries two, picked by how the read is made:
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.
+### A character's Orpheus tuning
+
+Lane character-tuning (S2 of `plans/orpheus-retune.md`): the synthetic preset may carry Orpheus's **tuning** --
+`synthetic.tuning` `{temperature?, top_p?, repeat_penalty?, takes?}`, the ranges of the editor's tts op
+(`common/lib/ttsTuning.mjs`). It is the default of every Orpheus read the character's preset answers for; a read's own
+tuning (`posts narrate … --take --temperature …`) beats it; Kokoro and eSpeak NG ignore it, as Orpheus ignores a speed.
+Cards have no character (a card's narration is spoken in its own voice or `render.narration`'s), so a character's
+tuning never reaches one; a card keeps its own `narration.tuning`.
+
+| Named starting point | temperature | top_p | repeat penalty | |
+|---|---|---|---|---|
+| **Steady** | 0.4 | 0.8 | 1.2 | cooler and narrower: steadier pitch and pace (the repeat penalty held: a cooler sampler loops more readily) |
+| **Default** | 0.55 | 0.85 | 1.2 | `ORPHEUS_SAMPLER`, the operator's pick by ear (12 Oct 2026) |
+| **Lively** | 0.75 | 0.92 | 1.25 | warmer and wider: more varied intonation, a touch quicker; kept under 0.8, where words slur |
+
+The names cover the sampler; `takes` (the takes a chunk gets) is a number of its own. A value equal to its default is
+not kept, and a tuning with nothing left is no key (takes 3 included: a character naming no takes reads with the
+editor's `tts.orpheus.takes`, and the preset and `--json` say that number, never one the read would not use).
+
+- **CLI:** `umtool cast set <id> --tuning steady|default|lively --temperature t --top-p p --repeat-penalty r
+ --chunk-takes n` (any of them; `default` takes one off; `--no-tuning`), the same on `cast add` and `cast project <p>
+ add|set`. `--json` says `tuning: {tuning, name, effective, takesFrom}`.
+- **Try it:** the preset's tuning row on the Voices page -- Steady / Default / Lively fill the numbers (always shown;
+ an edited one is "custom"); a line this character reads in the project, prefilled (its first own line of 8 words or
+ more, else its longest, else a stock line; any line may be typed); **Read it** is a job (`umtool cast try <p>
+ <character> --text … --temperature … --reading 0`: the editor's tts, on its `tts` lane); **Another reading** the same
+ line and numbers at the next reading. Each try is levelled to -20 LUFS (as an audition) in
+ `<p>/narration/auditions/` and listed (`tries.json`: text, numbers, reading, Play), the newest 12 per character; a try
+ that falls off takes its file with it (`cast try <p> <character> --clear` empties the list). A try is **scratch**: no
+ take on any post, nothing written to the draft. While render mode holds the machine, the read says it waits for the
+ render; another umtool job running is said in place and Read it opens again when it ends. The tries' writes hold a
+ lock (`tries.json.lock`), and a tuned try's files that no row names are swept once ten minutes old. `--scope
+ cast|project` looks the character up in one layer (the preset's: the cast and this video may both hold an id).
+- **Keep these settings** runs `cast set` (a cast character) or `cast project <p> set` (this video's own): one write,
+ an undo point.
+- **Where it is asked:** a post's take (`posts narrate --take`, the bench's Read again), every piece of a thread read
+ and each screen line, when the character's preset answers for its voice and the engine is Orpheus. A line's own
+ tuning (the flags, the bench's Tune, a `--for`/`--tuned` piece) beats it field by field (a line asking only its takes
+ keeps the character's sampler). The take records `tuningAsked`: `"preset"` (the character's) or `true` (its own); a
+ thread read's parts each record theirs, and its `read.tuned` keeps only the read's own, so a later read asks the
+ character's as it is then. `cast reread` of a take whose tuning was the character's passes its reading, not its old
+ tuning. A character with no tuning: every ask, key and record as before.
+- **The Tune on the bench starts from what a plain press reads now:** the piece's character's tuning (none: the
+ defaults), unless its last read was the line's own (`tuningAsked` true) -- then those numbers, and they stay its
+ own. A press asks as the line's own only what differs from the character's (`umtool/lib/report/tuneAsk.mjs`), so a
+ plain Read again of a character's line asks the character's tuning as it is then; Defaults on a Lively line asks the
+ three defaults as its own. The panel says where it starts ("The Teller: Lively", "defaults", "this line's own"), and
+ on a line whose last read was its own offers **Use <character>'s** (back to the character: "preset" again). A
+ thread read's Tune starts from his own piece. The baseline is read again on every mount and before a press that
+ asks a number of the line's own: one that changed under an edited draft is said and nothing is sent (the next press
+ reads what is shown); a baseline that cannot be read is said with a retry (an untouched press still goes: it asks
+ nothing of its own).
+- **Keep for the character, on the bench:** the Tune's **Keep this tuning for <character>** (a post's script, a thread
+ read, a screen line: the character whose preset reads that piece, one `GET /api/report/post-narration?reads=all`
+ per item, the playing read's voice overrides kept -- a piece given another voice on purpose has no button) runs the
+ same `cast set` / `cast project <p> set` (its takes only when typed), and says what was kept and what that leaves
+ made with other settings (`umtool cast stale`). Its panels read the item's pieces again after it.
+- A screen line whose speaker is written as a display name, not a handle, is read with its character's tuning but is
+ not listed stale (the stale list knows a screen line's character by its handle).
+- **Stale, never re-made:** a picked Orpheus read of the character is made with OTHER SETTINGS when its character's
+ preset answers for it now in the voice it was made in, its tuning was not asked by its own line (the take's
+ `tuningAsked` is not `true`; a take that says nothing but records a tuning off the defaults was asked so), and the
+ tuning it records (none: the defaults) differs from the character's -- the sampler's values, and `takes` only when the
+ character names them; the reading is never compared. A recorded or converted read never is. The preset and the
+ characters table say "N reads by this character were made with other settings" with the items; `umtool cast stale
+ <p> [<character>] [--json]` lists them. Re-reading them is a press elsewhere (the re-read queue), never automatic.
+
### 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
diff --git a/umtool/e2e/character-tuning.spec.ts b/umtool/e2e/character-tuning.spec.ts
@@ -0,0 +1,344 @@
+import { test, expect } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { createHash } from "node:crypto";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+import { TUNING_LINE } from "./fixtures/tuning-fixture.mjs";
+
+// ---------------------------------------------------------------------------
+// A CHARACTER's ORPHEUS TUNING, in its preset on the Voices page (lane character-tuning, S2 of
+// plans/orpheus-retune.md; components/projects/CharacterTuning.tsx, /api/report/voices, lib/report/castCli.mjs
+// `cast set|try|stale`). Fixture: e2e/fixtures/tuning-fixture.mjs -- this video's own "teller" (orpheus · tara) and
+// three reads of it (made with the defaults; with its line's own tuning; recorded). Every step a press:
+//
+// Lively fills the numbers; a number edited is "custom"
+// the line it reads in this project, prefilled; Read it (pressed twice: one job) -> a job (the stub editor's tts)
+// -> a try, reading 0; Another reading -> reading 1, then 2 -- counted from the line as it is said, not as typed
+// another job running: said in place, the buttons open again when it ends; a job umtool no longer knows: failed
+// Keep these settings (takes 3 typed) -> umtool cast project <p> set: the preset says the tuning kept, the note
+// beside it, the takes field as stored; an unsaved edit above it stays
+// the route refuses a flag as a character and a tuning value that is not a number
+// the read made with the defaults is now one made with other settings (listed, never re-made)
+// and nothing the cut shows changed: the manifest, every drawn card, no take
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const P = "reports/tuning-fixture";
+const DIR = path.join(FIXTURE, "reports", "tuning-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const CHARACTERS = path.join(DIR, "narration", "characters.json");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+
+type Tts = { route: string; text?: string; engine?: string; voice?: string; tuning?: Record<string, number>; reading?: number };
+const ttsAsks = () => (existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Tts[]) : []).filter((r) => r.route === "tts" && r.voice === "tara");
+const sha = (s: string) => createHash("sha1").update(s).digest("hex");
+const takeFiles = () => readdirSync(path.join(DIR, "narration", "posts"), { recursive: true }).map(String).sort();
+/** Every post item's card as drawn (the card page, plain and following) and its plan: what the cut shows. */
+const drawn = async () => {
+ const { postCardHtml, postItemPlan } = (await import("../report-to-video/post-item.mjs")) as unknown as {
+ postCardHtml: (e: unknown, o: Record<string, unknown>) => string; postItemPlan: (e: unknown, r?: unknown) => unknown;
+ };
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { render?: unknown; timeline: unknown[] };
+ return m.timeline.map((e) => sha(JSON.stringify([postCardHtml(e, { width: 1080, height: 1350 }), postCardHtml(e, { width: 1080, height: 1350, follow: true }), postItemPlan(e, m.render)])));
+};
+
+test.beforeAll(() => {
+ for (const f of [MANIFEST, CHARACTERS]) if (!existsSync(`${f}.pristine`)) copyFileSync(f, `${f}.pristine`);
+});
+const reset = () => {
+ for (const f of [MANIFEST, CHARACTERS]) copyFileSync(`${f}.pristine`, f);
+ rmSync(CHARACTERS.replace(/\.json$/, ".undo.json"), { force: true });
+ rmSync(path.join(DIR, "narration", "auditions"), { recursive: true, force: true });
+ // The takes a test made (the fixture's own are each post's take-1), and a read's marker.
+ for (const id of ["1", "2", "3"]) {
+ const dir = path.join(DIR, "narration", "posts", id);
+ if (!existsSync(dir)) continue;
+ for (const f of readdirSync(dir)) if (!f.startsWith("take-1.")) rmSync(path.join(dir, f), { recursive: true, force: true });
+ }
+};
+test.beforeEach(() => {
+ test.setTimeout(240_000);
+ reset();
+});
+test.afterAll(reset);
+
+test("a character's tuning: Lively, Read it, Another reading, Keep -- its stale read listed, nothing shown changed", async ({ page }) => {
+ const manifestBefore = readFileSync(MANIFEST, "utf8");
+ const cardsBefore = await drawn();
+ const takesBefore = takeFiles();
+ const asksBefore = ttsAsks().length;
+
+ await page.goto(urls.voicesHref(P));
+ const row = page.locator('[data-voices-character="teller"]');
+ await expect(row).toBeVisible({ timeout: 30_000 });
+ await row.locator('[data-voices-preset-open="teller"]').click();
+ const ed = page.locator('[data-preset-editor="teller"]');
+ const tune = ed.locator('[data-tuning="teller"]');
+ await expect(tune).toHaveAttribute("data-tuning-name", "default");
+ await expect(tune.locator("[data-tuning-stale]")).toHaveAttribute("data-tuning-stale", "0");
+ // The line it reads in this project, prefilled.
+ await expect(tune.locator("[data-tuning-text]")).toHaveValue(TUNING_LINE);
+
+ // Lively: the numbers shown under the name; one edited is custom; Lively again.
+ await tune.getByRole("radio", { name: /Orpheus tuning: Lively/ }).click();
+ await expect(tune).toHaveAttribute("data-tuning-name", "lively");
+ await expect(tune.locator('[data-tuning-field="temperature"]')).toHaveValue("0.75");
+ await expect(tune.locator('[data-tuning-field="top_p"]')).toHaveValue("0.92");
+ await expect(tune.locator('[data-tuning-field="repeat_penalty"]')).toHaveValue("1.25");
+ await tune.locator('[data-tuning-field="temperature"]').fill("0.8");
+ await expect(tune.locator("[data-tuning-custom]")).toBeVisible();
+ await tune.locator('[data-tuning-pick="lively"]').click();
+ await expect(tune.locator("[data-tuning-custom]")).toHaveCount(0);
+
+ // The line typed with doubled spaces: what is SAID collapses them (Another reading counts from that, review 1 #3).
+ const typed = TUNING_LINE.replace(/ /g, " ");
+ await tune.locator("[data-tuning-text]").fill(typed);
+ // Read it, pressed twice at once (review 1 #5): one job, one ask, nothing "already running".
+ await tune.getByRole("button", { name: "Read the line with these settings" }).dblclick();
+ await expect(tune.locator('[data-tuning-try="0"]')).toBeVisible({ timeout: 60_000 });
+ let asks = ttsAsks().slice(asksBefore);
+ expect(asks).toHaveLength(1);
+ expect(asks[0].tuning).toEqual({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
+ expect(asks[0].reading).toBeUndefined();
+ expect(asks[0].text).toBe(TUNING_LINE);
+ await expect(tune.locator("[data-tuning-blocked]")).toHaveCount(0);
+ await expect(tune.locator('[data-tuning-try="0"] [data-tuning-try-numbers]')).toContainText("Lively · temperature 0.75 · top_p 0.92 · repeat penalty 1.25");
+ await expect(tune.locator('[data-tuning-try="0"] [data-tuning-try-audio]')).toHaveAttribute("src", /narration%2Fauditions%2F[0-9a-f]{20}\.wav/);
+
+ // Another reading: the same line and numbers, reading 1; and again, reading 2.
+ const another = tune.getByRole("button", { name: "Read the same line again, the next reading" });
+ await another.click();
+ await expect(tune.locator('[data-tuning-try="1"]')).toBeVisible({ timeout: 60_000 });
+ await expect(another).toBeEnabled({ timeout: 60_000 });
+ await another.click();
+ await expect(tune.locator('[data-tuning-try="2"]')).toBeVisible({ timeout: 60_000 });
+ asks = ttsAsks().slice(asksBefore);
+ expect(asks).toHaveLength(3);
+ expect(asks.map((a) => a.reading)).toEqual([undefined, 1, 2]);
+ expect(asks[1].tuning).toEqual(asks[0].tuning);
+ await expect(tune.locator("[data-tuning-tries]")).toHaveAttribute("data-tuning-tries", "3");
+ await expect(tune.locator("[data-tuning-status]")).toContainText("reading 2 made");
+
+ // Another job running: said in place, Read it closed until it ends (umtool runs one job at a time).
+ let busy = true;
+ const tryPost = (u: URL) => u.pathname === "/api/report/voices" && !u.search;
+ const busyJob = (u: URL) => u.pathname === "/api/report/voices" && u.searchParams.get("job") === "busy-1";
+ await page.route(tryPost, async (route) => {
+ const body = route.request().postDataJSON() as { op?: string } | null;
+ if (route.request().method() === "POST" && body?.op === "try") {
+ return route.fulfill({ status: 409, contentType: "application/json", body: JSON.stringify({ error: "another job is running", busy: true, running: { id: "busy-1", kind: "cast-audition reports/tuning-fixture", state: "running", error: null } }) });
+ }
+ return route.continue();
+ });
+ await page.route(busyJob, (route) => route.fulfill({ contentType: "application/json", body: JSON.stringify({ id: "busy-1", state: busy ? "running" : "done", error: null }) }));
+ await tune.locator("[data-tuning-read]").click();
+ await expect(tune.locator("[data-tuning-blocked]")).toContainText("Another job is running (cast-audition reports/tuning-fixture): Read it is open again when it ends.");
+ await expect(tune.locator("[data-tuning-read]")).toBeDisabled();
+ busy = false;
+ await expect(tune.locator("[data-tuning-blocked]")).toHaveCount(0, { timeout: 10_000 });
+ await expect(tune.locator("[data-tuning-read]")).toBeEnabled();
+ await page.unroute(tryPost);
+ await page.unroute(busyJob);
+ expect(ttsAsks().slice(asksBefore), "the refused press asked nothing").toHaveLength(3);
+
+ // A job umtool no longer knows (restarted: 404 on its poll) is a failed read -- never "made", nothing played (review 1 #4).
+ const goneJob = (u: URL) => u.pathname === "/api/report/voices" && u.searchParams.get("job") === "gone-1";
+ await page.route(tryPost, async (route) => {
+ const body = route.request().postDataJSON() as { op?: string } | null;
+ if (route.request().method() === "POST" && body?.op === "try") return route.fulfill({ contentType: "application/json", body: JSON.stringify({ ok: true, job: { id: "gone-1", state: "running", error: null } }) });
+ return route.continue();
+ });
+ await page.route(goneJob, (route) => route.fulfill({ status: 404, contentType: "application/json", body: JSON.stringify({ error: "no such job" }) }));
+ await tune.locator("[data-tuning-read]").click();
+ await expect(tune.locator("[data-tuning-error]")).toContainText("the read failed: no such job");
+ await expect(tune.locator("[data-tuning-status]")).toHaveCount(0);
+ await expect(tune.locator("[data-tuning-read]")).toBeEnabled();
+ await page.unroute(tryPost);
+ await page.unroute(goneJob);
+
+ // The route: a flag is never a character; a tuning value is a number (review 1 #16).
+ const refused = await page.evaluate(async (project) => {
+ const ask = async (body: Record<string, unknown>) => {
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ return [r.status, ((await r.json()) as { error?: string }).error ?? ""];
+ };
+ return [
+ await ask({ op: "try", who: "--project", text: "x", tuning: { temperature: 0.7 }, reading: 0 }),
+ await ask({ op: "character-set", scope: "project", id: "teller", tuning: { temperature: [0.7] } }),
+ ];
+ }, P);
+ expect(refused[0]).toEqual([400, "a try is of a character: its id, or @handle"]);
+ expect(refused[1]).toEqual([400, "tuning.temperature is a number (got [0.7])"]);
+
+ // An edit above the tuning, not saved yet: Keep must not throw it away (review 1 #6).
+ await ed.locator("[data-preset-direction]").fill("slower, warmer");
+ // Takes 3 typed: not what is stored (none), so Keep is open (review 1 #17); the CLI's note is said beside it, and the
+ // field shows what is stored -- none, the setting's (review 1 #7). The note is the CLI's when the setting is not 3;
+ // here it is laid on the route's answer, as the CLI words it.
+ await tune.locator('[data-tuning-field="takes"]').fill("3");
+ const keepSet = (u: URL) => u.pathname === "/api/report/voices" && !u.search;
+ await page.route(keepSet, async (route) => {
+ const body = route.request().postDataJSON() as { op?: string } | null;
+ if (route.request().method() !== "POST" || body?.op !== "character-set") return route.continue();
+ const res = await route.fetch();
+ const j = (await res.json()) as Record<string, unknown>;
+ return route.fulfill({ response: res, json: { ...j, notes: ["takes 3 is Orpheus's default and is not kept: its reads take the editor's setting (4)"] } });
+ });
+
+ // Keep these settings: the CLI's own command; the preset says it is kept; the read made with the defaults is stale.
+ await tune.getByRole("button", { name: /Keep these settings for The Teller \(this video\)/ }).click();
+ await expect(page.locator("[data-voices-status]")).toContainText("The Teller: Orpheus tuning kept (Lively) for this video only");
+ const kept = (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; synthetic?: { tuning?: Record<string, number> } }[] }).characters.find((c) => c.id === "teller");
+ expect(kept?.synthetic?.tuning).toEqual({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
+ const tune2 = page.locator('[data-preset-editor="teller"] [data-tuning="teller"]');
+ await expect(tune2.locator("[data-tuning-note]")).toContainText("note: takes 3 is Orpheus's default and is not kept");
+ await expect(tune2.locator('[data-tuning-field="takes"]')).toHaveValue("");
+ await expect(ed.locator("[data-preset-direction]")).toHaveValue("slower, warmer");
+ await page.unroute(keepSet);
+ await expect(tune2).toHaveAttribute("data-tuning-kept", "yes");
+ await expect(tune2.locator("[data-tuning-effective]")).toContainText("kept: Lively · temperature 0.75 · top_p 0.92 · repeat penalty 1.25");
+ await expect(tune2.locator("[data-tuning-stale]")).toHaveAttribute("data-tuning-stale", "1");
+ await expect(tune2.locator("[data-tuning-stale]")).toContainText("1 read by this character was made with other settings: p-1");
+ await expect(tune2.locator("[data-tuning-stale-item]")).toHaveCount(1);
+ await expect(row.locator("[data-voice-stale]")).toHaveAttribute("data-voice-stale", "1");
+ // The tries are still there after the keep (scratch, the project's).
+ await expect(tune2.locator("[data-tuning-tries]")).toHaveAttribute("data-tuning-tries", "3");
+
+ // Nothing the cut shows changed: the manifest byte for byte, every card as drawn, no take made, no script written.
+ expect(readFileSync(MANIFEST, "utf8")).toBe(manifestBefore);
+ expect(await drawn()).toEqual(cardsBefore);
+ expect(takeFiles()).toEqual(takesBefore);
+});
+
+// THE BENCH (after S3, lane line-rerun): the character's tuning reaches its post's Read again; the Tune's numbers beat
+// it; "Keep this tuning for <character>" keeps them as the character's (cast project <p> set) and says what that leaves
+// stale -- and the card draws what it drew.
+type BenchTake = { file: string; tuning?: Record<string, number>; tuningAsked?: true | "preset"; reading?: number };
+const takesOf = (id: string) => ((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string; narration?: { takes?: BenchTake[] } }[] }).timeline.find((e) => e.id === id)!.narration?.takes ?? []);
+const benchAsks = () => (existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as (Tts & { out?: string })[]) : []).filter((r) => r.route === "tts" && String(r.out ?? "").includes("/tuning-fixture/narration/posts/1/"));
+const drawnCard = async (page: import("@playwright/test").Page) => {
+ const frame = page.frameLocator('[data-post-card-frame="read"]');
+ await expect(frame.locator("[data-post-words]")).toContainText("bridge", { timeout: 15_000 });
+ return frame.locator("body").evaluate((b) => ({
+ words: b.querySelector("[data-post-words]")?.textContent ?? null,
+ blocks: [...b.querySelectorAll("[data-post-block]")].map((x) => [x.getAttribute("data-post-block"), x.textContent]),
+ tiles: [...b.querySelectorAll("[data-thread-tile]")].map((x) => [x.getAttribute("data-thread-tile"), x.getAttribute("data-thread-mode")]),
+ follow: b.getAttribute("data-post-follow"),
+ }));
+};
+
+test("the post bench: Read again asks the character's Lively (\"preset\"); the Tune's numbers beat it (true); Keep for the character -- the card unchanged", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1400 });
+ await page.goto(urls.voicesHref(P));
+ // The character's tuning, kept through its command (the Voices page's Keep is the first test's).
+ const kept0 = 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-set", scope: "project", id: "teller", tuning: { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 } }) });
+ return r.status;
+ }, P);
+ expect(kept0).toBe(200);
+ await page.goto(urls.postBenchHref(P, "p-1"));
+ const panel = page.locator('[data-post-narration="p-1"]');
+ await expect(panel.locator("[data-post-take]")).toHaveCount(1, { timeout: 30_000 });
+ const before = await drawnCard(page);
+ const asked0 = benchAsks().length;
+
+ // Read again: the character's tuning asked, recorded as its ("preset").
+ await panel.locator('[aria-label="Read again"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 });
+ expect(benchAsks().length).toBe(asked0 + 1);
+ // (The Read again carries the takes its last read was made with -- S3's rule -- and the character's sampler under it.)
+ expect(benchAsks().at(-1)!.tuning).toMatchObject({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
+ expect(takesOf("p-1")[1]).toMatchObject({ tuningAsked: "preset", tuning: { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 } });
+
+ // The Tune's numbers, this line only: they beat the character's, and say so (true).
+ await panel.locator("[data-read-tune] summary").click();
+ await panel.locator('[aria-label="temperature, this line only"]').fill("0.9");
+ await panel.locator('[aria-label="Read again with this tuning"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 30_000 });
+ expect(benchAsks().at(-1)!.tuning?.temperature).toBe(0.9);
+ expect(takesOf("p-1")[2]).toMatchObject({ tuningAsked: true });
+ expect(takesOf("p-1")[2].tuning?.temperature).toBe(0.9);
+
+ // Keep this tuning for the character: its command; what it kept, and that this read (the picked one, made with the
+ // defaults) was made with other settings.
+ await panel.getByRole("button", { name: "Keep this tuning for The Teller" }).click();
+ await expect(panel.locator("[data-read-tune-kept]")).toContainText("kept for The Teller (this video only)", { timeout: 15_000 });
+ await expect(panel.locator("[data-read-tune-kept]")).toContainText("this read was made with other settings");
+ const teller = (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; synthetic?: { tuning?: Record<string, number> } }[] }).characters.find((c) => c.id === "teller");
+ expect(teller?.synthetic?.tuning?.temperature).toBe(0.9);
+
+ // The card draws what it drew: no take was picked, no words changed.
+ await page.reload();
+ expect(await drawnCard(page)).toEqual(before);
+});
+
+// REVIEW 2, THE MUST: a plain Read again under a tuned character asks the CHARACTER's tuning as it is now -- never the
+// last read's numbers as the line's own. Twice under Lively ("preset" both), the character made Steady: the playing
+// read is stale, and a third plain Read again asks Steady, "preset".
+const setTeller = (page: import("@playwright/test").Page, tuning: Record<string, number>) =>
+ page.evaluate(async ([project, t]) => {
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-set", scope: "project", id: "teller", tuning: t }) });
+ return r.status;
+ }, [P, tuning] as const);
+const staleOfTeller = (page: import("@playwright/test").Page) =>
+ page.evaluate(async (project) => ((await (await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&stale=teller`)).json()) as { items?: string[] }).items ?? [], P);
+
+test("review 2: a plain Read again asks the character's tuning as it is now (\"preset\"), never the last read's as its own", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1400 });
+ await page.goto(urls.voicesHref(P));
+ expect(await setTeller(page, { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 })).toBe(200);
+ await page.goto(urls.postBenchHref(P, "p-1"));
+ const panel = page.locator('[data-post-narration="p-1"]');
+ await expect(panel.locator("[data-post-take]")).toHaveCount(1, { timeout: 30_000 });
+ const before = await drawnCard(page);
+ const again = panel.locator('[aria-label="Read again"]');
+ // Twice under Lively: the second press starts from the first's (Lively, the character's) -- still the character's.
+ await again.click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 });
+ await expect(again).toBeEnabled({ timeout: 30_000 });
+ await again.click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 30_000 });
+ expect(takesOf("p-1")[1].tuningAsked).toBe("preset");
+ expect(takesOf("p-1")[2].tuningAsked).toBe("preset");
+ // The Tune says where its numbers start: the character's.
+ await panel.locator("[data-read-tune] summary").click();
+ await expect(panel.locator("[data-read-tune-baseline]")).toContainText("The Teller: Lively");
+ // Play the latest, then the character becomes Steady: that read is stale.
+ await panel.locator('[aria-label="Pick take 3"]').click();
+ await expect(panel.locator('[data-post-take="3"]')).toHaveAttribute("data-post-take-picked", "1");
+ expect(await setTeller(page, { temperature: 0.4, top_p: 0.8 })).toBe(200);
+ expect(await staleOfTeller(page)).toContain("p-1");
+ // A third plain press asks Steady, the character's now, and says so.
+ await page.reload();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 30_000 });
+ const asked0 = benchAsks().length;
+ await panel.locator('[aria-label="Read again"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(4, { timeout: 30_000 });
+ expect(benchAsks().length).toBe(asked0 + 1);
+ const sent = benchAsks().at(-1)!.tuning ?? {};
+ expect([sent.temperature, sent.top_p, sent.repeat_penalty ?? 1.2]).toEqual([0.4, 0.8, 1.2]);
+ expect(takesOf("p-1")[3].tuningAsked).toBe("preset");
+ // Defaults, this line only (review 2 #3): the three defaults asked as the line's own.
+ await panel.locator("[data-read-tune] summary").click();
+ await panel.locator('[aria-label="Tuning back to the defaults"]').click();
+ await panel.locator('[aria-label="Read again with this tuning"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(5, { timeout: 30_000 });
+ const dflt = benchAsks().at(-1)!.tuning ?? {};
+ expect([dflt.temperature, dflt.top_p]).toEqual([0.55, 0.85]);
+ expect(takesOf("p-1")[4].tuningAsked).toBe(true);
+ // Back to the character (review 3 #3): the line's own last read, its Tune's "Use The Teller's" -- the next press
+ // asks nothing of its own, Steady is read, recorded "preset".
+ await expect(panel.locator("[data-read-tune-baseline]")).toContainText("this line's own", { timeout: 15_000 });
+ await panel.locator('[aria-label="Use The Teller\'s tuning for this line"]').click();
+ await expect(panel.locator("[data-read-tune-baseline]")).toContainText("The Teller: Steady");
+ await panel.locator('[aria-label="Read again with this tuning"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(6, { timeout: 30_000 });
+ const back = benchAsks().at(-1)!.tuning ?? {};
+ expect([back.temperature, back.top_p]).toEqual([0.4, 0.8]);
+ expect(takesOf("p-1")[5].tuningAsked).toBe("preset");
+ // The card draws what it drew (take 3 plays: words as drafted).
+ await page.reload();
+ expect(await drawnCard(page)).toEqual(before);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -39,6 +39,7 @@ import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
import { makeUiOpsFixture } from "./ui-ops-fixture.mjs";
import { makeVoicesFixture } from "./voices-fixture.mjs";
+import { makeTuningFixture } from "./tuning-fixture.mjs";
import { makeRecordFilterFixture } from "./record-filter-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
@@ -1931,6 +1932,8 @@ makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "ou
makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ff });
// The Voices page (voices.spec.ts): Host's clips (the real voice) and post items by @hostman and @guest.
makeVoicesFixture({ reports, channels: CHANNELS, manifest, ff });
+// A character's Orpheus tuning on the Voices page (character-tuning.spec.ts): its own character, three reads.
+makeTuningFixture({ reports, manifest, ff });
// Record -> filter -> preview on the record page (record-filter.spec.ts): three one-part post items, no cast.
makeRecordFilterFixture({ reports, manifest });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
diff --git a/umtool/e2e/fixtures/tuning-fixture.mjs b/umtool/e2e/fixtures/tuning-fixture.mjs
@@ -0,0 +1,48 @@
+// A CHARACTER's ORPHEUS TUNING (character-tuning.spec.ts; components/projects/CharacterTuning.tsx, lib/report/castCli.mjs
+// `cast set|try|stale`): one character of this video's own, "teller" (orpheus · tara), and the reads it makes --
+//
+// reports/tuning-fixture/
+// p-1 @invented_teller_fixture its picked take orpheus · tara, made with the DEFAULTS (a 262 Hz tone): stale once a tuning is kept
+// p-2 @invented_teller_fixture its picked take made with its line's OWN tuning (temperature 0.9): never stale
+// p-3 @invented_teller_fixture its picked take RECORDED: never stale
+// narration/characters.json teller, no tuning yet
+//
+// The cast (<fixture>/.umtool/cast.json) is not used: the character is this video's own. The editor is the suite's
+// stub (its tts writes a tone and reports the tuning it was asked). Invented people, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const TUNING = "tuning-fixture";
+export const TUNING_LINE = "The teller says the bridge over the river was closed for the whole long winter.";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n");
+};
+
+/** @param {{ reports: string, manifest: Function, ff: (args: string[]) => void }} o */
+export function makeTuningFixture({ reports, manifest, ff }) {
+ const dir = path.join(reports, TUNING);
+ const made = (o = {}) => ({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...o });
+ const post = (id, text, take) => ({
+ type: "post", id: `p-${id}`, post: `tuningx/${id}`, platform: "x", author: "The Teller", handle: "invented_teller_fixture", date: `2026-10-30T1${id}:00:00.000Z`, text,
+ url: `https://x.com/invented_teller_fixture/status/${id}`, engagement: { likes: 1 }, section: 0,
+ narration: { script: text, takes: [{ seconds: 2, script: text, at: "2026-11-02T00:00:00.000Z", ...take }], pick: 0 },
+ });
+ const tone = (rel) => {
+ mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
+ ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", path.join(dir, rel)]);
+ };
+ const timeline = [
+ post("1", TUNING_LINE, { file: "narration/posts/1/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", tuning: made(), reading: 0 }),
+ post("2", "The teller answers a second question about the ferry and its fares.", { file: "narration/posts/2/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", tuning: made({ temperature: 0.9 }), reading: 0, tuningAsked: true }),
+ post("3", "The teller reads this one aloud in a voice of his own.", { file: "narration/posts/3/take-1.recorded.wav", engine: "recorded", voice: "operator" }),
+ ];
+ for (const e of timeline) tone(e.narration.takes[0].file);
+ write(dir, "video.manifest.json", manifest(TUNING, "The Tuning Fixture", {}, timeline));
+ write(path.join(dir, "narration"), "characters.json", {
+ format: "umtool-project-characters", version: 1,
+ characters: [{ id: "teller", name: "The Teller", handles: ["invented_teller_fixture"], synthetic: { voice: "orpheus:tara" } }],
+ });
+ return dir;
+}
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -70,10 +70,11 @@ export const GROUPS = [
" | 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",
+ " PRESET -- synthetic (voice, speed, Orpheus tuning) and recorded (convert, clean, trim, a direction) -- a project's",
" characters, its OWN (characters.json: anonymous ones), their drift, an audition of candidate voices",
" | assign <p> [--model] [--dry-run] | assign <p> --accept <id>|--accept-all|--reject <id>|--change <id> …",
" PROPOSED characters for authors with none, by rule; nothing applied until a person accepts",
+ " | try <p> <character> [--tuning …] [--reading N|--another] | stale <p> [<character>]",
],
docs: [
["`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]`",
@@ -86,6 +87,10 @@ export const GROUPS = [
"**AUTO-ASSIGNMENT BY RULE** ([knobs.md](knobs.md#proposed-characters-cast-assign)): every post item's author gets a character -- the item's own, this video's, its voice map's or the cast's; an author with none a **PROPOSED** character of this video: an id from the handle, their name, a STOCK Kokoro voice -- the next, in one fixed rotation (a male and a female voice in turn), that this project does not use yet; a gender hint only from the profile's own stated pronouns when the capture carries them. Proposals are kept apart in `<project>/narration/characters.json` (`proposed`; the same writer, an undo point: `cast project <p> undo`) and are **applied to nothing** -- no item, no picked read -- until a person accepts. `--accept <id>` / `--accept-all`: this video's character, named (`narration.character`) on that author's items that name none -- no take made or changed (a picked read in another voice shows as drift); `--change <id>`: its voice (a stock one only), speed, name, direction or anonymity -- the row is then a person's, never re-sent to a model or overwritten; `--reject <id>` / `--reject-all`: dropped. An author an anonymous character covers is never proposed for and never sent to a model. A proposal whose author has a character now is dropped by the next run. `--dry-run` writes nothing. **`--model`** (on request only): the generation task `cast-assign`, routed by `settings.generation` like the other tasks, is asked per author (display name, bio, post text -- untrusted) for `{character, voice, speed, direction}`; each field is checked (a stock voice, a speed 0.5–2, one plain line, control characters stripped) and laid over the rule's row, which stays when the answer fails. Refused: **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)"],
+ ["`cast set <id> [--tuning steady\\|default\\|lively] [--temperature t] [--top-p p] [--repeat-penalty r] [--chunk-takes n] [--no-tuning]` (and `cast add`, `cast project <p> add\\|set`)",
+ "**A CHARACTER's ORPHEUS TUNING** ([knobs.md](knobs.md#a-characters-orpheus-tuning)): on its synthetic preset -- a named starting point (Steady, Default, Lively: temperature, top_p and repeat penalty together) and the numbers over it; `default` takes one off; a value equal to its default is not kept (takes 3 too: its reads then take the editor's `tts.orpheus.takes`). The default of every Orpheus read the character's preset answers for; a read's own tuning flags beat it; Kokoro and eSpeak NG ignore it. `--json` says `tuning` with every value its reads are asked with (`effective`). Out of range: **exit 1**"],
+ ["`cast try <project> <character\\|@handle> [--text \"…\" \\| --item <id> \\| --line <n>] [the tuning flags] [--reading N \\| --another] [--scope cast\\|project] [--list \\| --clear] [--json] [--progress ndjson]` · `cast stale <project> [<character>] [--json]`",
+ "**TRY IT**: one line read in the character's own voice with a tuning (its own, or the flags over it) and a reading, through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` and kept in a short list (`tries.json`, the newest 12 per character; `--list`, `--clear`) -- SCRATCH: no take on any post, nothing in the draft. **STALE**: the picked Orpheus reads of a character made with other settings than its tuning now (a read whose line asked its own tuning, or a recorded one, never is; takes compared only when the character names them) -- listed, never re-made"],
],
},
{
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -87,9 +87,16 @@ 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 Orpheus tuning flags (castCli.mjs tuningFlagsOf): a named starting point and the numbers over it. */
+const tuningArgs = () => [
+ pick("--tuning", ["steady", "default", "lively"], { help: "Orpheus's tuning: a named starting point" }),
+ opt("--temperature", { help: "0.1–1.5 (or default)" }), opt("--top-p", { help: "0.05–1 (or default)" }),
+ opt("--repeat-penalty", { help: "1–2 (or default)" }), opt("--chunk-takes", { help: "the takes a chunk gets, 1–6 (or default)" }),
+];
/** 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)" }),
+ ...tuningArgs(),
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" }),
@@ -142,7 +149,7 @@ export const VERBS = Object.freeze([
]),
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"),
+ opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--no-speed"), bool("--no-tuning"), 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", []),
@@ -154,7 +161,7 @@ export const VERBS = Object.freeze([
], { 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"),
+ bool("--no-voice", "no voice of its own: the layers under it"), bool("--no-convert"), bool("--no-speed"), bool("--no-tuning"), 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" }),
@@ -166,6 +173,14 @@ export const VERBS = Object.freeze([
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"),
], Q),
+ // A character's Orpheus tuning tried on a line (scratch: no take, nothing in the draft) and its stale reads (lane character-tuning).
+ form("cast try", "project", "one line read in a character's voice with a tuning and a reading (scratch)", [
+ project(), arg("character", { allowAt: true, help: "a character id or @handle" }), opt("--text", { type: "text" }), opt("--item"), num("--line"),
+ ...tuningArgs(), num("--reading", { help: "0 the first; 1, 2, … read again differently" }), bool("--another", "the next reading after the highest kept"),
+ pick("--scope", ["cast", "project"], { help: "the layer the character is looked up in (the same id may be both)" }),
+ bool("--list", "the tries kept and the line the page prefills"), bool("--clear", "the character's tries removed"), bool("--no-hold"),
+ ], { shape: "cast try <project> <character>", ...Q }),
+ form("cast stale", "project", "the reads made with other settings than a character's tuning now (listed, never re-made)", [project(), arg("character", { allowAt: true, required: false })], { shape: "cast stale <project> <character>" }),
form("cast use", "draft", "the voice a character reads in, here or everywhere", [project(), arg("character", { allowAt: true }), arg("voice", { help: "engine:voice" }), bool("--everywhere", "the cast's voice, not this project's")], { shape: "cast use <project> <character> <voice>" }),
form("cast reread", "project", "the items that say a character in another voice, read again", [project(), arg("character", { allowAt: true }), dry()], Q),
// C3: PROPOSED characters by rule (a model only on request), kept apart until a person accepts one (castCli.mjs assignCommand).
diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs
@@ -5,8 +5,10 @@
// when the project names one (speakers.json, as `umtool speaker-check` reads it: TitaNet-small, local) -- a
// reference to compare with, NEVER a target.
//
-// <project>/narration/auditions/<key>.wav the candidate, -20 LUFS, 48 kHz mono (key: sha1(engine|voice|text))
-// <project>/narration/auditions/<key>.json { key, engine, voice, text, seconds, lufs, at, jobId, disclosure }
+// <project>/narration/auditions/<key>.wav the candidate, -20 LUFS, 48 kHz mono (key: sha1(engine|voice|text); a
+// TUNED one's -- an Orpheus tuning or a reading: characterTuning.mjs
+// `umtool cast try` -- sha1(engine|voice|text|tuning|reading))
+// <project>/narration/auditions/<key>.json { key, engine, voice, text, seconds, lufs, at, jobId, disclosure, tuning?, reading? }
// <project>/narration/auditions/ref-<speaker>.wav an excerpt of the real voice, the same loudness (to listen to)
// <project>/narration/auditions/scores.json { version, rows: { "<key>|<speaker>": { score, speaker, at, model } } }
//
@@ -25,6 +27,7 @@ import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-
import { ENGINE_WEIGHT, speakerFor } from "umtool-report-to-video/cast";
import { REPORTS_ROOT } from "../paths.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { ORPHEUS_DEFAULT_TAKES, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
const execFileP = promisify(execFile);
const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
@@ -53,8 +56,20 @@ export class AuditionError extends Error {
}
}
-/** A candidate's cache key: sha1 of `engine|voice|text`, 20 hex. */
-export const auditionKey = (engine, voice, text) => createHash("sha1").update(`${engine}|${voice}|${text}`).digest("hex").slice(0, 20);
+/**
+ * A candidate's cache key: sha1 of `engine|voice|text`, 20 hex -- and, for a TUNED one (an Orpheus tuning off the
+ * defaults, normalised; or a reading past the first), of `tuned:` and the JSON of [engine, voice, text, tuning,
+ * reading]. An untuned key starts with an engine's name, never `tuned:`, so no text makes the two collide. With neither
+ * the key is the one it always was (a candidate kept before is still a cache hit).
+ */
+export function auditionKey(engine, voice, text, { tuning = null, reading = 0 } = {}) {
+ const t = normalizeTtsTuning(tuning, { takes: ORPHEUS_DEFAULT_TAKES });
+ const r = Number.isInteger(reading) && reading > 0 ? reading : 0;
+ const tuned = Object.keys(t).length > 0 || r > 0;
+ return createHash("sha1").update(tuned ? `tuned:${JSON.stringify([engine, voice, text, t, r])}` : `${engine}|${voice}|${text}`).digest("hex").slice(0, 20);
+}
+/** Is a key's ask a tuned one (a tuning off the defaults, or a reading past the first)? */
+export const isTunedAsk = ({ tuning = null, reading = 0 } = {}) => Object.keys(normalizeTtsTuning(tuning, { takes: ORPHEUS_DEFAULT_TAKES })).length > 0 || (Number.isInteger(reading) && reading > 0);
/** The candidates as `[{ engine, voice, spec, weight }]` from `kokoro:am_michael,orpheus:zac` (a bare voice: `engine`). */
export function candidatesOf(list, engine = "kokoro") {
@@ -181,11 +196,14 @@ export const auditionDirOf = (project, reportsRoot = REPORTS_ROOT) =>
const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile();
-/** Each candidate's record and file: `[{ ...candidate, key, file, rel, cached, meta }]`. */
+/**
+ * Each candidate's record and file: `[{ ...candidate, key, file, rel, cached, meta }]`. A candidate may carry its own
+ * `tuning` and `reading` (`umtool cast try`): they are in its key and its ask.
+ */
export async function auditionPlan(dir, candidates, text, { relBase = AUDITION_DIR } = {}) {
const out = [];
for (const c of candidates) {
- const key = auditionKey(c.engine, c.voice, text);
+ const key = auditionKey(c.engine, c.voice, text, { tuning: c.tuning ?? null, reading: c.reading ?? 0 });
const file = path.join(dir, `${key}.wav`);
const meta = await readFile(path.join(dir, `${key}.json`), "utf8").then((t) => JSON.parse(t), () => null);
out.push({ ...c, key, file, rel: `${relBase}/${key}.wav`, cached: !!meta && (await fileThere(file)), meta });
@@ -234,25 +252,44 @@ export async function synthesizeAuditions(dir, plan, text, { ask = null, editor
}
}
try {
- const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
+ const via = await import("umtool-report-to-video/narrate-via-editor");
+ const askTts = ask ?? via.askEditorTts;
+ const { opWaitOf } = via;
for (const [n, c] of todo.entries()) {
emit("audition", { phase: "ask", n: n + 1, of: todo.length, voice: c.spec, weight: c.weight });
emit("note", { message: `${c.spec}${c.weight === "heavy" ? " (heavy: Orpheus)" : ""}: asking the editor (${n + 1}/${todo.length})…` });
const raw = path.join(dir, `${c.key}.raw.wav`);
let res;
+ // A tuned candidate's tuning and reading are asked; an untuned one's ask is the one it always was.
+ const tuning = normalizeTtsTuning(c.tuning ?? null, { takes: ORPHEUS_DEFAULT_TAKES });
+ const reading = Number.isInteger(c.reading) && c.reading > 0 ? c.reading : 0;
+ let waitSaid = false;
+ // While render mode holds the machine, an Orpheus job waits at the heavy slot: said once, in the job's log.
+ const onState = (st) => {
+ const w = opWaitOf(st);
+ if (waitSaid || w.state !== "slot" || !/render/i.test(String(w.line ?? ""))) return;
+ waitSaid = true;
+ emit("note", { message: `${c.spec}: waiting for the render -- render mode holds the machine; the read is made when it lets go (${w.line})` });
+ emit("audition", { phase: "waiting", for: "render", voice: c.spec, line: w.line });
+ };
try {
- res = await askTts({ text, engine: c.engine, voice: c.voice, out: raw }, { ...(editor ? { editor } : {}), emit });
+ res = await askTts({ text, engine: c.engine, voice: c.voice, out: raw, ...(Object.keys(tuning).length ? { tuning } : {}), ...(reading ? { reading } : {}) }, { ...(editor ? { editor } : {}), emit, onState });
} catch (err) {
throw new AuditionError(`${c.spec} was not synthesized: ${err instanceof Error ? err.message : err} -- the candidates made are kept; run it again`);
}
if (!(await fileThere(raw))) throw new AuditionError(`the editor's job ${res?.jobId ?? "?"} finished but ${c.key}.raw.wav is not there`);
await levelTo(raw, c.file);
await rm(raw, { force: true });
- const { measureTake } = await import("./postNarrationCli.mjs");
+ const { measureTake, tunedOfResult } = await import("./postNarrationCli.mjs");
const m = await measureTake(c.file);
+ if (typeof res?.result?.note === "string" && res.result.note) emit("note", { message: `${c.spec}: ${res.result.note}` });
const meta = {
key: c.key, engine: c.engine, voice: c.voice, text, seconds: m.seconds, lufs: m.lufs, at: new Date().toISOString(),
...(res?.jobId ? { jobId: res.jobId } : {}), ...(typeof res?.result?.disclosure === "string" ? { disclosure: res.result.disclosure } : {}),
+ // What it was made with, as the editor reports it (Orpheus: every tuning value and the reading).
+ ...tunedOfResult(res?.result),
+ // A TUNED ask's (characterTuning.mjs: a try): what was asked, so a sweep tells it from a candidate's cache.
+ ...(Object.keys(tuning).length || reading ? { asked: { tuning, reading } } : {}),
};
await writeFile(path.join(dir, `${c.key}.json`), `${JSON.stringify(meta, null, 1)}\n`);
c.meta = meta;
diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs
@@ -16,6 +16,9 @@
// [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]
// umtool cast use <p> <character|@handle> <voice> [--everywhere] [--json]
// umtool cast reread <p> <character|@handle> [--dry-run] [--json]
+// umtool cast try <p> <character|@handle> [--text "…" | --item <id> | --line <n>] [the tuning flags] [--reading N | --another]
+// [--list | --clear] [--no-hold] [--json] [--progress ndjson] one line read with a tuning (scratch)
+// umtool cast stale <p> [<character|@handle>] [--json] the reads made with other settings than its tuning now
// umtool cast assign <p> [--model] [--dry-run] [--json] PROPOSED characters for the authors with none
// umtool cast assign <p> --accept <id> | --accept-all | --reject <id> | --reject-all
// umtool cast assign <p> --change <id> [--voice <engine:voice>] [--speed s] [--name "…"] [--anonymous [--shown "…"] | --no-anonymous]
@@ -27,35 +30,50 @@ import {
charactersOf, findCharacter, idOfHandle, isQualifiedVoice, isStockVoice, nextAnonName, projectCharactersOf, proposalCharacter, shownNameOf, upgradeCharacter,
} from "umtool-report-to-video/cast";
import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
+import { characterTuning, characterTuningNormal, characterVoice } from "umtool-report-to-video/cast";
+import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_NAMED, ORPHEUS_TUNING_NAMES, quantizeTtsTuningValue, ttsReadingError, ttsTuningNameOf, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { readManifest } from "../projects/report.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 \"…\"]";
+const TUNING_USAGE = "[--tuning steady|default|lively] [--temperature <t>|default] [--top-p <p>|default] [--repeat-penalty <r>|default] [--chunk-takes <n>|default]";
+const PRESET_FLAGS = "[--speed <s>] [--tuning steady|default|lively] [--temperature <t>] [--top-p <p>] [--repeat-penalty <r>] [--chunk-takes <n>] [--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,…]",
` ${PRESET_FLAGS}`,
" [--avatar …] [--note \"…\"] [--narrator] [--json]",
- " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json]",
+ " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-tuning] [--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> set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-voice] [--no-convert] [--no-speed] [--no-tuning] [--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]",
+ " umtool cast try <project> <character|@handle> [--text \"…\" | --item <id> | --line <n>]",
+ ` ${TUNING_USAGE}`,
+ " [--reading N | --another] [--scope cast|project] [--list | --clear] [--no-hold] [--json] [--progress ndjson]",
+ " umtool cast stale <project> [<character|@handle>] [--json]",
" umtool cast assign <project> [--model] [--dry-run] [--json]",
" umtool cast assign <project> --accept <id> | --accept-all | --reject <id> | --reject-all [--json]",
" umtool cast assign <project> --change <id> [--voice <engine:voice>] [--speed <s>] [--name \"…\"] [--anonymous [--shown \"…\"] | --no-anonymous] [--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) 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).",
+ " SYNTHETIC: the STOCK voice they read in (--voice engine:voice) and its speed (--speed 0.5-2; Orpheus has none),",
+ " and ORPHEUS's TUNING for their reads (Kokoro and eSpeak NG ignore it): a named starting point (--tuning steady,",
+ " default or lively: temperature, top_p and repeat penalty together) and the numbers, any of them over it",
+ " (--temperature 0.1-1.5, --top-p 0.05-1, --repeat-penalty 1-2, --chunk-takes 1-6: the takes a chunk gets; `default`",
+ " takes one off; --tuning default puts the sampler's three back and keeps its takes; --no-tuning drops all of it,",
+ " and goes with no other tuning flag). A value equal to its default is not kept",
+ " (takes 3 included: a character with no takes of its own reads with the editor's tts.orpheus.takes). It is the",
+ " default of every Orpheus read the character's preset answers for; a read's own tuning flags beat it. --json says",
+ " `tuning` (its own, its name, every value its reads are asked with: `effective`).",
" 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",
@@ -89,6 +107,16 @@ export const CAST_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).",
+ " try: ONE LINE read in the character's own voice with a tuning (its own, or the flags laid over it) and a reading",
+ " (--reading N; --another: the next after the highest kept for that line and tuning) -- the editor's tts op, a",
+ " job -- levelled to -20 LUFS in <p>/narration/auditions/ and kept in a short list (tries.json, the newest 12 per",
+ " character; --list shows it and the line the page prefills, --clear empties it). SCRATCH: no take on any post,",
+ " nothing written to the draft. The line: --text, else --item / --line (as audition), else the character's first",
+ " own line in the project, else a stock line. --scope cast|project: the character of that layer (the same id may be",
+ " the cast's and this video's own; none: this video's own first). Keep a tuning with cast set / cast project <p> set.",
+ " stale: every picked Orpheus read of a character (or of all) made with OTHER SETTINGS than its tuning now -- a",
+ " read whose tuning its own line asked is never stale; a recorded read never; takes compared only when the",
+ " character names its takes. Listed, never re-made.",
" assign: every post item's author gets a character BY RULE (no model): the item's own, this video's, its voice map's",
" or the cast's; an author with none, a PROPOSED character of this video -- an id from the handle, their name, a",
" STOCK Kokoro voice, the next in one fixed rotation that this project does not use yet (a gender hint only from",
@@ -106,7 +134,7 @@ export const CAST_USAGE = [
" 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", "--speed", "--enhance", "--trim", "--trim-pad", "--direction", "--shown", "--accept", "--reject", "--change"]);
+const VALUED = new Set(["--scope", "--tuning", "--temperature", "--top-p", "--repeat-penalty", "--chunk-takes", "--reading", "--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", "--accept", "--reject", "--change"]);
const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean);
function parse(args) {
@@ -179,9 +207,67 @@ function fieldsOf(p) {
f.direction = d;
}
if (p.str("--shown") !== null) f.shown = p.str("--shown").trim();
+ const tuning = tuningFlagsOf(p);
+ if (tuning) f.tuning = tuning;
return f;
}
+/** The flags that set a character's tuning field, and the field each sets (S1's words: readTuning.mjs). */
+export const CHARACTER_TUNING_FLAGS = Object.freeze({ "--temperature": "temperature", "--top-p": "top_p", "--repeat-penalty": "repeat_penalty", "--chunk-takes": "takes" });
+
+/**
+ * The tuning flags given: `{ named, set }` -- `named` a named starting point (--tuning) or null, `set` each field a
+ * flag gave (quantised and in range; null: `default`, the field off) -- or null when none is given.
+ */
+export function tuningFlagsOf(p) {
+ const named0 = p.str("--tuning");
+ const set = {};
+ let any = named0 !== null;
+ for (const [flag, field] of Object.entries(CHARACTER_TUNING_FLAGS)) {
+ const raw = p.str(flag);
+ if (raw === null) continue;
+ any = true;
+ if (raw.trim().toLowerCase() === "default") {
+ set[field] = null;
+ continue;
+ }
+ const v = quantizeTtsTuningValue(field, raw.trim() === "" ? Number.NaN : Number(raw));
+ const e = ttsTuningValueError(field, v, flag);
+ if (e) throw new CastError(e.replace(/\(got NaN\)$/, `(got ${raw || "nothing"})`));
+ set[field] = v;
+ }
+ if (!any) return null;
+ let named = null;
+ if (named0 !== null) {
+ named = named0.trim().toLowerCase();
+ if (!ORPHEUS_TUNING_NAMES.includes(named)) throw new CastError(`--tuning is ${ORPHEUS_TUNING_NAMES.join(", ")} (got ${named0 || "nothing"})`);
+ }
+ return { named, set };
+}
+
+/**
+ * A tuning with the flags laid over `before` (pure): a named starting point replaces the sampler's three values (the
+ * takes kept), then each field flag; normalised as a character keeps it (cast.mjs characterTuningNormal).
+ */
+export function tuningOver(before, f) {
+ let t = { ...characterTuningNormal(before) };
+ if (f?.named) t = { ...(t.takes !== undefined ? { takes: t.takes } : {}), ...ORPHEUS_TUNING_NAMED[f.named] };
+ for (const [k, v] of Object.entries(f?.set ?? {})) {
+ if (v === null) delete t[k];
+ else t[k] = v;
+ }
+ return characterTuningNormal(t);
+}
+
+/** What a tuning write says beside it: takes 3 is not kept (the setting's are used), and a voice that ignores a tuning. */
+function tuningNotes(c, f, settingTakes) {
+ const notes = [];
+ if (f?.tuning?.set?.takes === ORPHEUS_DEFAULT_TAKES && settingTakes !== ORPHEUS_DEFAULT_TAKES) notes.push(`takes ${ORPHEUS_DEFAULT_TAKES} is Orpheus's default and is not kept: its reads take the editor's setting (${settingTakes})`);
+ const voice = characterVoice(c);
+ if (Object.keys(characterTuning(c)).length && voice && !String(voice).startsWith("orpheus:")) notes.push(`${voice} has no sampler: its reads ignore the tuning (Orpheus's) until its voice is an Orpheus one`);
+ return notes;
+}
+
/**
* A convert entry with the flags' keys laid over it, and what makes no sense together refused in a sentence: the
* target's own pitch drops the semitones (nothing is followed to move), 0 semitones is no entry.
@@ -213,12 +299,24 @@ export function characterFrom(before, id, f, p, { layer = "cast", anon = () => A
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;
+ // Its Orpheus tuning: the flags laid over the one it has; a tuning equal to the defaults is none.
+ if (f.tuning) {
+ const t = tuningOver(syn.tuning, f.tuning);
+ if (Object.keys(t).length) syn.tuning = t;
+ else delete syn.tuning;
+ }
+ if (p.has("--no-tuning")) {
+ if (f.tuning) throw new CastError("--no-tuning drops the whole tuning: not with --tuning, --temperature, --top-p, --repeat-penalty or --chunk-takes");
+ delete syn.tuning;
+ }
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;
+ delete syn.tuning;
}
if (syn.speed !== undefined && !syn.voice) throw new CastError("--speed is its voice's: give the character a voice too (--voice <engine:voice>)");
+ if (syn.tuning !== undefined && !syn.voice) throw new CastError("a tuning is its voice's: give the character a voice too (--voice orpheus:<voice>)");
if (Object.keys(syn).length) c.synthetic = syn;
else delete c.synthetic;
// The recorded preset.
@@ -274,6 +372,22 @@ export function characterFrom(before, id, f, p, { layer = "cast", anon = () => A
return upgradeCharacter(c);
}
+/**
+ * What a write says of the character's tuning: `json` `{ tuning: { tuning, name, effective, takesFrom }, notes? }`
+ * (characterTuning.mjs tuningView: every value its reads are asked with -- the editor's takes when it names none) and
+ * the `text` lines.
+ */
+async function tuningOut(c, f = {}) {
+ const T = await import("./characterTuning.mjs");
+ const settingTakes = await T.orpheusTakesSetting();
+ const view = T.tuningView(characterTuning(c), settingTakes);
+ const notes = tuningNotes(c, f, settingTakes);
+ return {
+ json: { tuning: view, ...(notes.length ? { notes } : {}) },
+ text: `${view.tuning ? `\n Orpheus tuning: ${T.tuningWords(view)}` : ""}${notes.map((n) => `\n note: ${n}`).join("")}`,
+ };
+}
+
/** 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;
@@ -293,7 +407,9 @@ 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}` : ""}`;
+ const t = characterTuning(c);
+ const tuned = Object.keys(t).length ? ` tuning ${ttsTuningNameOf(t)} (${Object.entries(t).map(([k, v]) => `${k} ${v}`).join(", ")})` : "";
+ return `${c.id.padEnd(16)} ${voice.padEnd(20)}${tuned} ${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}` : ""}`;
};
@@ -315,7 +431,8 @@ export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {})
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, project: ownRead.doc, speakers });
+ const settingTakes = await (await import("./characterTuning.mjs")).orpheusTakesSetting();
+ const view = projectCharacters(manifest, { map, cast: castRead.cast, project: ownRead.doc, speakers, settingTakes });
return { manifest, map, castRead, ownRead, speakers, view };
}
@@ -358,7 +475,8 @@ async function projectCharactersCommand(project, op, rest, p, { reportsRoot, out
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)}`);
+ const tv = await tuningOut(r.character, f);
+ out({ ok: true, scope: "project", changed: r.changed, character: characterView(r.character), ...tv.json, token: r.token }, `${r.changed} in ${project.id}: ${line(r.character)}${tv.text}`);
return 0;
}
if (op === "rm" || op === "remove") {
@@ -489,7 +607,8 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
chars[at] = c;
return { changed: "updated", character: c };
}, { what: `${sub} ${id}` });
- out({ ok: true, changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} ${line(r.character)}`);
+ const tv = await tuningOut(r.character, f);
+ out({ ok: true, changed: r.changed, character: characterView(r.character), ...tv.json, token: r.token }, `${r.changed} ${line(r.character)}${tv.text}`);
return 0;
}
if (sub === "rm" || sub === "remove") {
@@ -528,6 +647,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
for (const c of view.characters) {
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.stale?.length) log(` ${c.stale.length} read(s) made with other settings than its tuning now: ${[...new Set(c.stale.map((d) => d.id))].join(", ")} -- umtool cast stale ${project.id} ${c.character?.id ?? c.key}`);
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)`);
@@ -641,8 +761,10 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
return failed ? 1 : 0;
}
if (sub === "audition") return await auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes });
+ if (sub === "try") return await tryCommand(rest, p, { reportsRoot, log, err, ask, lanes });
+ if (sub === "stale") return await staleCommand(rest, p, { reportsRoot, out });
if (sub === "assign") return await assignCommand(rest, p, { reportsRoot, out, json, model, log });
- throw new CastError(`cast: ls, add, set, rm, undo, project, audition, use, reread or assign (not ${sub})`);
+ throw new CastError(`cast: ls, add, set, rm, undo, project, audition, try, stale, use, reread or assign (not ${sub})`);
} catch (e) {
if (e instanceof CastError || e?.name === "AuditionError" || e?.name === "SayError") {
if (json) log(JSON.stringify({ ok: false, error: e.message }, null, 2));
@@ -654,6 +776,128 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
}
}
+/** The layer a character an audition found is of: this video's own ("project"), the cast's, or null (an author). */
+function layerOf(character, castRead, ownRead) {
+ if (projectCharactersOf(ownRead?.doc).some((c) => c.id === character.id)) return "project";
+ return charactersOf(castRead?.cast).some((c) => c.id === character.id) ? "cast" : null;
+}
+
+/**
+ * `umtool cast try <p> <character|@handle> …`: ONE LINE read in the character's own voice with a tuning and a reading
+ * (characterTuning.mjs: scratch, kept in a short list), or the list (--list), or the list emptied (--clear).
+ */
+async function tryCommand(rest, p, { reportsRoot, log, err, ask, lanes }) {
+ const [ref, who] = rest;
+ if (!ref || !who) throw new CastError("cast try takes the project and the character (its id, or @handle)");
+ const A = await import("./castAudition.mjs");
+ const T = await import("./characterTuning.mjs");
+ const json = p.has("--json");
+ const ndjson = p.str("--progress") === "ndjson";
+ const say = (s) => (ndjson ? err(s) : !json && log(s));
+ const emit = (ev, f = {}) => {
+ if (ev === "note") say(f.message);
+ else if (ndjson) log(JSON.stringify({ ev: "cast-try", ...f }));
+ };
+ const project = await projectOf(ref, reportsRoot);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CastError(`${project.id} has no manifest`);
+ const castRead = await castForProject(project.dir, reportsRoot);
+ const ownRead = await readProjectCharacters(project.dir);
+ if (p.has("--no-tuning")) throw new CastError("cast try reads with a tuning: --tuning default for the defaults (--no-tuning is cast set's)");
+ if (p.str("--reading") !== null && p.has("--another")) throw new CastError("--reading N or --another, not both");
+ // --scope: the layer the character is looked up in -- the cast's, or this video's own (the same id may be both);
+ // none: this video's own first, then the cast's, then an author.
+ const scope = p.str("--scope");
+ if (scope !== null && scope !== "cast" && scope !== "project") throw new CastError(`--scope is cast or project (got ${scope || "nothing"})`);
+ let character;
+ if (scope === "cast") {
+ character = findCharacter(castRead.cast, String(who).replace(/^@+/, ""));
+ if (!character) throw new CastError(`${who} is not in the cast (umtool cast ls)`);
+ } else if (scope === "project") {
+ const h = handleKey(who);
+ const c = projectCharactersOf(ownRead.doc).find((x) => x.id === String(who).toLowerCase()) ?? projectCharactersOf(ownRead.doc).find((x) => (x.handles ?? []).includes(h));
+ if (!c) throw new CastError(`${who} is not one of ${project.id}'s own characters (umtool cast project ${project.id})`);
+ character = { ...c, name: shownNameOf(c) };
+ } else character = await A.auditionCharacter(castRead.cast, who, { project, manifest });
+ const layer = scope ?? layerOf(character, castRead, ownRead);
+ const spec = characterVoice(character);
+ const settingTakes = await T.orpheusTakesSetting();
+ const kept = characterTuning(character);
+ const who0 = { id: character.id, name: character.name, layer, voice: spec ?? null, tuning: T.tuningView(kept, settingTakes) };
+ if (p.has("--clear")) {
+ const r = await T.clearTries(project.dir, character.id, layer);
+ if (json) log(JSON.stringify({ ok: true, project: project.id, character: who0, ...r }, null, 2));
+ else log(`${character.name}: ${r.cleared} tr${r.cleared === 1 ? "y" : "ies"} cleared in ${project.id}`);
+ return 0;
+ }
+ const said = await A.auditionLine(project, manifest, character, { text: p.str("--text"), item: p.str("--item"), line: p.str("--line") });
+ if (p.has("--list")) {
+ const rows = (await T.readTries(project.dir)).filter((r) => T.rowOf(r, character.id, layer));
+ if (json) log(JSON.stringify({ ok: true, project: project.id, character: who0, line: said, settingTakes, tries: rows }, null, 2));
+ else {
+ log(`${character.name} (${spec ?? "no voice of its own"}${kept && Object.keys(kept).length ? `; ${T.tuningWords(who0.tuning)}` : ""}): ${rows.length} tr${rows.length === 1 ? "y" : "ies"} in ${project.id}; the line: "${said.text}" (${said.from})`);
+ for (const r of rows) log(` reading ${r.reading} ${T.tuningWords(T.tuningView(r.tuning, settingTakes))} ${r.rel} "${String(r.text).slice(0, 60)}"`);
+ }
+ return 0;
+ }
+ if (!spec || !voiceRefOf(spec)?.engine) throw new CastError(`${character.name} has no stock voice of its own to try (umtool cast set ${character.id} --voice orpheus:<voice>)`);
+ const cand = A.candidatesOf([spec])[0];
+ const f = tuningFlagsOf(p);
+ const readingRaw = p.str("--reading");
+ let tuning = f ? tuningOver(kept, f) : kept;
+ if (cand.engine !== "orpheus") {
+ if (f || readingRaw !== null || p.has("--another")) throw new CastError(`a tuning and a reading are Orpheus's: ${spec} reads the same every time (umtool cast audition compares voices)`);
+ tuning = {};
+ }
+ let reading = 0;
+ if (readingRaw !== null) {
+ const n = readingRaw.trim() === "" ? Number.NaN : Number(readingRaw);
+ const e = ttsReadingError(n, "--reading");
+ if (e) throw new CastError(e.replace(/got NaN\)$/, `got ${readingRaw || "nothing"})`));
+ reading = n;
+ } else if (p.has("--another")) reading = T.nextReading(await T.readTries(project.dir), character.id, { voice: spec, text: said.text, tuning }, layer);
+ const dir = A.auditionDirOf(project);
+ const plan = await A.auditionPlan(dir, [{ ...cand, tuning, reading }], said.text);
+ emit("try", { phase: "start", voice: spec, reading, tuning });
+ const r = await A.synthesizeAuditions(dir, plan, said.text, { ask, emit, hold: !p.has("--no-hold"), lanes });
+ const c = plan[0];
+ const row = {
+ key: c.key, character: character.id, layer, voice: spec, text: said.text, from: said.from, tuning, ...(c.meta?.tuning ? { made: c.meta.tuning } : {}), reading,
+ rel: c.rel, seconds: c.meta?.seconds ?? null, lufs: c.meta?.lufs ?? null, at: new Date().toISOString(), ...(c.meta?.jobId ? { jobId: c.meta.jobId } : {}),
+ };
+ const k = await T.addTry(project.dir, row);
+ const view = T.tuningView(tuning, settingTakes);
+ if (json) log(JSON.stringify({ ok: true, project: project.id, character: who0, try: row, tuning: view, fresh: r.fresh, jobs: r.jobs, swept: k.removed }, null, 2));
+ else if (ndjson) log(JSON.stringify({ ev: "cast-try", phase: "done", key: row.key, reading, fresh: r.fresh }));
+ else log(`${character.name}: ${spec}, ${cand.engine === "orpheus" ? `${T.tuningWords(view)}, reading ${reading}` : "its voice"}${r.fresh ? "" : " (kept already)"} -- ${row.rel}`);
+ return 0;
+}
+
+/** `umtool cast stale <p> [<character|@handle>]`: the reads made with other settings than a character's tuning now. */
+async function staleCommand(rest, p, { reportsRoot, out }) {
+ const [ref, who] = rest;
+ if (!ref) throw new CastError("cast stale takes the project (and a character, or @handle)");
+ const project = await projectOf(ref, reportsRoot);
+ const v = await projectView(project, { reportsRoot });
+ let rows = v.view.tuningStale ?? [];
+ let id = null;
+ if (who) {
+ const t = handlesOf(who, v.castRead, v.view, v.ownRead);
+ if (!t.character) throw new CastError(`${who} is no character in ${project.id} (umtool cast project ${project.id})`);
+ id = t.character.id;
+ rows = rows.filter((r) => r.character === id);
+ }
+ const items = [...new Set(rows.map((r) => r.id))];
+ const said = (t) => `temperature ${t.temperature}, top_p ${t.top_p}, repeat penalty ${t.repeat_penalty}, takes ${t.takes}`;
+ out({ ok: true, project: project.id, character: id, count: rows.length, items, reads: rows }, [
+ rows.length
+ ? `${rows.length} read${rows.length === 1 ? "" : "s"} ${id ? `by ${id} ` : ""}made with other settings than ${id ? "its" : "their character's"} tuning now (listed, never re-made):`
+ : `no read ${id ? `by ${id} ` : ""}was made with other settings than ${id ? "its" : "its character's"} tuning now`,
+ ...rows.map((r) => ` ${r.id} ${r.role} (${r.character}): made with ${said(r.made)}${r.reading ? `, reading ${r.reading}` : ""} -- now ${said(r.want)}`),
+ ].join("\n"));
+ return 0;
+}
+
/** `umtool cast audition …` */
async function auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }) {
const A = await import("./castAudition.mjs");
diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs
@@ -10,11 +10,17 @@ import { postNarrationKnobs } from "umtool-report-to-video/post-narration";
import { handleKey, readSpeedOf, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
import {
castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, proposalsOf, recordedPresetOf,
- shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT,
+ shownNameOf, speakerFor, takeReads, tuningStale, voiceDrift, ENGINE_WEIGHT,
} from "umtool-report-to-video/cast";
import { characterLines } from "./castAudition.mjs";
import { tuningArgvOf } from "./readTuning.mjs";
+/**
+ * A take's reading asked again, and none of its tuning: a take whose tuning was its CHARACTER's (`tuningAsked`
+ * "preset", lane character-tuning) is re-read with the character's tuning as it is then, never pinned to the old one.
+ */
+const readingArgvOf = (t) => (Number.isInteger(t?.reading) && t.reading > 0 ? ["--reading", String(t.reading)] : []);
+
const str = (v) => (typeof v === "string" ? v : "");
/**
@@ -90,9 +96,11 @@ export function authorsOf(manifest) {
* 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).
+ * one -- the read falls to the layers under it). `tuningStale` every picked Orpheus read made with other settings than
+ * its character's tuning now (cast.mjs tuningStale; `settingTakes` the editor's tts.orpheus.takes), and each
+ * character row its own (`stale`).
*/
-export function projectCharacters(manifest, { map = {}, cast = null, project = null, speakers = [] } = {}) {
+export function projectCharacters(manifest, { map = {}, cast = null, project = null, speakers = [], settingTakes = undefined } = {}) {
const render = manifest?.render ?? {};
const k = postNarrationKnobs({}, render);
const resolve = resolverFor({ map, cast, project, render });
@@ -100,6 +108,7 @@ export function projectCharacters(manifest, { map = {}, cast = null, project = n
const layer = projectPresetMap(project, map);
const pchars = projectCharactersOf(project);
const drift = voiceDrift(manifest, resolve);
+ const stale = tuningStale(manifest, resolve, settingTakes !== undefined ? { settingTakes } : {});
const groups = new Map();
for (const a of authorsOf(manifest).values()) {
const own = pchars.find((c) => (c.handles ?? []).includes(a.handle)) ?? null;
@@ -136,6 +145,8 @@ export function projectCharacters(manifest, { map = {}, cast = null, project = n
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)),
+ // Its reads made with other settings than its tuning now (stale, never re-made by itself).
+ stale: g.character ? stale.filter((d) => d.character === g.character.id) : [],
speaker: sp?.name ?? null,
lines: characterLines(manifest, g.handles).slice(0, 8),
};
@@ -152,6 +163,7 @@ export function projectCharacters(manifest, { map = {}, cast = null, project = n
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 }),
+ tuningStale: stale,
cast: charactersOf(cast).length,
own: pchars.map((c) => rowCharacter(c, "project")).map((c, i) => ({ ...c, handles: pchars[i].handles ?? [] })),
itemCharacters,
@@ -229,7 +241,7 @@ export function rereadPlan(projectId, manifest, drift, handles) {
// from the character's preset or the item (that is what a re-read takes anew). Its own tuning and reading too
// (readTuning.mjs: what is not Orpheus's default) -- a reading picked by ear is read again the same way.
const keepSpeed = !r.thread && typeof t?.speed === "number" && t.speed !== 1 && t.speedAsked !== "preset" && t.speedAsked !== "item";
- const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : [...(keepSpeed ? ["--speed", String(t.speed)] : []), ...tuningArgvOf(t)])];
+ const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : [...(keepSpeed ? ["--speed", String(t.speed)] : []), ...(t?.tuningAsked === "preset" ? readingArgvOf(t) : tuningArgvOf(t))])];
return { ...r, take: t?.file ?? null, argv };
});
return { items, skipped };
diff --git a/umtool/lib/report/characterTuning.mjs b/umtool/lib/report/characterTuning.mjs
@@ -0,0 +1,168 @@
+// A CHARACTER's ORPHEUS TUNING, AUDITIONED (lane character-tuning, S2 of plans/orpheus-retune.md; umtool/docs/knobs.md,
+// "A character's tuning"): what the preset says it reads with, every number filled (the takes the editor will really
+// use), and the short list of TRIES -- one line read in the character's voice with a tuning and a reading, so two
+// readings compare by ear at one loudness. Read by `umtool cast set|try|stale` and the Voices page.
+//
+// <project>/narration/auditions/<key>.wav|json the try itself: an audition (castAudition.mjs), keyed with its
+// tuning and reading, levelled to -20 LUFS
+// <project>/narration/auditions/tries.json { version: 1, rows: [{ key, character, layer, voice, text, tuning,
+// made?, reading, rel, seconds, lufs, at, jobId? }] }, newest first
+//
+// A try is SCRATCH: it makes no take on any post and writes nothing to the draft or the manifest. Each character (of
+// one layer: the cast's, or this video's own -- the same id may be both) keeps its TRY_KEEP newest; a row that falls
+// off takes its files with it when they are a tuned ask's (an untuned one is the candidate audition's cache, and
+// stays). Every write holds `tries.json.lock` (a terminal's `cast try` beside the page's job), and sweeps a tuned
+// ask's files that no row names once they are ORPHAN_AGE_MS old (a row lost to a broken file, a try that failed
+// after its synthesis). `umtool cast try <p> <character> --clear` empties a character's list.
+//
+// Plain ESM: the CLI runs under bare node.
+import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { ORPHEUS_DEFAULT_TAKES, TTS_TUNING_RANGES, ttsTuningNameOf } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { characterTuningNormal, effectiveCharacterTuning } from "umtool-report-to-video/cast";
+import { REPO_ROOT } from "../paths.mjs";
+import { AUDITION_DIR, isTunedAsk } from "./castAudition.mjs";
+import { withNotesLock } from "../annotations/store.mjs";
+
+/** How many tries a character keeps in a project. */
+export const TRY_KEEP = 12;
+export const TRIES_FILE = `${AUDITION_DIR}/tries.json`;
+/** A tuned ask's files no row names are swept once they are this old (a try still being kept is younger). */
+export const ORPHAN_AGE_MS = 10 * 60 * 1000;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+/**
+ * The editor's `tts.orpheus.takes` (its settings.json, SETTINGS_FILE when set): the takes a read with none of its own
+ * gets. ORPHEUS_DEFAULT_TAKES when the file or the key is not there (or out of range).
+ */
+export async function orpheusTakesSetting(env = process.env) {
+ const file = env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
+ try {
+ const t = JSON.parse(await readFile(file, "utf8"))?.tts?.orpheus?.takes;
+ const r = TTS_TUNING_RANGES.takes;
+ return Number.isInteger(t) && t >= r.min && t <= r.max ? t : ORPHEUS_DEFAULT_TAKES;
+ } catch {
+ return ORPHEUS_DEFAULT_TAKES;
+ }
+}
+
+/**
+ * A tuning as the preset and `--json` say it: `{ tuning, name, effective, takesFrom }` -- `tuning` the character's own
+ * (normalised; null for none), `name` its named starting point or "custom", `effective` every value its reads are
+ * asked with (cast.mjs effectiveCharacterTuning: its takes, else the setting's), `takesFrom` "character" or "setting".
+ */
+export function tuningView(tuning, settingTakes = ORPHEUS_DEFAULT_TAKES) {
+ const t = characterTuningNormal(tuning);
+ return {
+ tuning: Object.keys(t).length ? t : null,
+ name: ttsTuningNameOf(t),
+ effective: effectiveCharacterTuning(t, settingTakes),
+ takesFrom: t.takes !== undefined ? "character" : "setting",
+ };
+}
+
+/** A tuning in words: "lively: temperature 0.75, top_p 0.92, repeat penalty 1.25, takes 3 (the setting's)". */
+export function tuningWords(view) {
+ const e = view.effective;
+ return `${view.name}: temperature ${e.temperature}, top_p ${e.top_p}, repeat penalty ${e.repeat_penalty}, takes ${e.takes}${view.takesFrom === "setting" ? " (the setting's)" : ""}`;
+}
+
+const triesPath = (dir) => path.join(/* turbopackIgnore: true */ dir, ...TRIES_FILE.split("/"));
+
+/** A project's tries, newest first (none: `[]`; a file that does not parse reads as none). */
+export async function readTries(dir) {
+ try {
+ const j = JSON.parse(await readFile(triesPath(dir), "utf8"));
+ return Array.isArray(j?.rows) ? j.rows.filter((r) => isObj(r) && typeof r.key === "string" && typeof r.character === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+async function writeTries(dir, rows) {
+ const file = triesPath(dir);
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = tmpPathFor(file);
+ await writeFile(tmp, `${JSON.stringify({ version: 1, rows }, null, 1)}\n`);
+ await rename(tmp, file);
+}
+
+/** Is a row a character's of one layer (the cast's, or this video's own)? */
+export const rowOf = (r, character, layer = null) => r.character === character && (r.layer ?? null) === (layer ?? null);
+
+const auditionsOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ...AUDITION_DIR.split("/"));
+const KEY_RE = /^[0-9a-f]{20}$/;
+
+/** The files of the rows dropped that no row kept names, when they are a tuned ask's (an untuned key is the candidates' cache). */
+async function sweepDropped(dir, dropped, kept) {
+ const still = new Set(kept.map((r) => r.key));
+ const removed = [];
+ for (const r of dropped) {
+ if (still.has(r.key) || !isTunedAsk({ tuning: r.tuning, reading: r.reading }) || !KEY_RE.test(r.key)) continue;
+ for (const ext of [".wav", ".json"]) await rm(path.join(auditionsOf(dir), `${r.key}${ext}`), { force: true });
+ still.add(r.key);
+ removed.push(r.key);
+ }
+ return removed;
+}
+
+/** Every TUNED ask's files (its record says `asked`) that no row names, ORPHAN_AGE_MS old or more. */
+export async function sweepOrphans(dir, kept, { now = Date.now(), ageMs = ORPHAN_AGE_MS } = {}) {
+ const named = new Set(kept.map((r) => r.key));
+ const removed = [];
+ for (const f of await readdir(auditionsOf(dir)).catch(() => [])) {
+ const key = f.replace(/\.json$/, "");
+ if (!f.endsWith(".json") || !KEY_RE.test(key) || named.has(key)) continue;
+ const meta = await readFile(path.join(auditionsOf(dir), f), "utf8").then(JSON.parse, () => null);
+ if (!isObj(meta?.asked)) continue;
+ const at = Date.parse(String(meta.at ?? ""));
+ if (Number.isFinite(at) && now - at < ageMs) continue;
+ for (const ext of [".wav", ".json"]) await rm(path.join(auditionsOf(dir), `${key}${ext}`), { force: true });
+ removed.push(key);
+ }
+ return removed;
+}
+
+/** `fn(rows)` holding the tries' lock: what it returns is `{ rows, dropped, result }`; the rows written, files swept. */
+async function withTries(dir, fn) {
+ await mkdir(auditionsOf(dir), { recursive: true });
+ return withNotesLock(triesPath(dir), async () => {
+ const { rows, dropped, result } = await fn(await readTries(dir));
+ await writeTries(dir, rows);
+ const removed = [...(await sweepDropped(dir, dropped, rows)), ...(await sweepOrphans(dir, rows))];
+ return { ...result, rows, removed };
+ });
+}
+
+/**
+ * ONE TRY KEPT: `row` first in the list (a row of the same key, character and layer before it is replaced), that
+ * character's rows past TRY_KEEP dropped and their tuned files swept. Returns `{ rows, removed }`.
+ */
+export function addTry(dir, row) {
+ return withTries(dir, (all0) => {
+ const all = all0.filter((r) => !(r.key === row.key && rowOf(r, row.character, row.layer)));
+ const next = [row, ...all];
+ const dropped = next.filter((r) => rowOf(r, row.character, row.layer)).slice(TRY_KEEP);
+ return { rows: next.filter((r) => !dropped.includes(r)), dropped, result: {} };
+ });
+}
+
+/** A character's tries emptied (their tuned files swept). Returns `{ cleared, removed }`. */
+export async function clearTries(dir, character, layer = null) {
+ const r = await withTries(dir, (all) => {
+ const dropped = all.filter((x) => rowOf(x, character, layer));
+ return { rows: all.filter((x) => !rowOf(x, character, layer)), dropped, result: { cleared: dropped.length } };
+ });
+ return { cleared: r.cleared, removed: r.removed };
+}
+
+/** The same ask (voice, text, tuning) as a row? -- the rows "Another reading" counts from. */
+export const sameAsk = (r, { voice, text, tuning }) => r.voice === voice && r.text === text && JSON.stringify(characterTuningNormal(r.tuning)) === JSON.stringify(characterTuningNormal(tuning));
+
+/** The reading after the highest kept for this character (of `layer`) and ask (1 when none is kept: another than the first). */
+export function nextReading(rows, character, ask, layer = null) {
+ const mine = rows.filter((r) => rowOf(r, character, layer) && sameAsk(r, ask)).map((r) => (Number.isInteger(r.reading) ? r.reading : 0));
+ return (mine.length ? Math.max(...mine) : 0) + 1;
+}
diff --git a/umtool/lib/report/characterTuning.test.mjs b/umtool/lib/report/characterTuning.test.mjs
@@ -0,0 +1,421 @@
+// A CHARACTER's ORPHEUS TUNING (lane character-tuning, S2 of plans/orpheus-retune.md): kept on the synthetic preset
+// through the cast's one writer (`umtool cast set` / `cast project <p> set`), normalised, said with every value its
+// reads are asked with; the resolution chain carrying it (a character without one: the entry it always was); a TRY --
+// one line read with a tuning and a reading, scratch, in a short list; the reads made with other settings (stale,
+// never re-made); and THE PIN: keeping a tuning, or trying one, leaves the manifest and every drawn card as they were.
+// No editor: the tts op is a stub. Each test makes its own world (reports root, cast, project, settings): any one runs
+// alone.
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { existsSync } from "node:fs";
+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, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { ORPHEUS_TUNING_NAMED } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { castCommand } from "./castCli.mjs";
+import { castFile, castWrite } from "./castStore.mjs";
+import { auditionKey } from "./castAudition.mjs";
+import { ORPHAN_AGE_MS, TRIES_FILE, TRY_KEEP, addTry, nextReading, readTries, tuningView } from "./characterTuning.mjs";
+import { projectCharacters, resolverFor } from "./castProject.mjs";
+import { effectiveCharacterTuning, presetEntryOf, tuningStale } from "umtool-report-to-video/cast";
+import { readTuningOf, resolvePieceVoice } from "umtool-report-to-video/post-say";
+import { postCardHtml, postItemPlan } from "umtool-report-to-video/post-item";
+
+const BASE = await mkdtemp(path.join(tmpdir(), "umtool-tuning-"));
+after(() => rm(BASE, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+
+const LIVELY = { ...ORPHEUS_TUNING_NAMED.lively };
+const STEADY_KEPT = { temperature: 0.4, top_p: 0.8 }; // Steady as kept: its repeat penalty is the default's
+const MADE = (o = {}) => ({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 4, ...o });
+const LINE = "The teller says the bridge was closed for the whole of the long winter.";
+const TELLER = "invented_teller";
+const OTHER = "invented_other";
+
+const wavOf = async (file, seconds = 1.2) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...VOICE_A, seconds }), { before: 0.2, after: 0.2 })));
+};
+/** The editor's tts op, stubbed: `out` written, the effective tuning reported as the editor reports it (Orpheus). */
+const stubAsk = (asked, settingTakes = 4) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out);
+ return {
+ jobId: `job-${asked.length}`,
+ result: {
+ wav: body.out, engine: body.engine, voice: body.voice, disclosure: `Narration: synthetic voice (${body.engine} · ${body.voice})`,
+ ...(body.engine === "orpheus" ? { tuning: { ...MADE({ takes: settingTakes }), ...(body.tuning ?? {}) }, reading: body.reading ?? 0, seedBase: 1234 + 9973 * (body.reading ?? 0) } : {}),
+ },
+ };
+};
+
+const take = (o) => ({ file: "narration/posts/1/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", seconds: 1.2, script: LINE, ...o });
+const post = (id, handle, o = {}) => ({ type: "post", id: `p-${id}`, post: `tellerx/${id}`, platform: "x", author: handle === TELLER ? "The Teller" : "Another One", handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `${LINE} (${id})`, ...o });
+// "teller" reads p-1 (an Orpheus take made with the defaults), p-2 (a take whose own line asked a tuning), p-3 (a
+// recorded take); "other" reads p-4 in Kokoro.
+const timeline = () => [
+ post("1", TELLER, { narration: { script: LINE, takes: [take({ tuning: MADE(), reading: 0 })], pick: 0 } }),
+ post("2", TELLER, { narration: { script: LINE, takes: [take({ file: "narration/posts/2/take-1.orpheus-tara.wav", tuning: MADE({ temperature: 0.9 }), reading: 0, tuningAsked: true })], pick: 0 } }),
+ post("3", TELLER, { narration: { script: LINE, takes: [{ file: "narration/posts/3/take-1.recorded.wav", engine: "recorded", voice: "operator", seconds: 1.2, script: LINE }], pick: 0 } }),
+ post("4", OTHER, { narration: { script: "Another line.", takes: [{ file: "narration/posts/4/take-1.kokoro-af_heart.wav", engine: "kokoro", voice: "af_heart", seconds: 1, script: "Another line." }], pick: 0 } }),
+];
+
+/**
+ * A WORLD of its own: a reports root (its cast.json), the editor's settings (tts.orpheus.takes: `settingTakes`), the
+ * project "tuning" (its manifest), and -- unless `bare` -- the cast's teller (orpheus:tara) and other (kokoro:af_heart).
+ */
+async function world({ settingTakes = 4, bare = false } = {}) {
+ const root = await mkdtemp(path.join(BASE, "w-"));
+ const settings = path.join(root, "settings.json");
+ await writeFile(settings, JSON.stringify({ tts: { orpheus: { takes: settingTakes } } }));
+ process.env.SETTINGS_FILE = settings;
+ const dir = path.join(root, "tuning");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "tuning", title: "Tuning", render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, timeline: timeline(),
+ }, null, 2));
+ const cast = async (args, extra = {}) => {
+ const lines = [];
+ const code = await castCommand(args, { reportsRoot: root, log: (s) => lines.push(s), err: (s) => lines.push(s), ...extra });
+ return { code, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) };
+ };
+ if (!bare) {
+ assert.equal((await cast(["add", "teller", "--name", "The Teller", "--voice", "orpheus:tara", "--handles", TELLER])).code, 0);
+ assert.equal((await cast(["add", "other", "--name", "Another One", "--voice", "kokoro:af_heart", "--handles", OTHER])).code, 0);
+ }
+ const manifestText = () => readFile(path.join(dir, "video.manifest.json"), "utf8");
+ const BOX = { width: 1080, height: 1350 };
+ const drawn = async () => {
+ const m = JSON.parse(await manifestText());
+ return m.timeline.map((e) => JSON.stringify([postCardHtml(e, BOX), postCardHtml(e, { ...BOX, follow: true }), postItemPlan(e, m.render)]));
+ };
+ const castJson = async () => JSON.parse(await readFile(castFile(root), "utf8"));
+ return { root, dir, cast, manifestText, drawn, castJson };
+}
+
+test("cast set: a tuning on the synthetic preset -- a named starting point, the numbers over it, the defaults kept as none", async () => {
+ const w = await world();
+ let r = await w.cast(["set", "teller", "--json"]);
+ assert.deepEqual(r.json().tuning, { tuning: null, name: "default", effective: { ...MADE() }, takesFrom: "setting" }, "every value its reads are asked with: the setting's takes (4)");
+ r = await w.cast(["set", "teller", "--tuning", "lively", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.synthetic.tuning, LIVELY);
+ assert.equal(r.json().tuning.name, "lively");
+ assert.deepEqual(r.json().tuning.effective, effectiveCharacterTuning(LIVELY, 4));
+ // A number over it: custom; the others kept.
+ r = await w.cast(["set", "teller", "--temperature", "0.8000000001", "--json"]);
+ assert.deepEqual(r.json().character.synthetic.tuning, { ...LIVELY, temperature: 0.8 });
+ assert.equal(r.json().tuning.name, "custom");
+ // `default` takes one field off.
+ r = await w.cast(["set", "teller", "--temperature", "default", "--json"]);
+ assert.deepEqual(r.json().character.synthetic.tuning, { top_p: LIVELY.top_p, repeat_penalty: LIVELY.repeat_penalty });
+ // Takes: 5 is kept.
+ r = await w.cast(["set", "teller", "--chunk-takes", "5", "--json"]);
+ assert.equal(r.json().character.synthetic.tuning.takes, 5);
+ assert.equal(r.json().tuning.takesFrom, "character");
+ // --tuning default puts the sampler's three back and KEEPS the takes (a name covers the sampler only).
+ r = await w.cast(["set", "teller", "--tuning", "default", "--json"]);
+ assert.deepEqual(r.json().character.synthetic.tuning, { takes: 5 });
+ // Takes 3 is Orpheus's default and is NOT kept -- and the preset says the setting's (4) is what is used.
+ r = await w.cast(["set", "teller", "--chunk-takes", "3", "--json"]);
+ assert.equal(r.json().character.synthetic.tuning, undefined);
+ assert.equal(r.json().tuning.effective.takes, 4, "never a number the read would not use");
+ assert.match(r.json().notes[0], /takes 3 is Orpheus's default and is not kept: its reads take the editor's setting \(4\)/);
+ await w.cast(["set", "teller", "--tuning", "steady"]);
+ r = await w.cast(["set", "teller", "--no-tuning", "--json"]);
+ assert.equal("tuning" in r.json().character.synthetic, false);
+ assert.deepEqual(Object.keys((await w.castJson()).characters[0].synthetic), ["voice"], "the file keeps no empty tuning");
+ // Refused in the flag's words, nothing written.
+ const before = await readFile(castFile(w.root), "utf8");
+ for (const [args, re] of [
+ [["--temperature", "9"], /--temperature must be a number from 0\.1 to 1\.5 \(got 9\)/],
+ [["--chunk-takes", "x"], /--chunk-takes must be a whole number from 1 to 6 \(got x\)/],
+ [["--tuning", "loud"], /--tuning is steady, default, lively \(got loud\)/],
+ [["--no-tuning", "--temperature", "0.7"], /--no-tuning drops the whole tuning: not with --tuning, --temperature/],
+ ]) {
+ r = await w.cast(["set", "teller", ...args]);
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.equal(await readFile(castFile(w.root), "utf8"), before);
+ // Undo puts the last one back.
+ await w.cast(["set", "teller", "--tuning", "lively"]);
+ await w.cast(["set", "teller", "--tuning", "steady"]);
+ r = await w.cast(["undo", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual((await w.castJson()).characters[0].synthetic.tuning, LIVELY);
+ // A Kokoro voice keeps it and ignores it (as Orpheus ignores a speed), and says so.
+ r = await w.cast(["set", "other", "--tuning", "steady", "--json"]);
+ assert.match(r.json().notes.join(" "), /kokoro:af_heart has no sampler: its reads ignore the tuning/);
+});
+
+test("the cast's file refuses a tuning that is not a character's, whole -- a null value too (review 1 #13)", async () => {
+ const w = await world();
+ for (const [tuning, re] of [
+ [{ top_k: 40 }, /synthetic\.tuning\.top_k is not a character's tuning field/],
+ [{ temperature: 9 }, /synthetic\.tuning\.temperature must be a number from 0\.1 to 1\.5 \(got 9\)/],
+ [{ temperature: null }, /synthetic\.tuning\.temperature must be a number from 0\.1 to 1\.5 \(got null\)/],
+ [{ temperature: 0.7, takes: null }, /synthetic\.tuning\.takes must be a whole number from 1 to 6 \(got null\)/],
+ [{}, /synthetic\.tuning names no value/],
+ ["warm", /synthetic\.tuning must be/],
+ ]) {
+ await assert.rejects(castWrite(castFile(w.root), (chars) => { chars.find((c) => c.id === "teller").synthetic.tuning = tuning; }), re, JSON.stringify(tuning));
+ }
+});
+
+test("cast project <p> set: the twin for this video's own character; a tuning needs a voice", async () => {
+ const w = await world();
+ let r = await w.cast(["project", "tuning", "add", "visitor", "--name", "A Visitor", "--handles", "invented_visitor", "--tuning", "lively"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /a tuning is its voice's: give the character a voice too/);
+ r = await w.cast(["project", "tuning", "add", "visitor", "--name", "A Visitor", "--voice", "orpheus:leo", "--handles", "invented_visitor", "--tuning", "steady", "--repeat-penalty", "1.3", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.synthetic.tuning, { ...ORPHEUS_TUNING_NAMED.steady, repeat_penalty: 1.3 });
+ r = await w.cast(["project", "tuning", "set", "visitor", "--no-voice", "--json"]);
+ assert.equal(r.json().character.synthetic, undefined, "no voice: no tuning either");
+});
+
+test("THE PIN: a character with no tuning is the layer entry it always was; one with a tuning carries it to the read", () => {
+ assert.deepEqual(presetEntryOf({ id: "a", synthetic: { voice: "orpheus:tara" } }), { voice: "orpheus:tara", character: "a" });
+ assert.deepEqual(presetEntryOf({ id: "a", synthetic: { voice: "kokoro:am_adam", speed: 1.1 } }), { voice: "kokoro:am_adam", speed: 1.1, character: "a" });
+ // Defaults spelled out are no tuning at all.
+ assert.deepEqual(presetEntryOf({ id: "a", synthetic: { voice: "orpheus:tara", tuning: { temperature: 0.55, takes: 3 } } }), { voice: "orpheus:tara", character: "a" });
+ const entry = presetEntryOf({ id: "a", synthetic: { voice: "orpheus:tara", tuning: LIVELY } });
+ assert.deepEqual(entry, { voice: "orpheus:tara", tuning: LIVELY, character: "a" });
+ const o = { cast: { [TELLER]: entry }, narrator: "leo", engine: "orpheus" };
+ assert.deepEqual(resolvePieceVoice({ handle: TELLER, role: "post" }, { ...o, self: TELLER }), { engine: "orpheus", voice: "tara", from: "cast", tuning: LIVELY, character: "a" });
+ // No character: no tuning key anywhere.
+ assert.deepEqual(resolvePieceVoice({ handle: "nobody", role: "post" }, { ...o, self: "nobody" }), { engine: "orpheus", voice: "leo", from: "narrator" });
+ // The line's own beats the character's; an engine without a sampler has none.
+ assert.deepEqual(readTuningOf({ preset: LIVELY, engine: "orpheus" }), { tuning: LIVELY, asked: "preset" });
+ assert.deepEqual(readTuningOf({ flag: { temperature: 0.9 }, preset: LIVELY, engine: "orpheus" }), { tuning: { temperature: 0.9 }, asked: true });
+ assert.equal(readTuningOf({ flag: {}, preset: {}, engine: "orpheus" }), null);
+ assert.equal(readTuningOf({ preset: LIVELY, engine: "kokoro" }), null);
+});
+
+// ---- stale ----------------------------------------------------------------------------------------------------------
+
+const castOf = (tuning, voice = "orpheus:tara") => ({ format: "umtool-cast", version: 2, characters: [{ id: "teller", name: "The Teller", handles: [TELLER], synthetic: { voice, ...(tuning ? { tuning } : {}) } }] });
+const manifestOf = (edit = (tl) => tl) => ({ timeline: edit(timeline()) });
+const staleOf = (m, tuning, settingTakes = 4) => tuningStale(m, resolverFor({ cast: castOf(tuning) }), { settingTakes });
+
+test("stale: a picked Orpheus read made with other settings than its character's tuning now", () => {
+ const m = manifestOf();
+ assert.deepEqual(staleOf(m, null), [], "no tuning: nothing is stale (p-1 was made with the defaults; p-2 asked its own)");
+ // Lively: p-1 only -- p-2's tuning was its line's own, p-3 is recorded, p-4 is another character's Kokoro read.
+ const rows = staleOf(m, LIVELY);
+ assert.deepEqual(rows.map((r) => [r.id, r.character, r.role]), [["p-1", "teller", "post"]]);
+ assert.deepEqual(rows[0].made, MADE());
+ assert.deepEqual(rows[0].want, effectiveCharacterTuning(LIVELY, 4));
+ // Takes: compared only when the character names them (a read with none records the setting's).
+ assert.deepEqual(staleOf(m, { takes: 4 }), [], "4 is what it was made with");
+ assert.deepEqual(staleOf(m, { takes: 5 }).map((r) => r.id), ["p-1"]);
+ // A take made with the character's tuning (tuningAsked "preset") is stale when the character changes, fresh when not.
+ const m2 = manifestOf((tl) => {
+ tl[0].narration.takes[0] = { ...tl[0].narration.takes[0], tuning: MADE(LIVELY), tuningAsked: "preset", reading: 2 };
+ return tl;
+ });
+ assert.deepEqual(staleOf(m2, LIVELY), []);
+ assert.deepEqual(staleOf(m2, STEADY_KEPT).map((r) => [r.id, r.reading]), [["p-1", 2]], "the reading is said, never compared");
+ // An S1 take with no provenance and a sampler value off the defaults was asked by its line: never stale.
+ const m3 = manifestOf((tl) => {
+ tl[0].narration.takes[0] = { ...tl[0].narration.takes[0], tuning: MADE({ top_k: 40 }) };
+ return tl;
+ });
+ assert.deepEqual(staleOf(m3, LIVELY), []);
+ // A read now in ANOTHER voice is drift, not stale.
+ assert.deepEqual(tuningStale(m, resolverFor({ cast: castOf(LIVELY, "orpheus:leah") }), { settingTakes: 4 }), []);
+});
+
+test("stale (review 1 #1): a changed tts.orpheus.takes does not hide a read made with the defaults", () => {
+ // Made with the defaults while the setting was 3 (it records takes 3, says nothing of where its tuning came from);
+ // the setting is 4 now. Its TAKES are the old setting, not its line's ask: it is stale for Lively all the same.
+ const m = manifestOf((tl) => {
+ tl[0].narration.takes[0] = { ...tl[0].narration.takes[0], tuning: MADE({ takes: 3 }) };
+ return tl;
+ });
+ assert.deepEqual(staleOf(m, LIVELY, 3).map((r) => r.id), ["p-1"]);
+ assert.deepEqual(staleOf(m, LIVELY, 4).map((r) => r.id), ["p-1"], "the same at setting 4");
+ assert.deepEqual(staleOf(m, null, 4), [], "a character with no tuning: nothing");
+});
+
+test("stale (review 1 #2): a thread read's part that IS another take answers as that take does", () => {
+ // p-1's picked take is a thread read whose post part is take-1 (made with the character's Lively, tuningAsked
+ // "preset", reading 3); the thread take itself records no tuning.
+ const m = manifestOf((tl) => {
+ const own = take({ tuning: MADE(LIVELY), tuningAsked: "preset", reading: 3 });
+ const thread = { file: "narration/posts/1/take-2.orpheus-thread.wav", engine: "orpheus", voice: "tara+leo", seconds: 3, script: LINE, read: { kind: "thread" }, parts: [{ role: "post", voice: "tara", engine: "orpheus", take: "take-1.orpheus-tara", file: own.file, text: LINE }] };
+ tl[0].narration = { script: LINE, takes: [own, thread], pick: 1 };
+ return tl;
+ });
+ assert.deepEqual(staleOf(m, LIVELY), [], "made with the character's own: fresh");
+ const moved = staleOf(m, STEADY_KEPT);
+ assert.deepEqual(moved.map((r) => [r.id, r.reading, r.thread]), [["p-1", 3, true]], "the character changed: stale, its source take's reading said");
+ assert.deepEqual(moved[0].made, MADE(LIVELY));
+});
+
+test("cast stale and the project's view list the stale reads; listing writes nothing", async () => {
+ const w = await world();
+ await w.cast(["set", "teller", "--tuning", "lively"]);
+ const before = await w.manifestText();
+ const view = projectCharacters(JSON.parse(before), { cast: castOf(LIVELY), settingTakes: 4 });
+ assert.deepEqual(view.characters.find((c) => c.character?.id === "teller").stale.map((d) => d.id), ["p-1"]);
+ assert.deepEqual(view.tuningStale.map((d) => d.id), ["p-1"]);
+ const r = await w.cast(["stale", "tuning", "teller", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([r.json().count, r.json().items], [1, ["p-1"]]);
+ const t = await w.cast(["stale", "tuning"]);
+ assert.match(t.text(), /1 read made with other settings than their character's tuning now \(listed, never re-made\):\n {2}p-1 post \(teller\): made with temperature 0\.55/);
+ assert.equal(await w.manifestText(), before);
+});
+
+// ---- tries --------------------------------------------------------------------------------------------------------
+
+test("the audition key: an untuned ask keeps the key it always had; a tuned one never collides with an untuned text (review 1 #15)", () => {
+ const old = createHash("sha1").update(`orpheus|tara|${LINE}`).digest("hex").slice(0, 20);
+ assert.equal(auditionKey("orpheus", "tara", LINE), old);
+ assert.equal(auditionKey("orpheus", "tara", LINE, { tuning: { temperature: 0.55, takes: 3 }, reading: 0 }), old, "the defaults spelled out are no tuning");
+ const lively = auditionKey("orpheus", "tara", LINE, { tuning: LIVELY });
+ assert.notEqual(lively, old);
+ assert.notEqual(auditionKey("orpheus", "tara", LINE, { tuning: LIVELY, reading: 1 }), lively);
+ // An untuned text that spells a tuned key's old tail is another key.
+ assert.notEqual(auditionKey("orpheus", "tara", "a", { reading: 1 }), auditionKey("orpheus", "tara", "a|{}|1"));
+ assert.notEqual(auditionKey("orpheus", "tara", "a", { tuning: LIVELY }), auditionKey("orpheus", "tara", `a|${JSON.stringify(LIVELY)}|0`));
+});
+
+test("cast try: a line read with a tuning and a reading -- scratch, a short list, the manifest and every drawn card untouched", async () => {
+ const w = await world();
+ const before = await w.manifestText();
+ const cards = await w.drawn();
+ await w.cast(["set", "teller", "--tuning", "lively"]);
+ // The list before any try: none, and the line the page prefills (its own first line of enough words).
+ let r = await w.cast(["try", "tuning", "teller", "--list", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().tries, []);
+ assert.deepEqual(r.json().line, { text: LINE, from: "item:p-1" });
+ assert.equal(r.json().character.layer, "cast");
+ assert.equal(r.json().character.tuning.name, "lively");
+ const asked = [];
+ const ask = stubAsk(asked);
+ // Its own tuning (no flags): asked with it, the first reading.
+ r = await w.cast(["try", "tuning", "teller", "--json"], { ask, lanes: null });
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(asked[0].tuning, LIVELY);
+ assert.equal("reading" in asked[0], false);
+ assert.equal(r.json().try.reading, 0);
+ assert.deepEqual(r.json().try.made, MADE(LIVELY), "what the editor says it was made with");
+ assert.ok(existsSync(path.join(w.dir, r.json().try.rel)));
+ // Another reading (review 1 #3): counted from what is kept -- the line as it is SAID (whitespace collapsed), not as typed.
+ r = await w.cast(["try", "tuning", "teller", "--text", LINE.replace(/ /g, " "), "--another", "--json"], { ask, lanes: null });
+ assert.equal(asked[1].reading, 1);
+ r = await w.cast(["try", "tuning", "teller", "--text", `${LINE} `, "--another", "--json"], { ask, lanes: null });
+ assert.equal(asked[2].reading, 2, "the next after the highest kept");
+ // Steady over it, typed text: its own key, its own list row (Steady's repeat penalty is the default's: not asked).
+ r = await w.cast(["try", "tuning", "teller", "--tuning", "steady", "--text", "A line typed in.", "--json"], { ask, lanes: null });
+ assert.deepEqual(asked[3].tuning, STEADY_KEPT);
+ r = await w.cast(["try", "tuning", "teller", "--list", "--json"]);
+ assert.deepEqual(r.json().tries.map((x) => [x.text === LINE, x.reading, x.layer]), [[false, 0, "cast"], [true, 2, "cast"], [true, 1, "cast"], [true, 0, "cast"]], "newest first");
+ assert.equal(nextReading(r.json().tries, "teller", { voice: "orpheus:tara", text: LINE, tuning: LIVELY }, "cast"), 3);
+ // The defaults tried: no tuning key, no reading key -- the ask an audition always made.
+ await w.cast(["try", "tuning", "teller", "--tuning", "default", "--json"], { ask, lanes: null });
+ assert.deepEqual(Object.keys(asked[4]).sort(), ["engine", "out", "text", "voice"]);
+ // Refused, each in a sentence (review 1 #12): out of range, both readings, --no-tuning, a Kokoro voice given a tuning.
+ for (const [who, args, re] of [
+ ["teller", ["--reading", "-1"], /--reading must be a whole number from 0 to 99999/],
+ ["teller", ["--reading", "2", "--another"], /--reading N or --another, not both/],
+ ["teller", ["--no-tuning"], /cast try reads with a tuning: --tuning default for the defaults/],
+ ["other", ["--tuning", "lively"], /a tuning and a reading are Orpheus's: kokoro:af_heart reads the same every time/],
+ ]) {
+ r = await w.cast(["try", "tuning", who, ...args], { ask, lanes: null });
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.equal(asked.length, 5, "a refusal asks nothing");
+ // THE PIN: no take, no script, nothing in the manifest; every card drawn as it was.
+ assert.equal(await w.manifestText(), before, "the manifest is byte-identical");
+ assert.deepEqual(await w.drawn(), cards, "every card's drawn text and structure are byte-identical");
+ assert.equal(existsSync(path.join(w.dir, "narration", "posts")), false, "no take file made");
+});
+
+test("the tries are a short list: the newest TRY_KEEP per character, a dropped tuned try's files swept; --clear keeps the untuned cache (review 1 #10)", async () => {
+ const w = await world();
+ await w.cast(["set", "teller", "--tuning", "lively"]);
+ const asked = [];
+ const ask = stubAsk(asked);
+ // An untuned try (the candidates' cache key): its file must survive every sweep.
+ let r = await w.cast(["try", "tuning", "teller", "--tuning", "default", "--text", "Short.", "--json"], { ask, lanes: null });
+ const untuned = r.json().try.key;
+ assert.equal(untuned, auditionKey("orpheus", "tara", "Short."));
+ for (let n = 0; n <= TRY_KEEP; n += 1) {
+ r = await w.cast(["try", "tuning", "teller", "--reading", String(n), "--text", "Short.", "--json"], { ask, lanes: null });
+ assert.equal(r.code, 0, r.text());
+ }
+ const list = (await w.cast(["try", "tuning", "teller", "--list", "--json"])).json().tries;
+ assert.equal(list.length, TRY_KEEP);
+ assert.deepEqual(list.map((x) => x.reading), Array.from({ length: TRY_KEEP }, (_, i) => TRY_KEEP - i));
+ const auditions = path.join(w.dir, "narration", "auditions");
+ assert.ok(!existsSync(path.join(auditions, `${auditionKey("orpheus", "tara", "Short.", { tuning: LIVELY, reading: 0 })}.wav`)), "the dropped tuned try's file is swept");
+ assert.ok(existsSync(path.join(auditions, `${untuned}.wav`)), "the dropped untuned try's file stays (the candidates' cache)");
+ r = await w.cast(["try", "tuning", "teller", "--clear", "--json"]);
+ assert.equal(r.json().cleared, TRY_KEEP);
+ assert.deepEqual((await w.cast(["try", "tuning", "teller", "--list", "--json"])).json().tries, []);
+ const left = await readdir(auditions);
+ assert.ok(!left.includes(`${list[0].key}.wav`), "a cleared tuned try's file is swept");
+ assert.ok(left.includes(`${untuned}.wav`), "--clear leaves the untuned file");
+});
+
+test("cast try --scope (review 1 #8): the cast's character and this video's own of the same id are kept apart", async () => {
+ const w = await world();
+ await w.cast(["set", "teller", "--tuning", "lively"]);
+ await w.cast(["project", "tuning", "add", "teller", "--name", "The Teller Here", "--voice", "orpheus:leo", "--handles", "invented_teller_here", "--tuning", "steady"]);
+ let r = await w.cast(["try", "tuning", "teller", "--scope", "cast", "--list", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([r.json().character.layer, r.json().character.voice, r.json().character.tuning.name], ["cast", "orpheus:tara", "lively"]);
+ r = await w.cast(["try", "tuning", "teller", "--scope", "project", "--list", "--json"]);
+ assert.deepEqual([r.json().character.layer, r.json().character.voice, r.json().character.tuning.name], ["project", "orpheus:leo", "steady"]);
+ r = await w.cast(["try", "tuning", "teller", "--list", "--json"]);
+ assert.equal(r.json().character.layer, "project", "no scope: this video's own first");
+ const asked = [];
+ r = await w.cast(["try", "tuning", "teller", "--scope", "cast", "--text", "A line.", "--json"], { ask: stubAsk(asked), lanes: null });
+ assert.equal(r.code, 0, r.text());
+ assert.equal(asked[0].voice, "tara");
+ assert.deepEqual(asked[0].tuning, LIVELY);
+ assert.equal((await w.cast(["try", "tuning", "teller", "--scope", "cast", "--list", "--json"])).json().tries.length, 1);
+ assert.equal((await w.cast(["try", "tuning", "teller", "--scope", "project", "--list", "--json"])).json().tries.length, 0, "the cast's try is not this video's character's");
+ r = await w.cast(["try", "tuning", "teller", "--scope", "everywhere"]);
+ assert.match(r.text(), /--scope is cast or project \(got everywhere\)/);
+});
+
+test("the tries' writes hold a lock (review 1 #14): writes at once all land; a tuned file no row names is swept once old", async () => {
+ const w = await world({ bare: true });
+ const row = (key, reading) => ({ key, character: "teller", layer: "cast", voice: "orpheus:tara", text: "x", tuning: LIVELY, reading, rel: `narration/auditions/${key}.wav`, at: new Date().toISOString() });
+ await Promise.all([addTry(w.dir, row("a".repeat(20), 0)), addTry(w.dir, row("b".repeat(20), 1)), addTry(w.dir, row("c".repeat(20), 2))]);
+ assert.deepEqual((await readTries(w.dir)).map((r) => r.key).sort(), ["a", "b", "c"].map((c) => c.repeat(20)));
+ // Orphans: a tuned ask's files no row names -- swept once ORPHAN_AGE_MS old; a young one (a try still being kept)
+ // and an untuned candidate's stay. A tries.json that does not parse loses its rows; the sweep tidies their files.
+ const auditions = path.join(w.dir, "narration", "auditions");
+ const meta = async (key, o) => {
+ await writeFile(path.join(auditions, `${key}.json`), JSON.stringify({ key, engine: "orpheus", voice: "tara", text: "x", ...o }));
+ await writeFile(path.join(auditions, `${key}.wav`), "RIFF");
+ };
+ const old = new Date(Date.now() - ORPHAN_AGE_MS - 60_000).toISOString();
+ await meta("d".repeat(20), { at: old, asked: { tuning: LIVELY, reading: 0 } });
+ await meta("e".repeat(20), { at: new Date().toISOString(), asked: { tuning: LIVELY, reading: 1 } });
+ await meta("f".repeat(20), { at: old });
+ await writeFile(path.join(w.dir, ...TRIES_FILE.split("/")), "{ not json");
+ const r = await addTry(w.dir, row("9".repeat(20), 0));
+ assert.deepEqual(r.removed, ["d".repeat(20)]);
+ const left = await readdir(auditions);
+ for (const k of ["e", "f"]) assert.ok(left.includes(`${k.repeat(20)}.wav`), `${k}: kept`);
+ assert.ok(!left.includes(`${"d".repeat(20)}.wav`));
+ assert.ok(!left.some((f) => f.endsWith(".lock")), "the lock is let go");
+});
+
+test("tuningView: the takes the editor will use, said", () => {
+ assert.deepEqual(tuningView(null, 3), { tuning: null, name: "default", effective: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, takesFrom: "setting" });
+ assert.equal(tuningView({ takes: 3 }, 5).effective.takes, 5, "takes 3 is not kept: the setting's");
+ assert.equal(tuningView({ takes: 2 }, 5).effective.takes, 2);
+});
diff --git a/umtool/lib/report/characterTuningWiring.test.mjs b/umtool/lib/report/characterTuningWiring.test.mjs
@@ -0,0 +1,215 @@
+// A CHARACTER's TUNING REACHES ITS READS (lane character-tuning, the wiring after S3): a single post's take
+// (makeTake), a thread read and a screen line (postThreadRead.mjs threadTake) are asked with the character's Orpheus
+// tuning when their line asks none of its own, and record `tuningAsked: "preset"`; a line's own tuning beats it
+// (`true`). THE PIN: a character WITHOUT a tuning asks, keys and records exactly as main did (5958688a0) -- the
+// hashes below were taken from main's code before a line of this wiring was written. No editor (a stub tts);
+// temp dirs; invented people.
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+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_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { castPresetMap } from "umtool-report-to-video/cast";
+import { makeTake } from "./postNarrationCli.mjs";
+import { threadTake } from "./postThreadRead.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-tuning-wiring-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+const LIVELY = { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 };
+const wavOf = async (file, seconds = 0.6) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...VOICE_B, seconds }), { before: 0.1, after: 0.1 })));
+};
+const stubAsk = (asked) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out);
+ return {
+ jobId: `job-${asked.length}`,
+ result: { wav: body.out, engine: body.engine, voice: body.voice, ...(body.engine === "orpheus" ? { tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...(body.tuning ?? {}) }, reading: body.reading ?? 0 } : {}) },
+ };
+};
+const NO_RED = { terms: [], markup: {}, slurs: null };
+const IMG = { src: "posts-media/ferry-x/7/7_1.png", kind: "image", width: 900, height: 1400 };
+const ITEM = {
+ type: "post", id: "p-7", post: "ferry-x/7", platform: "x", author: "Ferry Teller", handle: "invented_ferry", date: "2026-10-02T10:00:00.000Z",
+ text: "Here is what they sent.", media: [IMG], narration: { script: "Here is what they sent." },
+ screens: [{ id: "s1", media: 0, kind: "dm", read: "all", lines: [{ who: "invented_river", text: "Are the tolls going up?" }, { who: "invented_ferry", text: "Not this year." }] }],
+};
+/** The cast: the item's author (orpheus:tara) and the screen's other speaker (orpheus:leo), each with `tuning` when given. */
+const castDoc = (ferry = null, river = null) => ({
+ format: "umtool-cast", version: 2, characters: [
+ { id: "ferry", name: "Ferry Teller", handles: ["invented_ferry"], synthetic: { voice: "orpheus:tara", ...(ferry ? { tuning: ferry } : {}) } },
+ { id: "river", name: "River Talk", handles: ["invented_river"], synthetic: { voice: "orpheus:leo", ...(river ? { tuning: river } : {}) } },
+ ],
+});
+
+async function project(name, cast) {
+ const root = path.join(ROOT, name);
+ const dir = path.join(root, "p");
+ await mkdir(path.join(dir, "narration"), { recursive: true });
+ await mkdir(path.join(root, ".umtool"), { recursive: true });
+ await writeFile(path.join(root, ".umtool", "cast.json"), JSON.stringify(cast, null, 1));
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: name, title: name, provenance: { channelsDir: "../channels", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "orpheus", voice: "zac" } }, timeline: [ITEM],
+ }, null, 2));
+ return { id: name, dir };
+}
+const read = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const sha = (v) => createHash("sha1").update(JSON.stringify(v)).digest("hex");
+/** A take as the pin compares it: everything but its time and job. */
+const stable = (t) => {
+ const { at: _a, jobId: _j, ...rest } = t;
+ return { ...rest, ...(Array.isArray(rest.parts) ? { parts: rest.parts.map(({ at: _pa, jobId: _pj, ...p }) => p) } : {}) };
+};
+const bodies = (asked, dir) => asked.map((b) => ({ ...b, out: path.relative(dir, b.out) }));
+const layersOf = (cast) => ({ map: {}, cast: castPresetMap(cast), item: null, names: {} });
+
+/** A single post's take of p-7, and its thread read with the screen (two of its pieces another character's). */
+async function readsOf(name, cast, { tuning = null, tuned = {} } = {}) {
+ const p = await project(name, cast);
+ const asked = [];
+ const one = await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED, ...(tuning ? { tuning } : {}) });
+ const single = asked.splice(0);
+ const thread = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, ...layersOf(cast), tuned });
+ return { p, single, take: one.take, threadAsks: asked, thread };
+}
+
+// Taken on main's code (5958688a0, merged as 8824428b1) before the wiring: a character with NO tuning.
+const MAIN = {
+ single: "9f675482a1264083457304cfdb409dcdc35774db",
+ take: "923bcf133ac164c200e898c18656c2dda2ae2075",
+ threadAsks: "126f1f4da6c72d2605b0ea15cf6399938608cd83",
+ threadTake: "6b3b40cf343afd894f348c40a672b3d67d190938",
+ keys: "FAKE-TEST-VALUE",
+};
+
+test("THE PIN: a character with no tuning -- the post's take, the thread read and its screen lines ask, key and record as main did", async () => {
+ const r = await readsOf("pin", castDoc());
+ const got = {
+ single: sha(bodies(r.single, r.p.dir)),
+ take: sha(stable(r.take)),
+ threadAsks: sha(bodies(r.threadAsks, r.p.dir)),
+ threadTake: sha(stable(r.thread.take)),
+ keys: sha(r.thread.parts.map((x) => x.key)),
+ };
+ if (process.env.PIN_PRINT) console.log(JSON.stringify(got, null, 2));
+ assert.deepEqual(got, MAIN);
+});
+
+const STEADY = { temperature: 0.4, top_p: 0.8 };
+
+test("a post's take: the character's tuning asked and recorded as \"preset\"; the line's own beats it, field by field", async () => {
+ const r = await readsOf("single", castDoc(LIVELY));
+ assert.deepEqual(r.single[0].tuning, LIVELY);
+ assert.equal(r.take.tuningAsked, "preset");
+ assert.deepEqual(r.take.tuning, { temperature: 0.75, top_p: 0.92, top_k: 50, min_p: 0, repeat_penalty: 1.25, takes: 3 });
+ // The line's own sampler value: asked over the character's, recorded as its own.
+ const p = await project("single-own", castDoc(LIVELY));
+ const asked = [];
+ let t = (await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED, tuning: { temperature: 0.9 } })).take;
+ assert.deepEqual(asked[0].tuning, { ...LIVELY, temperature: 0.9 });
+ assert.equal(t.tuningAsked, true);
+ // Only its takes: the character's sampler kept, still the character's.
+ t = (await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED, tuning: { takes: 5 } })).take;
+ assert.deepEqual(asked[1].tuning, { ...LIVELY, takes: 5 });
+ assert.equal(t.tuningAsked, "preset");
+ // A Kokoro voice is asked none of the character's (no sampler); the take records none.
+ const k = await project("single-kokoro", { ...castDoc(LIVELY), characters: [{ ...castDoc(LIVELY).characters[0], synthetic: { voice: "kokoro:af_heart", tuning: LIVELY } }, castDoc().characters[1]] });
+ const ka = [];
+ t = (await makeTake(k, (await read(k)).timeline[0], { ask: stubAsk(ka), redaction: NO_RED })).take;
+ assert.equal("tuning" in ka[0], false);
+ assert.equal(t.tuningAsked, undefined);
+ // The take validates (the writer refused nothing): it is the item's now.
+ assert.equal((await read(p)).timeline[0].narration.takes.at(-1).tuningAsked, "preset");
+});
+
+test("a thread read and its screen lines: each piece asked its own character's tuning; the read's own beats it; read.tuned keeps only the read's", async () => {
+ const r = await readsOf("thread", castDoc(LIVELY, STEADY));
+ // Post piece and the author's own line: Lively; the other speaker's line: Steady (repeat penalty the default's: not asked).
+ const byText = Object.fromEntries(r.threadAsks.map((b) => [b.text, b.tuning]));
+ assert.deepEqual(byText["Here is what they sent."], LIVELY);
+ assert.deepEqual(byText["Not this year."], LIVELY);
+ assert.deepEqual(byText["Are the tolls going up?"], STEADY);
+ const parts = r.thread.take.parts;
+ assert.ok(parts.every((x) => x.tuningAsked === "preset"), JSON.stringify(parts.map((x) => [x.role, x.tuningAsked])));
+ assert.equal(r.thread.take.read.tuned, undefined, "a character's tuning is not the read's: a later read asks the character's as it is then");
+ // The keys: a tuned part is another file than the untuned one.
+ const pin = await readsOf("thread-pin", castDoc());
+ assert.notDeepEqual(r.thread.parts.map((x) => x.key), pin.thread.parts.map((x) => x.key));
+ // One line's own tuning (the Tune, --for): that piece's, asked over the character's and recorded as the read's.
+ const p = await project("thread-own", castDoc(LIVELY, STEADY));
+ const asked = [];
+ const own = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, ...layersOf(castDoc(LIVELY, STEADY)), tuned: { "screen:s1:0": { tuning: { temperature: 0.9 } } } });
+ const line = own.take.parts.find((x) => x.role === "screen:s1:0");
+ assert.deepEqual([line.tuning, line.tuningAsked], [{ ...STEADY, temperature: 0.9 }, true]);
+ // read.tuned keeps the read's OWN values as asked (review 2 #9): a later read lays them over the character's then.
+ assert.deepEqual(own.take.read.tuned["screen:s1:0"].tuning, { temperature: 0.9 });
+ assert.equal(own.take.parts.find((x) => x.role === "post").tuningAsked, "preset");
+});
+
+test("stale over real takes: the character's tuning changed -- its post take, its thread pieces and its screen line; the line's own never", async () => {
+ const { tuningStale } = await import("umtool-report-to-video/cast");
+ const { resolverFor } = await import("./castProject.mjs");
+ const r = await readsOf("stale", castDoc(LIVELY, STEADY));
+ const m = await read(r.p);
+ // The thread read is the playing take (picked last). The character as it was: nothing stale.
+ assert.deepEqual(tuningStale(m, resolverFor({ cast: castDoc(LIVELY, STEADY) }), { settingTakes: 3 }), []);
+ // Ferry is Steady now: his post piece and his own screen line are stale; the other speaker's line is not.
+ const rows = tuningStale(m, resolverFor({ cast: castDoc(STEADY, STEADY) }), { settingTakes: 3 });
+ assert.deepEqual(rows.map((x) => [x.role, x.character]).sort(), [["post", "ferry"], ["screen:s1:1", "ferry"]]);
+ // The single post take (not playing) is not counted: only what plays is.
+ const m2 = { ...m, timeline: m.timeline.map((e) => ({ ...e, narration: { ...e.narration, pick: 0 } })) };
+ assert.deepEqual(tuningStale(m2, resolverFor({ cast: castDoc(STEADY, STEADY) }), { settingTakes: 3 }).map((x) => x.role), ["post"]);
+ // A line asked its own tuning: never stale, whatever the character does.
+ const p = await project("stale-own", castDoc(LIVELY, STEADY));
+ await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk([]), lanes: null, ...layersOf(castDoc(LIVELY, STEADY)), tuned: { "screen:s1:1": { tuning: { temperature: 0.9 } } } });
+ const m3 = await read(p);
+ assert.deepEqual(tuningStale(m3, resolverFor({ cast: castDoc(STEADY, STEADY) }), { settingTakes: 3 }).map((x) => x.role), ["post"]);
+});
+
+test("rereadPlan: a take whose tuning was its character's is re-read with the character's as it is then (its reading kept, no tuning flags)", async () => {
+ const { rereadPlan } = await import("./castProject.mjs");
+ const made = (o) => ({ temperature: 0.75, top_p: 0.92, top_k: 50, min_p: 0, repeat_penalty: 1.25, takes: 3, ...o });
+ const m = { timeline: [
+ { type: "post", id: "p-1", handle: "x", narration: { takes: [{ file: "a.wav", engine: "orpheus", voice: "zac", tuning: made(), tuningAsked: "preset", reading: 2 }], pick: 0 } },
+ { type: "post", id: "p-2", handle: "x", narration: { takes: [{ file: "b.wav", engine: "orpheus", voice: "zac", tuning: made({ temperature: 0.9 }), tuningAsked: true }], pick: 0 } },
+ ] };
+ const drift = (id) => ({ id, handle: "x", role: "post", reads: "orpheus:zac", want: "orpheus:leah", kind: "tts", thread: false });
+ const plan = rereadPlan("p", m, [drift("p-1"), drift("p-2")], ["x"]);
+ assert.deepEqual(plan.items.map((x) => x.argv.slice(4)), [
+ ["--take", "--reading", "2"],
+ ["--take", "--temperature", "0.9", "--top-p", "0.92", "--repeat-penalty", "1.25", "--chunk-takes", "3"],
+ ]);
+});
+
+test("review 2 #2: a thread piece's ownership is decided from the values AS ASKED -- an explicit default over a character's is the read's own", async () => {
+ const p = await project("thread-explicit", castDoc(LIVELY, STEADY));
+ const asked = [];
+ const r = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, ...layersOf(castDoc(LIVELY, STEADY)), tuned: { post: { tuning: { temperature: 0.55 } }, "screen:s1:0": { tuning: { temperature: 0.55, top_p: 0.85, repeat_penalty: 1.2 } } } });
+ const post = r.take.parts.find((x) => x.role === "post");
+ // temperature 0.55 over Lively: read with Lively's top_p and repeat penalty and the default temperature -- the read's own.
+ assert.deepEqual([post.tuning, post.tuningAsked], [{ top_p: 0.92, repeat_penalty: 1.25 }, true]);
+ assert.deepEqual(r.take.read.tuned.post.tuning, { temperature: 0.55 });
+ // All three defaults over Steady: read with the defaults (nothing left to key), still the read's own.
+ const line = r.take.parts.find((x) => x.role === "screen:s1:0");
+ assert.deepEqual([line.tuning, line.tuningAsked], [undefined, true]);
+ assert.deepEqual(r.take.read.tuned["screen:s1:0"].tuning, { temperature: 0.55, top_p: 0.85, repeat_penalty: 1.2 });
+ // Neither is stale when the characters change: they are the read's own.
+ const { tuningStale } = await import("umtool-report-to-video/cast");
+ const { resolverFor } = await import("./castProject.mjs");
+ const roles = tuningStale(await read(p), resolverFor({ cast: castDoc(STEADY, LIVELY) }), { settingTakes: 3 }).map((x) => x.role);
+ assert.ok(!roles.includes("post") && !roles.includes("screen:s1:0"), JSON.stringify(roles));
+});
+
+test("review 2 #9: a thread read's own takes over a character's tuning are kept in read.tuned (the sampler still the character's)", async () => {
+ const p = await project("thread-takes", castDoc(LIVELY));
+ const r = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk([]), lanes: null, ...layersOf(castDoc(LIVELY)), tuned: { post: { tuning: { takes: 5 } } } });
+ const post = r.take.parts.find((x) => x.role === "post");
+ assert.deepEqual([post.tuning, post.tuningAsked], [{ ...LIVELY, takes: 5 }, "preset"]);
+ assert.deepEqual(r.take.read.tuned.post.tuning, { takes: 5 });
+});
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -403,9 +403,17 @@ export async function makeTake(project, e, { script = null, note = null, engine
const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {});
const said = spokenRead(words, e, red);
// Its tuning and reading (--reading, --temperature, …): sent only when asked -- an ask without them is the one it always was.
+ // ITS CHARACTER's TUNING (lane character-tuning): the synthetic preset's that answered for the voice, asked when the
+ // line asks none of its own (the line's beats it; an engine with no sampler is asked none of the character's). A
+ // character with no tuning: the ask, and the take, as they always were.
+ // Field by field: the line's own values over the character's (post-say.mjs tuningAskOf, the thread read's rule too).
+ const { tuningAskOf } = await import("umtool-report-to-video/post-say");
+ const ta = tuningAskOf({ own: tuning, preset: said0.tuning ?? null, engine: eng });
+ const asked = ta.tuning;
+ const tuningAsked = ta.asked;
const ttsBody = (text) => ({
text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}),
- ...(tuning && Object.keys(tuning).length ? { tuning } : {}), ...(reading !== null ? { reading } : {}),
+ ...(asked ? { tuning: asked } : {}), ...(reading !== null ? { reading } : {}),
});
let { jobId, result } = await askTts(ttsBody(said.text), { ...(editor ? { editor } : {}), emit });
if (result?.note) emit("note", { message: `${e.id}: ${result.note}` });
@@ -454,6 +462,8 @@ export async function makeTake(project, e, { script = null, note = null, engine
// What it was made with, as the editor's result says it (Orpheus: every tuning value and the reading), so it can be
// made again exactly; an engine without a sampler reports neither.
...tunedOfResult(result),
+ // Where that tuning came from: its line's own (true) or its character's ("preset": stale when that changes).
+ ...(tuningAsked ? { tuningAsked } : {}),
// What its audio does with the slurs the script holds (post-slurs.mjs), and its words when timed for a beep.
...(slurs ? { slurs } : {}), ...(timed ? { words: timed } : {}),
// The pronunciation entries it said (post-say.mjs; `umtool posts say <p> stale` reads them).
diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs
@@ -62,7 +62,7 @@ import { chosenLineTakes, chronoPieces, lineTakesOf } from "umtool-report-to-vid
import { cardText, parentsOf, saysShownDraft, shownDraftOf } from "umtool-report-to-video/post-item";
import { planContext } from "umtool-report-to-video/post-conversation";
import { spokenRead, termsFor } from "umtool-report-to-video/post-redact";
-import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say";
+import { readSpeedOf, resolvePieceVoice, tuningAskOf } from "umtool-report-to-video/post-say";
import { SCREEN_LINE_GAP, parseScreenRole, screenWho, screensOf, shapeSpans } from "umtool-report-to-video/post-screens";
import { readManifest } from "../projects/report.mjs";
import { ORPHEUS_DEFAULT_TAKES, TTS_TUNING_FIELDS, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
@@ -75,6 +75,8 @@ const r3 = (v) => Math.round(v * 1000) / 1000;
const str = (v) => (typeof v === "string" ? v : "");
const norm = (t) => str(t).replace(/\s+/g, " ").trim();
const isTuneObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+/** A piece's character's Orpheus tuning (resolvePieceVoice's `tuning`), held for the tuning pass below: `{}` for none. */
+const presetTuningOf = (v) => (v?.engine === "orpheus" && isTuneObj(v.tuning) && Object.keys(v.tuning).length ? { presetTuning: v.tuning } : {});
/** The project's parts cache (relative to its folder). */
export const PARTS_CACHE = "narration/parts-cache";
@@ -301,7 +303,7 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i
}
const v = resolvePieceVoice({ handle, role: sw.self ? "post" : p.role }, { map, cast, item, overrides, self: str(e.handle), voice: null, narrator, engine: eng });
const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: sw.self ? e.narration?.speed ?? null : null, engine: v.engine });
- pieces.push({ role: p.role, handle, who: p.who, speaker: str(p.who), date: null, line: written, 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, ...(said.anonymised ? { anonymised: said.anonymised } : {}) });
+ pieces.push({ role: p.role, handle, who: p.who, speaker: str(p.who), date: null, line: written, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), ...presetTuningOf(v), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) });
continue;
}
const written = p.role === "post" ? own || script || "" : draftScript(p.text).script;
@@ -316,7 +318,7 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i
}
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, ...(said.anonymised ? { anonymised: said.anonymised } : {}) });
+ 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 } : {}), ...presetTuningOf(v), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) });
}
if (!fromRead && !pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`);
if (!pieces.length) throw new ThreadReadError(`${e.id} has nothing to read (its screen ${fromRead?.id ?? ""} reads no line)`);
@@ -334,15 +336,28 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i
// EACH SYNTHESIZED PIECE's READING AND TUNING (lane line-rerun): the one asked for its role (`tuned[role]`), else
// the whole read's (`tuned["*"]`), else the one the playing read gave it while it says the same words (`inherit`,
// posts screen read's) -- a reading "next" one past the highest its words were read at.
+ // ITS CHARACTER's TUNING (lane character-tuning): a piece whose read asks no tuning of its own is asked its
+ // character's (the synthetic preset's that answered for its voice: `presetTuning`), and says so (`tuningAsked`:
+ // "preset"; its own: true). A character with no tuning: the piece as it always was.
for (const pc of pieces) {
+ const preset = pc.presetTuning ?? null;
+ delete pc.presetTuning;
if (pc.take) continue;
const kept = isTuneObj(inherit?.[pc.role]) && norm(inherit[pc.role].said) === norm(pc.text) ? inherit[pc.role] : null;
const ask = tuned?.[pc.role] ?? tuned?.["*"] ?? kept;
+ // Field by field: the read's own values AS ASKED over the character's (post-say.mjs tuningAskOf: makeTake's rule
+ // -- an explicit default is the read's own); the tuning asked and keyed is then normalised (S3's key rule).
+ const ta = tuningAskOf({ own: isTuneObj(ask) && isTuneObj(ask.tuning) ? ask.tuning : null, preset, engine: pc.engine ?? "orpheus" });
+ const t = ta.tuning ? tuningOf(ta.tuning) : null;
+ if (t) pc.tuning = t;
+ // (An explicit default over a character's tuning is the read's own even when nothing is left to key: said so.)
+ if (ta.asked && (t || (ta.asked === true && preset))) pc.tuningAsked = ta.asked;
+ // The read's own values as asked (its takes too) over a character's: what `read.tuned` keeps, so a later read asks
+ // them again. With no character tuning, S3's record as it was (the tuning asked).
+ if (ta.own && preset) pc.ownTuning = ta.own;
if (!isTuneObj(ask)) continue;
const reading = ask.reading === "next" ? nextPartReading(e, pc.role, pc.text) : Number.isInteger(ask.reading) ? ask.reading : 0;
- const tuning = tuningOf(ask.tuning);
if (reading > 0) pc.reading = reading;
- if (tuning) pc.tuning = tuning;
}
const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()];
const states = pieces.map((p) => p.slurs).filter(Boolean);
@@ -453,7 +468,9 @@ export function readParts(plan) {
if (pc.take) return [{ piece, para: 0, role: pc.role, voice: pc.voice, text: pc.text, file: pc.take.file, take: pc.take.id, key: null, ...line }];
const eng = pc.engine ?? plan.engine;
const tune = { ...(pc.reading ? { reading: pc.reading } : {}), ...(pc.tuning ? { tuning: pc.tuning } : {}) };
- return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), ...tune, text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null, tune), ...line }));
+ // Where its tuning came from (not in its key: the same tuning is the same audio, whoever asked it).
+ const from = pc.tuningAsked ? { tuningAsked: pc.tuningAsked } : {};
+ return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), ...tune, ...from, text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null, tune), ...line }));
});
}
@@ -475,7 +492,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : `
t += gap;
const s = Number(seconds[i]);
// A part from a take (--post-take) says which (`take`: its id); a synthesized one its parts-cache file and voice.
- const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, ...(typeof p.line === "string" ? { line: p.line, speaker: str(p.speaker) } : {}), voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), ...(p.reading ? { reading: p.reading } : {}), ...(p.tuning ? { tuning: p.tuning } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), start: r3(t), seconds: r3(s), gapBefore: gap };
+ const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, ...(typeof p.line === "string" ? { line: p.line, speaker: str(p.speaker) } : {}), voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), ...(p.reading ? { reading: p.reading } : {}), ...(p.tuning ? { tuning: p.tuning } : {}), ...(p.tuningAsked ? { tuningAsked: p.tuningAsked } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), start: r3(t), seconds: r3(s), gapBefore: gap };
t += s;
return row;
});
@@ -486,7 +503,11 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : `
export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null, postTake = null, screens = true, lineTakes = {}, pieces = [] }) {
// Each piece's reading and tuning, as made (lane line-rerun), with the words it said: a later read of the same words
// keeps it (posts screen read), and `--tuned` asks it again exactly (castProject.mjs threadArgvOf).
- const tuned = Object.fromEntries((pieces ?? []).filter((pc) => !pc.take && (pc.reading || pc.tuning)).map((pc) => [pc.role, { ...(pc.reading ? { reading: pc.reading } : {}), ...(pc.tuning ? { tuning: pc.tuning } : {}), said: pc.text }]));
+ // Only the READ's OWN values (as asked, its takes too) are kept: a tuning that came from the piece's character is not
+ // the read's, so a later read asks the character's as it is then (lane character-tuning; review 2 #9). A piece with
+ // no character tuning: its own as S3 kept it (the tuning asked).
+ const ownTuning = (pc) => (pc.ownTuning ? pc.ownTuning : pc.tuning && pc.tuningAsked !== "preset" ? pc.tuning : null);
+ const tuned = Object.fromEntries((pieces ?? []).filter((pc) => !pc.take && (pc.reading || ownTuning(pc))).map((pc) => [pc.role, { ...(pc.reading ? { reading: pc.reading } : {}), ...(ownTuning(pc) ? { tuning: ownTuning(pc) } : {}), said: pc.text }]));
return {
kind: "thread", parents: parentsSelector(parents),
...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }),
diff --git a/umtool/lib/report/tuneAsk.mjs b/umtool/lib/report/tuneAsk.mjs
@@ -0,0 +1,126 @@
+// THE TUNE's NUMBERS ON THE BENCH (lane character-tuning, review 2; components/projects/read/ReadAgain.tsx): where a
+// line's Tune starts, what a press asks as the line's OWN, and what a "Keep for <character>" keeps -- pure, so the
+// rule is one and tested.
+//
+// the BASELINE what a plain press reads the piece with now: its character's tuning (none: the defaults), unless
+// its last read was the line's own (`tuningAsked` true; made before that was recorded: a sampler value
+// off the defaults) -- then those numbers, and they stay the line's own
+// a PRESS with no character, S3's rule (what differs from the defaults); with one, what differs from the
+// character's tuning (all of the sampler when the last read was the line's own) -- nothing changed on
+// a character's line asks none of the sampler, so the character's is asked as it is then; the takes
+// when given (S3: a recorded takes is passed back)
+// a KEEP the sampler as it stands (top k, min p only when not their defaults) and the takes only when typed
+//
+// Plain ESM, pure.
+import { ORPHEUS_TUNING_DEFAULTS, TTS_TUNING_FIELDS } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+
+export const TUNE_SAMPLER = Object.freeze(["temperature", "top_p", "top_k", "min_p", "repeat_penalty"]);
+const DEFAULTS = ORPHEUS_TUNING_DEFAULTS;
+const num = (v) => (v !== "" && v !== null && v !== undefined && Number.isFinite(Number(v)) ? Number(v) : null);
+
+/** Was a read the line's own? `tuningAsked` true -- or, made before it was recorded, a sampler value off the defaults. */
+export function madeOwnOf(tuning, tuningAsked) {
+ if (tuningAsked === true) return true;
+ if (tuningAsked !== undefined && tuningAsked !== null) return false;
+ return TUNE_SAMPLER.some((k) => typeof tuning?.[k] === "number" && tuning[k] !== DEFAULTS[k]);
+}
+
+/** S3's ask (ReadAgain.tsx tuningAsked): the sampler values off the defaults, and the takes whenever given. */
+export function defaultsAskOf(draft) {
+ const out = {};
+ for (const k of TTS_TUNING_FIELDS) {
+ const v = num(draft?.[k]);
+ if (v !== null && (k === "takes" || v !== DEFAULTS[k])) out[k] = v;
+ }
+ return Object.keys(out).length ? out : null;
+}
+
+/**
+ * The Tune's starting numbers, as its fields hold them (strings): the baseline's sampler (`baseline` null: S3's -- the
+ * last read's), and the last read's takes.
+ * @param {{ madeWith?: Record<string, number> | null, baseline?: { character: { tuning: Record<string, number> | null } | null, madeOwn: boolean } | null }} o
+ */
+export function tuneStartOf({ madeWith = null, baseline = null } = {}) {
+ // No character (none now, or one since removed): S3's rule -- the last read's numbers (review 3 #4).
+ const b = !baseline || baseline.madeOwn || !baseline.character ? madeWith : baseline.character.tuning ?? null;
+ return Object.fromEntries(TTS_TUNING_FIELDS.map((k) => {
+ const v = k === "takes" ? madeWith?.takes : b?.[k];
+ return [k, v !== undefined && v !== null ? String(v) : k in DEFAULTS ? String(DEFAULTS[k]) : ""];
+ }));
+}
+
+/**
+ * What a press asks as the line's own (null: nothing of its own -- the character's, or the defaults, as they are now).
+ * @param {Record<string, string>} draft
+ * @param {{ character: { tuning: Record<string, number> | null } | null, madeOwn: boolean } | null} [baseline]
+ */
+export function tuneAskOf(draft, baseline = null) {
+ if (!baseline?.character) return defaultsAskOf(draft);
+ const out = {};
+ for (const k of TUNE_SAMPLER) {
+ const v = num(draft?.[k]);
+ const was = baseline.character.tuning?.[k] ?? DEFAULTS[k];
+ if (v !== null && (baseline.madeOwn || v !== was)) out[k] = v;
+ }
+ const takes = num(draft?.takes);
+ if (takes !== null) out.takes = takes;
+ return Object.keys(out).length ? out : null;
+}
+
+/**
+ * What a Keep keeps: the sampler as it stands (top k and min p only when not their defaults), the takes only when typed.
+ * @param {Record<string, string>} draft
+ * @param {{ takesTyped?: boolean }} [o]
+ */
+export function keepAskOf(draft, { takesTyped = false } = {}) {
+ const out = {};
+ for (const k of TUNE_SAMPLER) {
+ const v = num(draft?.[k]);
+ if (v !== null && ((k !== "top_k" && k !== "min_p") || v !== DEFAULTS[k])) out[k] = v;
+ }
+ const takes = num(draft?.takes);
+ if (takesTyped && takes !== null) out.takes = takes;
+ return out;
+}
+
+/**
+ * A thread read's Tune starts from HIS piece (the `post` part) -- never the first tuned part of another piece.
+ * @param {any} parts
+ */
+export function threadTuneMadeOf(parts) {
+ const p = (Array.isArray(parts) ? parts : []).find((x) => x?.role === "post" && typeof x?.take !== "string") ?? null;
+ return p ? { tuning: p.tuning ?? null, tuningAsked: p.tuningAsked } : null;
+}
+
+/** Does an ask name a sampler value (anything but the takes)? -- a press that does is checked against a fresh baseline. */
+export const asksSampler = (ask) => !!ask && Object.keys(ask).some((k) => k !== "takes");
+
+/** Two baselines the same (the character, its tuning, whose the last read was)? */
+export function sameBaseline(a, b) {
+ const key = (x) => JSON.stringify(x ? [x.character?.name ?? null, x.character ? x.character.tuning ?? {} : null, !!x.madeOwn] : null);
+ return key(a) === key(b);
+}
+
+/**
+ * A press while the baseline is NOT KNOWN (being read, or its read failed): an untouched draft asks nothing of its
+ * own -- only the takes -- unless the last read was the line's own (then S3's rule: its numbers again); an edited
+ * draft waits for the baseline (null: no press).
+ */
+export function unknownBaselineAskOf(draft, { madeOwn = false, dirty = false } = {}) {
+ if (dirty) return { waits: true, ask: null };
+ if (madeOwn) return { waits: false, ask: defaultsAskOf(draft) };
+ const takes = num(draft?.takes);
+ return { waits: false, ask: takes !== null ? { takes } : null };
+}
+
+/**
+ * "Use <character>'s" (review 3 #3): a line whose last read was its own, back to its character -- the draft at the
+ * character's tuning, and the baseline as if the last read were the character's, so the next press asks nothing of
+ * its own (the takes only) and records "preset".
+ * @param {Record<string, number> | null} madeWith
+ * @param {{ character: { tuning: Record<string, number> | null } | null, madeOwn: boolean }} baseline
+ */
+export function characterTuneOf(madeWith, baseline) {
+ const b = { ...baseline, madeOwn: false };
+ return { baseline: b, draft: tuneStartOf({ madeWith, baseline: b }) };
+}
diff --git a/umtool/lib/report/tuneAsk.test.mjs b/umtool/lib/report/tuneAsk.test.mjs
@@ -0,0 +1,112 @@
+// THE TUNE's NUMBERS ON THE BENCH (lane character-tuning, review 2; tuneAsk.mjs): the baseline a press starts from,
+// what it asks as the line's own, what a Keep keeps, and the thread Tune's piece. Each test names the review finding
+// it holds, and what the rule before the fix did (S3's: the last read's numbers, every one off the defaults, sent as the
+// line's own).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { asksSampler, characterTuneOf, defaultsAskOf, keepAskOf, madeOwnOf, sameBaseline, threadTuneMadeOf, tuneAskOf, tuneStartOf, unknownBaselineAskOf } from "./tuneAsk.mjs";
+
+const LIVELY = { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 };
+const STEADY = { temperature: 0.4, top_p: 0.8 };
+const MADE_LIVELY = { temperature: 0.75, top_p: 0.92, top_k: 50, min_p: 0, repeat_penalty: 1.25, takes: 3 };
+const asCharacter = (tuning, madeOwn = false) => ({ character: { name: "The Teller", tuning }, madeOwn });
+
+test("review 2 #1: a plain press after a read under the character's Lively asks NONE of the sampler as the line's own", () => {
+ // The last read was the character's ("preset"): the Tune starts from the character's tuning NOW.
+ const made = { tuning: MADE_LIVELY, tuningAsked: "preset" };
+ const b = asCharacter(LIVELY, madeOwnOf(made.tuning, made.tuningAsked));
+ const draft = tuneStartOf({ madeWith: made.tuning, baseline: b });
+ assert.deepEqual(tuneAskOf(draft, b), { takes: 3 }, "only the recorded takes (S3's rule): the sampler is the character's");
+ // The rule before the fix: the last read's numbers, as the line's own.
+ assert.deepEqual(defaultsAskOf(tuneStartOf({ madeWith: made.tuning })), { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25, takes: 3 });
+ // The character is Steady now: the Tune starts there, and a plain press still asks none of the sampler.
+ const now = asCharacter(STEADY, false);
+ const d2 = tuneStartOf({ madeWith: made.tuning, baseline: now });
+ assert.deepEqual([d2.temperature, d2.top_p, d2.repeat_penalty], ["0.4", "0.8", "1.2"]);
+ assert.deepEqual(tuneAskOf(d2, now), { takes: 3 });
+ // The line's own last read stays its own: its numbers are the baseline, all of the sampler asked.
+ const own = asCharacter(STEADY, madeOwnOf({ ...MADE_LIVELY, temperature: 0.9 }, true));
+ const d3 = tuneStartOf({ madeWith: { ...MADE_LIVELY, temperature: 0.9 }, baseline: own });
+ assert.deepEqual(tuneAskOf(d3, own), { temperature: 0.9, top_p: 0.92, top_k: 50, min_p: 0, repeat_penalty: 1.25, takes: 3 });
+ // Made before `tuningAsked` was recorded: a sampler value off the defaults was the line's own; the defaults were not.
+ assert.equal(madeOwnOf({ temperature: 0.7 }, undefined), true);
+ assert.equal(madeOwnOf({ temperature: 0.55, takes: 4 }, undefined), false);
+ assert.equal(madeOwnOf({ temperature: 0.7 }, "preset"), false);
+});
+
+test("review 2 #3: Defaults on a Lively character's line asks the three defaults as the line's own", () => {
+ const b = asCharacter(LIVELY, false);
+ const defaults = { temperature: "0.55", top_p: "0.85", top_k: "50", min_p: "0", repeat_penalty: "1.2", takes: "" };
+ assert.deepEqual(tuneAskOf(defaults, b), { temperature: 0.55, top_p: 0.85, repeat_penalty: 1.2 });
+ // The rule before the fix asked nothing (and the character's Lively was read).
+ assert.equal(defaultsAskOf(defaults), null);
+ // One number changed: only it is the line's own (the rest laid under it are the character's).
+ assert.deepEqual(tuneAskOf({ ...tuneStartOf({ baseline: b }), temperature: "0.9" }, b), { temperature: 0.9 });
+ // No character: S3's rule, exactly.
+ const none = { character: null, madeOwn: false };
+ assert.deepEqual(tuneAskOf({ ...defaults, temperature: "0.7" }, none), defaultsAskOf({ ...defaults, temperature: "0.7" }));
+ assert.equal(tuneAskOf(defaults, none), null);
+});
+
+test("review 2 #4: a thread read's Tune starts from his piece, never another piece's first tuned part", () => {
+ const parts = [
+ { role: "parent:0", voice: "leo", tuning: STEADY, tuningAsked: "preset" },
+ { role: "post", voice: "tara", tuning: LIVELY, tuningAsked: "preset" },
+ { role: "post", voice: "tara", tuning: LIVELY, tuningAsked: "preset" },
+ ];
+ assert.deepEqual(threadTuneMadeOf(parts), { tuning: LIVELY, tuningAsked: "preset" });
+ // The rule before the fix: the first part with a tuning (the parent's Steady).
+ assert.deepEqual(parts.find((p) => p.tuning)?.tuning, STEADY);
+ // His line from a take (--post-take) is no synthesized piece: nothing to start from.
+ assert.equal(threadTuneMadeOf([{ role: "post", take: "take-1.recorded", voice: "operator" }]), null);
+});
+
+test("review 2 #5: a Keep pins the character's takes only when the takes field was typed", () => {
+ const draft = { temperature: "0.9", top_p: "0.92", top_k: "50", min_p: "0", repeat_penalty: "1.25", takes: "4" };
+ assert.deepEqual(keepAskOf(draft), { temperature: 0.9, top_p: 0.92, repeat_penalty: 1.25 }, "the recorded takes (the editor's setting) are not pinned");
+ assert.deepEqual(keepAskOf(draft, { takesTyped: true }), { temperature: 0.9, top_p: 0.92, repeat_penalty: 1.25, takes: 4 });
+ // Top k and min p go only when not their defaults (a character does not keep them: the route says so).
+ assert.deepEqual(keepAskOf({ ...draft, top_k: "40" }).top_k, 40);
+});
+
+test("review 3 #1: a draft edited against Lively while the character became Steady is NOT sent; pressed again, what is shown is read", () => {
+ // Loaded as Lively; the operator changes only top_p.
+ const was = asCharacter(LIVELY, false);
+ const draft = { ...tuneStartOf({ madeWith: MADE_LIVELY, baseline: was }), top_p: "0.9" };
+ const a = tuneAskOf(draft, was);
+ assert.deepEqual(a, { top_p: 0.9, takes: 3 });
+ assert.equal(asksSampler(a), true, "it names a sampler value of its own: the baseline is read again before it is sent");
+ // Read again: Steady now. It changed under the draft -- nothing is sent (the press is refused, the new baseline said).
+ const now = asCharacter(STEADY, false);
+ assert.equal(sameBaseline(now, was), false);
+ assert.equal(sameBaseline(asCharacter({ ...LIVELY }, false), was), true);
+ // Sent as it was, it would have read {temperature 0.4 (Steady's), top_p 0.9} while the Tune showed 0.75.
+ // Pressed again against Steady, the draft as shown is the line's own: every number that differs from Steady's.
+ assert.deepEqual(tuneAskOf(draft, now), { temperature: 0.75, top_p: 0.9, repeat_penalty: 1.25, takes: 3 });
+ // An untouched press names no sampler value: sent at once (the character's is asked as it is then).
+ assert.equal(asksSampler({ takes: 3 }), false);
+});
+
+test("review 3 #2: the baseline unknown -- an untouched press asks nothing of its own, an edited one waits", () => {
+ const draft = tuneStartOf({ madeWith: MADE_LIVELY, baseline: null });
+ assert.deepEqual(unknownBaselineAskOf(draft, { madeOwn: false }), { waits: false, ask: { takes: 3 } });
+ assert.deepEqual(unknownBaselineAskOf(draft, { madeOwn: false, dirty: true }), { waits: true, ask: null });
+ // A line whose last read was its own: its numbers again (S3's rule), still its own.
+ assert.deepEqual(unknownBaselineAskOf(tuneStartOf({ madeWith: { ...MADE_LIVELY, temperature: 0.9 }, baseline: null }), { madeOwn: true }).ask, { temperature: 0.9, top_p: 0.92, repeat_penalty: 1.25, takes: 3 });
+});
+
+test("review 3 #3: Use <character>'s -- a line whose last read was its own goes back to its character: nothing of its own asked", () => {
+ const b = asCharacter(STEADY, true);
+ const own = { ...MADE_LIVELY, temperature: 0.9 };
+ assert.ok(asksSampler(tuneAskOf(tuneStartOf({ madeWith: own, baseline: b }), b)), "before: its own numbers, asked as its own");
+ const back = characterTuneOf(own, b);
+ assert.deepEqual([back.draft.temperature, back.draft.top_p, back.draft.repeat_penalty], ["0.4", "0.8", "1.2"], "the draft at the character's");
+ assert.deepEqual(tuneAskOf(back.draft, back.baseline), { takes: 3 }, "the next press asks only the takes: recorded \"preset\"");
+});
+
+test("review 3 #4: no character now, the last read the character's since removed -- the Tune starts from the last read's numbers (S3)", () => {
+ const none = { character: null, madeOwn: false };
+ const d = tuneStartOf({ madeWith: MADE_LIVELY, baseline: none });
+ assert.deepEqual([d.temperature, d.top_p, d.repeat_penalty, d.takes], ["0.75", "0.92", "1.25", "3"]);
+ assert.deepEqual(tuneStartOf({ madeWith: MADE_LIVELY, baseline: none }), tuneStartOf({ madeWith: MADE_LIVELY }), "S3's start, exactly");
+});
diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs
@@ -13,7 +13,9 @@
// "characters": [ { "id": "thequartering", "name": "TheQuartering",
// "handles": ["thequartering"], // X handles / channel slugs (no @, lower case)
// "synthetic": { "voice": "kokoro:am_michael", // <tts engine>:<stock voice>
-// "speed": 1.1 }, // the tts op's speed, 0.5-2 (absent: 1)
+// "speed": 1.1, // the tts op's speed, 0.5-2 (absent: 1)
+// "tuning": { "temperature": 0.75, "top_p": 0.92, // ORPHEUS's tuning (absent: its
+// "repeat_penalty": 1.25, "takes": 4 } }, // defaults; a value equal to one is left out)
// "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
@@ -53,7 +55,9 @@
// (`umtool cast audition`, the Voices panel), never a target -- the editor's
// convert op refuses a file as a target, and this file holds no path to one.
//
-// PURE and dependency-free (the CLI, the app and the lint read it).
+// PURE, no I/O (the CLI, the app and the lint read it); its one import outside this package is the tuning's ranges
+// and defaults (yt-dlp-transcript-common/lib/ttsTuning.mjs, plain ESM).
+import { CHARACTER_TUNING_FIELDS, ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS, normalizeTtsTuning, parseTtsTuning, quantizeTtsTuningValue, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
import { CONTEXT_VOICE_DEFAULTS, TTS_ENGINE_IDS, handleKey, voiceRefOf, voiceSpecOf } from "./post-say.mjs";
export { voiceRefOf, voiceSpecOf };
@@ -67,7 +71,7 @@ export const CAST_KEYS = Object.freeze(["id", "name", "handles", "synthetic", "r
/** 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 SYNTHETIC_KEYS = Object.freeze(["voice", "speed", "tuning"]);
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. */
@@ -160,6 +164,51 @@ export const characterVoice = (c) => (isObj(c?.synthetic) && c.synthetic.voice !
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's ORPHEUS TUNING (lane character-tuning, S2 of plans/orpheus-retune.md): `synthetic.tuning`, any of
+// temperature, top_p, repeat_penalty and takes (common/lib/ttsTuning.mjs CHARACTER_TUNING_FIELDS, its ranges). Kept
+// NORMALISED: a value equal to its default is left out (`takes` against ORPHEUS_DEFAULT_TAKES, as a re-read's flags
+// are: readTuning.mjs), and a tuning with nothing left is no key at all. It is the default for every Orpheus read the
+// character's preset answers for; a line's own tuning beats it (post-say.mjs readTuningOf). Kokoro and eSpeak NG
+// ignore it, as Orpheus ignores a speed.
+// ---------------------------------------------------------------------------
+
+/** A tuning as a character keeps it: the character fields only, quantised, each equal to its default left out. */
+export const characterTuningNormal = (t) => {
+ const n = normalizeTtsTuning(t, { takes: ORPHEUS_DEFAULT_TAKES });
+ const out = {};
+ for (const k of CHARACTER_TUNING_FIELDS) if (n[k] !== undefined) out[k] = n[k];
+ return out;
+};
+
+/** A character's tuning (`synthetic.tuning`), normalised: `{}` for none. */
+export const characterTuning = (c) => characterTuningNormal(isObj(c?.synthetic) ? c.synthetic.tuning : null);
+
+/** What is wrong with a character's tuning, as sentences that start at `w`. */
+export function characterTuningErrors(t, w) {
+ if (!isObj(t)) return [`${w} must be {${CHARACTER_TUNING_FIELDS.join("?, ")}?}`];
+ const errors = [];
+ for (const k of Object.keys(t)) if (!CHARACTER_TUNING_FIELDS.includes(k)) errors.push(`${w}.${k} is not a character's tuning field (${CHARACTER_TUNING_FIELDS.join(", ")})`);
+ if (errors.length) return errors;
+ const parsed = parseTtsTuning(t, { name: w });
+ if (!parsed.ok) return [parsed.error.replace(/^"|"(?= must)/g, "")];
+ // parseTtsTuning leaves a null or undefined value out (an ask's "not given"); a kept tuning names numbers only.
+ for (const k of Object.keys(t)) if (!(k in parsed.value)) errors.push(ttsTuningValueError(k, t[k], `${w}.${k}`));
+ if (errors.length) return errors;
+ if (!Object.keys(t).length) return [`${w} names no value (leave it out for the defaults)`];
+ return [];
+}
+
+/**
+ * The tuning a character's reads are ASKED WITH, every field filled: its own values over Orpheus's defaults, and
+ * `takes` its own else `settingTakes` (the editor's tts.orpheus.takes: what a read with no takes of its own gets --
+ * never a number the read would not use). `{ temperature, top_p, top_k, min_p, repeat_penalty, takes }`.
+ */
+export function effectiveCharacterTuning(tuning, settingTakes = ORPHEUS_DEFAULT_TAKES) {
+ const t = characterTuningNormal(tuning);
+ return { ...ORPHEUS_TUNING_DEFAULTS, ...Object.fromEntries(Object.entries(t).filter(([k]) => k !== "takes")), takes: t.takes ?? settingTakes };
+}
+
/**
* 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.
@@ -202,8 +251,9 @@ export function characterErrors(c, w, { layer = "cast" } = {}) {
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 (!isObj(syn) || Object.keys(syn).some((k) => !SYNTHETIC_KEYS.includes(k))) errors.push(`${w}.synthetic must be {voice, speed?, tuning?}`);
else {
+ if (syn.tuning !== undefined) errors.push(...characterTuningErrors(syn.tuning, `${w}.synthetic.tuning`));
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]}`);
}
@@ -316,7 +366,7 @@ export function validateProjectCharacters(doc, where = "characters.json", { mani
/**
* THE STOCK VOICES a proposal may name, by engine -- common/lib/ttsApps.ts KOKORO_VOICES and ORPHEUS_VOICES (a test
- * holds them equal; this file stays dependency-free). Kokoro's are `a*` American, `b*` British, `?f_` female, `?m_` male.
+ * holds them equal; this file does not import the editor's TypeScript). Kokoro's are `a*` American, `b*` British, `?f_` female, `?m_` male.
*/
export const STOCK_VOICES = Object.freeze({
kokoro: Object.freeze([
@@ -484,12 +534,16 @@ 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. */
+/**
+ * A character's SYNTHETIC preset as a layer's entry (post-say.mjs voiceSourceOf): `{ voice, speed?, tuning?, character }`,
+ * or null when it has no stock voice. `tuning` only when it has one: a character without is the entry it always was.
+ */
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 };
+ const tuning = characterTuning(c);
+ return { voice, ...(speed !== null && speed !== 1 ? { speed } : {}), ...(Object.keys(tuning).length ? { tuning } : {}), character: c.id };
}
/** The cast as a preset layer: `{ "<handle>": { voice, speed?, character } }` -- castVoiceMap with each character's speed and id. */
@@ -751,5 +805,111 @@ export function castDrift(manifest, { cast, map = {}, resolve }) {
return { drift, overrides };
}
+// ---------------------------------------------------------------------------
+// STALE READS (lane character-tuning): a picked Orpheus read made with other settings than its character's now.
+// ---------------------------------------------------------------------------
+
+const SAMPLER_FIELDS = Object.freeze(["temperature", "top_p", "top_k", "min_p", "repeat_penalty"]);
+/** A tuning's sampler values, every one filled (a missing one is Orpheus's default), quantised. */
+const samplerOf = (t) => Object.fromEntries(SAMPLER_FIELDS.map((k) => {
+ const q = quantizeTtsTuningValue(k, isObj(t) ? t[k] : undefined);
+ return [k, typeof q === "number" && Number.isFinite(q) ? q : ORPHEUS_TUNING_DEFAULTS[k]];
+}));
+
+/** The take of item `e` a thread read's part names (`{ take: "<id>", file }`): the item's take with that file or id, else null. */
+function partSourceTake(e, take, part) {
+ const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : [];
+ return takes.find((x) => x !== take && isObj(x) && typeof x.file === "string" && (x.file === part.file || x.file.split("/").pop().replace(/\.wav$/i, "") === part.take)) ?? null;
+}
+
+/**
+ * HOW ONE READ OF A PICKED TAKE WAS MADE (`role`): `{ tuning, asked, reading }` -- the tuning as the editor reported it
+ * (a thread read's synthesized part of that role, else the take's own; null when it records none: made with the
+ * defaults), where it came from (the take's `tuningAsked`: true, "preset" or undefined) and its reading. A thread
+ * read's part that IS another take of the item (`{ take: "<id>" }`, --post-take) answers as that take does.
+ */
+export function madeOf(e, take, role = "post", seen = new Set()) {
+ const parts = Array.isArray(take?.parts) ? take.parts : [];
+ const ref = parts.find((p) => p?.role === role && typeof p?.take === "string");
+ if (ref && !seen.has(take)) {
+ const src = partSourceTake(e, take, ref);
+ if (src && !isThreadTake(src)) return madeOf(e, src, "post", new Set([...seen, take]));
+ }
+ const part = parts.find((p) => p?.role === role && typeof p?.take !== "string" && isObj(p?.tuning));
+ // Where it came from: the piece's own part says so (one asked its explicit defaults has a provenance and no tuning).
+ const said = parts.find((p) => p?.role === role && typeof p?.take !== "string" && p?.tuningAsked !== undefined);
+ return {
+ tuning: part ? part.tuning : isObj(take?.tuning) ? take.tuning : null,
+ // A thread read's part says where its own tuning came from; else the take does.
+ asked: said?.tuningAsked ?? part?.tuningAsked ?? take?.tuningAsked,
+ reading: Number.isInteger(take?.reading) ? take.reading : 0,
+ };
+}
+
+/**
+ * A thread read's SCREEN LINES as reads (`[{ handle, role, engine, voice, kind: "tts" }]`, one per line): each line
+ * synthesized in its speaker's voice, its handle the speaker as written (a line whose speaker is a handle answers to
+ * that handle's character; one named otherwise answers to none here). takeReads leaves them out (drift does not judge
+ * them); the stale list does.
+ */
+function screenReadsOf(take) {
+ const seen = new Map();
+ for (const p of Array.isArray(take?.parts) ? take.parts : []) {
+ if (typeof p?.role !== "string" || !p.role.startsWith("screen:") || typeof p.take === "string" || typeof p.voice !== "string" || seen.has(p.role)) continue;
+ const h = handleKey(str(p.speaker));
+ if (!h) continue;
+ seen.set(p.role, { handle: h, role: p.role, engine: str(p.engine) || str(take.engine) || null, voice: p.voice, kind: "tts" });
+ }
+ return [...seen.values()];
+}
+
+/**
+ * EVERY PICKED ORPHEUS READ OF A CHARACTER MADE WITH OTHER SETTINGS THAN ITS TUNING NOW, pure -- `[{ id, handle, role,
+ * character, made, want, reading, thread }]`. `resolve(e, role, handle, take, read)` says the voice now as castProject.mjs
+ * resolverFor does (`{ engine, voice, character?, tuning? }`). A read is STALE when all of these hold:
+ * - it is synthesized, by Orpheus (a recorded, converted or derived read never is) -- a post's take, a thread read's
+ * pieces, and its screen lines (screenReadsOf);
+ * - a character's preset answers for it now (the item's own, this video's, the cast's), in the voice it was made
+ * in (another voice is drift: cast.mjs voiceDrift);
+ * - its tuning was not ASKED BY THE LINE: the take's `tuningAsked` is not true -- and a take that says nothing of
+ * where its tuning came from but records a SAMPLER value off the defaults was asked so (S1's flags; its takes are
+ * never looked at here: they record the editor's setting at the time, which may have changed since);
+ * a thread read's part that is another take answers as that take does (madeOf);
+ * - the tuning it was made with (none recorded: the defaults) differs from the character's: the sampler's five
+ * values, each a default when unsaid; `takes` ONLY when the character names its takes (a read with none of its own
+ * records the editor's setting, `settingTakes`); the reading is never compared (a reading is a pick, not a setting).
+ */
+export function tuningStale(manifest, resolve, { settingTakes = ORPHEUS_DEFAULT_TAKES } = {}) {
+ const rows = [];
+ const defaults = samplerOf(null);
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ if (e?.type !== "post") continue;
+ const take = playing(e);
+ if (!take) continue;
+ for (const r of [...takeReads(e, take), ...screenReadsOf(take)]) {
+ if (r.kind !== "tts" || !r.handle || r.engine !== "orpheus") continue;
+ const want = resolve(e, r.role, r.handle, take, r);
+ if (!want?.character || want.engine !== "orpheus" || !sameVoice({ engine: r.engine, voice: r.voice }, want)) continue;
+ const how = madeOf(e, take, r.role);
+ const made = how.tuning;
+ const madeS = samplerOf(made);
+ const madeTakes = isObj(made) && Number.isInteger(made.takes) ? made.takes : null;
+ // Asked by its line: said so, or (saying nothing) a sampler value off the defaults -- never judged by its takes.
+ const off = SAMPLER_FIELDS.some((k) => madeS[k] !== defaults[k]);
+ if (how.asked === true || (how.asked === undefined && off)) continue;
+ const wantT = characterTuningNormal(want.tuning);
+ const wantS = samplerOf(wantT);
+ const differs = SAMPLER_FIELDS.some((k) => madeS[k] !== wantS[k]) || (wantT.takes !== undefined && (madeTakes ?? settingTakes) !== wantT.takes);
+ if (!differs) continue;
+ rows.push({
+ id: e.id, handle: handleKey(r.handle), role: r.role, character: want.character,
+ made: { ...madeS, takes: madeTakes ?? settingTakes }, want: effectiveCharacterTuning(wantT, settingTakes),
+ reading: how.reading, thread: isThreadTake(take),
+ });
+ }
+ }
+ return rows;
+}
+
/** The voice an engine reads a context author in when nothing names one (re-exported for the panel). */
export { CONTEXT_VOICE_DEFAULTS };
diff --git a/umtool/report-to-video/characters.test.mjs b/umtool/report-to-video/characters.test.mjs
@@ -73,7 +73,7 @@ test("validation: the presets' shape, in the cast -- a voice and a convert targe
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({ synthetic: { voice: "kokoro:am_michael", emotion: "on" } }).some((e) => /synthetic must be \{voice, speed\?, tuning\?\}/.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)));
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -202,7 +202,10 @@ const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice",
// every tuning value (the defaults included) and the reading (0 = the first) -- so it can be made again exactly.
// `forReading` (lane line-rerun): the take was made from words that are not the post's as drafted -- stamped by the
// writer when it is made; while it plays the card follows the shown text (post-item.mjs readEditOf).
-const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading", "forReading"]);
+// `tuningAsked` (lane character-tuning): where an Orpheus take's tuning came from -- true (its line's own: the
+// command's flags, the bench's Tune), "preset" (its character's: stale when that changes, cast.mjs tuningStale).
+// Absent: none was asked (the defaults), or unknown (made before it was recorded).
+const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading", "forReading", "tuningAsked"]);
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).
@@ -210,8 +213,9 @@ const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "param
// `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1).
// `take`: a thread read's part that IS one of the item's takes (postThreadRead.mjs --post-take): that take's id.
// `reading`, `tuning` (lane line-rerun): the reading and the tuning a thread read's part was asked at (absent: the
-// first reading, the defaults), as postThreadRead.mjs keys and asks it.
-const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take", "line", "speaker", "reading", "tuning"]);
+// first reading, the defaults), as postThreadRead.mjs keys and asks it; `tuningAsked` where that tuning came from
+// (true: the read's own, "preset": the piece's character's -- a take's `tuningAsked`, per piece).
+const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take", "line", "speaker", "reading", "tuning", "tuningAsked"]);
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"];
@@ -685,6 +689,7 @@ export function validatePostNarration(e) {
errors.push(...takeLexiconErrors(t.lexicon, `${tw}.lexicon`));
if (t.said !== undefined && (typeof t.said !== "string" || t.said.length > 50000)) errors.push(`${tw}.said must be the words its read said`);
if (t.speedAsked !== undefined && t.speedAsked !== true && t.speedAsked !== "item" && t.speedAsked !== "preset") errors.push(`${tw}.speedAsked must be true, "item" or "preset"`);
+ if (t.tuningAsked !== undefined && t.tuningAsked !== true && t.tuningAsked !== "preset") errors.push(`${tw}.tuningAsked must be true (its line's own tuning) or "preset" (its character's)`);
errors.push(...tuningProblems(t.tuning, t.reading, tw));
if (t.forReading !== undefined && t.forReading !== true) errors.push(`${tw}.forReading must be true (or absent)`);
if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`);
@@ -756,6 +761,7 @@ export function validatePostNarration(e) {
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.reading !== undefined || p.tuning !== undefined) errors.push(...tuningProblems(p.tuning, p.reading, pw));
+ if (p.tuningAsked !== undefined && p.tuningAsked !== true && p.tuningAsked !== "preset") errors.push(`${pw}.tuningAsked must be true (the read's own tuning) or "preset" (its character's)`);
if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i>, media:<i> or screen:<id>:<line> (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(", ")}`);
if (p.take !== undefined && !(typeof p.take === "string" && n.takes.some((x) => x !== t && takeIdOf(x) === p.take))) errors.push(`${pw}.take must be the id of another of its takes (the take this part is)`);
diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs
@@ -260,7 +260,7 @@ 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. */
+/** A layer's entry as `{ voice, speed?, tuning?, 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;
@@ -268,11 +268,13 @@ function entryOf(v) {
const hit = (entry, from) => ({
spec: entry.voice, from,
...(typeof entry.speed === "number" && Number.isFinite(entry.speed) ? { speed: entry.speed } : {}),
+ // A character's Orpheus tuning (cast.mjs presetEntryOf: only when it has one).
+ ...(isObj(entry.tuning) && Object.keys(entry.tuning).length ? { tuning: entry.tuning } : {}),
...(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, speed?, character? }` --
+ * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from, speed?, tuning?, 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";
@@ -312,14 +314,50 @@ export function voiceForPiece(piece, o) {
}
/**
- * 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.
+ * The voice one piece is said in, RESOLVED: `{ engine, voice, from, speed?, tuning?, character? }` -- a bare voice in
+ * the read's `engine`, one that names its own engine in that one; `speed`, `tuning` 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, speed, character } = voiceSourceOf(piece, o);
+ const { spec, from, speed, tuning, 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, ...(speed !== undefined ? { speed } : {}), ...(character ? { character } : {}) };
+ return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from, ...(speed !== undefined ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(character ? { character } : {}) };
+}
+
+/**
+ * THE TUNING A READ IS ASKED WITH, pure (lane character-tuning): the line's own (`flag`: the take's --temperature …
+ * flags, a line's "use for this line only") beats its character's (`preset`: the synthetic preset's that answered for
+ * the voice) -- `{ tuning, asked: true | "preset" }`, the take's `tuningAsked` -- or null: none to ask (no tuning
+ * either way, or an engine that has no sampler: Kokoro, eSpeak NG). An empty tuning is none.
+ */
+/**
+ * THE TUNING ONE READ IS ASKED WITH, AND WHOSE IT IS -- the one rule a post's take (makeTake, the bench's take op) and
+ * every piece of a thread read follow (lane character-tuning, review 2): `own` the line's own values AS ASKED (the
+ * flags, the bench's Tune, a `--for`/`--tuned` piece; never normalised first: an explicit default is the line's own),
+ * `preset` its character's. Returns `{ tuning, asked, own }`: `tuning` the line's values over the character's, field
+ * by field (null: none); `asked` true when the line names a sampler value of its own (or asks any value with no
+ * character tuning to lay it over), "preset" when the sampler is the character's (a line asking only its takes keeps
+ * the character's sampler), null when nothing is asked; `own` the line's values as asked (null: none). An engine with no
+ * sampler is asked the line's own as it is (the editor says it ignores them) and none of the character's.
+ * @param {{ own?: Record<string, number> | null, preset?: Record<string, number> | null, engine?: string | null }} [o]
+ * @returns {{ tuning: Record<string, number> | null, asked: true | "preset" | null, own: Record<string, number> | null }}
+ */
+export function tuningAskOf({ own = null, preset = null, engine = null } = {}) {
+ const mine = isObj(own) ? Object.fromEntries(Object.entries(own).filter(([, v]) => typeof v === "number" && Number.isFinite(v))) : {};
+ const hasOwn = Object.keys(mine).length > 0;
+ if (engine !== "orpheus") return { tuning: hasOwn ? mine : null, asked: null, own: hasOwn ? mine : null };
+ const pre = isObj(preset) && Object.keys(preset).length ? preset : null;
+ const tuning = pre ? { ...pre, ...mine } : hasOwn ? mine : null;
+ const ownSampler = Object.keys(mine).some((k) => k !== "takes");
+ const asked = !tuning ? null : ownSampler || !pre ? true : "preset";
+ return { tuning, asked, own: hasOwn ? mine : null };
+}
+
+export function readTuningOf({ flag = null, preset = null, engine = null } = {}) {
+ if (engine !== "orpheus") return null;
+ if (isObj(flag) && Object.keys(flag).length) return { tuning: flag, asked: true };
+ if (isObj(preset) && Object.keys(preset).length) return { tuning: preset, asked: "preset" };
+ return null;
}
/**