// 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. // // /narration/auditions/.wav|json the try itself: an audition (castAudition.mjs), keyed with its // tuning and reading, levelled to -20 LUFS // /narration/auditions/tries.json { version: 1, rows: [{ key, character, layer, voice, text, tuning, // made?, reading, rel, seconds, lufs, at, jobId? }] }, newest first // // A try is SCRATCH: it makes no take on any post and writes nothing to the draft or the manifest. Each character (of // one layer: the cast's, or this video's own -- the same id may be both) keeps its TRY_KEEP newest; a row that falls // off takes its files with it when they are a tuned ask's (an untuned one is the candidate audition's cache, and // stays). Every write holds `tries.json.lock` (a terminal's `cast try` beside the page's job), and sweeps a tuned // ask's files that no row names once they are ORPHAN_AGE_MS old (a row lost to a broken file, a try that failed // after its synthesis). `umtool cast try

--clear` empties a character's list. // // Plain ESM: the CLI runs under bare node. import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { ORPHEUS_DEFAULT_TAKES, TTS_TUNING_RANGES, ttsTuningNameOf } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; import { characterTuningNormal, effectiveCharacterTuning } from "umtool-report-to-video/cast"; import { REPO_ROOT } from "../paths.mjs"; import { AUDITION_DIR, isTunedAsk } from "./castAudition.mjs"; import { withNotesLock } from "../annotations/store.mjs"; /** How many tries a character keeps in a project. */ export const TRY_KEEP = 12; export const TRIES_FILE = `${AUDITION_DIR}/tries.json`; /** A tuned ask's files no row names are swept once they are this old (a try still being kept is younger). */ export const ORPHAN_AGE_MS = 10 * 60 * 1000; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** * The editor's `tts.orpheus.takes` (its settings.json, SETTINGS_FILE when set): the takes a read with none of its own * gets. ORPHEUS_DEFAULT_TAKES when the file or the key is not there (or out of range). */ export async function orpheusTakesSetting(env = process.env) { const file = env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); try { const t = JSON.parse(await readFile(file, "utf8"))?.tts?.orpheus?.takes; const r = TTS_TUNING_RANGES.takes; return Number.isInteger(t) && t >= r.min && t <= r.max ? t : ORPHEUS_DEFAULT_TAKES; } catch { return ORPHEUS_DEFAULT_TAKES; } } /** * A tuning as the preset and `--json` say it: `{ tuning, name, effective, takesFrom }` -- `tuning` the character's own * (normalised; null for none), `name` its named starting point or "custom", `effective` every value its reads are * asked with (cast.mjs effectiveCharacterTuning: its takes, else the setting's), `takesFrom` "character" or "setting". */ export function tuningView(tuning, settingTakes = ORPHEUS_DEFAULT_TAKES) { const t = characterTuningNormal(tuning); return { tuning: Object.keys(t).length ? t : null, name: ttsTuningNameOf(t), effective: effectiveCharacterTuning(t, settingTakes), takesFrom: t.takes !== undefined ? "character" : "setting", }; } /** A tuning in words: "lively: temperature 0.75, top_p 0.92, repeat penalty 1.25, takes 3 (the setting's)". */ export function tuningWords(view) { const e = view.effective; return `${view.name}: temperature ${e.temperature}, top_p ${e.top_p}, repeat penalty ${e.repeat_penalty}, takes ${e.takes}${view.takesFrom === "setting" ? " (the setting's)" : ""}`; } const triesPath = (dir) => path.join(/* turbopackIgnore: true */ dir, ...TRIES_FILE.split("/")); /** A project's tries, newest first (none: `[]`; a file that does not parse reads as none). */ export async function readTries(dir) { try { const j = JSON.parse(await readFile(triesPath(dir), "utf8")); return Array.isArray(j?.rows) ? j.rows.filter((r) => isObj(r) && typeof r.key === "string" && typeof r.character === "string") : []; } catch { return []; } } async function writeTries(dir, rows) { const file = triesPath(dir); await mkdir(path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify({ version: 1, rows }, null, 1)}\n`); await rename(tmp, file); } /** Is a row a character's of one layer (the cast's, or this video's own)? */ export const rowOf = (r, character, layer = null) => r.character === character && (r.layer ?? null) === (layer ?? null); const auditionsOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ...AUDITION_DIR.split("/")); const KEY_RE = /^[0-9a-f]{20}$/; /** The files of the rows dropped that no row kept names, when they are a tuned ask's (an untuned key is the candidates' cache). */ async function sweepDropped(dir, dropped, kept) { const still = new Set(kept.map((r) => r.key)); const removed = []; for (const r of dropped) { if (still.has(r.key) || !isTunedAsk({ tuning: r.tuning, reading: r.reading }) || !KEY_RE.test(r.key)) continue; for (const ext of [".wav", ".json"]) await rm(path.join(auditionsOf(dir), `${r.key}${ext}`), { force: true }); still.add(r.key); removed.push(r.key); } return removed; } /** Every TUNED ask's files (its record says `asked`) that no row names, ORPHAN_AGE_MS old or more. */ export async function sweepOrphans(dir, kept, { now = Date.now(), ageMs = ORPHAN_AGE_MS } = {}) { const named = new Set(kept.map((r) => r.key)); const removed = []; for (const f of await readdir(auditionsOf(dir)).catch(() => [])) { const key = f.replace(/\.json$/, ""); if (!f.endsWith(".json") || !KEY_RE.test(key) || named.has(key)) continue; const meta = await readFile(path.join(auditionsOf(dir), f), "utf8").then(JSON.parse, () => null); if (!isObj(meta?.asked)) continue; const at = Date.parse(String(meta.at ?? "")); if (Number.isFinite(at) && now - at < ageMs) continue; for (const ext of [".wav", ".json"]) await rm(path.join(auditionsOf(dir), `${key}${ext}`), { force: true }); removed.push(key); } return removed; } /** `fn(rows)` holding the tries' lock: what it returns is `{ rows, dropped, result }`; the rows written, files swept. */ async function withTries(dir, fn) { await mkdir(auditionsOf(dir), { recursive: true }); return withNotesLock(triesPath(dir), async () => { const { rows, dropped, result } = await fn(await readTries(dir)); await writeTries(dir, rows); const removed = [...(await sweepDropped(dir, dropped, rows)), ...(await sweepOrphans(dir, rows))]; return { ...result, rows, removed }; }); } /** * ONE TRY KEPT: `row` first in the list (a row of the same key, character and layer before it is replaced), that * character's rows past TRY_KEEP dropped and their tuned files swept. Returns `{ rows, removed }`. */ export function addTry(dir, row) { return withTries(dir, (all0) => { const all = all0.filter((r) => !(r.key === row.key && rowOf(r, row.character, row.layer))); const next = [row, ...all]; const dropped = next.filter((r) => rowOf(r, row.character, row.layer)).slice(TRY_KEEP); return { rows: next.filter((r) => !dropped.includes(r)), dropped, result: {} }; }); } /** A character's tries emptied (their tuned files swept). Returns `{ cleared, removed }`. */ export async function clearTries(dir, character, layer = null) { const r = await withTries(dir, (all) => { const dropped = all.filter((x) => rowOf(x, character, layer)); return { rows: all.filter((x) => !rowOf(x, character, layer)), dropped, result: { cleared: dropped.length } }; }); return { cleared: r.cleared, removed: r.removed }; } /** The same ask (voice, text, tuning) as a row? -- the rows "Another reading" counts from. */ export const sameAsk = (r, { voice, text, tuning }) => r.voice === voice && r.text === text && JSON.stringify(characterTuningNormal(r.tuning)) === JSON.stringify(characterTuningNormal(tuning)); /** The reading after the highest kept for this character (of `layer`) and ask (1 when none is kept: another than the first). */ export function nextReading(rows, character, ask, layer = null) { const mine = rows.filter((r) => rowOf(r, character, layer) && sameAsk(r, ask)).map((r) => (Number.isInteger(r.reading) ? r.reading : 0)); return (mine.length ? Math.max(...mine) : 0) + 1; }