Archilyzer · Source

archilyzer

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

commit 7af86a77074c78a374cf91f26994f434eb3e3cf1
parent 8edf642041107c443b927c972e3412680bfd8988
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 10:25:15 -0500

cast tuning review 1: stale by the sampler, a part's own take, locked tries, scoped tries

- tuningStale decides "asked by its line" from the sampler's five values only:
  a changed tts.orpheus.takes no longer hides a read made with the defaults.
- madeOf: a thread read's part that is another take answers with that take's
  tuning, provenance and reading.
- A kept tuning refuses a null value (validation checks the parsed keys).
- A tuned audition key is `tuned:` + JSON: no untuned text collides with it;
  the untuned key is byte-identical (pinned).
- tries.json: every write holds tries.json.lock; a tuned ask's files no row
  names are swept once ten minutes old; rows carry their layer.
- cast try --scope cast|project looks the character up in one layer; refuses
  --reading with --another, and --no-tuning; cast set refuses --no-tuning with
  a tuning flag; the help says --tuning default keeps the takes.
- Tests: each makes its own world (runs alone); one per finding above,
  an untuned file surviving --clear, three concurrent writes.

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

Diffstat:
Mumtool/lib/report/castAudition.mjs | 9++++++---
Mumtool/lib/report/castCli.mjs | 42+++++++++++++++++++++++++++++++-----------
Mumtool/lib/report/characterTuning.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mumtool/lib/report/characterTuning.test.mjs | 407+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mumtool/report-to-video/cast.mjs | 46++++++++++++++++++++++++++++++++++------------
5 files changed, 402 insertions(+), 198 deletions(-)

diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs @@ -58,14 +58,15 @@ export class AuditionError extends Error { /** * 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). + * 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 ? `${engine}|${voice}|${text}|${JSON.stringify(t)}|${r}` : `${engine}|${voice}|${text}`).digest("hex").slice(0, 20); + 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); @@ -287,6 +288,8 @@ export async function synthesizeAuditions(dir, plan, text, { ask = null, editor ...(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 @@ -57,7 +57,7 @@ export const CAST_USAGE = [ " 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]", + " [--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]", @@ -69,7 +69,8 @@ export const CAST_USAGE = [ " 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 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`).", @@ -111,7 +112,8 @@ export const CAST_USAGE = [ " 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.", + " 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.", @@ -132,7 +134,7 @@ export const CAST_USAGE = [ " Exit 0 done · 1 refused or failed · 2 usage.", ].join("\n"); -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 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) { @@ -303,7 +305,10 @@ export function characterFrom(before, id, f, p, { layer = "cast", anon = () => A if (Object.keys(t).length) syn.tuning = t; else delete syn.tuning; } - if (p.has("--no-tuning")) 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; @@ -798,21 +803,36 @@ async function tryCommand(rest, p, { reportsRoot, log, err, ask, lanes }) { 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); + 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); + 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) => r.character === character.id); + 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})`); @@ -835,14 +855,14 @@ async function tryCommand(rest, p, { reportsRoot, log, err, ask, lanes }) { 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 }); + } 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, voice: spec, text: said.text, from: said.from, tuning, ...(c.meta?.tuning ? { made: c.meta.tuning } : {}), reading, + 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); diff --git a/umtool/lib/report/characterTuning.mjs b/umtool/lib/report/characterTuning.mjs @@ -5,25 +5,31 @@ // // <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 +// <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 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. +// 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, rename, rm, writeFile } from "node:fs/promises"; +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); @@ -83,48 +89,80 @@ async function writeTries(dir, rows) { 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 sweep(dir, dropped, kept) { +async function sweepDropped(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 }); + 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 and character before it is replaced), the character's - * rows past TRY_KEEP dropped and their tuned files swept. Returns `{ 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 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) }; +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) { - 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) }; +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 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)); +/** 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 @@ -3,7 +3,8 @@ // 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. +// 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"; @@ -17,143 +18,164 @@ 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 { 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 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; +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 }))); }; -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) => { +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(), ...(body.tuning ?? {}) }, reading: body.reading ?? 0, seedBase: 1234 + 9973 * (body.reading ?? 0) } : {}), + ...(body.engine === "orpheus" ? { tuning: { ...MADE({ takes: settingTakes }), ...(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 } }), +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 } }), ]; -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)])); -}; + +/** + * 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 () => { - 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"); + 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 cast(["set", "teller", "--tuning", "lively", "--json"]); + 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 cast(["set", "teller", "--temperature", "0.8000000001", "--json"]); + 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 cast(["set", "teller", "--temperature", "default", "--json"]); + 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; 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"]); + // 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"); - r = await cast(["set", "teller", "--chunk-takes", "3", "--json"]); - assert.equal(r.json().character.synthetic.tuning.takes, undefined); + // --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\)/); - // 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"]); + 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); - 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\)/); + 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 cast(["set", "teller", "--tuning", "lively"]); - await cast(["set", "teller", "--tuning", "steady"]); - r = await cast(["undo", "--json"]); + 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(JSON.parse(await readFile(castFile(ROOT), "utf8")).characters[0].synthetic.tuning, LIVELY); + 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. - await cast(["add", "other", "--name", "Another One", "--voice", "kokoro:af_heart", "--handles", "other"]); - r = await cast(["set", "other", "--tuning", "steady", "--json"]); + 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/); - 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); +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(file, (chars) => { chars.find((c) => c.id === "teller").synthetic.tuning = tuning; }), re); + 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 () => { - let r = await cast(["project", "tuning", "add", "visitor", "--name", "A Visitor", "--handles", "visitor", "--tuning", "lively"]); + 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 cast(["project", "tuning", "add", "visitor", "--name", "A Visitor", "--voice", "orpheus:leo", "--handles", "visitor", "--tuning", "steady", "--repeat-penalty", "1.3", "--json"]); + 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 cast(["project", "tuning", "set", "visitor", "--no-voice", "--json"]); + r = await w.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", () => { @@ -163,8 +185,8 @@ test("THE PIN: a character with no tuning is the layer entry it always was; one 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" }); + 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. @@ -174,64 +196,103 @@ test("THE PIN: a character with no tuning is the layer entry it always was; one 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), []); +// ---- 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 = stale(LIVELY); + 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(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"); + 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 = 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 }), []); + 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), 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(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"]); - await cast(["set", "teller", "--tuning", "lively"]); - const r = await cast(["stale", "tuning", "teller", "--json"]); + 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 cast(["stale", "tuning"]); + 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 manifestText(), before, "listing writes nothing"); + assert.equal(await w.manifestText(), before); }); -test("the audition key: an untuned ask keeps the key it always had; a tuning or a reading is a new one", () => { +// ---- 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); - assert.notEqual(auditionKey("orpheus", "tara", LINE, { reading: 1 }), old); + // 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 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"]); + 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 cast(["try", "tuning", "teller", "--list", "--json"]); + 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" }); @@ -240,57 +301,117 @@ test("cast try: a line read with a tuning and a reading -- scratch, a short list 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 }); + 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(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.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); - 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); + 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 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/); + 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 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"); + 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", async () => { +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); - await cast(["try", "tuning", "teller", "--clear"]); + // 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) { - const r = await cast(["try", "tuning", "teller", "--reading", String(n), "--text", "Short.", "--json"], { ask, lanes: null }); + 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 cast(["try", "tuning", "teller", "--list", "--json"])).json().tries; + 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 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"]); + 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 cast(["try", "tuning", "teller", "--list", "--json"])).json().tries, []); - assert.ok(!(await readdir(path.join(DIR, "narration", "auditions"))).some((f) => f === `${list[0].key}.wav`)); + 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", () => { diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -57,7 +57,7 @@ // // 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 { 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 }; @@ -192,6 +192,9 @@ export function characterTuningErrors(t, w) { 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 []; } @@ -813,16 +816,31 @@ const samplerOf = (t) => Object.fromEntries(SAMPLER_FIELDS.map((k) => { 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; +} + /** - * 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). + * 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 madeTuningOf(take, role = "post") { +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)); - if (part) return part.tuning; - return isObj(take?.tuning) ? take.tuning : null; + return { + tuning: part ? part.tuning : isObj(take?.tuning) ? take.tuning : null, + asked: take?.tuningAsked, + reading: Number.isInteger(take?.reading) ? take.reading : 0, + }; } /** @@ -833,7 +851,9 @@ export function madeTuningOf(take, role = "post") { * - 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); + * 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). @@ -849,11 +869,13 @@ export function tuningStale(manifest, resolve, { settingTakes = ORPHEUS_DEFAULT_ 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 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; - const off = SAMPLER_FIELDS.some((k) => madeS[k] !== defaults[k]) || (madeTakes !== null && madeTakes !== settingTakes); - if (take.tuningAsked === true || (take.tuningAsked === undefined && off)) continue; + // 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); @@ -861,7 +883,7 @@ export function tuningStale(manifest, resolve, { settingTakes = ORPHEUS_DEFAULT_ 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), + reading: how.reading, thread: isThreadTake(take), }); } }