commit 3dcbfe46cdf95d135b764bbadc420ce777a9aef8
parent 4c45f197b1bcad5a225238e588a872887011c391
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 09:33:07 -0500
umtool cast: a character carries an Orpheus tuning; try it; its stale reads
The synthetic preset gains `tuning` (temperature, top_p, repeat_penalty,
takes), kept normalised through the cast's one writer: `umtool cast set` and
`cast project <p> set|add` take --tuning steady|default|lively and the numbers
over it (--temperature, --top-p, --repeat-penalty, --chunk-takes; `default`
takes one off; --no-tuning). --json says every value its reads are asked
with, the editor's takes when it names none.
The named starting points live once in common/lib/ttsTuning.mjs (added
exports only). The chain carries a character's tuning to a read
(presetEntryOf, voiceSourceOf, resolvePieceVoice); a character without one is
the entry it always was. readTuningOf: the line's own beats the character's.
`umtool cast try <p> <character>`: one line read in its voice with a tuning
and a reading, scratch, levelled, in a short list (tries.json, 12 per
character, dropped tuned files swept); an untuned audition keeps its key.
`umtool cast stale <p> [<character>]`: the picked Orpheus reads made with
other settings than the character's tuning now, never re-made.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
10 files changed, 943 insertions(+), 36 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/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,19 @@ 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 `engine|voice|text|<tuning>|<reading>`. 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 ? `${engine}|${voice}|${text}|${JSON.stringify(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 +195,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 +251,42 @@ 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),
};
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,49 @@ 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] [--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; --no-tuning, or --tuning default, the defaults again). 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 +106,15 @@ 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. 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 +132,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(["--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 +205,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 +297,21 @@ 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")) 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 +367,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 +402,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 +426,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 +470,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 +602,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 +642,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 +756,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 +771,113 @@ 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);
+ const character = await A.auditionCharacter(castRead.cast, who, { project, manifest });
+ const layer = 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);
+ 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) => r.character === character.id);
+ 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 });
+ 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, 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,7 +10,7 @@ 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";
@@ -90,9 +90,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 +102,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 +139,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 +157,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,
diff --git a/umtool/lib/report/characterTuning.mjs b/umtool/lib/report/characterTuning.mjs
@@ -0,0 +1,130 @@
+// 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, 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 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). `umtool cast try <p> <character> --clear` empties a character's list.
+//
+// Plain ESM: the CLI runs under bare node.
+import { mkdir, readFile, 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";
+
+/** How many tries a character keeps in a project. */
+export const TRY_KEEP = 12;
+export const TRIES_FILE = `${AUDITION_DIR}/tries.json`;
+
+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);
+}
+
+/** 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 sweep(dir, dropped, kept) {
+ const still = new Set(kept.map((r) => r.key));
+ const auditions = path.join(/* turbopackIgnore: true */ dir, ...AUDITION_DIR.split("/"));
+ const removed = [];
+ for (const r of dropped) {
+ if (still.has(r.key) || !isTunedAsk({ tuning: r.tuning, reading: r.reading }) || !/^[0-9a-f]{20}$/.test(r.key)) continue;
+ for (const ext of [".wav", ".json"]) await rm(path.join(auditions, `${r.key}${ext}`), { force: true });
+ still.add(r.key);
+ removed.push(r.key);
+ }
+ return removed;
+}
+
+/**
+ * ONE TRY KEPT: `row` first in the list (a row of the same key and character before it is replaced), the character's
+ * rows past TRY_KEEP dropped and their tuned files swept. Returns `{ rows, removed }`.
+ */
+export async function addTry(dir, row) {
+ const all = (await readTries(dir)).filter((r) => !(r.key === row.key && r.character === row.character));
+ const next = [row, ...all];
+ const mine = next.filter((r) => r.character === row.character);
+ const dropped = mine.slice(TRY_KEEP);
+ const kept = next.filter((r) => !dropped.includes(r));
+ await writeTries(dir, kept);
+ return { rows: kept, removed: await sweep(dir, dropped, kept) };
+}
+
+/** A character's tries emptied (their tuned files swept). Returns `{ cleared, removed }`. */
+export async function clearTries(dir, character) {
+ const all = await readTries(dir);
+ const dropped = all.filter((r) => r.character === character);
+ const kept = all.filter((r) => r.character !== character);
+ if (dropped.length) await writeTries(dir, kept);
+ return { cleared: dropped.length, removed: await sweep(dir, dropped, kept) };
+}
+
+/** 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 and ask (1 when none is kept: another than the first). */
+export function nextReading(rows, character, ask) {
+ const mine = rows.filter((r) => r.character === character && 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,300 @@
+// 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; every project is a temp dir.
+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 { TRY_KEEP, nextReading, 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 ROOT = await mkdtemp(path.join(tmpdir(), "umtool-tuning-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+// The editor's settings: tts.orpheus.takes is 4 here, so a character naming no takes reads with 4.
+const SETTINGS = path.join(ROOT, "settings.json");
+await writeFile(SETTINGS, JSON.stringify({ tts: { orpheus: { takes: 4 } } }));
+process.env.SETTINGS_FILE = SETTINGS;
+delete process.env.UMTOOL_CAST_FILE;
+
+const LIVELY = { ...ORPHEUS_TUNING_NAMED.lively };
+const MADE = (o = {}) => ({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 4, ...o });
+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 })));
+};
+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")) };
+};
+/** The editor's tts op, stubbed: `out` written, the effective tuning reported as the editor reports it (Orpheus). */
+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, disclosure: `Narration: synthetic voice (${body.engine} · ${body.voice})`,
+ ...(body.engine === "orpheus" ? { tuning: { ...MADE(), ...(body.tuning ?? {}) }, reading: body.reading ?? 0, seedBase: 1234 + 9973 * (body.reading ?? 0) } : {}),
+ },
+ };
+};
+
+// THE PROJECT: "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 DIR = path.join(ROOT, "tuning");
+const LINE = "The teller says the bridge was closed for the whole of the long winter.";
+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 });
+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 } }),
+];
+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 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)]));
+};
+
+test("cast set: a tuning on the synthetic preset -- a named starting point, the numbers over it, the defaults kept as none", async () => {
+ let r = await cast(["add", "teller", "--name", "The Teller", "--voice", "orpheus:tara", "--handles", "teller", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.equal(r.json().character.synthetic.tuning, undefined, "no tuning asked: none kept");
+ 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 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 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 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; 3 is Orpheus's default and is NOT kept -- and the preset says the setting's (4) is what is used.
+ r = await cast(["set", "teller", "--chunk-takes", "5", "--json"]);
+ assert.equal(r.json().character.synthetic.tuning.takes, 5);
+ assert.equal(r.json().tuning.takesFrom, "character");
+ r = await cast(["set", "teller", "--chunk-takes", "3", "--json"]);
+ assert.equal(r.json().character.synthetic.tuning.takes, 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\)/);
+ // The Default starting point (or --no-tuning): none at all, no key.
+ r = await cast(["set", "teller", "--tuning", "default", "--json"]);
+ assert.equal("tuning" in r.json().character.synthetic, false);
+ await cast(["set", "teller", "--tuning", "steady"]);
+ r = await cast(["set", "teller", "--no-tuning", "--json"]);
+ assert.equal("tuning" in r.json().character.synthetic, false);
+ const kept = JSON.parse(await readFile(castFile(ROOT), "utf8")).characters[0];
+ assert.deepEqual(Object.keys(kept.synthetic), ["voice"], "the file keeps no empty tuning");
+ // Refused in the flag's words.
+ r = await cast(["set", "teller", "--temperature", "9"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /--temperature must be a number from 0\.1 to 1\.5 \(got 9\)/);
+ r = await cast(["set", "teller", "--chunk-takes", "x"]);
+ assert.match(r.text(), /--chunk-takes must be a whole number from 1 to 6 \(got x\)/);
+ r = await cast(["set", "teller", "--tuning", "loud"]);
+ assert.match(r.text(), /--tuning is steady, default, lively \(got loud\)/);
+ // Undo puts the last one back.
+ await cast(["set", "teller", "--tuning", "lively"]);
+ await cast(["set", "teller", "--tuning", "steady"]);
+ r = await cast(["undo", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(JSON.parse(await readFile(castFile(ROOT), "utf8")).characters[0].synthetic.tuning, LIVELY);
+ // A Kokoro voice keeps it and ignores it (as Orpheus ignores a speed), and says so.
+ await cast(["add", "other", "--name", "Another One", "--voice", "kokoro:af_heart", "--handles", "other"]);
+ r = await cast(["set", "other", "--tuning", "steady", "--json"]);
+ assert.match(r.json().notes.join(" "), /kokoro:af_heart has no sampler: its reads ignore the tuning/);
+ await cast(["set", "other", "--no-tuning"]);
+});
+
+test("the cast's file refuses a tuning that is not a character's, whole", async () => {
+ const file = castFile(ROOT);
+ 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\)/],
+ [{}, /synthetic\.tuning names no value/],
+ ["warm", /synthetic\.tuning must be/],
+ ]) {
+ await assert.rejects(castWrite(file, (chars) => { chars.find((c) => c.id === "teller").synthetic.tuning = tuning; }), re);
+ }
+});
+
+test("cast project <p> set: the twin for this video's own character; a tuning needs a voice", async () => {
+ let r = await cast(["project", "tuning", "add", "visitor", "--name", "A Visitor", "--handles", "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 cast(["project", "tuning", "add", "visitor", "--name", "A Visitor", "--voice", "orpheus:leo", "--handles", "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 cast(["project", "tuning", "set", "visitor", "--no-voice", "--json"]);
+ assert.equal(r.json().character.synthetic, undefined, "no voice: no tuning either");
+ await cast(["project", "tuning", "rm", "visitor"]);
+});
+
+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);
+});
+
+test("stale: a picked Orpheus read made with other settings than its character's tuning now -- listed, never re-made", async () => {
+ const before = await manifestText();
+ const m = JSON.parse(before);
+ const castOf = (tuning) => ({ format: "umtool-cast", version: 2, characters: [{ id: "teller", name: "The Teller", handles: ["teller"], synthetic: { voice: "orpheus:tara", ...(tuning ? { tuning } : {}) } }] });
+ const stale = (tuning, o = {}) => tuningStale(m, resolverFor({ cast: castOf(tuning) }), { settingTakes: 4, ...o });
+ // No tuning: nothing is stale (p-1 was made with the defaults; p-2 asked its own).
+ assert.deepEqual(stale(null), []);
+ // 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 = stale(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(stale({ takes: 4 }), [], "4 is what it was made with");
+ assert.deepEqual(stale({ takes: 5 }).map((r) => r.id), ["p-1"]);
+ assert.deepEqual(stale(null, { settingTakes: 5 }), [], "a read made under another setting is not the character's to call stale");
+ // A take made with the character's tuning (tuningAsked "preset") is stale when the character changes, fresh when not.
+ const m2 = JSON.parse(before);
+ m2.timeline[0].narration.takes[0] = { ...m2.timeline[0].narration.takes[0], tuning: MADE(LIVELY), tuningAsked: "preset", reading: 2 };
+ assert.deepEqual(tuningStale(m2, resolverFor({ cast: castOf(LIVELY) }), { settingTakes: 4 }), []);
+ const moved = tuningStale(m2, resolverFor({ cast: castOf(ORPHEUS_TUNING_NAMED.steady) }), { settingTakes: 4 });
+ assert.deepEqual(moved.map((r) => [r.id, r.reading]), [["p-1", 2]], "the reading is said, never compared");
+ // An S1 take with no provenance and a tuning off the defaults was asked by its line: never stale.
+ const m3 = JSON.parse(before);
+ m3.timeline[0].narration.takes[0] = { ...m3.timeline[0].narration.takes[0], tuning: MADE({ top_k: 40 }) };
+ assert.deepEqual(tuningStale(m3, resolverFor({ cast: castOf(LIVELY) }), { settingTakes: 4 }), []);
+ // A read now in ANOTHER voice is drift, not stale.
+ assert.deepEqual(tuningStale(m, resolverFor({ cast: { ...castOf(LIVELY), characters: [{ ...castOf(LIVELY).characters[0], synthetic: { voice: "orpheus:leah", tuning: LIVELY } }] } }), { settingTakes: 4 }), []);
+ // The project's view: the character's row and the whole list; `cast stale` says it.
+ const view = projectCharacters(m, { 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"]);
+ await cast(["set", "teller", "--tuning", "lively"]);
+ const r = await 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 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 manifestText(), before, "listing writes nothing");
+});
+
+test("the audition key: an untuned ask keeps the key it always had; a tuning or a reading is a new one", () => {
+ 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);
+ assert.notEqual(auditionKey("orpheus", "tara", LINE, { reading: 1 }), old);
+});
+
+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 before = await manifestText();
+ const cards = await drawn();
+ const postsBefore = existsSync(path.join(DIR, "narration", "posts")) ? await readdir(path.join(DIR, "narration", "posts"), { recursive: true }) : [];
+ await 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 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 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(DIR, r.json().try.rel)));
+ // Another reading: the same text and tuning, reading 1.
+ r = await cast(["try", "tuning", "teller", "--another", "--json"], { ask, lanes: null });
+ assert.equal(asked[1].reading, 1);
+ assert.deepEqual(asked[1].tuning, LIVELY);
+ assert.equal(r.json().try.reading, 1);
+ // Steady over it, typed text: its own key, its own list row.
+ r = await cast(["try", "tuning", "teller", "--tuning", "steady", "--text", "A line typed in.", "--json"], { ask, lanes: null });
+ assert.deepEqual(asked[2].tuning, { temperature: 0.4, top_p: 0.8 }, "Steady, its repeat penalty the default's (not asked)");
+ assert.equal(asked[2].text, "A line typed in.");
+ r = await cast(["try", "tuning", "teller", "--list", "--json"]);
+ assert.deepEqual(r.json().tries.map((x) => [x.text === LINE, x.reading]), [[false, 0], [true, 1], [true, 0]], "newest first");
+ assert.equal(nextReading(r.json().tries, "teller", { voice: "orpheus:tara", text: LINE, tuning: LIVELY }), 2);
+ // The defaults tried: no tuning key, no reading key -- the ask an audition always made.
+ await cast(["try", "tuning", "teller", "--tuning", "default", "--json"], { ask, lanes: null });
+ assert.deepEqual(Object.keys(asked[3]).sort(), ["engine", "out", "text", "voice"]);
+ // Out of range, and a Kokoro voice (no sampler) refused a tuning.
+ r = await cast(["try", "tuning", "teller", "--reading", "-1"], { ask, lanes: null });
+ assert.match(r.text(), /--reading must be a whole number from 0 to 99999/);
+ r = await cast(["try", "tuning", "other", "--tuning", "lively"], { ask, lanes: null });
+ assert.match(r.text(), /a tuning and a reading are Orpheus's: kokoro:af_heart reads the same every time/);
+ // THE PIN: no take, no script, nothing in the manifest; every card drawn as it was.
+ assert.equal(await manifestText(), before, "the manifest is byte-identical");
+ assert.deepEqual(await drawn(), cards, "every card's drawn text and structure are byte-identical");
+ const postsAfter = existsSync(path.join(DIR, "narration", "posts")) ? await readdir(path.join(DIR, "narration", "posts"), { recursive: true }) : [];
+ assert.deepEqual(postsAfter, postsBefore, "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", async () => {
+ const asked = [];
+ const ask = stubAsk(asked);
+ await cast(["try", "tuning", "teller", "--clear"]);
+ for (let n = 0; n <= TRY_KEEP; n += 1) {
+ const r = await cast(["try", "tuning", "teller", "--reading", String(n), "--text", "Short.", "--json"], { ask, lanes: null });
+ assert.equal(r.code, 0, r.text());
+ }
+ const list = (await 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 firstKey = auditionKey("orpheus", "tara", "Short.", { tuning: LIVELY, reading: 0 });
+ assert.ok(!existsSync(path.join(DIR, "narration", "auditions", `${firstKey}.wav`)), "the dropped try's file is swept");
+ const r = await cast(["try", "tuning", "teller", "--clear", "--json"]);
+ assert.equal(r.json().cleared, TRY_KEEP);
+ assert.deepEqual((await cast(["try", "tuning", "teller", "--list", "--json"])).json().tries, []);
+ assert.ok(!(await readdir(path.join(DIR, "narration", "auditions"))).some((f) => f === `${list[0].key}.wav`));
+});
+
+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/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 } 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,48 @@ 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, "")];
+ 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 +248,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 +363,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 +531,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 +802,71 @@ 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 tuning a picked take says one of its reads was made with (`role`): a thread read's part's (its first
+ * synthesized part of that role), else the take's own -- as the editor reported it; null when it records none (made
+ * before the tuning existed, i.e. with the defaults).
+ */
+export function madeTuningOf(take, role = "post") {
+ const parts = Array.isArray(take?.parts) ? take.parts : [];
+ const part = parts.find((p) => p?.role === role && typeof p?.take !== "string" && isObj(p?.tuning));
+ if (part) return part.tuning;
+ return isObj(take?.tuning) ? take.tuning : null;
+}
+
+/**
+ * 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 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 one off the defaults was asked so (S1's flags);
+ * - 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)) {
+ 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 made = madeTuningOf(take, r.role);
+ const madeS = samplerOf(made);
+ const madeTakes = isObj(made) && Number.isInteger(made.takes) ? made.takes : null;
+ const off = SAMPLER_FIELDS.some((k) => madeS[k] !== defaults[k]) || (madeTakes !== null && madeTakes !== settingTakes);
+ if (take.tuningAsked === true || (take.tuningAsked === 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: Number.isInteger(take.reading) ? take.reading : 0, 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/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,27 @@ 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.
+ */
+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;
}
/**