Archilyzer · Source

archilyzer

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

commit 294abc5e18a4cec733cbd01030b755e98df4c732
parent fdd53ccba2000e0507c42d8a108375150c2b1613
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 09:46:36 -0500

umtool: a thread read takes a reading and a tuning -- the whole read's, one piece's, each piece's; re-reads join the list unpicked

- postThreadRead.mjs: threadReadPlan `tuned` ({"*"|role: {reading|"next", tuning}}) and `inherit` (the playing
  read's, kept while a piece says the same words); partKey/voiceSig add the reading and tuning only when asked
  (literal sha pin: an untuned part keeps its key); parts and read.tuned record them; threadTake keepPick.
- posts narrate <p> <item> --take [--reading N|next] [--no-pick]; with --thread: --reading/tuning flags for the
  whole read, --for <role> for one piece, --tuned <role>=reading:N,… repeatable. --list flags a script edited
  before reads were kept apart from the card (json: scriptEdit).
- posts screen <p> <item> read: the same flags, the playing read's readings kept.
- castProject.mjs threadArgvOf: --tuned from read.tuned (5 lines added at its end).
- post-narration.mjs: a part may carry reading and tuning.

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

Diffstat:
Mumtool/lib/report/castProject.mjs | 5+++++
Mumtool/lib/report/postNarration.test.mjs | 7++++---
Mumtool/lib/report/postNarrationCli.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Aumtool/lib/report/postReadAgain.test.mjs | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postScreensCli.mjs | 18+++++++++++++++++-
Mumtool/lib/report/postThreadRead.mjs | 78+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/report/postsCli.mjs | 4++--
Aumtool/lib/report/threadTuned.test.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-narration.mjs | 5++++-
9 files changed, 397 insertions(+), 40 deletions(-)

diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -192,6 +192,11 @@ export function threadArgvOf(read, { handles = [], author = null, takes = null } const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === x.file) : -1; a.push("--line-take", `${r}=${at >= 0 ? at + 1 : x.n}`); } + // Each piece's reading and tuning (lane line-rerun, `read.tuned`): asked again exactly. + for (const [r, x] of Object.entries(read.tuned ?? {})) { + const kv = [...(Number.isInteger(x?.reading) && x.reading > 0 ? [`reading:${x.reading}`] : []), ...Object.entries(x?.tuning ?? {}).map(([k, v]) => `${k}:${v}`)]; + if (kv.length) a.push("--tuned", `${r}=${kv.join(",")}`); + } return a; } diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs @@ -226,15 +226,16 @@ test("the tuning flags are quantised as the editor quantises them", () => { assert.equal(tuningFlags(s({ "--temperature": "1.5004" })).tuning.temperature, 1.5); }); -test("the tuning flags: refused out of range in the flag's words, and anywhere but one item's --take", async () => { +test("the tuning flags: refused out of range in the flag's words, and anywhere but one item's --take (a thread read takes them since lane line-rerun; --for/--tuned are a thread read's)", async () => { await project("tf", [item("1", { narration: { script: "read me" } })]); for (const [args, re] of [ [["narrate", "tf", "p-1", "--take", "--top-p", "3"], /--top-p must be a number from 0\.05 to 1 \(got 3\)/], [["narrate", "tf", "p-1", "--take", "--chunk-takes", "2.5"], /--chunk-takes must be a whole number from 1 to 6/], [["narrate", "tf", "p-1", "--take", "--reading", "-2"], /--reading must be a whole number from 0 to 99999/], [["narrate", "tf", "p-1", "--reading", "1"], /--reading go with one item's --take/], - [["narrate", "tf", "p-1", "--take", "--thread", "--temperature", "0.7"], /--temperature go with one item's --take .* a thread read and --all --take do not take them/], - [["narrate", "tf", "--all", "--take", "--reading", "1"], /--reading go with one item's --take/], + [["narrate", "tf", "p-1", "--take", "--reading", "soon"], /--reading must be a whole number from 0 to 99999 .*got soon -- or next/], + [["narrate", "tf", "p-1", "--take", "--for", "post", "--reading", "1"], /--for and --tuned are a thread read's/], + [["narrate", "tf", "--all", "--take", "--reading", "1"], /--reading go with one item's --take .*--all --take does not take them/], ]) { const r = await cli(args); assert.notEqual(r.code, 0, args.join(" ")); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -25,11 +25,11 @@ import { mkdir, readFile, readdir, rename, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { - NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, + NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextReadingOf, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, } from "umtool-report-to-video/post-narration"; import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast"; import { convertAskOf, stepPitchOf } from "./derivePitch.mjs"; -import { excerptSpansOf, postItemPlan, postReadText } from "umtool-report-to-video/post-item"; +import { excerptSpansOf, postItemPlan, postReadText, scriptEditOf } from "umtool-report-to-video/post-item"; import { partRoles } from "umtool-report-to-video/post-thread"; import { spokenRead } from "umtool-report-to-video/post-redact"; import { projectRedaction } from "./postRedaction.mjs"; @@ -37,7 +37,7 @@ import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs"; import { TUNING_FLAGS } from "./readTuning.mjs"; -import { TTS_TUNING_FIELDS, quantizeTtsTuningValue, ttsReadingError, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; +import { TTS_TUNING_FIELDS, normalizeTtsTuning, quantizeTtsTuningValue, ttsReadingError, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -48,7 +48,7 @@ export const NARRATE_USAGE = [ "usage: umtool posts narrate <project> --import [--dry-run] [--json]", " umtool posts narrate <project> --list [--json]", " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", - " [--reading N] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]", + " [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--no-pick]", " [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full", " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]", " umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] [--no-convert]", @@ -60,7 +60,8 @@ export const NARRATE_USAGE = [ " [--pitch target|source|contour] [--semitones <n>]", " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]", " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--post-take <n>]", - " [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--force] [--dry-run]", + " [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--force] [--dry-run] [--no-pick]", + " [--reading N|next] [tuning flags] [--for <role>] [--tuned <role|*>=reading:N,temperature:t,…]…", " umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new", " read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)", " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", @@ -99,8 +100,12 @@ export const NARRATE_USAGE = [ " Orpheus (its seeds move; a new cached file), the same N again the same file. --temperature (0.1-1.5) --top-p", " (0.05-1) --top-k (0-200) --min-p (0-0.5) --repeat-penalty (1-2) --chunk-takes (1-6, the tries a sentence gets):", " Orpheus's TUNING for this read, any of them, the rest its defaults. The take records the tuning (every value) and", - " the reading it was made with. Kokoro and eSpeak NG ignore both (the editor says so). One item's --take only: not", - " --thread, not --all.", + " the reading it was made with. Kokoro and eSpeak NG ignore both (the editor says so). One item's --take only, not", + " --all. --reading next: one past the highest reading these words were read at (0 for new words). --no-pick: the", + " new take joins the list unpicked (--pick <n> makes it the one; the bench's Read again does this).", + " With --thread: the whole read's, every synthesized piece read anew (next: each one past its own highest); --for", + " <role> (post, quoted, parent:<i>, linked:<i>, screen:<id>:<line>) one piece's only, the others from the cache;", + " --tuned <role|*>=reading:N,temperature:t,… (repeatable) each piece's exactly (what a read's `read.tuned` says).", " --post-take <n> (--take --thread): his own line is the item's take n (as --list numbers them: a recording, or one", " converted to his character's voice), not synthesized -- the context around it is; each part records where it came from.", " --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op", @@ -274,8 +279,11 @@ export function narrationLines(e, render) { `${e.id} ${isNarrated(e) ? "NARRATED" : n.off ? "narration off" : "not narrated"}${n.approved ? " · approved" : ""} ${plan.total.toFixed(2)} s`, ` script: ${n.script ? JSON.stringify(n.script) : "(none)"}`, ]; + // EDITED BEFORE READS WERE KEPT APART FROM THE CARD (post-item.mjs scriptEditOf "legacy"): its card follows the script. + if (scriptEditOf(e) === "legacy") lines.push(` ${LEGACY_EDIT}`); (n.takes ?? []).forEach((tk, i) => { - lines.push(` ${t?.index === i ? "▶" : " "} #${i + 1} ${tk.file} ${Number(tk.seconds).toFixed(2)} s ${tk.engine ?? "?"} · ${tk.voice ?? "?"}${tk.parts?.length ? ` ${tk.parts.length} parts` : ""}${tk.note ? ` note: ${tk.note}` : ""}${tk.script && tk.script !== n.script ? " (an older script)" : ""}`); + const tuned = [...(Number.isInteger(tk.reading) && tk.reading > 0 ? [`reading ${tk.reading}`] : []), ...Object.entries(normalizeTtsTuning(tk.tuning)).map(([k, v]) => `${k} ${v}`)]; + lines.push(` ${t?.index === i ? "▶" : " "} #${i + 1} ${tk.file} ${Number(tk.seconds).toFixed(2)} s ${tk.engine ?? "?"} · ${tk.voice ?? "?"}${tuned.length ? ` ${tuned.join(", ")}` : ""}${tk.parts?.length ? ` ${tk.parts.length} parts` : ""}${tk.note ? ` note: ${tk.note}` : ""}${tk.script && tk.script !== n.script ? " (an older script)" : ""}`); }); if (plan.narration) { const k = postNarrationKnobs(e, render); @@ -286,6 +294,9 @@ export function narrationLines(e, render) { return lines; } +/** What a legacy edited script is told (`--list`, the bench): the fact, and what moves it to the new rule. */ +export const LEGACY_EDIT = "edited before reads were kept apart from the card: its card follows the script -- save the script again to keep the card to the post's words"; + /** `k=v` words as a narration patch (the post's mix, or with `cut` the cut's). */ export function mixPatchOf(pairs, { cut = false } = {}) { const out = {}; @@ -361,7 +372,7 @@ export async function transcriptionLaneHeld() { } } -export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, tuning = null, reading = null, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS } = {}) { +export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, tuning = null, reading = null, keepPick = false, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS } = {}) { const k = postNarrationKnobs(e, render); const words = String(script ?? e.narration?.script ?? "").trim(); if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`); @@ -446,7 +457,7 @@ export async function makeTake(project, e, { script = null, note = null, engine // What it SAID, when an anonymous handle made that differ from the script (post-anon.mjs): the lint reads it. ...(said.anonymised ? { said: said.text } : {}), }; - const patch = { addTake: take, ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; + const patch = { addTake: take, ...(keepPick ? { keepPick: true } : {}), ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; const { result: wrote, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); return { take, result: wrote, editNotes, ...(deferred ? { deferred } : {}) }; } @@ -492,15 +503,56 @@ export function tuningFlags(str) { if (err) throw new NarrateError(err.replace(/ \(got NaN\)$/, ` (got ${str(flag) || "nothing"})`)); tuning[field] = v; } - const reading = num("--reading"); - if (reading !== null) { + // `--reading next` (lane line-rerun): one past the highest reading of these words -- worked out where the words are. + const next = String(str("--reading") ?? "").trim().toLowerCase() === "next"; + const reading = next ? (flags.push("--reading"), "next") : num("--reading"); + if (reading !== null && !next) { const err = ttsReadingError(reading, "--reading"); - if (err) throw new NarrateError(err.replace(/got NaN\)$/, `got ${str("--reading") || "nothing"})`)); + if (err) throw new NarrateError(err.replace(/got NaN\)$/, `got ${str("--reading") || "nothing"} -- or next`)); } if (!flags.length) return null; return { tuning: Object.keys(tuning).length ? tuning : null, reading, flags }; } +/** The fields `--tuned` names: the reading and the tuning's own (llama-server's names). */ +const TUNED_FIELDS = new Set(["reading", ...TTS_TUNING_FIELDS]); + +/** + * A THREAD READ's readings and tunings by piece (lane line-rerun): `{ "<role>" | "*": { reading?, tuning? } }` -- + * `--reading N|next` and the tuning flags for the whole read ("*"), or for one piece with `--for <role>`; and + * `--tuned <role|*>=reading:N,temperature:t,…` (repeatable: what a read's record asks again exactly). `{}` with none. + */ +export function threadTunedOf(tuned, { str, multi }) { + const out = {}; + const forRole = str("--for"); + if (forRole !== null && !/^(post|quoted|parent:\d|linked:\d{1,2}|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(String(forRole))) { + throw new NarrateError(`--for names one piece of the read: post, quoted, parent:<i>, linked:<i> or screen:<id>:<line> (got ${forRole})`); + } + if (forRole !== null && !tuned) throw new NarrateError("--for goes with --reading and the tuning flags: what that piece is read with"); + if (tuned) out[forRole ?? "*"] = { ...(tuned.reading !== null ? { reading: tuned.reading } : {}), ...(tuned.tuning ? { tuning: tuned.tuning } : {}) }; + for (const raw of multi("--tuned")) { + const m = /^([^=]+)=(.+)$/.exec(String(raw).trim()); + if (!m) throw new NarrateError(`--tuned takes <role>=reading:N,temperature:t,… (got ${raw})`); + const t = {}; + let reading = null; + for (const kv of m[2].split(",")) { + const [k, v] = kv.split(":").map((x) => x?.trim()); + if (!TUNED_FIELDS.has(k) || v === undefined || v === "") throw new NarrateError(`--tuned ${m[1]}: ${kv} is not one of ${[...TUNED_FIELDS].join(", ")} with a value`); + if (k === "reading") { + reading = v === "next" ? "next" : Number(v); + if (reading !== "next" && ttsReadingError(reading)) throw new NarrateError(`--tuned ${m[1]}: ${ttsReadingError(reading, "reading")}`); + } else { + const q = quantizeTtsTuningValue(k, Number(v)); + const err = ttsTuningValueError(k, q, `--tuned ${m[1]} ${k}`); + if (err) throw new NarrateError(err); + t[k] = q; + } + } + out[m[1]] = { ...(reading !== null ? { reading } : {}), ...(Object.keys(t).length ? { tuning: t } : {}) }; + } + return out; +} + /** * A just-made take's WORD TIMINGS (for a beep over a slur it says): the editor's * transcription of its file, aligned to the script it read (word-zoom.mjs @@ -529,10 +581,14 @@ export async function narrateCommand(project, words, flags, { json = false, dryR const pairs = words.filter((w) => /^[A-Za-z][A-Za-z.]*=/.test(w)); const ref = words.find((w) => !/^[A-Za-z][A-Za-z.]*=/.test(w)) ?? null; const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir))); - // A read's tuning and reading are one item's new take's (not a thread read's, not --all's: S1 of the re-tune plan). + // A read's tuning and reading are one item's new take's -- a single read's, or a thread read's (lane line-rerun: + // the whole read's, or one piece's with --for) -- never --all's. const tuned = tuningFlags(str); - if (tuned && !(flags.has("--take") && !flags.has("--thread") && !flags.has("--all") && ref)) { - throw new NarrateError(`${tuned.flags.join(", ")} go with one item's --take (umtool posts narrate <p> <item> --take --reading 1); a thread read and --all --take do not take them`); + if (tuned && !(flags.has("--take") && !flags.has("--all") && ref)) { + throw new NarrateError(`${tuned.flags.join(", ")} go with one item's --take (umtool posts narrate <p> <item> --take --reading 1); --all --take does not take them`); + } + if ((str("--for") !== null || multi("--tuned").length) && !(flags.has("--take") && flags.has("--thread"))) { + throw new NarrateError("--for and --tuned are a thread read's (umtool posts narrate <p> <item> --take --thread --for screen:<id>:<line> --reading next)"); } if (flags.has("--import")) { @@ -576,7 +632,7 @@ export async function narrateCommand(project, words, flags, { json = false, dryR } if (flags.has("--list") || (!ref && !flags.has("--all"))) { - if (json) out(JSON.stringify({ ok: true, items: tl.map((e) => ({ id: e.id, narrated: isNarrated(e), narration: e.narration ?? null, seconds: postItemPlan(e, render).total })) }, null, 2)); + if (json) out(JSON.stringify({ ok: true, items: tl.map((e) => ({ id: e.id, narrated: isNarrated(e), narration: e.narration ?? null, seconds: postItemPlan(e, render).total, ...(scriptEditOf(e) ? { scriptEdit: scriptEditOf(e) } : {}) })) }, null, 2)); else { const narrated = tl.filter(isNarrated).length; out(`${project.id}: ${tl.length} post item(s), ${narrated} narrated, ${tl.filter((e) => e.narration?.approved).length} approved`); @@ -775,18 +831,24 @@ export async function narrateCommand(project, words, flags, { json = false, dryR postTake: str("--post-take"), // ITS SCREENS (post-screens.mjs): read after his words unless --no-screens; a line from a take (--line-take). screens: !flags.has("--no-screens"), lineTakes: lineTakesOf(multi("--line-take")), + // Its readings and tunings (lane line-rerun): the whole read's, one piece's (--for), each piece's (--tuned). + tuned: threadTunedOf(tuned, { str, multi }), keepPick: flags.has("--no-pick"), }); } if (str("--post-take") !== null) throw new NarrateError("--post-take is a thread read's (umtool posts narrate <p> <item> --take --thread --post-take <n>)"); if (multi("--line-take").length) throw new NarrateError("--line-take is a thread read's (umtool posts narrate <p> <item> --take --thread --line-take screen:<id>:<line>=<n>)"); if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { + // `--reading next` (lane line-rerun): one past the highest reading of the words this take reads. + const words = String(str("--script") ?? e.narration?.script ?? "").trim(); + const asked = tuned?.reading === "next" ? { ...tuned, reading: nextReadingOf(e.narration?.takes, words) } : tuned; + const keepPick = flags.has("--no-pick"); const r = await makeTake(project, e, { script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"), - speed: speedFlag(str), ...(tuned ? { tuning: tuned.tuning, reading: tuned.reading } : {}), render, emit: (_ev, f) => !json && f?.message && out(f.message), + speed: speedFlag(str), ...(asked ? { tuning: asked.tuning, reading: asked.reading } : {}), keepPick, render, emit: (_ev, f) => !json && f?.message && out(f.message), }); - if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, narration: r.result.narration, token: r.result.token }, null, 2)); - else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}${tunedLabel(tuned)}`); + if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, picked: !keepPick, narration: r.result.narration, token: r.result.token }, null, 2)); + else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), ${keepPick ? "not picked (--pick to play it)" : "picked"}${r.take.note ? ` — note: ${r.take.note}` : ""}${tunedLabel(asked)}`); return 0; } const patch = pairs.length ? mixPatchOf(pairs) : {}; diff --git a/umtool/lib/report/postReadAgain.test.mjs b/umtool/lib/report/postReadAgain.test.mjs @@ -0,0 +1,106 @@ +// READ AGAIN on the post bench (lane line-rerun, S3 of the Orpheus re-tune plan): a re-read that joins the list +// unpicked, the next reading of a text, a script saved FOR READING (`narration.forReading`: the one writer marks it, +// undo restores it), a spoken edit that would say what a screen masks refused when written, and an item edited +// before the rule found by --list. Temp dirs, a stub tts, invented people. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postsCommand } from "./postsCli.mjs"; +import { LEGACY_EDIT, makeTake } from "./postNarrationCli.mjs"; +import { StructureRefused, manifestToken, undoStructural, updatePostNarration } from "./manifest.mjs"; +import { nextReadingOf } from "umtool-report-to-video/post-narration"; +import { scriptEditOf, shownDraftOf } from "umtool-report-to-video/post-item"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-read-again-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const wav = (f, secs) => execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]); +const TEXT = "The ferry runs at noon.\n\nBring a coat for the crossing."; +const item = (o = {}) => ({ type: "post", id: "p-1", post: "ferry-x/1", platform: "x", author: "Ferry Fan", handle: "ferryfan", date: "2026-10-30T10:00:00.000Z", text: TEXT, ...o }); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "ferry-x", channelsDir: path.join(ROOT, "channels") }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, + timeline, + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const stub = (asked) => async (body) => { + asked.push(body); + wav(body.out, 1.1); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1.1, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...(body.tuning ?? {}) }, reading: body.reading ?? 0 } }; +}; +const cli = async (args) => { + const lines = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + return { code, out: lines.join("\n") }; +}; + +test("READ AGAIN: the next reading of the saved script, a take that joins the list UNPICKED (keepPick) and records its reading", async () => { + const p = await project("again", [item({ narration: { script: shownDraftOf(item()), engine: "orpheus", voice: "zac" } })]); + const asked = []; + await makeTake(p, (await manifest(p)).timeline[0], { ask: stub(asked), redaction: null }); + let e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.pick, 0); + const reading = nextReadingOf(e.narration.takes, e.narration.script); + assert.equal(reading, 1); + await makeTake(p, e, { reading, tuning: { temperature: 0.7 }, keepPick: true, ask: stub(asked), redaction: null }); + e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.takes.length, 2); + assert.equal(e.narration.pick, 0, "the playing take stays the one"); + assert.equal(e.narration.takes[1].reading, 1); + assert.equal(e.narration.takes[1].tuning.temperature, 0.7); + assert.equal(asked[1].reading, 1); + assert.equal(nextReadingOf(e.narration.takes, e.narration.script), 2); +}); + +test("THE ONE WRITER marks a script saved for reading (forReading) and clears it when it says the post's words as drafted; undo restores it with the script", async () => { + const p = await project("marker", [item({ narration: { script: shownDraftOf(item()) } })]); + const set = async (script) => updatePostNarration(p.dir, "p-1", { script }, { token: await manifestToken(p.dir) }); + await set("The ferry runs at twelve noon.\n\nBring a coat for the crossing."); + let e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.forReading, true); + assert.equal(scriptEditOf(e), "reading"); + // Paragraphs merged are an edit too. + await set("The ferry runs at noon. Bring a coat for the crossing."); + assert.equal((await manifest(p)).timeline[0].narration.forReading, true); + await set(shownDraftOf(item())); + e = (await manifest(p)).timeline[0]; + assert.equal("forReading" in e.narration, false); + assert.equal(scriptEditOf(e), null); + // Undo goes back to an undo point (writes close together share one): whichever script it restores, the marker is + // restored with it -- never an edited script without it (that would be "legacy"). + await undoStructural(p.dir, { token: await manifestToken(p.dir) }); + e = (await manifest(p)).timeline[0]; + assert.notEqual(scriptEditOf(e), "legacy", "undo restores the marker with the script"); + assert.equal(e.narration.forReading === true, scriptEditOf(e) === "reading"); +}); + +test("A SPOKEN EDIT that says what a screen masks (an e-mail, a number) or a redacted line holds is refused when it is written", async () => { + const sc = { id: "s1", media: 0, kind: "email", read: "all", lines: [{ text: "Tickets from desk@ferry.example" }, { text: "booking ref 88231907" }, { text: "the captain's home street name", redact: true }] }; + const media = [{ src: "posts-media/ferry-x/1/1_1.png", kind: "image", width: 900, height: 1400 }]; + const p = await project("hidden", [item({ media, screens: [sc], narration: { script: shownDraftOf(item()) } })]); + const set = async (script) => updatePostNarration(p.dir, "p-1", { script }, { token: await manifestToken(p.dir) }); + await assert.rejects(() => set("Write to desk@ferry.example for tickets."), (err) => err instanceof StructureRefused && /the script says an e-mail address that line 0 of screen s1 masks/.test(err.errors.join(" "))); + await assert.rejects(() => set("Your booking is 88231907."), (err) => err instanceof StructureRefused && /a number that line 1 of screen s1 masks/.test(err.errors.join(" "))); + await assert.rejects(() => set("He named the captain's home street name aloud."), (err) => err instanceof StructureRefused && /redacted/.test(err.errors.join(" "))); + await set("The ferry runs at twelve noon."); + assert.equal((await manifest(p)).timeline[0].narration.forReading, true); +}); + +test("EDITED BEFORE THE RULE: --list (and --json) says which items' scripts were edited before reads were kept apart from the card", async () => { + const p = await project("legacy", [item({ narration: { script: "Something else entirely." } }), { ...item({ narration: { script: shownDraftOf(item()) } }), id: "p-2", post: "ferry-x/2" }]); + const r = await cli(["narrate", p.id, "--list"]); + assert.equal(r.code, 0, r.out); + assert.equal(r.out.split(LEGACY_EDIT).length - 1, 1, r.out); + const j = await cli(["narrate", p.id, "--list", "--json"]); + const items = JSON.parse(j.out).items; + assert.deepEqual(items.map((x) => x.scriptEdit ?? null), ["legacy", null]); +}); diff --git a/umtool/lib/report/postScreensCli.mjs b/umtool/lib/report/postScreensCli.mjs @@ -43,6 +43,8 @@ export const SCREEN_USAGE = [ " umtool posts screen <project> <item> rm <id> [--json]", " umtool posts screen <project> <item> check <id> [--by <name>] [--undo] [--json]", " umtool posts screen <project> <item> read [--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run] [--json]", + " [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]", + " [--for screen:<id>:<line>|post|…] [--tuned <role|*>=reading:N,…]… [--no-pick]", " umtool posts screen <project> <item> record <id> <line> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim]", " [--no-convert] [--pitch target|source|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events] [--json]", " A post's SCREENS: the text screenshots it carries (a DM exchange or an email in its video, a screenshot attached),", @@ -61,6 +63,9 @@ export const SCREEN_USAGE = [ " read: the thread read with the screens (posts narrate <p> <item> --take --thread): his words from the take that plays", " (--post-take n: another), each read line in its speaker's voice; --line-take: that line from the item's take n;", " a line's CHOSEN take (take.<n>=, the bench's select) in its place. A recording nobody chose is said, never read in.", + " --reading N|next and the tuning flags: every synthesized piece read anew (next: each one past its own highest);", + " with --for <role> that one piece only (the bench's Read again on a line), the rest from the parts cache. Each piece", + " keeps the reading the playing read gave it while it says the same words. --no-pick: the new take is not picked.", " record: ONE LINE in your voice -- the line as the read says it (its shapes and redaction left out) recorded, then", " cleaned and converted to its SPEAKER's character's stock voice (none: kept as recorded; --as may only name that one),", " each a new take, none of them picked; choose it for the line (set <id> take.<n>=<take>), then read. --check-words", @@ -380,13 +385,16 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js if (verb === "read") { if (!screens.length) fail(`${e.id} has no screens to read (add one first)`); const { threadCommand, parentsSelector } = await import("./postThreadRead.mjs"); - const { lineTakesOf } = await import("./postNarrationCli.mjs"); + const { lineTakesOf, threadTunedOf, tuningFlags } = await import("./postNarrationCli.mjs"); const postTake = flag("--post-take") ?? defaultPostTake(e); const o = screenReadOptions(e, { flags, flag, multi }); return threadCommand(project, e, { manifest, json, out, ...o, parents: parentsSelector(o.parents), engine: flag("--engine"), note: flag("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, // The playing read's (re-attached while their lines say the same), the screens' CHOSEN ones over them, the flags' over all. postTake, lineTakes: { ...defaultLineTakes(e), ...chosenLineTakes(e), ...lineTakesOf(multi("--line-take")) }, + // Its readings and tunings (lane line-rerun): the flags' (--reading, the tuning flags, --for, --tuned), over the + // playing read's -- each piece's kept while it says the same words. + tuned: threadTunedOf(tuningFlags(flag), { str: flag, multi }), inherit: playingTuned(e), keepPick: flags.has("--no-pick"), }); } if (verb === "record") { @@ -456,6 +464,14 @@ export function defaultPostTake(e) { return at >= 0 ? at + 1 : null; } +/** The playing thread read's pieces' readings and tunings (`read.tuned`, each with the words it said), or `{}`. */ +export function playingTuned(e) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + const k = Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0; + const t = takes[k]?.read; + return t?.kind === "thread" && isObj(t.tuned) ? t.tuned : {}; +} + /** * The lines the playing thread read took from takes (`read.lineTakes`), found again by their files -- each ONLY while * its line still says what it said then (`line`, stored with it): a line edited, removed or moved is read afresh, never diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -65,6 +65,7 @@ import { spokenRead, termsFor } from "umtool-report-to-video/post-redact"; import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say"; import { SCREEN_LINE_GAP, parseScreenRole, screenWho, screensOf, shapeSpans } from "umtool-report-to-video/post-screens"; import { readManifest } from "../projects/report.mjs"; +import { TTS_TUNING_FIELDS, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -73,6 +74,7 @@ const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const r3 = (v) => Math.round(v * 1000) / 1000; const str = (v) => (typeof v === "string" ? v : ""); const norm = (t) => str(t).replace(/\s+/g, " ").trim(); +const isTuneObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** The project's parts cache (relative to its folder). */ export const PARTS_CACHE = "narration/parts-cache"; @@ -121,10 +123,41 @@ export async function projectCastMap(dir) { /** * A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when - * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before). + * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before), and + * of its READING and TUNING when it asks one (lane line-rerun: `…|r2`, `…|t{"temperature":0.7}` -- none, reading 0 or + * a tuning of the defaults: the key as before, so every part already cached is found). */ -/** @type {(engine: string, voice: string, text: string, speed?: number | null) => string} */ -export const partKey = (engine, voice, text, speed = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}`).digest("hex"); +/** @type {(engine: string, voice: string, text: string, speed?: number | null, tune?: { reading?: number, tuning?: Record<string, number> } | null) => string} */ +export const partKey = (engine, voice, text, speed = null, tune = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}${tuneSig(tune)}`).digest("hex"); + +/** A part's reading and tuning as its key and its "is it up to date" say them: "" for none (the first reading, the defaults). */ +export function tuneSig(tune) { + const r = Number.isInteger(tune?.reading) && tune.reading > 0 ? `|r${tune.reading}` : ""; + const t = tuningOf(tune?.tuning); + return `${r}${t ? `|t${JSON.stringify(t)}` : ""}`; +} + +/** A tuning with the sampler's defaults left out (takes kept as asked), in the fields' order; null when none is left. */ +export function tuningOf(tuning) { + const n = normalizeTtsTuning(tuning); + const out = Object.fromEntries(TTS_TUNING_FIELDS.filter((k) => n[k] !== undefined).map((k) => [k, n[k]])); + return Object.keys(out).length ? out : null; +} + +/** + * THE NEXT READING of one piece's words (lane line-rerun, "Read again"): one past the highest reading any take's part + * of that role recorded for those words (a part with none: 0), or 0 when no take read them. + */ +export function nextPartReading(e, role, text) { + let hi = -1; + for (const t of Array.isArray(e?.narration?.takes) ? e.narration.takes : []) { + for (const p of Array.isArray(t?.parts) ? t.parts : []) { + if (p?.role !== role || norm(p.text) !== norm(text) || p.take) continue; + hi = Math.max(hi, Number.isInteger(p.reading) ? p.reading : 0); + } + } + return hi + 1; +} /** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */ export function parentsSelector(v) { @@ -166,7 +199,7 @@ export function seenIds(manifest, e) { * @param {{ red?: any, map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, parents?: string, * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o] */ -export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null, screens = true, names = {}, lineTakes = {} } = {}) { +export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null, screens = true, names = {}, lineTakes = {}, tuned = {}, inherit = {} } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; @@ -294,6 +327,19 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i take: { n: postTake.n, id: takeIdOf(t), file: t.file, ...(t.engine ? { engine: t.engine } : {}) }, }; } + // EACH SYNTHESIZED PIECE's READING AND TUNING (lane line-rerun): the one asked for its role (`tuned[role]`), else + // the whole read's (`tuned["*"]`), else the one the playing read gave it while it says the same words (`inherit`, + // posts screen read's) -- a reading "next" one past the highest its words were read at. + for (const pc of pieces) { + if (pc.take) continue; + const kept = isTuneObj(inherit?.[pc.role]) && norm(inherit[pc.role].said) === norm(pc.text) ? inherit[pc.role] : null; + const ask = tuned?.[pc.role] ?? tuned?.["*"] ?? kept; + if (!isTuneObj(ask)) continue; + const reading = ask.reading === "next" ? nextPartReading(e, pc.role, pc.text) : Number.isInteger(ask.reading) ? ask.reading : 0; + const tuning = tuningOf(ask.tuning); + if (reading > 0) pc.reading = reading; + if (tuning) pc.tuning = tuning; + } const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()]; const states = pieces.map((p) => p.slurs).filter(Boolean); return { @@ -402,12 +448,13 @@ export function readParts(plan) { const line = typeof pc.line === "string" ? { line: pc.line, speaker: str(pc.speaker) } : {}; if (pc.take) return [{ piece, para: 0, role: pc.role, voice: pc.voice, text: pc.text, file: pc.take.file, take: pc.take.id, key: null, ...line }]; const eng = pc.engine ?? plan.engine; - return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null), ...line })); + const tune = { ...(pc.reading ? { reading: pc.reading } : {}), ...(pc.tuning ? { tuning: pc.tuning } : {}) }; + return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), ...tune, text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null, tune), ...line })); }); } /** Each piece's `engine:voice` (and its speed, when it has one), in order, once each -- what a read sounds like, for "is it up to date". */ -const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => (p.take ? `take:${typeof p.take === "object" ? p.take.id : p.take}` : `${p.engine ?? fallback}:${p.voice}${typeof p.speed === "number" && p.speed !== 1 ? `x${p.speed}` : ""}`)))].join("+"); +const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => (p.take ? `take:${typeof p.take === "object" ? p.take.id : p.take}` : `${p.engine ?? fallback}:${p.voice}${typeof p.speed === "number" && p.speed !== 1 ? `x${p.speed}` : ""}${tuneSig(p)}`)))].join("+"); /** * THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece, @@ -424,7 +471,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : ` t += gap; const s = Number(seconds[i]); // A part from a take (--post-take) says which (`take`: its id); a synthesized one its parts-cache file and voice. - const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, ...(typeof p.line === "string" ? { line: p.line, speaker: str(p.speaker) } : {}), voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), start: r3(t), seconds: r3(s), gapBefore: gap }; + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, ...(typeof p.line === "string" ? { line: p.line, speaker: str(p.speaker) } : {}), voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), ...(p.reading ? { reading: p.reading } : {}), ...(p.tuning ? { tuning: p.tuning } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), start: r3(t), seconds: r3(s), gapBefore: gap }; t += s; return row; }); @@ -432,7 +479,10 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : ` } /** The `read` record of a take: how it was asked for (only what differs from the defaults). */ -export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null, postTake = null, screens = true, lineTakes = {} }) { +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null, postTake = null, screens = true, lineTakes = {}, pieces = [] }) { + // Each piece's reading and tuning, as made (lane line-rerun), with the words it said: a later read of the same words + // keeps it (posts screen read), and `--tuned` asks it again exactly (castProject.mjs threadArgvOf). + const tuned = Object.fromEntries((pieces ?? []).filter((pc) => !pc.take && (pc.reading || pc.tuning)).map((pc) => [pc.role, { ...(pc.reading ? { reading: pc.reading } : {}), ...(pc.tuning ? { tuning: pc.tuning } : {}), said: pc.text }])); return { kind: "thread", parents: parentsSelector(parents), ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), @@ -445,6 +495,7 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = ...(screens ? {} : { screens: false }), // Each with the line it said then (`line`): it is re-attached only while the line says the same (defaultLineTakes). ...(Object.keys(lineTakes ?? {}).length ? { lineTakes: Object.fromEntries(Object.entries(lineTakes).map(([r, lt]) => [r, { n: lt.n, file: lt.take.file, ...(typeof lt.line === "string" ? { line: lt.line } : {}) }])) } : {}), + ...(Object.keys(tuned).length ? { tuned } : {}), }; } @@ -485,7 +536,7 @@ export async function threadTake(project, e, opts = {}) { manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, postTake: postTakeN = null, - screens = true, lineTakes: lineTakesN = {}, names: names0 = undefined, + screens = true, lineTakes: lineTakesN = {}, names: names0 = undefined, tuned = {}, inherit = {}, keepPick = false, } = opts; const manifest = m0 ?? (await readManifest(project.dir)); if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); @@ -510,7 +561,7 @@ export async function threadTake(project, e, opts = {}) { })); // The characters' names (a screen's `who` may be one), to their handles. const names = names0 !== undefined ? names0 : characterNames(L); - const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake, screens, names, lineTakes }); + const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake, screens, names, lineTakes, tuned, inherit }); for (const [r, lt] of Object.entries(lineTakes)) lt.line = plan.pieces.find((pc) => pc.role === r)?.line; const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); @@ -576,7 +627,7 @@ export async function threadTake(project, e, opts = {}) { emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.engine === plan.engine ? p.voice : `${p.engine}:${p.voice}`}): asking the editor…` }); await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); try { - const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p), ...(typeof p.speed === "number" ? { speed: p.speed } : {}) }, { ...(editor ? { editor } : {}), emit }); + const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), ...(p.tuning ? { tuning: p.tuning } : {}), ...(p.reading ? { reading: p.reading } : {}) }, { ...(editor ? { editor } : {}), emit }); if (jobId) jobs.push(jobId); } catch (err) { throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`); @@ -622,9 +673,10 @@ export async function threadTake(project, e, opts = {}) { ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), // Where its parts' speeds came from: --speed (kept as asked), else their characters' presets / the item's own. ...(plan.pieces.some((p) => typeof p.speed === "number") ? { speedAsked: typeof speed === "number" ? true : "preset" } : {}), - read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake, screens, lineTakes }), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake, screens, lineTakes, pieces: plan.pieces }), }; - const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; + // A re-read (--no-pick, the bench's Read again) joins the list unpicked: Pick makes it the one. + const patch = { addTake: take, ...(keepPick ? { keepPick: true } : {}), ...(plan.script ? { script: plan.script } : {}) }; // THE ITEM CHANGED WHILE ITS READ WAS MADE (a bench edit during minutes of synthesis): what was read is not what it // holds now -- refused, never kept as a stale read (the parts made are cached: running it again is quick). const nowE = ((await readManifest(project.dir))?.timeline ?? []).find((x) => x?.id === e.id); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -199,9 +199,9 @@ export const POSTS_USAGE = [ " none: the rule as it stands", ].join("\n"); -const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--reading", "--temperature", "--top-p", "--top-k", "--min-p", "--repeat-penalty", "--chunk-takes", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take", "--line-take", "--from", "--media", "--kind", "--title", "--line", "--read", "--unread", "--by", "--ref"]); +const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--reading", "--for", "--tuned", "--temperature", "--top-p", "--top-k", "--min-p", "--repeat-penalty", "--chunk-takes", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take", "--line-take", "--from", "--media", "--kind", "--title", "--line", "--read", "--unread", "--by", "--ref"]); /** The valued flags that may be given more than once (each value kept, in order). */ -const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span", "--line-take", "--line"]); +const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span", "--line-take", "--line", "--tuned"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; diff --git a/umtool/lib/report/threadTuned.test.mjs b/umtool/lib/report/threadTuned.test.mjs @@ -0,0 +1,112 @@ +// A THREAD READ's READINGS AND TUNINGS (lane line-rerun, S3 of the Orpheus re-tune plan): the whole read's, one +// piece's (--for), each piece's (--tuned, `read.tuned`); the parts cache key unchanged when none is asked; a re-read +// that joins the list unpicked. No editor (a stub tts); temp dirs; invented people. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { nextPartReading, partKey, threadReadPlan, threadTake, tuneSig } from "./postThreadRead.mjs"; +import { threadTunedOf, tuningFlags } from "./postNarrationCli.mjs"; +import { playingTuned } from "./postScreensCli.mjs"; +import { threadArgvOf } from "./castProject.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-thread-tuned-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const wavOf = async (file, seconds = 0.6) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...VOICE_B, seconds }), { before: 0.1, after: 0.1 }))); +}; +const stubAsk = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out); + return { jobId: `job-${asked.length}`, result: { wav: body.out, ...(body.reading !== undefined ? { reading: body.reading } : {}) } }; +}; +const NO_RED = { terms: [], markup: {}, slurs: null }; +const IMG = { src: "posts-media/bridge-x/7/7_1.png", kind: "image", width: 900, height: 1400 }; +const ITEM = { + type: "post", id: "p-7", post: "bridge-x/7", platform: "x", author: "Bridge Fan", handle: "bridgefan", date: "2026-10-02T10:00:00.000Z", + text: "Here is what they sent.", media: [IMG], narration: { script: "Here is what they sent." }, + screens: [{ id: "s1", media: 0, kind: "dm", read: "all", lines: [{ who: "rivertalk", text: "Are the tolls going up?" }, { who: "bridgefan", text: "Not this year." }] }], +}; + +async function project(name, item = ITEM) { + const dir = path.join(ROOT, name); + await mkdir(path.join(dir, "narration"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "orpheus", voice: "zac" } }, timeline: [item], + }, null, 2)); + return { id: name, dir }; +} +const read = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const LAYERS = { map: {}, cast: {}, item: null, names: {} }; + +test("partKey: no reading and no tuning (or reading 0, a tuning of the defaults) is the key as before -- literally", () => { + assert.equal(partKey("orpheus", "zac", "Hello there."), "4346bef9f0b9c27145409883bb57d513ba3112f5"); + assert.equal(partKey("orpheus", "zac", "Hello there.", null, { reading: 0, tuning: { temperature: 0.55, top_p: 0.85 } }), "4346bef9f0b9c27145409883bb57d513ba3112f5"); + assert.equal(partKey("kokoro", "af_heart", "Hello there.", 1.1), "93d7f42c6ed1c5ac5fe0ae346a3ace3abd007740"); + const r1 = partKey("orpheus", "zac", "Hello there.", null, { reading: 1 }); + assert.notEqual(r1, "4346bef9f0b9c27145409883bb57d513ba3112f5"); + assert.notEqual(partKey("orpheus", "zac", "Hello there.", null, { tuning: { temperature: 0.7 } }), r1); + assert.equal(tuneSig({ reading: 2, tuning: { top_p: 0.9, temperature: 0.7 } }), '|r2|t{"temperature":0.7,"top_p":0.9}'); +}); + +test("--reading/--for/--tuned as a thread read's tuned map; refused in their own words", () => { + const flags = (o) => ({ str: (k) => (k in o ? o[k] : null), multi: (k) => o[`multi:${k}`] ?? [] }); + const a = flags({ "--reading": "next", "--for": "screen:s1:1", "--temperature": "0.7" }); + assert.deepEqual(threadTunedOf(tuningFlags(a.str), a), { "screen:s1:1": { reading: "next", tuning: { temperature: 0.7 } } }); + const b = flags({ "--reading": "2" }); + assert.deepEqual(threadTunedOf(tuningFlags(b.str), b), { "*": { reading: 2 } }); + const c = flags({ "multi:--tuned": ["post=reading:3,top_p:0.9", "screen:s1:0=reading:1"] }); + assert.deepEqual(threadTunedOf(null, c), { post: { reading: 3, tuning: { top_p: 0.9 } }, "screen:s1:0": { reading: 1 } }); + assert.throws(() => threadTunedOf(null, flags({ "multi:--tuned": ["post=pitch:3"] })), /not one of reading, temperature/); + assert.throws(() => threadTunedOf(null, flags({ "--for": "post" })), /--for goes with --reading/); + const d = flags({ "--for": "nowhere", "--reading": "1" }); + assert.throws(() => threadTunedOf(tuningFlags(d.str), d), /--for names one piece/); +}); + +test("ONE LINE READ AGAIN: --for screen:s1:1 --reading next asks only that line (reading 1), the rest from the cache; the take joins unpicked and records the reading", async () => { + const p = await project("one-line"); + const asked = []; + const first = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS }); + assert.equal(asked.length, 3); + assert.ok(asked.every((b) => b.reading === undefined && b.tuning === undefined), "an untuned read asks as before"); + const e1 = (await read(p)).timeline[0]; + assert.equal(e1.narration.pick, 0); + assert.equal(nextPartReading(e1, "screen:s1:1", first.plan.pieces.find((x) => x.role === "screen:s1:1").text), 1); + const again = await threadTake(p, e1, { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS, tuned: { "screen:s1:1": { reading: "next", tuning: { temperature: 0.7 } } }, keepPick: true }); + assert.equal(asked.length, 4, "one part asked"); + assert.deepEqual([asked[3].reading, asked[3].tuning], [1, { temperature: 0.7 }]); + const e2 = (await read(p)).timeline[0]; + assert.equal(e2.narration.takes.length, 2); + assert.equal(e2.narration.pick, 0, "--no-pick: the playing take stays the one"); + const t2 = e2.narration.takes[1]; + assert.deepEqual(Object.keys(t2.read.tuned), ["screen:s1:1"]); + assert.equal(t2.read.tuned["screen:s1:1"].reading, 1); + assert.equal(t2.parts.find((x) => x.role === "screen:s1:1").reading, 1); + assert.equal(t2.parts.find((x) => x.role === "post").reading, undefined); + assert.ok(again.parts.filter((x) => x.role !== "screen:s1:1").every((x) => x.cached)); + // Next again: 2. + await threadTake(p, e2, { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS, tuned: { "screen:s1:1": { reading: "next" } }, keepPick: true }); + assert.equal(asked.at(-1).reading, 2); +}); + +test("the playing read's readings are KEPT by a later read while each piece says the same words (posts screen read), and asked again exactly by --tuned (threadArgvOf)", async () => { + const p = await project("keep"); + const asked = []; + await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS, tuned: { "screen:s1:0": { reading: 3 } } }); + const e = (await read(p)).timeline[0]; + const inherit = playingTuned(e); + assert.equal(inherit["screen:s1:0"].reading, 3); + // The same words: kept -- up to date, nothing asked. + const r = await threadTake(p, e, { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS, inherit }); + assert.equal(r.upToDate, true); + // The line's words changed: its reading is not carried to other words. + const changed = { ...e, screens: [{ ...e.screens[0], lines: [{ who: "rivertalk", text: "Are the fares going up?" }, e.screens[0].lines[1]] }] }; + const plan = threadReadPlan({ timeline: [changed], render: {} }, changed, { red: NO_RED, ...LAYERS, inherit }); + assert.equal(plan.pieces.find((x) => x.role === "screen:s1:0").reading, undefined); + assert.deepEqual(threadArgvOf(e.narration.takes[0].read).filter((x, i, a) => x === "--tuned" || a[i - 1] === "--tuned"), ["--tuned", "screen:s1:0=reading:3"]); +}); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -207,7 +207,9 @@ const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "param // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). // `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1). // `take`: a thread read's part that IS one of the item's takes (postThreadRead.mjs --post-take): that take's id. -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take", "line", "speaker"]); +// `reading`, `tuning` (lane line-rerun): the reading and the tuning a thread read's part was asked at (absent: the +// first reading, the defaults), as postThreadRead.mjs keys and asks it. +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take", "line", "speaker", "reading", "tuning"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -750,6 +752,7 @@ export function validatePostNarration(e) { if (p.speaker !== undefined && typeof p.speaker !== "string") errors.push(`${pw}.speaker must be the screen line's speaker it was made for`); if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); + if (p.reading !== undefined || p.tuning !== undefined) errors.push(...tuningProblems(p.tuning, p.reading, pw)); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i>, media:<i> or screen:<id>:<line> (the text it reads)`); if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); if (p.take !== undefined && !(typeof p.take === "string" && n.takes.some((x) => x !== t && takeIdOf(x) === p.take))) errors.push(`${pw}.take must be the id of another of its takes (the take this part is)`);