commit 4a7b44bd6f7cd779d14e91a451456340b4fa9a92
parent 402488c3bcc861098ada1154cdf54d4e96873266
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 12:00:35 -0500
Merge main (S3, lane/line-rerun) into lane/character-tuning
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
46 files changed, 2719 insertions(+), 184 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -67,8 +67,28 @@
- A cast voice change's re-read (`umtool cast reread`) asks the picked take's own reading and non-default tuning
again, as it does its own speed.
- A card's narration may carry `tuning` and `reading`. A card without them is asked, keyed and kept as before.
- - These flags work only on one item's `--take`, not with `--thread` or `--all --take`. Only the spoken read changes:
- no card's text changes.
+ - These flags work only on one item's `--take` (a thread read's too, since the bullet above), not with
+ `--all --take`. Only the spoken read changes: no card's text changes.
+- **umtool: a line is read again from the post bench, heard as it lands, and picked, with no agent.** Under a post's
+ script, beside each screen line, on a thread read and on the narration page's cards: **Read again** (the same words,
+ the next reading), **Read edited text** (saved, then read) and **Tune ▾** (the six numbers for this line only,
+ started from how it was last made). The new read joins the list unpicked and plays as it lands (a box, on by
+ default, remembered per browser); **Pick** makes it the one, and the one it replaced stays a press away.
+ - What the card shows never changes. A take made from words that are not the post's is stamped when it is made,
+ and while it plays the card follows the post's own words, and its thread tiles keep their times, whatever the
+ script says later. An item playing a take from before this (no stamp, other words) is flagged by
+ `umtool posts narrate <p> --list` and on the bench; reading it again moves it to the rule.
+ - A screen line can be **said as** other words (`umtool posts screen <p> <item> set <id> said.<n>="…"`). It is never
+ drawn, and one that says a masked number or e-mail, or a redacted line, is refused.
+ - A thread read takes `--reading N|next` and the tuning flags, for the whole read or one piece (`--for <role>`),
+ and records each piece's (`--tuned` asks them again). One line read again re-synthesizes only that line.
+ - A card's narration has its own command, `umtool narration <p> <card>`: `--read` keeps a reading without changing
+ the card, `--pick <key>` plays one, and a verdict on the same words is kept.
+ - One read of a post at a time: a double press is one read, and a second press while one runs is refused in place.
+ A read that makes nothing (it already says that) says so, and only a take a job made is played or marked new.
+ While render mode holds the machine, a pressed read says it is waiting for the render.
+ - A cast re-read now always asks a take's recorded `takes` again, so a settings default other than 3 no longer
+ changes it.
- **A tag can be offered under the site's More filters, per site or for the whole corpus.** A site's Tags tab (Sites → a site → Tags) replaces Visibility with **Placement**: Inherit, Main row, More filters, Hidden. Main row and More filters both override a tag the corpus hides, which "Shown here" said it did but never saved. On /tags, a definition's **More filters** box sets the corpus default. The CLI twin is a new `tags` op, `present`: `pnpm ops tags --json '{"op":"present","site":"<site>","tag":{"id":"<tag>","secondary":true}}'` changes one row of `sites/<site>/tags.json`, keeping its other rows and fields; `null` clears a field so the site inherits it again. It is refused, with nothing written, for an unknown site, a tag the corpus does not define, or a field a site cannot set (rules, sites). Needs a rebuild and deploy of the site.
- **umtool: a `take --priority` or `render-mode on -- …` signalled while it turns render mode on lets it go before it exits.**
The signal handlers used to go on only after the claim (the state file and the editor's lanes, held over HTTP), so a
diff --git a/plans/orpheus-retune.md b/plans/orpheus-retune.md
@@ -1,7 +1,8 @@
# Orpheus re-tune and re-run, by the operator alone
-Status: **planned 15 Nov 2026; S1 in progress (16 Nov 2026, `lane/orpheus-tuning`).** Written to be
-picked up cold (after a usage reset). S2, S3 and S4 are not started.
+Status: **planned 15 Nov 2026; S1 done (merged 2dff0a631, shipped 16 Nov 2026); S3 done (`lane/line-rerun`,
+merged 17 Nov 2026; S3b, re-read one sentence, is a follow-up after S4); S2 in progress
+(`lane/character-tuning`).** Written to be picked up cold (after a usage reset). S4 is not started.
## The ask (operator, 15 Nov 2026)
@@ -65,6 +66,8 @@ not a new model.
### S1. The engine takes a tuning and a seed (`lane/orpheus-tuning`; plumbing, no UI)
+**Done** — merged 2dff0a631, shipped 16 Nov 2026.
+
- A synthesis may carry `tuning: { temperature?, top_p?, top_k?, min_p?, repeat_penalty?, takes? }` and
`reading?: integer` (ruled 16 Nov: ONE word end to end — the ops body, the result, the sidecar, the cache
key, a card's `narration.reading`, a post take's `reading`, the CLI's `--reading N`; "variant" already
@@ -110,6 +113,8 @@ not a new model.
### S3. Re-type and re-run a line where it is read (`lane/line-rerun`; post bench, screen lines, card narration)
+**In progress** (17 Nov 2026). S3b (re-read one sentence) is a follow-up, not in this lane.
+
- For every synthesized read (a post's script, a screen line, a card's narration, a thread read): the
text is editable in place; the buttons are
- **Read again**: the same text, the next reading (`reading` + 1, not the cache);
diff --git a/umtool/app/api/report/narration/audio/route.ts b/umtool/app/api/report/narration/audio/route.ts
@@ -9,7 +9,9 @@ export const dynamic = "force-dynamic";
// GET ?project&card: the narration's kept voice for that card's CURRENT words
// and voice (out/narration/<key>.wav), or a 404 until it is synthesized. Names,
-// never paths: the file is found from the manifest's narration.
+// never paths: the file is found from the manifest's narration. `&key=<key>`:
+// another reading kept for that card (lane line-rerun) -- its record must name
+// the card.
export async function GET(request: Request) {
const url = new URL(request.url);
const r = await resolveReport(url.searchParams.get("project") ?? "");
@@ -18,8 +20,12 @@ export async function GET(request: Request) {
const n = narrationsOf(r.manifest).find((x: { id: string }) => x.id === card);
if (!n) return new Response("not a card with a narration", { status: 404 });
const dir = narrationDir(path.join(r.project.dir, "out"));
- if (!(await readNarrationRecord(dir, n.key))) return new Response("this narration has not been synthesized yet", { status: 404 });
- const abs = resolveInRoots(narrationWavPath(dir, n.key));
+ const asked = url.searchParams.get("key");
+ if (asked !== null && !/^[0-9a-f]{64}$/.test(asked)) return new Response("not a reading's key", { status: 400 });
+ const key = asked ?? n.key;
+ const rec = await readNarrationRecord(dir, key);
+ if (!rec || rec.id !== card) return new Response("this narration has not been synthesized yet", { status: 404 });
+ const abs = resolveInRoots(narrationWavPath(dir, key));
const st = abs ? await stat(abs).catch(() => null) : null;
if (!abs || !st?.isFile()) return new Response("this narration has not been synthesized yet", { status: 404 });
return rangeResponse(request, {
diff --git a/umtool/app/api/report/narration/play/route.ts b/umtool/app/api/report/narration/play/route.ts
@@ -1,5 +1,8 @@
import { jobView, runningJob, startJob } from "@/lib/jobs";
-import { narrateCardSteps } from "@/lib/report/driver.mjs";
+import path from "node:path";
+import { UMTOOL_DIR, narrateCardSteps } from "@/lib/report/driver.mjs";
+import { parseTtsTuning, ttsReadingError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { renderWaitSentence } from "@/lib/report/renderMode.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { narrationsOf } from "umtool-report-to-video/narration";
@@ -10,8 +13,13 @@ export const dynamic = "force-dynamic";
// (GET /api/report/build?job=<id>), then plays from
// /api/report/narration/audio. A voice already kept is a quick no-op job.
// One job at a time, as every job here: a running build is a 409.
+// { project, card, again: true, reading?: N | "next", tuning?, text? } (lane line-rerun: Read again, Read edited
+// text, Tune): ONE READING kept for the card, the card not changed -- `umtool narration <p> <card> --read …` as the
+// job; Pick is the narration route's `pick`.
+const TUNING_FLAG_OF: Record<string, string> = { temperature: "--temperature", top_p: "--top-p", top_k: "--top-k", min_p: "--min-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" };
+
export async function POST(request: Request) {
- const body = (await request.json().catch(() => null)) as { project?: string; card?: string } | null;
+ const body = (await request.json().catch(() => null)) as { project?: string; card?: string; again?: boolean; reading?: number | "next"; tuning?: unknown; text?: string } | null;
const r = await resolveReport(String(body?.project ?? ""));
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const card = String(body?.card ?? "");
@@ -21,6 +29,27 @@ export async function POST(request: Request) {
const running = runningJob();
if (running) return Response.json({ error: `a job is already running (${running.kind})` }, { status: 409 });
try {
+ if (body?.again) {
+ const flags: string[] = [];
+ if (body.reading !== undefined && body.reading !== null) {
+ if (body.reading !== "next" && ttsReadingError(body.reading)) return Response.json({ error: ttsReadingError(body.reading) }, { status: 400 });
+ flags.push("--reading", String(body.reading));
+ }
+ if (body.tuning !== undefined && body.tuning !== null) {
+ const t = parseTtsTuning(body.tuning);
+ if (!t.ok) return Response.json({ error: t.error }, { status: 400 });
+ for (const [k, v] of Object.entries(t.value)) flags.push(TUNING_FLAG_OF[k], String(v));
+ }
+ if (typeof body.text === "string" && body.text.trim()) flags.push("--text", body.text.trim());
+ const step = {
+ cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, label: `${card}: a reading of its narration (asks the editor)`, timeoutMs: 15 * 60_000,
+ argv: [process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "narration", r.project.id, card, "--read", ...flags],
+ };
+ const job = startJob(`narrate ${r.project.id} ${card}`, [step], { project: r.project.id });
+ // While render mode gives the machine to a render, the reading waits for it -- said in place.
+ const waiting = renderWaitSentence();
+ return Response.json({ ok: true, job: jobView(job), ...(waiting ? { waiting } : {}) }, { headers: { "cache-control": "no-store" } });
+ }
const job = startJob(`narrate ${r.project.id} ${card}`, narrateCardSteps(r.project, card), { project: r.project.id });
return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } });
} catch (e) {
diff --git a/umtool/app/api/report/narration/route.ts b/umtool/app/api/report/narration/route.ts
@@ -18,6 +18,7 @@ export const dynamic = "force-dynamic";
// reject { note } rejected; the note says what is wrong (required)
// clear {} no verdict (the note is kept)
// note { note } the note alone
+// pick { key } another reading kept for the card plays (umtool narration --pick)
// edit { text, token? } the card's narration words, through the manifest
// writer (snapshot, validators, the edit-notes
// guard); an edit clears the verdict
@@ -81,8 +82,20 @@ export async function POST(request: Request) {
invalidateProjects();
break;
}
+ case "pick": {
+ // ANOTHER READING the card plays (lane line-rerun): `umtool narration <p> <card> --pick <key>`, the CLI's own
+ // command -- its words, reading and tuning; a verdict on the same words kept.
+ const key = String(body.key ?? "");
+ if (!/^[0-9a-f]{64}$/.test(key)) return Response.json({ error: "key must be a kept reading's key" }, { status: 400 });
+ const { cardNarrationCommand } = await import("@/lib/report/cardNarrationCli.mjs");
+ const said: string[] = [];
+ const code = await cardNarrationCommand([r.project.id, card, "--pick", key, "--json"], { out: (x: string) => said.push(x), err: (x: string) => said.push(x) });
+ if (code !== 0) return Response.json({ error: (() => { try { return JSON.parse(said.join("\n")).error; } catch { return said.join(" "); } })() }, { status: 400 });
+ invalidateProjects();
+ break;
+ }
default:
- return Response.json({ error: "action must be approve, reject, clear, note or edit" }, { status: 400 });
+ return Response.json({ error: "action must be approve, reject, clear, note, edit or pick" }, { status: 400 });
}
} catch (e) {
if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -1,7 +1,7 @@
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import {
- POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takeIdOf, takesDirOf,
+ POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextReadingOf, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takeIdOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
import { postItemPlan } from "umtool-report-to-video/post-item";
import { jobState, resultLine, startJob } from "@/lib/research/case-editor";
@@ -27,6 +27,7 @@ import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs";
import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
import { getJob, runningJob, startJob as startUmtoolJob, type Job } from "@/lib/jobs";
import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { renderWaitSentence } from "@/lib/report/renderMode.mjs";
export const dynamic = "force-dynamic";
@@ -50,6 +51,9 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// takes) and `reading` (0 = the first; 1, 2, … another reading)
// are sent as asked -- the take records what the editor says it
// was made with (`tuning`, every value; `reading`)
+// `reading: "next"`: one past the highest reading of these words
+// (lane line-rerun, Read again); `keepPick`: the take joins the list
+// unpicked. One read of a post at a time: a second is a 409 `busy`.
// POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit)
// GET ?project&id&convert=1 what a convert of this post defaults to: its author's character in
// the cast (else the narrator) and that character's convert
@@ -79,9 +83,18 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// job running `umtool posts screen <p> <item> record <id> <n>
// --recording <upload>` -- recorded, cleaned, converted to the
// speaker's character, none picked; the upload removed when it ends
-// POST {project, op: "screen-read", id} MAKE THE READ with its screens: a umtool job running `umtool posts
-// screen <p> <item> read` (the screens' chosen line takes in it)
+// POST {project, op: "screen-read", id, for?, reading?, tuning?, keepPick?}
+// MAKE THE READ with its screens: a umtool job running `umtool posts
+// screen <p> <item> read` (the screens' chosen line takes in it);
+// `for` (screen:<id>:<n>) `reading` (N | "next") `tuning`: one line
+// read again (--for --reading --temperature …), `keepPick`: --no-pick
+// POST {project, op: "thread-read", id, reading?, tuning?}
+// THE THREAD READ AGAIN (lane line-rerun): `posts screen … read` with
+// screens, else `posts narrate <p> <item> --take --thread` asked as the
+// playing read was -- every synthesized piece's next reading, unpicked
// GET ?project&id&screenJob=<job> either job: its state, its result, and -- ended -- the entry as it is
+// GET ?project&id&pending=1 the post's read being made or made and not kept: {jobId, file,
+// script, note} -- the bench follows `?job` with them to land its take
const noStore = { "cache-control": "no-store" };
type Entry = Record<string, unknown> & { id: string; type?: string; narration?: Record<string, unknown> };
@@ -125,10 +138,20 @@ export async function GET(request: Request) {
}
return Response.json({ ok: true, prompts }, { headers: noStore });
}
+ if (id && q.get("pending") !== null) {
+ // THE READ OF THIS POST BEING MADE, or made and not yet kept (review 2, finding 2): its marker's job, file and
+ // words -- a bench that lost it follows the same `?job` GET to land its take. `{ pending: null }` when there is none.
+ const e = postsOf(m).find((x) => x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ const marker = (await readFile(pendingFileOf(r.project.dir, e), "utf8").then(JSON.parse, () => null)) as { jobId?: string; file?: string; script?: string; note?: string } | null;
+ const kept = marker?.file && ((e.narration?.takes ?? []) as Array<{ file?: string }>).some((t) => t.file === marker.file);
+ return Response.json({ ok: true, pending: marker?.jobId && marker.file && !kept ? { jobId: marker.jobId, file: marker.file, script: marker.script ?? null, note: marker.note ?? null } : null }, { headers: noStore });
+ }
if (id && q.get("screenJob") !== null) {
const j = getJob(String(q.get("screenJob")));
if (!j || !screenJobKinds(r.project.id, id).includes(j.kind)) return Response.json({ error: "no such job" }, { status: 404 });
- return Response.json(await screenJobView(r.project.dir, id, j), { headers: noStore });
+ const waiting = j.state === "running" ? renderWaitSentence() : null;
+ return Response.json({ ...(await screenJobView(r.project.dir, id, j)), ...(waiting ? { waiting } : {}) }, { headers: noStore });
}
if (id && !job && q.get("convert") !== null) {
// What a convert of this post defaults to (`posts narrate --recording`'s rule: the author's character, else the narrator).
@@ -152,8 +175,18 @@ export async function GET(request: Request) {
if (!rel.startsWith(`${takesDirOf(postIdOf(e))}/take-`) || rel.includes("..") || !rel.endsWith(".wav")) return Response.json({ error: "not a take of this post" }, { status: 400 });
try {
const st = await jobState(job);
- if (!st.done) return Response.json({ state: "running", status: st.status }, { headers: noStore });
- if (st.status !== "done") return Response.json({ state: "failed", status: st.status, error: st.tail.slice(-3).join(" / ") }, { headers: noStore });
+ // While render mode gives the machine to a render, the read waits for it -- and says so (lane line-rerun).
+ const waiting = !st.done ? renderWaitSentence() : null;
+ if (!st.done) return Response.json({ state: "running", status: st.status, ...(waiting ? { waiting } : {}) }, { headers: noStore });
+ // The post's marker goes only when it names THIS job (review 2, finding 4): another tab's older job never clears
+ // a newer claim.
+ const marker = (await readFile(pendingFileOf(r.project.dir, e), "utf8").then(JSON.parse, () => null)) as { jobId?: string } | null;
+ if (marker?.jobId === job) await rm(pendingFileOf(r.project.dir, e), { force: true });
+ if (st.status !== "done") {
+ // A read that failed leaves nothing behind (its .ask.json would count as a take number).
+ await rm(`${path.join(r.project.dir, ...rel.split("/"))}.ask.json`, { force: true });
+ return Response.json({ state: "failed", status: st.status, error: st.tail.slice(-3).join(" / ") }, { headers: noStore });
+ }
const had = ((e.narration?.takes ?? []) as Array<{ file?: string }>).some((t) => t.file === rel);
if (!had) {
const abs = path.join(r.project.dir, ...rel.split("/"));
@@ -199,7 +232,7 @@ export async function GET(request: Request) {
const { slurs, lexicon } = spoken;
// What the POST asked (its speed and where it came from), kept beside the file until the take is made.
const askFile = `${abs}.ask.json`;
- const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset" } | null;
+ const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset"; keepPick?: boolean } | null;
await rm(askFile, { force: true });
const take = {
...(typeof ask?.speed === "number" ? { speed: ask.speed } : {}), ...(ask?.speedAsked !== undefined ? { speedAsked: ask.speedAsked } : {}),
@@ -215,7 +248,7 @@ export async function GET(request: Request) {
script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), ...(note ? { note } : {}),
};
const { result } = await withEditNotes(r.project, async () =>
- updatePostNarration(r.project.dir, id, { addTake: take, ...(script !== e.narration?.script ? { script } : {}) }, { token: await manifestToken(r.project.dir) }),
+ updatePostNarration(r.project.dir, id, { addTake: take, ...(ask?.keepPick ? { keepPick: true } : {}), ...(script !== e.narration?.script ? { script } : {}) }, { token: await manifestToken(r.project.dir) }),
);
// The editor's `note` (a tuning or reading its engine ignored), handed on so the bench can say so.
return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token, ...(typeof res.note === "string" && res.note ? { note: res.note } : {}) }, { headers: noStore });
@@ -287,13 +320,35 @@ async function postHere(request: Request) {
const id = String(body.id ?? "");
const token = body.token === undefined || body.token === null ? null : String(body.token);
try {
- if (body.op === "screen-read") {
- // MAKE THE READ with the screens (the bench's button): the CLI's own command as a umtool job.
+ if (body.op === "screen-read" || body.op === "thread-read") {
+ // MAKE THE READ with the screens (the bench's button), or a line of it / the whole read READ AGAIN (lane
+ // line-rerun: Read again, Tune): the CLI's own command as a umtool job -- one at a time (a second press: 409).
const e = postsOf(m).find((x) => x.id === id);
if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
const running = runningJob();
if (running) return Response.json({ error: `umtool is running another job (${running.kind}): make the read when it is done`, busy: true }, { status: 409 });
- const j = startUmtoolJob(screenJobKinds(r.project.id, id)[1], [{ label: `${id}: its read made with its screens`, argv: [process.execPath, cliPath(), "posts", "screen", r.project.id, id, "read", "--json"], cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000 }], { project: r.project.id });
+ let again: string[];
+ try {
+ again = readAgainArgv(body);
+ } catch (err) {
+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 });
+ }
+ const withScreens = Array.isArray(e.screens) && (e.screens as unknown[]).length > 0;
+ let argv: string[];
+ // --events: one result line (the job's `result`, screenJobView) -- the take this job MADE, or none and why.
+ if (body.op === "screen-read" || withScreens) argv = ["posts", "screen", r.project.id, id, "read", ...again, "--events"];
+ else {
+ // No screens: the thread read asked as the playing one was (castProject.mjs threadArgvOf), every piece anew.
+ const t = pickedTake(e) as { read?: Record<string, unknown> } | null;
+ if (t?.read?.kind !== "thread") return Response.json({ error: `${id} plays no thread read to read again` }, { status: 400 });
+ const { threadArgvOf } = await import("@/lib/report/castProject.mjs");
+ // Its pieces' own readings (`--tuned`) give way to the new one: every piece is read anew.
+ const asked = (threadArgvOf as (r: unknown, o: { takes: unknown }) => string[])(t.read, { takes: e.narration?.takes ?? [] });
+ const kept = asked.filter((x, i) => x !== "--tuned" && asked[i - 1] !== "--tuned");
+ argv = ["posts", "narrate", r.project.id, id, "--take", "--thread", ...kept, ...again, "--events"];
+ }
+ const label = body.op === "thread-read" ? `${id}: its thread read again` : body.for ? `${id}: ${String(body.for)} read again` : `${id}: its read made with its screens`;
+ const j = startUmtoolJob(screenJobKinds(r.project.id, id)[1], [{ label, argv: [process.execPath, cliPath(), ...argv], cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, ndjson: true, timeoutMs: 45 * 60 * 1000 }], { project: r.project.id });
return Response.json({ ok: true, job: { id: j.id, state: j.state } }, { headers: noStore });
}
if (body.op === "undo") {
@@ -314,40 +369,70 @@ async function postHere(request: Request) {
// Its tuning and reading (another reading of the same words): refused here in the editor's words, sent as asked.
const tuned = body.tuning === undefined || body.tuning === null ? null : parseTtsTuning(body.tuning);
if (tuned && !tuned.ok) return Response.json({ error: tuned.error }, { status: 400 });
- const reading = body.reading === undefined || body.reading === null ? null : body.reading;
+ // `reading: "next"` (Read again): one past the highest reading of these words (post-narration.mjs nextReadingOf).
+ const reading = body.reading === undefined || body.reading === null ? null : body.reading === "next" ? nextReadingOf(e.narration?.takes, script) : body.reading;
const readingError = reading === null ? null : ttsReadingError(reading);
if (readingError) return Response.json({ error: readingError }, { status: 400 });
- // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the
- // narrator's -- a single read's rule (readVoice.mjs).
- const said = await itemReadVoice(r.project, e, {
- render: (m.render ?? {}) as Record<string, unknown>,
- engine: typeof body.engine === "string" && body.engine ? body.engine : null,
- voice: typeof body.voice === "string" && body.voice ? body.voice : null,
- });
- const engine = String(said.engine ?? k.engine);
- const voice = String(said.voice ?? k.voice);
- const pid = postIdOf(e);
- const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
- await mkdir(dir, { recursive: true });
- const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice);
- // Its speed: the one asked for, else the item's own (`narration.speed`), else its character's (the synthetic
- // preset's that answered for the voice) -- makeTake's order.
- const askedSpeed = body.speed === undefined || body.speed === null ? (e.narration as { speed?: number } | undefined)?.speed ?? (said as { speed?: number }).speed : Number(body.speed);
- const speed = askedSpeed === undefined || askedSpeed === null || engine === "orpheus" ? undefined : Number(askedSpeed);
- // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
- // filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.mjs); the script is kept as written. The bench cannot word-time a take as it is made,
- // so a beep falls back to skip here (the CLI's --take times it and beeps).
- const red = await projectRedaction(r.project.dir, m);
- const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }).text;
- const out = path.join(r.project.dir, ...rel.split("/"));
- // Its speed and where it came from, for the take the GET makes when the job is done (a sidecar, removed then).
- if (speed) await writeFile(`${out}.ask.json`, JSON.stringify({ speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" }));
- const tuning = tuned?.ok && Object.keys(tuned.value).length ? tuned.value : null;
- const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) });
- // Echoed only for the engine that takes them (Orpheus): Kokoro and eSpeak NG ignore them (the editor's result
- // says so in its `note`, which the GET below hands on), so the answer never claims a tuning that is not used.
- const tunes = engine === "orpheus";
- return Response.json({ ok: true, jobId, file: rel, engine, voice, script, ...(tunes && tuning ? { tuning } : {}), ...(tunes && reading !== null ? { reading } : {}) }, { headers: noStore });
+ // ONE READ OF A POST AT A TIME: a second press while one is made is refused, never asked twice. The marker is
+ // TAKEN before the editor is asked (created exclusively: two presses at once cannot both take it; review 1,
+ // finding 4); a marker whose job ended, or one never given a job within two minutes, is stale and taken over.
+ const pendingFile = pendingFileOf(r.project.dir, e);
+ await mkdir(path.dirname(pendingFile), { recursive: true });
+ const claim = () => writeFile(pendingFile, JSON.stringify({ starting: true, at: new Date().toISOString() }), { flag: "wx" }).then(() => true, () => false);
+ if (!(await claim())) {
+ const pending = (await readFile(pendingFile, "utf8").then(JSON.parse, () => null)) as { jobId?: string; at?: string } | null;
+ const st = pending?.jobId ? await jobState(pending.jobId).catch(() => null) : null;
+ const young = !pending?.jobId && Date.now() - Date.parse(String(pending?.at ?? "")) < 120_000;
+ if ((st && !st.done) || young) return Response.json({ error: "a read of this post is being made: wait for it", busy: true }, { status: 409 });
+ await rm(pendingFile, { force: true });
+ if (!(await claim())) return Response.json({ error: "a read of this post is being made: wait for it", busy: true }, { status: 409 });
+ }
+ // From the claim to the marker naming its job, ONE try (review 2, finding 3): any throw takes the marker (and the
+ // .ask.json) away, so a failed press never answers 409 for two minutes.
+ let askFile: string | null = null;
+ try {
+ // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the
+ // narrator's -- a single read's rule (readVoice.mjs).
+ const said = await itemReadVoice(r.project, e, {
+ render: (m.render ?? {}) as Record<string, unknown>,
+ engine: typeof body.engine === "string" && body.engine ? body.engine : null,
+ voice: typeof body.voice === "string" && body.voice ? body.voice : null,
+ });
+ const engine = String(said.engine ?? k.engine);
+ const voice = String(said.voice ?? k.voice);
+ const pid = postIdOf(e);
+ const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
+ await mkdir(dir, { recursive: true });
+ const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice);
+ // Its speed: the one asked for, else the item's own (`narration.speed`), else its character's (the synthetic
+ // preset's that answered for the voice) -- makeTake's order.
+ const askedSpeed = body.speed === undefined || body.speed === null ? (e.narration as { speed?: number } | undefined)?.speed ?? (said as { speed?: number }).speed : Number(body.speed);
+ const speed = askedSpeed === undefined || askedSpeed === null || engine === "orpheus" ? undefined : Number(askedSpeed);
+ // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
+ // filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.mjs); the script is kept as written. The bench cannot word-time a take as it is made,
+ // so a beep falls back to skip here (the CLI's --take times it and beeps).
+ const red = await projectRedaction(r.project.dir, m);
+ const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }).text;
+ const out = path.join(r.project.dir, ...rel.split("/"));
+ // Its speed and where it came from, for the take the GET makes when the job is done (a sidecar, removed then).
+ // A re-read (`keepPick`, the bench's Read again) joins the list unpicked: said here too.
+ const keepPick = body.keepPick === true;
+ askFile = `${out}.ask.json`;
+ if (speed || keepPick) await writeFile(`${out}.ask.json`, JSON.stringify({ ...(speed ? { speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" } : {}), ...(keepPick ? { keepPick: true } : {}) }));
+ const tuning = tuned?.ok && Object.keys(tuned.value).length ? tuned.value : null;
+ const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) });
+ // The marker names its job, its file and what the take keeps (its words, its note): a bench that lost the job
+ // finds it again here and lands its take (GET ?pending).
+ await writeFile(pendingFile, JSON.stringify({ jobId, file: rel, script, ...(typeof body.note === "string" && body.note ? { note: body.note } : {}), at: new Date().toISOString() }));
+ // Echoed only for the engine that takes them (Orpheus): Kokoro and eSpeak NG ignore them (the editor's result
+ // says so in its `note`, which the GET below hands on), so the answer never claims a tuning that is not used.
+ const tunes = engine === "orpheus";
+ return Response.json({ ok: true, jobId, file: rel, engine, voice, script, ...(tunes && tuning ? { tuning } : {}), ...(tunes && reading !== null ? { reading } : {}) }, { headers: noStore });
+ } catch (err) {
+ await rm(pendingFile, { force: true });
+ if (askFile) await rm(askFile, { force: true });
+ throw err;
+ }
}
if (body.op === "derive") {
const takes = (e.narration?.takes ?? []) as Array<{ file: string; parts?: Array<{ n: number; file?: string }> }>;
@@ -511,6 +596,36 @@ async function record(request: Request) {
/** The umtool CLI (bin/umtool.mjs). */
const cliPath = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+
+/** The read of a post being made now (one at a time): `{ jobId, file, at }` beside its takes, removed when it ends. */
+const pendingFileOf = (dir: string, e: Entry) => path.join(dir, ...takesDirOf(postIdOf(e)).split("/"), ".reading.json");
+
+const TUNING_FLAG_OF: Record<string, string> = { temperature: "--temperature", top_p: "--top-p", top_k: "--top-k", min_p: "--min-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" };
+const ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/;
+
+/** A Read again's words for the CLI (lane line-rerun): `--for`, `--reading`, the tuning flags, `--no-pick`. */
+function readAgainArgv(body: Record<string, unknown>): string[] {
+ const a: string[] = [];
+ if (body.for !== undefined && body.for !== null) {
+ if (typeof body.for !== "string" || !ROLE_RE.test(body.for)) throw new Error("for must name one piece of the read (screen:<id>:<line>, post, quoted, parent:<i>)");
+ a.push("--for", body.for);
+ }
+ if (body.reading !== undefined && body.reading !== null) {
+ if (body.reading !== "next") {
+ const err = ttsReadingError(body.reading);
+ if (err) throw new Error(err);
+ }
+ a.push("--reading", String(body.reading));
+ }
+ if (body.tuning !== undefined && body.tuning !== null) {
+ const t = parseTtsTuning(body.tuning);
+ if (!t.ok) throw new Error(t.error);
+ for (const [k, v] of Object.entries(t.value)) a.push(TUNING_FLAG_OF[k], String(v));
+ }
+ if (a.includes("--for") && !a.includes("--reading") && !Object.values(TUNING_FLAG_OF).some((f) => a.includes(f))) throw new Error("for goes with a reading or a tuning");
+ if (body.keepPick === true || body.op === "thread-read") a.push("--no-pick");
+ return a;
+}
/** The jobs of one post item's screens: a line recorded, its read made. */
const screenJobKinds = (project: string, id: string) => [`screen-line ${project} ${id}`, `screen-read ${project} ${id}`];
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -16,6 +16,7 @@
// umtool check [<project> | --all] [--take <t>] [--json] exit 1 on anything blocking (--take: the take's quote rows)
// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json)
// umtool cast [ls|add|set|rm|undo|project|audition|use|reread] … the characters' voices across projects (castCli.mjs)
+// umtool narration <project> [<card>] [--read|--pick <key>|--text …] a card's narration and its readings (cardNarrationCli.mjs)
// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json)
// umtool quote-check <project> [--take <t>] [--clips a,b] [--status] is each clip's quote in the seconds it plays (quote-check.json; a take's: takes/<t>/)
// umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump
@@ -973,6 +974,8 @@ const COMMANDS = {
links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))),
// The cast: characters' voices across projects, auditions, a project's voices (operator, 6 Nov): lib/report/castCli.mjs.
cast: async () => process.exit(await (await import("../lib/report/castCli.mjs")).castCommand(argv.slice(argv.indexOf("cast") + 1))),
+ // A card's narration: its words, reading and tuning, its readings read again and picked (lane line-rerun): lib/report/cardNarrationCli.mjs.
+ narration: async () => process.exit(await (await import("../lib/report/cardNarrationCli.mjs")).cardNarrationCommand(argv.slice(argv.indexOf("narration") + 1))),
// Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs.
"speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))),
// Is each clip's quote in the seconds it plays (lane one-clock): the editor transcribes, quote-check.json keeps the rows.
diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import ReadAgain, { madeWithText, playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { MANIFEST_CHANGED } from "./timelineApi";
@@ -38,6 +39,12 @@ export type NarrationRow = {
judgedText: string;
judgedAt: string;
kept: { seconds: number; disclosure: string; mtimeMs: number } | null;
+ /** Its key now, reading and tuning, and every reading kept for it (lane line-rerun). */
+ key?: string;
+ reading?: number;
+ tuning?: Tuning | null;
+ madeWith?: Tuning | null;
+ readings?: Array<{ key: string; text: string; reading: number; tuning: Tuning | null; seconds: number; createdAt: string | null }>;
};
export type NarrationView = {
file: string;
@@ -284,6 +291,43 @@ function NarrationCard({
const dirty = text.trim() !== r.text;
const screen = [r.screen.kicker, r.screen.heading, r.screen.sub].filter(Boolean);
+ // ---- READ AGAIN (lane line-rerun): a reading kept for the card, the card not changed; Pick makes it play ----
+ const [auto, setAuto] = useAutoPlay();
+ const [reading, setReading] = useState<{ waiting: string | null } | null>(null);
+ const readingUrl = (key: string) => `/api/report/narration/audio?${new URLSearchParams({ project, card: r.id, key })}`;
+ const readAgain = (tuning: Tuning | null, words: string | null) =>
+ run(async () => {
+ if (words !== null) await act(r.id, "edit", { text: words });
+ const before = new Set((r.readings ?? []).map((x) => x.key));
+ const res = await fetch("/api/report/narration/play", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, card: r.id, again: true, reading: "next", ...(tuning ? { tuning } : {}) }) });
+ const j = (await res.json()) as { error?: string; job?: { id: string }; waiting?: string };
+ if (!res.ok || !j.job) throw new Error(j.error ?? `HTTP ${res.status}`);
+ setReading({ waiting: j.waiting ?? null });
+ try {
+ // A lost job (404, no state) failed; the bench out of reach is asked again, five times running at most
+ // (review 1, finding 5) -- nothing is played for a reading that did not end done.
+ let misses = 0;
+ for (;;) {
+ await new Promise((ok) => setTimeout(ok, 600));
+ const p = await fetch(`/api/report/build?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }).catch(() => null);
+ if (!p) {
+ if ((misses += 1) >= 5) throw new Error("the bench did not answer");
+ continue;
+ }
+ misses = 0;
+ const st = (await p.json().catch(() => ({}))) as { state?: string; error?: string | null };
+ if (!p.ok || !st.state) throw new Error(st.error ?? `the job is gone (HTTP ${p.status})`);
+ if (st.state === "running") continue;
+ if (st.state !== "done") throw new Error(st.error ?? "the reading was not made");
+ break;
+ }
+ } finally {
+ setReading(null);
+ }
+ const v = await refresh();
+ const fresh = v?.rows.find((x) => x.id === r.id)?.readings?.find((x) => !before.has(x.key));
+ if (fresh && auto) playNow(readingUrl(fresh.key));
+ });
return (
<article
@@ -403,6 +447,34 @@ function NarrationCard({
{r.kept && (
<audio ref={audio} controls preload="none" src={audioSrc(project, r)} data-narration-audio="" className="h-8 w-full" />
)}
+ <ReadAgain
+ what="the card"
+ busy={busy}
+ waiting={reading?.waiting ?? null}
+ canReadAgain={ready && !dirty}
+ edited={ready && dirty && !!text.trim()}
+ onReadAgain={(t) => void readAgain(t, null)}
+ onReadEdited={(t) => void readAgain(t, text)}
+ madeWith={r.madeWith ?? r.tuning ?? null}
+ autoplay={auto}
+ onAutoplay={setAuto}
+ />
+ {(r.readings?.length ?? 0) > 0 && (
+ <ul className="m-0 list-none space-y-0.5 p-0 text-[11px]" data-narration-readings={r.id}>
+ {r.readings!.map((x) => (
+ <li key={x.key} className="flex flex-wrap items-center gap-1.5" data-narration-reading={x.key.slice(0, 12)} data-playing={x.key === r.key ? "1" : undefined}>
+ <span className="font-mono">{madeWithText(x) || "reading 0"}</span>
+ <span className="tabular-nums">{Number(x.seconds).toFixed(1)} s</span>
+ {x.text !== r.text && <span className="truncate text-[var(--color-dim)]" title={x.text}>“{x.text}”</span>}
+ {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
+ <audio controls preload="none" src={readingUrl(x.key)} className="h-6 w-36" />
+ <button type="button" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={!ready || busy || x.key === r.key} onClick={() => void run(() => act(r.id, "pick", { key: x.key }))} aria-label={`Pick reading ${x.reading} of ${r.id}`} data-narration-reading-pick={x.key.slice(0, 12)}>
+ {x.key === r.key ? "playing" : "Pick"}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
{r.kept && <p className="text-[11px] text-[var(--color-dim)]">{r.kept.disclosure}</p>}
<DraftAlternatives address={`narrate/${r.id}/narration`} view={drafts} act={draftAct} />
{error && (
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -432,7 +432,21 @@ export default function PostBench({
}}
/>
<PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} />
- <PostThreadPanel project={project} entry={entry} plan={plan} render={render} before={before} scene={conversation} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} />
+ <PostThreadPanel
+ project={project}
+ entry={entry}
+ plan={plan}
+ render={render}
+ before={before}
+ scene={conversation}
+ setS={setS}
+ setEntry={(f) => setEntry((e) => f(e) as Entry)}
+ onEntry={(e, t) => {
+ setEntry(e as Entry);
+ setSaved(e as Entry);
+ setToken(t);
+ }}
+ />
<PostScreensPanel
project={project}
entry={entry}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -16,6 +16,8 @@ import { MIC_KEY, ls, useMic } from "./useMic";
import type { PostPlan } from "./review/PostItemPlayer";
import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
import PostAttachmentLane from "./PostAttachmentLane";
+import ReadAgain, { madeWithText, playNow, useAutoPlay, type KeepForCharacter, type Tuning } from "./read/ReadAgain";
+import { LEGACY_EDIT_TEXT, legacyReadOf } from "umtool-report-to-video/post-item";
// ---------------------------------------------------------------------------
// A POST's NARRATION ON THE BENCH (report-to-video/post-narration.mjs;
@@ -47,7 +49,7 @@ const PITCH_WORDS: Record<string, string> = {
source: "follow my pitch",
contour: "my intonation, at the voice's register",
};
-type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }>; words?: Array<{ w: string; start: number; end: number }> };
+type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; tuning?: Tuning; reading?: number; read?: { kind?: string }; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }>; words?: Array<{ w: string; start: number; end: number }> };
type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>;
type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> };
type Progress = { items: Array<{ id: string; n: number; plays: string; approved: boolean }>; counts: { posts: number; recorded: number; synthesized: number; none: number; approved: number } };
@@ -56,7 +58,7 @@ const fileUrl = (project: string, rel: string) => `/api/report/file?project=${en
const LABEL_KEY = "umtool.post-narration.label";
export default function PostNarrationPanel({
- project, entry, token, plan, render, onEntry, onTrim, s, setS, setPlaying, prev, next, fromPlay,
+ project, entry, token, plan, render, onEntry, onTrim, s, setS, setPlaying, prev, next, fromPlay, keepForCharacter,
}: {
project: string;
entry: Entry;
@@ -73,6 +75,8 @@ export default function PostNarrationPanel({
prev: string | null;
next: string | null;
fromPlay: boolean;
+ /** S2's seam (lane character-tuning): keep a Tune's numbers for the item's character. Absent: no button. */
+ keepForCharacter?: KeepForCharacter;
}) {
const n = entry.narration ?? {};
const takes = n.takes ?? [];
@@ -89,7 +93,7 @@ export default function PostNarrationPanel({
async (body: Record<string, unknown>) => {
setError(null);
const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body }) });
- const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[]; jobId?: string; file?: string; untouched?: boolean; why?: string; window?: Narration["window"] };
+ const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[]; jobId?: string; file?: string; untouched?: boolean; why?: string; window?: Narration["window"]; busy?: boolean };
if (!res.ok) {
setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`);
return null;
@@ -221,7 +225,7 @@ export default function PostNarrationPanel({
// ---- a re-take with direction (the editor's tts op) --------------------------
const [dir, setDir] = useState({ note: "", voice: "", speed: "" });
- const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null; pitch?: string | null; semitones?: number | null } } | null>(null);
+ const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; again?: boolean; waiting?: string | null; derive?: { from: number; op: string; engine?: string | null; voice?: string | null; pitch?: string | null; semitones?: number | null } } | null>(null);
// Derived takes still to make after a re-record ("re-run the chain"), from the new take.
const [chain, setChain] = useState<Array<{ from: number; step: Step }>>([]);
const [rerunChain, setRerunChain] = useState(true);
@@ -242,6 +246,52 @@ export default function PostNarrationPanel({
const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script });
if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: dir.note, script, state: "running" });
};
+ // A READ OF THIS POST MADE BUT NOT KEPT (a bench that lost it, review 2 finding 2): followed again on load, the same
+ // `?job` GET landing its take.
+ useEffect(() => {
+ let live = true;
+ fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&pending=1`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j: { pending?: { jobId: string; file: string; script: string | null; note: string | null } | null } | null) => {
+ const p = j?.pending;
+ if (live && p) setJob((cur) => (cur?.state === "running" ? cur : { id: p.jobId, file: p.file, note: p.note ?? "", script: p.script ?? n.script ?? "", state: "running", again: true }));
+ })
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [project, entry.id]);
+ // ---- READ AGAIN (lane line-rerun): the next reading, unpicked, played as it lands ------------------------------
+ const [autoplay, setAutoplay] = useAutoPlay();
+ const [landed, setLanded] = useState<string | null>(null);
+ // One press at a time, synchronously (review 1, finding 4): a second press before the first's answer is ignored.
+ const pressing = useRef(false);
+ const readAgain = async (words: string, tuning: Tuning | null) => {
+ const j = await post({ op: "take", script: words, reading: "next", keepPick: true, ...(tuning ? { tuning } : {}), voice: dir.voice || undefined });
+ if (!j) return;
+ if (j.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script: words, state: "running", again: true });
+ };
+ const press = async (fn: () => Promise<void>) => {
+ if (pressing.current || job?.state === "running") return;
+ pressing.current = true;
+ try {
+ await fn();
+ } finally {
+ pressing.current = false;
+ }
+ };
+ const readEdited = async (tuning: Tuning | null) => {
+ const saved = await post({ op: "set", patch: { script } });
+ if (saved) await readAgain(script, tuning);
+ };
+ // How this text was last made (its last synthesized take's tuning, else the playing take's): Tune starts there.
+ const madeWith = useMemo(() => {
+ const synth = takes.filter((t) => takeSourceOf(t).kind === "tts" && t.read?.kind !== "thread" && t.tuning);
+ const same = synth.filter((t) => (t.script ?? "").replace(/\s+/g, " ").trim() === (n.script ?? "").replace(/\s+/g, " ").trim());
+ return (same.at(-1) ?? (picked?.tuning ? picked : null) ?? synth.at(-1))?.tuning ?? null;
+ }, [takes, n.script, picked]);
+ const legacy = legacyReadOf(entry);
useEffect(() => {
if (!job || job.state !== "running") return;
const t = setTimeout(async () => {
@@ -249,18 +299,31 @@ export default function PostNarrationPanel({
project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}),
...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}), ...(job.derive.pitch ? { pitch: job.derive.pitch } : {}), ...(typeof job.derive.semitones === "number" ? { semitones: String(job.derive.semitones) } : {}) } : {}),
});
- const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" });
- const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string };
+ // The bench out of reach: asked again, up to five times running; then failed (review 1, finding 5).
+ const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" }).catch(() => null);
+ if (!r) {
+ const misses = (job.polls ?? 0) + 1;
+ // Lost, not failed (review 2, finding 2): the job and its file are kept -- Check again lands the take the same way.
+ setJob(misses >= 5 ? { ...job, state: "lost", error: "the bench did not answer" } : { ...job, polls: misses });
+ return;
+ }
+ const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string; waiting?: string };
if (j.state === "done") {
- setJob({ ...job, state: "done" });
- setStatus(`new take ${job.file} (picked)`);
+ setJob({ ...job, state: "done", waiting: null });
+ setStatus(job.again ? `new reading ${job.file} -- Pick makes it the one` : `new take ${job.file} (picked)`);
+ if (job.again) {
+ setLanded(job.file);
+ if (autoplay) playNow(fileUrl(project, job.file));
+ }
if (j.entry) onEntry(j.entry, j.token ?? null);
else window.location.reload();
} else if (j.state === "failed" || !r.ok) setJob({ ...job, state: "failed", error: j.error ?? `HTTP ${r.status}` });
- // Still queued or running on the editor: ask again.
- else setJob({ ...job, polls: (job.polls ?? 0) + 1 });
+ // Still queued or running on the editor (waiting for a render, it says so): ask again. No state: failed.
+ else if (j.state !== "running") setJob({ ...job, state: "failed", error: j.error ?? "the job is gone" });
+ else setJob({ ...job, polls: 0, waiting: j.waiting ?? null });
}, 1500);
return () => clearTimeout(t);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [job, project, entry.id]);
useEffect(() => {
@@ -294,13 +357,16 @@ export default function PostNarrationPanel({
// What a convert of THIS post defaults to: its author's character in the cast (else the narrator) -- the engine, the
// stock voice and the pitch every recording made that character's lands on (`umtool cast set <id> --convert-pitch …`).
const [castConvert, setCastConvert] = useState<{ name: string; engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null>(null);
+ // The character this item's read is made with (the convert's answer): S2 keeps a Tune for it.
+ const [character, setCharacter] = useState<{ id: string; name: string; layer?: string } | null>(null);
useEffect(() => {
let live = true;
setCastConvert(null);
fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&convert=1`, { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
- .then((j: { character?: { name: string } | null; convert?: { engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null } | null) => {
+ .then((j: { character?: { id?: string; name: string; layer?: string } | null; convert?: { engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null } | null) => {
if (live && j?.character && j.convert) setCastConvert({ name: j.character.name, ...j.convert });
+ if (live && j?.character) setCharacter(j.character as { id: string; name: string; layer?: string });
})
.catch(() => {});
return () => {
@@ -643,9 +709,11 @@ export default function PostNarrationPanel({
{src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}${convertPitchLabel(step) ? ` · pitch: ${convertPitchLabel(step)}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
</span>
<span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span>
+ {madeWithText(t) && <span className="font-mono text-text-2" data-post-take-made={i + 1}>{madeWithText(t)}</span>}
+ {landed === t.file && <span className="micro text-[var(--color-sel)]" data-post-take-new={i + 1}>new</span>}
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
<audio src={fileUrl(project, t.file)} controls preload="none" className="h-7" data-post-take-audio={i + 1} />
- <button type="button" className={btn} disabled={picked?.index === i} onClick={() => void set({ pick: i })} data-post-take-pick={i + 1}>
+ <button type="button" className={btn} disabled={picked?.index === i} onClick={() => void set({ pick: i })} aria-label={`Pick take ${i + 1}`} data-post-take-pick={i + 1}>
Pick
</button>
{src.kind === "take" && step && (
@@ -670,6 +738,7 @@ export default function PostNarrationPanel({
</button>
{t.note && <span className="text-text-2">“{t.note}”</span>}
</div>
+ {t.script && src.kind === "tts" && t.read?.kind !== "thread" && <div className="truncate pl-6 text-text-2" title={t.script} data-post-take-text={i + 1}>{t.script}</div>}
{(t.parts?.length ?? 0) > 1 && (
<ol className="m-0 mt-1 list-none space-y-0.5 pl-6 text-text-2" data-post-take-parts={i + 1}>
{t.parts!.map((p) => (
@@ -741,6 +810,20 @@ export default function PostNarrationPanel({
<span className="micro">script — the post, verbatim; add emotion with <sigh> <laugh> <chuckle> <groan> <gasp></span>
<textarea value={script} onChange={(e) => setScript(e.target.value)} rows={4} className="mt-1 w-full rounded border border-seam bg-ground px-2 py-1" data-post-script="" />
</label>
+ {legacy && <p className="m-0 text-text-2" data-post-script-legacy="">{LEGACY_EDIT_TEXT}</p>}
+ <ReadAgain
+ busy={job?.state === "running"}
+ waiting={job?.state === "running" ? job.waiting ?? null : null}
+ canReadAgain={!!(n.script ?? "").trim() && script === (n.script ?? "")}
+ edited={!!script.trim() && script !== (n.script ?? "")}
+ onReadAgain={(t) => void press(() => readAgain(n.script ?? "", t))}
+ onReadEdited={(t) => void press(() => readEdited(t))}
+ madeWith={madeWith}
+ character={character}
+ keepForCharacter={keepForCharacter}
+ autoplay={autoplay}
+ onAutoplay={setAutoplay}
+ />
<div className="flex flex-wrap items-center gap-1.5">
<button type="button" className={btn} disabled={script === (n.script ?? "")} onClick={() => void set({ script })} data-post-script-save="">
Save script
@@ -750,7 +833,12 @@ export default function PostNarrationPanel({
<button type="button" className={btn} disabled={!script.trim() || job?.state === "running"} onClick={() => void retake()} data-post-retake="">
{job?.state === "running" ? "Synthesizing on the editor…" : "Re-take with direction"}
</button>
- {job?.state === "failed" && <span className="text-[var(--color-blocking,#c33)]">{job.error}</span>}
+ {(job?.state === "failed" || job?.state === "lost") && <span className="text-[var(--color-blocking,#c33)]" data-post-take-failed="">{job.error}</span>}
+ {job?.state === "lost" && (
+ <button type="button" className={btn} onClick={() => setJob({ ...job, state: "running", polls: 0, error: undefined })} aria-label="Check again" data-post-take-check-again="">
+ Check again
+ </button>
+ )}
</div>
</section>
diff --git a/umtool/components/projects/PostScreensPanel.tsx b/umtool/components/projects/PostScreensPanel.tsx
@@ -6,7 +6,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
import { ownPictureOnly } from "umtool-report-to-video/post-item";
import { lineTakeWarnings, lineTakesOf, partRoles, threadReadErrors } from "umtool-report-to-video/post-thread";
import { postFileUrl } from "./review/PostItemPlayer";
-import { ScreenLineVoice, useScreenVoice, type LineTakeOption, type ScreenVoice, type VoiceEntry } from "./ScreenLineVoice";
+import { ScreenLineVoice, lineReadings, useScreenVoice, type LineTakeOption, type ScreenVoice, type VoiceEntry } from "./ScreenLineVoice";
// ---------------------------------------------------------------------------
// A POST's SCREENS ON THE BENCH (report-to-video/post-screens.mjs; docs/report-video.md, "Screens"; operator, 12 Nov:
@@ -21,7 +21,7 @@ import { ScreenLineVoice, useScreenVoice, type LineTakeOption, type ScreenVoice,
type Line = { who?: string; side?: "left" | "right"; text: string; time?: string; redact?: true };
type Read = "all" | "none" | Array<{ line: number; text?: string }>;
-type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read; lineTakes?: Record<string, string> };
+type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read; saidAs?: Record<string, string>; lineTakes?: Record<string, string> };
type LineRecs = Array<{ role: string; screen: string; n: number; takes: Array<{ n: number; id: string; take: { steps?: Array<{ op: string; voice?: string }>; engine?: string; screenLine?: { heard?: unknown } }; current: boolean; chosen: boolean }> }>;
/** A recording's step as the select says it: recorded, cleaned, converted to its voice. */
const stepOf = (t: { steps?: Array<{ op: string; voice?: string }>; engine?: string }) => {
@@ -202,6 +202,17 @@ function ScreenEditor({
setRead(on ? [...list, { line: n }] : list);
};
const setExcerpt = (n: number, text: string) => setRead([...readList(sc).filter((x) => x.line !== n), text.trim() ? { line: n, text } : { line: n }]);
+ // What line n is SAID AS (saidAs; lane line-rerun): never drawn -- the card shows the line as written.
+ const setSaidAs = (n: number, text: string) =>
+ setScreen((s) => {
+ const sa = { ...(s.saidAs ?? {}) };
+ if (text.trim()) sa[String(n)] = text;
+ else delete sa[String(n)];
+ const { saidAs: _a, ...rest } = s;
+ void _a;
+ return Object.keys(sa).length ? { ...rest, saidAs: sa } : rest;
+ });
+ const spaced = (t: string) => t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
const setLine = (n: number, patch: Partial<Line>) =>
setLines((lines) =>
lines.map((l, i) => {
@@ -334,6 +345,9 @@ function ScreenEditor({
{r && !l.redact && (
<input className="mt-0.5 w-full text-text-2" value={r.text ?? ""} placeholder="excerpt: the words read (all of them when empty)" onChange={(e) => setExcerpt(n, e.target.value)} data-post-screen-excerpt={n} />
)}
+ {d && !l.redact && (
+ <input className="mt-0.5 w-full text-text-2" value={sc.saidAs?.[String(n)] ?? ""} placeholder={`said as (the line as written when empty)`} onChange={(e) => setSaidAs(n, e.target.value)} aria-label={`said as, line ${n}`} data-post-screen-said-as={n} />
+ )}
{d && (d.cutBefore || d.cutAfter) && <span className="text-text-2">reads an excerpt</span>}
{shapes.length > 0 && !l.redact && <span className="text-text-2" data-post-screen-masked={n}> · masked: {shapes.join(", ")}</span>}
</td>
@@ -341,7 +355,11 @@ function ScreenEditor({
<input className="w-full" value={l.time ?? ""} onChange={(e) => setLine(n, { time: e.target.value || undefined })} data-post-screen-time={n} />
</td>
<td>
- <input type="checkbox" checked={!!l.redact} onChange={(e) => setLine(n, { redact: e.target.checked ? true : undefined })} data-post-screen-redact={n} aria-label={`redact line ${n}`} />
+ <input type="checkbox" checked={!!l.redact} onChange={(e) => {
+ setLine(n, { redact: e.target.checked ? true : undefined });
+ // A redacted line is never read: its said-as goes with it (review 1, finding 7).
+ if (e.target.checked) setSaidAs(n, "");
+ }} data-post-screen-redact={n} aria-label={`redact line ${n}`} />
<button type="button" className="ink-link ml-1" onClick={() => setScreen((s) => { const { checked: _c, ...rest } = withoutLines(s, [n]) as Screen; void _c; return rest; })} title="remove the line (the read follows it)" data-post-screen-line-remove={n}>
×
</button>
@@ -355,6 +373,12 @@ function ScreenEditor({
dirty={dirty}
options={(recs.find((x) => x.screen === sc.id && x.n === n)?.takes ?? []).map((x): LineTakeOption => ({ id: x.id, label: `take ${x.n} · ${stepOf(x.take)}${x.take.screenLine?.heard ? " · heard" : " · not heard"}`, current: x.current }))}
chosen={sc.lineTakes?.[String(n)]}
+ readings={lineReadings(entry, `screen:${sc.id}:${n}`)}
+ edited={(() => {
+ const said = sc.saidAs?.[String(n)];
+ const playing = lineReadings(entry, `screen:${sc.id}:${n}`).find((x) => x.picked);
+ return !!said && !!playing && spaced(playing.text) !== spaced(said);
+ })()}
onChoose={(id) =>
setScreen((s) => {
const lt = { ...(s.lineTakes ?? {}) };
diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread";
import { followKnobs } from "umtool-report-to-video/read-follow";
import { pickedTake } from "umtool-report-to-video/post-narration";
@@ -26,7 +27,7 @@ const ROLE_NAME = (r: string | null) =>
r === null ? "no text on the card" : r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r === "parent:0" ? "the post it answers" : r.startsWith("parent:") ? "the post that answers" : `attachment ${Number(r.slice(6)) + 1}'s words`;
export default function PostThreadPanel({
- project = null, entry, plan, render, before, scene = null, setS, setEntry,
+ project = null, entry, plan, render, before, scene = null, setS, setEntry, onEntry,
}: {
/** The project (its "Read without it" re-joins the take through the post-narration route). */
project?: string | null;
@@ -38,6 +39,8 @@ export default function PostThreadPanel({
scene?: Record<string, unknown> | null;
setS: (s: number) => void;
setEntry: (f: (e: Entry) => Entry) => void;
+ /** The writer's answer after a Read again (the entry as it is now, the manifest's token). */
+ onEntry?: (e: Entry, token: string | null) => void;
}) {
const own = (entry.thread ?? undefined) as Thread | undefined;
const k = threadKnobs(entry, render) as Required<Thread>;
@@ -66,6 +69,53 @@ export default function PostThreadPanel({
setRereading(null);
}
};
+ // READ THE THREAD AGAIN (lane line-rerun): every synthesized piece's next reading, a new take unpicked, played as
+ // it lands -- `posts screen … read` / `posts narrate … --take --thread` as a umtool job (op thread-read).
+ const playing = pickedTake(entry) as { read?: { kind?: string }; parts?: Array<{ reading?: number; tuning?: Tuning }> } | null;
+ const [autoplay, setAutoplay] = useAutoPlay();
+ const [again, setAgain] = useState<{ state: string; waiting?: string | null; error?: string | null; said?: string | null } | null>(null);
+ const poll = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pressing = useRef(false);
+ useEffect(() => () => {
+ if (poll.current) clearTimeout(poll.current);
+ }, []);
+ const readThreadAgain = async (tuning: Tuning | null) => {
+ if (!project || again?.state === "running" || pressing.current) return;
+ pressing.current = true;
+ try {
+ const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "thread-read", id: entry.id, reading: "next", ...(tuning ? { tuning } : {}) }) }).catch(() => null);
+ const j = res ? ((await res.json().catch(() => ({}))) as { job?: { id: string }; error?: string; busy?: boolean }) : { error: "the bench is out of reach" };
+ if (!res?.ok || !j.job) {
+ // Busy: said, the running one's state kept.
+ if (j.busy) setAgain((a) => (a?.state === "running" ? a : { state: "idle", said: j.error ?? "busy" }));
+ else setAgain({ state: "failed", error: j.error ?? `HTTP ${res?.status ?? "?"}` });
+ return;
+ }
+ setAgain({ state: "running" });
+ const jobId = j.job.id;
+ let misses = 0;
+ const tick = async () => {
+ const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&screenJob=${encodeURIComponent(jobId)}`, { cache: "no-store" }).catch(() => null);
+ const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; error?: string | null; waiting?: string; entry?: Entry | null; token?: string | null; result?: { take?: { file: string; n: number } | null; why?: string } | null }) : null;
+ misses = r ? 0 : misses + 1;
+ // Still running; the bench out of reach (up to five times running) is asked again. A lost job (404, no state) failed.
+ if ((r && v?.state === "running") || (!r && misses < 5)) {
+ setAgain({ state: "running", waiting: v?.waiting ?? null });
+ poll.current = setTimeout(tick, 1500);
+ return;
+ }
+ if (!r || !v?.state) return setAgain({ state: "failed", error: v?.error ?? `the job is gone${r ? ` (HTTP ${r.status})` : ""}` });
+ const made = v.state === "done" ? v.result?.take ?? null : null;
+ setAgain({ state: v.state === "done" ? "done" : "failed", error: v.error ?? null, said: v.state === "done" ? (made ? `take ${made.n} made, not picked` : `nothing made -- ${v.result?.why ?? "the read already says this"}`) : null });
+ // Only the take THIS job made plays (review 1, finding 2).
+ if (made && autoplay) playNow(`/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(made.file)}`);
+ if (v.entry) onEntry?.(v.entry, v.token ?? null);
+ };
+ poll.current = setTimeout(tick, 800);
+ } finally {
+ pressing.current = false;
+ }
+ };
const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null;
const setOwn = (patch: Thread) =>
setEntry((e) => {
@@ -112,6 +162,21 @@ export default function PostThreadPanel({
{layout.on ? "the card draws the conversation: each post read is shown in full, then shrinks and dims as the next comes in" : roles.length ? "his words only: the posts it answers are context" : "not narrated: the card as it is"}
</span>
</div>
+ {project && playing?.read?.kind === "thread" && (
+ <div className="mb-2">
+ <ReadAgain
+ what="the thread"
+ busy={again?.state === "running"}
+ waiting={again?.state === "running" ? again.waiting ?? null : null}
+ onReadAgain={(t) => void readThreadAgain(t)}
+ madeWith={playing.parts?.find((p) => p.tuning)?.tuning ?? null}
+ error={again?.state === "failed" ? again.error ?? "failed" : null}
+ note={again?.said ?? null}
+ autoplay={autoplay}
+ onAutoplay={setAutoplay}
+ />
+ </div>
+ )}
{sceneTiles.length > 0 && (
<p className="m-0 mb-2 text-text-2" data-post-thread-scene={sceneTiles.length}>
one scene with the item before:{" "}
diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useMic, ls } from "./useMic";
+import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
// ---------------------------------------------------------------------------
// A SCREEN LINE IN THE OPERATOR's VOICE, on the post bench's screens section (lib/report/screenLineRecord.mjs; the
@@ -14,7 +15,10 @@ import { useMic, ls } from "./useMic";
const LABEL_KEY = "umtool.post-narration.label";
-type Job = { id: string; what: string; role?: string; state: string; message?: string | null; error?: string | null };
+type Job = { id: string; what: string; role?: string; state: string; message?: string | null; error?: string | null; waiting?: string | null };
+type Part = { role?: string; file?: string; text?: string; reading?: number; tuning?: Tuning };
+type TakeLike = { file?: string; parts?: Part[]; read?: { kind?: string } };
+const fileUrl = (project: string, rel: string) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`;
export type VoiceEntry = Record<string, unknown> & { id: string };
/** The section's voice: one microphone, one take at a time, one job at a time. */
@@ -27,6 +31,9 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str
const [status, setStatus] = useState<string | null>(null);
const [prompts, setPrompts] = useState<Record<string, string>>({});
const poll = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const misses = useRef(0);
+ // One press at a time, synchronously (review 1, finding 4): a second press before the first's answer is ignored.
+ const pressing = useRef(false);
useEffect(() => () => {
if (poll.current) clearTimeout(poll.current);
}, []);
@@ -41,12 +48,17 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str
}, [loadPrompts]);
const follow = useCallback(
(j: Job) => {
+ // Each job its own count of missed polls (review 2, finding 5).
+ misses.current = 0;
setJob(j);
const tick = async () => {
const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&screenJob=${encodeURIComponent(j.id)}`, { cache: "no-store" }).catch(() => null);
- const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; message?: string; error?: string; entry?: VoiceEntry | null; token?: string | null; result?: { takes?: Array<{ n: number; step: string }>; notes?: string[] } | null }) : {};
- const state = v.state ?? (r ? "failed" : "running");
- setJob({ ...j, state, message: v.message ?? null, error: v.error ?? null });
+ const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; message?: string; error?: string; waiting?: string; entry?: VoiceEntry | null; token?: string | null; result?: { takes?: Array<{ n: number; step: string }>; notes?: string[]; upToDate?: boolean; why?: string; take?: { file: string; n: number; parts?: Array<{ role: string | null; file: string | null }> } | null } | null }) : {};
+ // A lost job (404, an answer with no state) has failed; the editor out of reach five times running too.
+ misses.current = r ? 0 : misses.current + 1;
+ const state = v.state ?? (r ? "failed" : misses.current >= 5 ? "failed" : "running");
+ if (!v.state && r) v.error ??= `the job is gone (HTTP ${r.status})`;
+ setJob({ ...j, state, message: v.message ?? null, error: v.error ?? null, waiting: v.waiting ?? null });
if (state === "running") {
poll.current = setTimeout(tick, 1500);
return;
@@ -63,7 +75,18 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str
});
const made = v.result?.takes ?? [];
setStatus(`${j.role}: ${made.map((x) => `take ${x.n} ${x.step}`).join(", ")} -- none picked; choose one for the line, Save, then make the read${(v.result?.notes ?? []).length ? ` (${(v.result?.notes ?? []).join("; ")})` : ""}`);
- } else setStatus("the read is made (picked)");
+ } else if (j.what === "again" && j.role) {
+ // A LINE READ AGAIN (lane line-rerun): the take THIS JOB made (its result), unpicked; its line's part plays
+ // as it lands. None made: said, and nothing plays (review 1, finding 2).
+ const made = v.result?.take ?? null;
+ if (!made) setStatus(`${j.role}: nothing made -- ${v.result?.why ?? "the read already says this"}`);
+ else {
+ const part = made.parts?.find((p) => p.role === j.role && p.file);
+ setLanded({ role: j.role, take: made.n - 1 });
+ if (part?.file && autoplayNow.current) playNow(fileUrl(project, part.file));
+ setStatus(`${j.role}: read again -- take ${made.n}, not picked; Pick makes it the one`);
+ }
+ } else setStatus(v.result?.take ? `the read is made: take ${v.result.take.n} (picked)` : `nothing made -- ${v.result?.why ?? "the read already says this"}`);
if (kept) setStatus((x) => `${x ?? ""} -- your unsaved edits are kept: Save, then reload the bench to see it`);
void loadPrompts();
}
@@ -113,6 +136,35 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str
}
follow({ id: j.job.id, what: "line", role, state: j.job.state });
};
+ // ---- READ A LINE AGAIN (lane line-rerun): `posts screen <p> <item> read --for <role> --reading next --no-pick` ----
+ const [autoplay, setAutoplay] = useAutoPlay();
+ const autoplayNow = useRef(autoplay);
+ autoplayNow.current = autoplay;
+ const [landed, setLanded] = useState<{ role: string; take: number } | null>(null);
+ const readLine = async (role: string, tuning: Tuning | null) => {
+ if (job?.state === "running" || pressing.current) return;
+ pressing.current = true;
+ setStatus(null);
+ try {
+ const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "screen-read", id, for: role, reading: "next", keepPick: true, ...(tuning ? { tuning } : {}) }) }).catch(() => null);
+ const j = r ? ((await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string; busy?: boolean }) : { error: "the bench is out of reach" };
+ if (!r?.ok || !j.job) {
+ // Busy (another job runs): said, without taking the running one's place.
+ if (j.busy) setStatus(j.error ?? "busy");
+ else setJob({ id: "", what: "again", role, state: "failed", error: j.error ?? `HTTP ${r?.status ?? "?"}` });
+ return;
+ }
+ follow({ id: j.job.id, what: "again", role, state: j.job.state });
+ } finally {
+ pressing.current = false;
+ }
+ };
+ const pickTake = async (index: number) => {
+ const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "set", id, patch: { pick: index } }) });
+ const j = (await r.json().catch(() => ({}))) as { entry?: VoiceEntry; token?: string; error?: string };
+ if (!r.ok || !j.entry) setStatus(j.error ?? `HTTP ${r.status}`);
+ else onEntry(j.entry, j.token ?? null);
+ };
const makeRead = async () => {
setStatus(null);
const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "screen-read", id }) });
@@ -123,7 +175,7 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str
}
follow({ id: j.job.id, what: "read", state: j.job.state });
};
- return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead };
+ return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead, readLine, pickTake, landed, autoplay, setAutoplay, project };
}
export type ScreenVoice = ReturnType<typeof useScreenVoice>;
@@ -131,8 +183,21 @@ export type ScreenVoice = ReturnType<typeof useScreenVoice>;
/** The recordings of one line, as the select offers them: `{ id, label, current }`. */
export type LineTakeOption = { id: string; label: string; current: boolean };
+/** One synthesized reading of a line: the take it is in (index), its part's file, words, reading and tuning. */
+export type LineReading = { take: number; picked: boolean; file: string | null; text: string; reading: number; tuning: Tuning | null };
+
+/** The readings of a line (`role`) in an item's takes: each take whose parts read it, synthesized. */
+export function lineReadings(entry: Record<string, unknown>, role: string): LineReading[] {
+ const n = (entry.narration ?? {}) as { takes?: TakeLike[]; pick?: number };
+ const pick = Number.isInteger(n.pick) ? (n.pick as number) : 0;
+ return (n.takes ?? []).flatMap((t, i) => {
+ const p = (t.parts ?? []).find((x) => x.role === role && !(x as { take?: string }).take);
+ return p ? [{ take: i, picked: i === pick, file: p.file ?? null, text: String(p.text ?? ""), reading: Number.isInteger(p.reading) ? (p.reading as number) : 0, tuning: p.tuning ?? null }] : [];
+ });
+}
+
/** ONE READ LINE's voice cell: Record / Stop / play back / Redo / Keep, and the take chosen for it. */
-export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoose }: { role: string; n: number; voice: ScreenVoice; dirty: boolean; options: LineTakeOption[]; chosen: string | undefined; onChoose: (id: string | undefined) => void }) {
+export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoose, readings = [], edited = false }: { role: string; n: number; voice: ScreenVoice; dirty: boolean; options: LineTakeOption[]; chosen: string | undefined; onChoose: (id: string | undefined) => void; readings?: LineReading[]; edited?: boolean }) {
const mine = voice.at === role && voice.phase === "recording";
const t = voice.takes[role];
const busy = voice.job?.state === "running";
@@ -169,6 +234,36 @@ export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoo
)}
{dirty && <span className="text-text-2" data-post-screen-record-save-first={n}>save first</span>}
</div>
+ {!chosen && (
+ <ReadAgain
+ what={`line ${n}`}
+ busy={busy}
+ waiting={busy && voice.job?.role === role ? voice.job?.waiting ?? null : null}
+ canReadAgain={!dirty}
+ edited={!dirty && edited}
+ onReadAgain={(t) => void voice.readLine(role, t)}
+ onReadEdited={(t) => void voice.readLine(role, t)}
+ madeWith={readings.find((x) => x.picked)?.tuning ?? null}
+ autoplay={voice.autoplay}
+ onAutoplay={voice.setAutoplay}
+ />
+ )}
+ {readings.length > 0 && (
+ <ul className="m-0 list-none space-y-0.5 p-0" data-post-screen-readings={n}>
+ {readings.map((x) => (
+ <li key={x.take} className="flex flex-wrap items-center gap-1.5" data-post-screen-reading={`${n}:${x.take + 1}`} data-picked={x.picked ? "1" : undefined}>
+ <span className="font-mono">take {x.take + 1}</span>
+ <span className="text-text-2">reading {x.reading}{x.tuning ? ` · ${Object.entries(x.tuning).map(([k, v]) => `${k} ${v}`).join(", ")}` : ""}</span>
+ {voice.landed?.role === role && voice.landed.take === x.take && <span className="micro" data-post-screen-reading-new="">new</span>}
+ {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
+ {x.file && <audio src={fileUrl(voice.project, x.file)} controls preload="none" className="h-6 w-32" />}
+ <button type="button" className={btn} disabled={x.picked || busy || dirty} onClick={() => void voice.pickTake(x.take)} aria-label={`Pick take ${x.take + 1} for line ${n}`} data-post-screen-reading-pick={`${n}:${x.take + 1}`}>
+ {x.picked ? "playing" : "Pick"}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
{options.length > 0 && (
<label className="flex items-center gap-1">
reads
diff --git a/umtool/components/projects/read/ReadAgain.tsx b/umtool/components/projects/read/ReadAgain.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { ls } from "../useMic";
+import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS, TTS_TUNING_FIELDS, TTS_TUNING_RANGES } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+
+// ---------------------------------------------------------------------------
+// READ AGAIN (lane line-rerun, S3 of the Orpheus re-tune plan): one line's
+// re-read controls, the same wherever a synthetic voice reads a line -- a
+// post's script, a screen line, a thread read, a card's narration.
+//
+// Read again the same words, the next reading
+// Read edited text the words as edited (saved first), read
+// Tune ▾ the six numbers for this line only, prefilled from
+// how it was last made
+// play when ready the new read plays as it lands (remembered per browser)
+//
+// Every press is a form and a job: the caller's route runs the umtool command.
+// The read made joins the list unpicked; the caller's Pick makes it the one.
+// `keepForCharacter` is S2's seam (lane character-tuning): absent, no button.
+// ---------------------------------------------------------------------------
+
+export type Tuning = Partial<Record<"temperature" | "top_p" | "top_k" | "min_p" | "repeat_penalty" | "takes", number>>;
+/** S2's seam: keep these numbers for the character (its command: `umtool cast set <id> --temperature …`). */
+export type KeepForCharacter = (tuning: Tuning) => Promise<string | null>;
+
+const AUTOPLAY_KEY = "umtool.reads.autoplay";
+const LABEL: Record<string, string> = { temperature: "temperature", top_p: "top p", top_k: "top k", min_p: "min p", repeat_penalty: "repeat penalty", takes: "takes" };
+// `takes` has no default here: empty is the editor's settings' own (tts.orpheus.takes), never a guessed 3.
+const DEFAULTS: Record<string, number> = { ...ORPHEUS_TUNING_DEFAULTS };
+void ORPHEUS_DEFAULT_TAKES;
+
+// ONE STORE for every mount (review 1, finding 9): a toggle on one line is the toggle on all of them, at once.
+const autoplayListeners = new Set<(on: boolean) => void>();
+let autoplayNow: boolean | null = null;
+
+/** Whether a new read plays as it lands: on unless this browser said otherwise -- one value for every mount. */
+export function useAutoPlay(): [boolean, (on: boolean) => void] {
+ const [on, setOn] = useState(true);
+ useEffect(() => {
+ if (autoplayNow === null) autoplayNow = ls.get(AUTOPLAY_KEY) !== "off";
+ setOn(autoplayNow);
+ autoplayListeners.add(setOn);
+ return () => {
+ autoplayListeners.delete(setOn);
+ };
+ }, []);
+ return [on, (v: boolean) => {
+ autoplayNow = v;
+ ls.set(AUTOPLAY_KEY, v ? "on" : "off");
+ for (const f of autoplayListeners) f(v);
+ }];
+}
+
+/** Play `url` now (a read that landed); a browser that refuses without a gesture is left silent. */
+export function playNow(url: string) {
+ try {
+ void new Audio(url).play().catch(() => {});
+ } catch {
+ // no audio here
+ }
+}
+
+/** The numbers that differ from Orpheus's defaults, or null: what a read asks. */
+export function tuningAsked(draft: Record<string, string>): Tuning | null {
+ const out: Tuning = {};
+ for (const k of TTS_TUNING_FIELDS as readonly (keyof Tuning)[]) {
+ const v = Number(draft[k]);
+ // `takes`: sent whenever one is given (the settings' may differ from 3); the sampler's: when not its default.
+ if (draft[k] !== "" && Number.isFinite(v) && (k === "takes" || v !== DEFAULTS[k])) out[k] = v;
+ }
+ return Object.keys(out).length ? out : null;
+}
+
+/** A tuning and a reading as a short phrase: "reading 2 · temperature 0.7". Defaults are not said. */
+export function madeWithText(t: { reading?: number | null; tuning?: Tuning | null }): string {
+ const bits = [...(t.reading ? [`reading ${t.reading}`] : []), ...Object.entries(t.tuning ?? {}).filter(([k, v]) => k !== "takes" && v !== DEFAULTS[k]).map(([k, v]) => `${LABEL[k] ?? k} ${v}`)];
+ return bits.join(" · ");
+}
+
+export default function ReadAgain({
+ what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay,
+}: {
+ /** What is read, in the controls' names: "" (the post), "line 2", "the thread", "the card". */
+ what?: string;
+ busy?: boolean;
+ /** Said in place while the read waits (render mode holds the machine). */
+ waiting?: string | null;
+ canReadAgain?: boolean;
+ /** The words differ from what was last saved: Read edited text is offered. */
+ edited?: boolean;
+ onReadAgain: (tuning: Tuning | null) => void;
+ /** Absent: no edited text here (a thread read). */
+ onReadEdited?: (tuning: Tuning | null) => void;
+ /** How the line was last made: the Tune numbers start from it. */
+ madeWith?: Tuning | null;
+ /** The character this line is read by, when known: S2 keeps a tuning for it. */
+ character?: { id: string; name: string; layer?: string } | null;
+ keepForCharacter?: KeepForCharacter;
+ error?: string | null;
+ /** What the last press came to, said in place ("take 4 made, not picked", "nothing made -- …"). */
+ note?: string | null;
+ /** Whether a new read plays as it lands (the caller's useAutoPlay: it plays it). */
+ autoplay: boolean;
+ onAutoplay: (on: boolean) => void;
+}) {
+ const start = (): Record<string, string> => Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, madeWith?.[k as keyof Tuning] !== undefined ? String(madeWith[k as keyof Tuning]) : k in DEFAULTS ? String(DEFAULTS[k]) : ""]));
+ const [draft, setDraft] = useState<Record<string, string>>(start);
+ const [kept, setKept] = useState<string | null>(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(() => setDraft(start()), [JSON.stringify(madeWith)]);
+ const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
+ const bad = TTS_TUNING_FIELDS.some((k: string) => {
+ const r = (TTS_TUNING_RANGES as Record<string, { min: number; max: number; integer: boolean }>)[k];
+ const v = Number(draft[k]);
+ // Empty is only `takes`'s (the settings' own); any other empty or out-of-range field holds every read back.
+ if (draft[k] === "") return k !== "takes";
+ return !Number.isFinite(v) || v < r.min || v > r.max || (r.integer && !Number.isInteger(v));
+ });
+ return (
+ <div className="flex flex-wrap items-center gap-1.5" data-read-again={what || "post"}>
+ <button type="button" className={btn} disabled={busy || bad || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again` : "Read again"} data-read-again-button="">
+ Read again
+ </button>
+ {onReadEdited && (
+ <button type="button" className={btn} disabled={busy || bad || !edited} onClick={() => onReadEdited(tuningAsked(draft))} aria-label={what ? `Read ${what} as edited` : "Read the edited text"} data-read-edited-button="">
+ Read edited text
+ </button>
+ )}
+ <details className="relative" data-read-tune="">
+ <summary className={cn(btn, "cursor-pointer list-none")} aria-label={what ? `Tune ${what} only` : "Tune this line only"}>
+ Tune ▾
+ </summary>
+ <div className="absolute z-10 mt-1 w-64 space-y-1 rounded border border-seam bg-[var(--color-panel)] p-2 shadow">
+ <span className="micro">this line only</span>
+ {TTS_TUNING_FIELDS.map((k: string) => {
+ const r = (TTS_TUNING_RANGES as Record<string, { min: number; max: number; integer: boolean }>)[k];
+ return (
+ <label key={k} className="flex items-center justify-between gap-2">
+ <span>{LABEL[k]}</span>
+ <input type="number" min={r.min} max={r.max} step={r.integer ? 1 : 0.01} value={draft[k]} placeholder={k === "takes" ? "settings" : undefined} onChange={(e) => setDraft({ ...draft, [k]: e.target.value })} className="w-20 rounded border border-seam bg-ground px-1 py-0.5" aria-label={`${LABEL[k]}, this line only`} data-read-tune-field={k} />
+ </label>
+ );
+ })}
+ <div className="flex flex-wrap gap-1.5 pt-1">
+ <button type="button" className={btn} disabled={busy || bad || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again with this tuning` : "Read again with this tuning"} data-read-tune-read="">
+ Read with these
+ </button>
+ <button type="button" className={btn} onClick={() => setDraft(Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, k in DEFAULTS ? String(DEFAULTS[k]) : ""])))} aria-label="Tuning back to the defaults" data-read-tune-defaults="">
+ Defaults
+ </button>
+ {keepForCharacter && character && (
+ <button type="button" className={btn} disabled={bad} onClick={() => void keepForCharacter(tuningAsked(draft) ?? {}).then(setKept)} aria-label={`Keep this tuning for ${character.name}`} data-read-tune-keep="">
+ Keep for {character.name}
+ </button>
+ )}
+ </div>
+ {kept && <span className="text-text-2" data-read-tune-kept="">{kept}</span>}
+ </div>
+ </details>
+ <label className="flex items-center gap-1 text-text-2">
+ <input type="checkbox" checked={autoplay} onChange={(e) => onAutoplay(e.target.checked)} aria-label="Play new reads when they land" data-read-autoplay="" />
+ play when ready
+ </label>
+ {busy && <span className="text-text-2" data-read-busy="">{waiting ?? "reading…"}</span>}
+ {!busy && note && <span className="text-text-2" data-read-note="">{note}</span>}
+ {error && <span className="text-[var(--color-blocking,#c33)]" data-read-error="">{error}</span>}
+ </div>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -48,6 +48,7 @@ Inbox cannot disagree about what is wrong with one.
| `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at. The intro (`render.intro`) is listed first, watched, not judged (`intro`, `stops` in `--json`) |
| `review-pass <project> [ls] [--json]` · `review-pass <project> mark <block> keep\|fix\|clear [--note T]` | the workspace's **review pass** (`?mode=review`): every block but the intro and a clip rejected for a cut reason, its answer and the block the pass resumes on; a Fix ("needs work", saying what) is a mark in `<project>/review-pass.json` on any block, a clip too — never a clip's verdict (`incorrect` is the bench's fact-error ruling, never written or overwritten here); a clip's Keep is its walk verdict (`window --verdict confirmed`), a post's or a card's a mark — `mark` writes one (a Fix needs `--note`; a clip takes `fix` and `clear`) ([knobs.md](knobs.md#the-review-pass)) |
| `review-pass <project> verdict like\|maybe\|no\|clear [--note T] [--json]` | the pass's **verdict on the draft**, one locked call: a draft that differs from its parent version only by what the walk and the review pass write (verdict, correction, reason, reject note, walk note, ★) judges the PARENT and saves nothing; otherwise the draft is saved as the next version and that is judged (`takes/verdicts.json`) |
+| `narration <project> [<card>] [--list] [--json]` · `<card> --read [--text "…"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` · `<card> --pick <key>` · `<card> [--text "…"] [--reading N] [tuning flags | --tuning-off]` | a **card's narration** and its readings ([knobs.md](knobs.md#a-cards-narration-read-again), `lib/report/cardNarrationCli.mjs`): the words a stock voice says over a card (spoken only — no card draws them), its reading and Orpheus tuning; `--read` asks the editor for one reading (a job; it waits while render mode holds the machine) and keeps it in `out/narration/` without changing the card (`--reading next`: one past the highest these words were read at); `--pick <key>` makes the card play a kept reading (its words, reading and tuning; nothing synthesized) — a verdict on the same words is kept; without either, the card's words, reading and tuning are set. The narration page's Read again, Read edited text, Tune and Pick run these. |
| `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) |
| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) |
| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
@@ -134,10 +135,10 @@ Inbox cannot disagree about what is wrong with one.
| `posts reread <project> <item> --pause "<word>[#<n>]=<seconds>\|@<take s>=<seconds>[,…]" [--target post\|parent:0\|quoted\|linked:0] [--dry-run] [--json]` | **pauses put in after words** of a narrated read, no TTS (`lib/report/postPause.mjs`; operator, 5 Nov: a countdown "20 10 4 0" read without a breath): the picked take cut just after each word named (half way into the quiet before the next word, at most 0.1 s past its end) and that much silence (0.05–3 s) put in -- each cut moved to the quietest 10 ms its word allows (40 ms before its timed end up to the next word, ±40 ms when they run together) when that is clearly quieter (~3 dB) than the timing's own, and each side of the silence faded over 10 ms, so a pause in normally paced speech does not click -- everything after moved on -- its words (by index), its parts (one a pause falls in grows), its length -- so word zooms, captions, slams, beeps and the read-follow stay on their words; an effect with a set `at` does not move (the plan counts them). A word is matched as a word zoom's is (case and edge punctuation aside; a phrase pauses after its last word; `#n` its n-th time in the read; `--target` counts only the words of the parts reading that piece). A derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`) picked in ONE write. **Absolute**, like a tempo: on a take whose last step is a pause it re-cuts from the take before (the pauses it had kept, a word named again takes the new seconds, `=0` takes one away). `--in-take <t>` puts it in a take's read. No word timings (**exit 1**, naming `posts narrate <p> <item> --words`), a word not read, an occurrence not there, nothing to change: **exit 1**; a malformed spec, seconds outside 0.05–3, `--pause` with another reread form: **exit 2** |
| `posts reread <project> <item> --revoice "<phrase>[#<n>]" --say "<what to say instead>" [--target <piece>] [--voice <v>\|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json]` | **one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it "choppy"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: "revoice", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2** |
| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it |
-| `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record …` (add: `--media <i> [--at <from>,<to>] --kind dm\|email\|post\|text [--id <id>] [--title "…"] [--from <file>] [--line "who: words"]… [--read all\|none\|<n>,…] [--unread omit\|dim] [--ref <channel>/<postId>]` or `--from-read [--media <i>] [--kind …]`; record: `<id> <line> --recording <file> [--as <the speaker's character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events]`; set: `<id> kind= title= media= at=<a>,<b>\|off unread= ref= read=all\|none\|<n>,… read.<n>="excerpt"\|on\|off line.add="who: words" line.<n>=off line.<n>.who= line.<n>.side=left\|right\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\|off take.<n>=<take n>\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`) | a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2** |
+| `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record …` (add: `--media <i> [--at <from>,<to>] --kind dm\|email\|post\|text [--id <id>] [--title "…"] [--from <file>] [--line "who: words"]… [--read all\|none\|<n>,…] [--unread omit\|dim] [--ref <channel>/<postId>]` or `--from-read [--media <i>] [--kind …]`; record: `<id> <line> --recording <file> [--as <the speaker's character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events]`; set: `<id> kind= title= media= at=<a>,<b>\|off unread= ref= read=all\|none\|<n>,… read.<n>="excerpt"\|on\|off line.add="who: words" line.<n>=off line.<n>.who= line.<n>.side=left\|right\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\|off take.<n>=<take n>\|off said.<n>="…"\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--reading N\|next] [tuning flags] [--for screen:<id>:<line>] [--tuned <role>=reading:N,…]… [--no-pick] [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`) | a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `said.<n>=` is what the voice SAYS for line n (`saidAs`: an acronym spelled out, a typo said right) -- never drawn, never the line's identity; one that says a masked shape or a redacted line is refused. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2** |
| `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
-| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--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= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. |
-| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: 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 pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own |
+| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--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= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"] [--reading N\|next] [--no-pick]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. |
+| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--reading N\|next] [tuning flags] [--for <role>] [--tuned <role\|*>=reading:N,…]… [--no-pick] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: 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 pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own |
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
| `posts character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2** |
| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
@@ -212,6 +213,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `review-pass <project> ls` | the review pass: each block's answer, and where it resumes | form · *project* |
| `review-pass <project> mark <block> keep\|fix\|clear [--note NOTE]` | a block's review-pass mark: keep (a post, a card), fix (needs work, saying what; any block) or clear | form · *project* |
| `review-pass <project> verdict like\|maybe\|no\|clear [--note NOTE]` | the draft's verdict at the pass's end: its parent's when only review fields differ, else saved as a version and judged | form · *project* |
+| `narration <project> [<card>] [--read] [--text TEXT] [--reading READING] [--pick PICK] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--tuning-off] [--list]` | a card's narration: its words, reading and tuning; a reading made, or picked | form · *draft* |
| `present <project> [--take TAKE] [--cut] [--public]` | present mode's address and slides | form · *project* |
| `set <project> <clip> key=value… [--mark MARK] [--take TAKE]` | a clip's knobs: claim, marks, audio, blur, fx … | form · *draft* |
| `intro <project> [key=value…] [--off] [--take TAKE] [--on]` | the intro the cut opens on (render.intro) | form · *draft* |
@@ -372,8 +374,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* |
| `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* |
| `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* |
-| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--reading N] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--post-take N] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
-| `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record [<screen>] [<line>] [key=value…] [--from-read] [--recording RECORDING] [--as AS] [--no-clean] [--no-convert] [--pitch target\|source\|contour] [--semitones N] [--check-words] [--media N] [--at AT] [--kind dm\|email\|post\|text] [--title TITLE] [--line LINE…] [--read READ] [--unread omit\|dim] [--by BY] [--undo] [--post-take N] [--line-take LINE-TAKE…] [--dry-run] [--in-take IN-TAKE]` | a post item's text screenshots: transcribed, drawn, read | form · *draft* |
+| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--reading READING] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--no-pick] [--for FOR] [--tuned TUNED…] [--thread] [--parents PARENTS] [--post-take N] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
+| `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record [<screen>] [<line>] [key=value…] [--from-read] [--recording RECORDING] [--as AS] [--no-clean] [--no-convert] [--pitch target\|source\|contour] [--semitones N] [--check-words] [--media N] [--at AT] [--kind dm\|email\|post\|text] [--title TITLE] [--line LINE…] [--read READ] [--unread omit\|dim] [--by BY] [--undo] [--post-take N] [--line-take LINE-TAKE…] [--reading READING] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--for FOR] [--no-pick] [--dry-run] [--in-take IN-TAKE]` | a post item's text screenshots: transcribed, drawn, read | form · *draft* |
| `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* |
| `posts character <project> <item> [<character>] [--clear]` | the character one post item's own read is made with | form · *draft* |
| `posts voices <project> ls\|set\|remove [<handle>] [<voice>]` | the voice map a thread read uses | form · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1432,7 +1432,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n
| **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in -- or, with **Filter before keeping**, the post waits: [filter, preview, Keep](#record-filter-preview-on-the-record-page) | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder**; **Use a sound file…** (a recording made elsewhere, for the part); the character it is read as, its direction, **▶ <voice> reads it** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id, spans?}` |
| a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` |
| a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done |
-| ANOTHER READING, tuned — the same words read again differently by Orpheus: `reading` N (0 the first; each one's seeds move, so a new cached file; the same N again the same file) and its `tuning` (`temperature` 0.1–1.5, `top_p` 0.05–1, `top_k` 0–200, `min_p` 0–0.5, `repeat_penalty` 1–2, `takes` 1–6; the rest Orpheus's defaults). The take records every tuning value and the reading it was made with (`tuning`, `reading`), from the editor's result; Kokoro and eSpeak NG ignore both and say so. Never changes the card's words | — (S3 of the re-tune plan adds the buttons) | `umtool posts narrate <p> <item> --take --reading 1 [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` (one item's `--take` only) | `op: "take", tuning?, reading?` → `{jobId, file}` |
+| ANOTHER READING, tuned — the same words read again differently by Orpheus: `reading` N (0 the first; each one's seeds move, so a new cached file; the same N again the same file) and its `tuning` (`temperature` 0.1–1.5, `top_p` 0.05–1, `top_k` 0–200, `min_p` 0–0.5, `repeat_penalty` 1–2, `takes` 1–6; the rest Orpheus's defaults). The take records every tuning value and the reading it was made with (`tuning`, `reading`), from the editor's result; Kokoro and eSpeak NG ignore both and say so. Never changes the card's words | **Read again**, **Tune ▾** ([below](#read-again-on-the-post-bench-a-line-re-read-tuned-picked)) | `umtool posts narrate <p> <item> --take --reading 1\|next [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--no-pick]` (one item's `--take`, a thread read's too; not `--all`) | `op: "take", tuning?, reading?` → `{jobId, file}` |
| a THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — |
| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>`; a convert's **pitch** ([below](#the-pitch-a-converted-read-lands-on)) | post bench, **run AI on take #n** (the op, an engine, a stock voice; for a convert on `seed-vc`, **pitch** and **semitones**) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v] [--pitch target\|source\|contour] [--semitones n]` | `op: "derive", from, op2, engine?, voice?, pitch?, semitones?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
| delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) |
@@ -1519,6 +1519,68 @@ snapshot and every script keep their words.
| `render.posts.slurs.edges` — the slurs EDGE-masked (a slur's word, its id or any of its forms names the whole slur, a listed one or the project's own): every form first letter, stars, last letter, in the case written ("n***a", "f****t"); absent, the first-letter mask | the Cut tab's Options → **Reads and voices** → Slur filter: a word, **Edge mask** · **First letter only** (the edges listed by mask) | `umtool posts slurs <p> edges <word>` · `edges <word> --off` (one writer, `updatePostSlurs`; a word naming no slur is refused, exit 2) · `ls` says `edges: n***a, f-slur` | — |
| what the cut masks | the Cut tab's Options → **Reads and voices** → Slur filter (how many masked) | `umtool posts slurs <p> ls [--json]`: per slur (its mask, never the word; an edged slur each form's mask, "/" between) and per post, and each read that needs word timings | — |
+## Read again on the post bench (a line re-read, tuned, picked)
+
+Re-type a line, press, hear the new read when it lands, pick it -- with no agent (lane line-rerun, S3 of the Orpheus
+re-tune plan; operator rulings 15 Nov 2026). Every button is a form and a job: the bench's route runs the umtool
+command below, the EDITOR synthesizes (`tts-file` jobs on its `tts` lane, one at a time), every write lands in the
+working draft. **An edit changes only what is SPOKEN**: what the card draws never changes (pinned:
+`report-to-video/post-reading-pin.test.mjs`). A stale read is listed and offered, never re-made by itself; nothing is
+deleted by a re-read; recorded takes and their enhance/convert chain are untouched.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| **Read again** — the same words, the NEXT reading (one past the highest reading of these words among the item's takes; new words: 0), a new take NOT picked | post bench, under the script: **Read again** | `umtool posts narrate <p> <item> --take --reading next --no-pick` | `op: "take", reading: "next", keepPick: true` |
+| **Read edited text** — the script saved (as **Save script**), then read | **Read edited text** | `--script "…"` then the above | `op: "set", patch: {script}` then `op: "take"` |
+| **Tune ▾** — temperature, top_p, top_k, min_p, repeat_penalty, takes for this line only, prefilled from how the text was last made; **Read with these** | **Tune ▾** | `--temperature … --top-p … --top-k … --min-p … --repeat-penalty … --chunk-takes …` | `tuning: {…}` |
+| play when ready — the new read plays as it lands (on by default, remembered per browser; one box for every line on the page) | the **play when ready** box | — (the CLI waits and prints the take) | — |
+| **Pick** — the new read made the one the cut plays; the one it replaces stays in the list, one press away | the take's **Pick** | `--pick <n>` | `patch: {pick}` |
+| a screen line **said as** (`screens[j].saidAs.<n>`) — what the voice says for that line instead of its words; never drawn, never the line's identity; one that says a masked shape or a redacted line is refused | Screens, the line's **said as** field (Save) | `umtool posts screen <p> <item> set <id> said.<n>="…"` (`=off` clears) | the bench's Save (`screens`) |
+| a LINE read again — that line's part only, the rest from the parts cache, joined into a new take, not picked; the line's readings listed with Play and Pick | Screens, the line's **Read again** / **Read edited text** / **Tune ▾** | `umtool posts screen <p> <item> read --for screen:<id>:<n> --reading next [tuning flags] --no-pick` | `op: "screen-read", for, reading, tuning, keepPick` |
+| the THREAD read again — every synthesized piece one past its own highest reading, a new take, not picked | Thread read, **Read again** / **Tune ▾** | `umtool posts screen <p> <item> read --reading next --no-pick` (with screens) · `umtool posts narrate <p> <item> --take --thread … --reading next --no-pick` | `op: "thread-read", reading, tuning` |
+
+- **A thread read's readings are per piece**: `--reading` and the tuning flags with `--thread` are the whole read's,
+ `--for <role>` (post, quoted, parent:<i>, linked:<i>, screen:<id>:<n>) one piece's, `--tuned <role|*>=reading:N,
+ temperature:t,…` (repeatable) each piece's exactly. The take records them: each part's `reading`/`tuning`, and
+ `read.tuned` (`{ <role>: { reading?, tuning?, said } }`). `posts screen read` keeps the playing read's reading for a
+ piece while it says the same words; a cast re-read asks them again (`--tuned`). A part with no reading and no tuning
+ keeps the parts-cache key it always had.
+- **One read of a post at a time**: a double press is one read; a second press while one is made is refused in place
+ (409), never asked twice. A read whose pieces already say this makes nothing and says so (the job's one result line,
+ `--events`); only a take the job made is played, marked new or named. A reading asked for a piece read from a take
+ (a recording) is refused: record it again.
+ While render mode holds the machine a pressed read says it is waiting for the render, and is made when it ends.
+- **The card follows the shown text; the playing take decides** (review 1's ruling). A take is stamped `forReading`
+ by the writer when it is made from words that are not the post's as drafted (a script edited for reading, a lexicon
+ word, a tag). While a stamped take plays, the post's blocks, the lit/dim follow and the parts' roles come from the
+ post's words as drafted -- timed by the read's parts one for one, else shared by words over the span his parts were
+ read in -- and the thread tiles keep their times, so no spoken edit moves, hides or dims for good a drawn word, or
+ changes when or how a thread tile shows (`read-follow.mjs followParts`, `post-thread.mjs partRoles`,
+ `threadSchedule`). Saving the script back, re-picking an older take or redrafting scripts changes nothing while that
+ take plays. `narration.forReading` (set by the script's writer) decides only for an item with no take playing. A
+ script saying what a screen masks or a redacted line holds is refused when it is written.
+- **A playing take from before the rule** (no stamp, and its words are not the post's): its card follows its words, as
+ it always did. `umtool posts narrate <p> --list` flags it (`--json`: `readEdit: "legacy"`), the bench says so in one
+ line: read it again to move it to the rule. Nothing migrates by itself.
+- **Keep for the character** (S2, lane character-tuning) is a seam: `ReadAgain`'s `keepForCharacter` prop; absent, no
+ button.
+
+## A card's narration, read again
+
+A card's `narration.text` is spoken only: no card draws it, so an edit changes what is said and the card's length.
+Its readings are the voices kept for it beside the build (`out/narration/<key>.wav`, each with its words, reading and
+the tuning it was asked with).
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a reading made and kept, the card NOT changed (`--reading next`: one past the highest these words were read at) | the narration page (`/browse/<p>/narration`), the card's **Read again** / **Tune ▾** | `umtool narration <p> <card> --read --reading next [tuning flags]` | `POST /api/report/narration/play {again: true, reading, tuning}` |
+| the card's words saved, then read | **Read edited text** | `umtool narration <p> <card> --read --text "…"` (or `--text "…"` to set them) | `action: "edit"` then the above |
+| the reading the card plays (its words, reading and tuning; nothing synthesized) | the reading's **Pick** | `umtool narration <p> <card> --pick <key>` | `POST /api/report/narration {action: "pick", key}` |
+| `narration.reading` / `narration.tuning` set by hand | — | `umtool narration <p> <card> --reading N` · tuning flags · `--tuning-off` | — |
+
+**A pick keeps the verdict** given on the same words (the review keys a verdict by the narration's key, which a
+reading moves: the pick moves the verdict with it). New words are not the words anybody approved.
+
## Pronunciation and voices (the lexicon, the voice map, a thread read)
Three plain commands do what hand-made scripts used to (operator, 4 Nov 2026: "we want the plain apps to do as much
diff --git a/umtool/e2e/narration-review.spec.ts b/umtool/e2e/narration-review.spec.ts
@@ -99,3 +99,34 @@ test("the build refuses a narrated card the review has not approved", async ({ r
expect(JSON.stringify(done)).toContain("timeline k02: its narration is not reviewed");
expect(existsSync(path.join(DIR, "out", "narration-review-fixture.mp4"))).toBe(false);
});
+
+test("A CARD READ AGAIN (lane line-rerun): Read again keeps a new reading without changing the card, Pick plays it, the verdict on the same words kept; the first reading one press away", async ({ page }) => {
+ await page.goto(urls.section(PROJECT, "narration"));
+ await page.locator("[data-narration-link]").click();
+ const k1 = page.locator('[data-narration-card="k01"]');
+ const card = () => manifest().timeline.find((e) => e.id === "k01")!.narration as { text: string; reading?: number };
+ const text = card().text;
+ const state = await k1.getAttribute("data-state");
+ for (const label of ["Read the card again", "Read the card as edited", "Tune the card only", "Play new reads when they land"]) await expect(k1.locator(`[aria-label="${label}"]`), label).toHaveCount(1);
+ const readings = k1.locator("[data-narration-reading]");
+ const had = await readings.count();
+ const before = ttsAsks().length;
+ await k1.locator('[aria-label="Read the card again"]').click();
+ // The first reading it kept (Play's, if any) and this one.
+ await expect.poll(() => readings.count(), { timeout: 60_000 }).toBeGreaterThan(had);
+ expect(ttsAsks().length).toBe(before + 1);
+ expect(card()).toMatchObject({ text });
+ expect(card().reading ?? 0).toBe(0);
+ // Pick the new reading: the card plays it -- its verdict on these words kept.
+ const fresh = k1.locator('[data-narration-reading]:not([data-playing])').last();
+ const key = await fresh.getAttribute("data-narration-reading");
+ await k1.locator(`[data-narration-reading-pick="${key}"]`).click();
+ await expect(k1.locator(`[data-narration-reading="${key}"]`)).toHaveAttribute("data-playing", "1");
+ expect(card().reading).toBeGreaterThan(0);
+ if (state) await expect(k1).toHaveAttribute("data-state", state);
+ // Back to the first: one press, nothing asked.
+ const asked = ttsAsks().length;
+ await k1.locator('[data-narration-reading]:not([data-playing]) [data-narration-reading-pick]').first().click();
+ await expect.poll(() => card().reading ?? 0).toBe(0);
+ expect(ttsAsks().length).toBe(asked);
+});
diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -592,3 +592,195 @@ test("THE RECORDING SESSION: part by part, a reload resumes, redo one, the last
await page.keyboard.press("Enter");
await expect(s).toHaveAttribute("data-record-session", "p-12");
});
+
+// ---------------------------------------------------------------------------
+// READ AGAIN (lane line-rerun, S3 of the Orpheus re-tune plan): from the post bench a line is read again, heard as it
+// lands, and picked, with no agent -- and what the card DRAWS never changes. An item of this test's own, p-31 (written
+// into the manifest here, so the specs that share p-11 and p-13 never see it): a two-paragraph post, its script its
+// words as drafted, one take; a screenshot on it read line by line.
+// ---------------------------------------------------------------------------
+
+const OWN_TEXT = "The ferry runs at noon.\n\nBring a coat for the crossing.";
+const OWN_TAKE = "narration/posts/31/take-1.orpheus-zac.wav";
+
+function addOwnItem() {
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ const base = m.timeline.find((x: { id: string }) => x.id === "p-13");
+ m.timeline.push({
+ ...base, id: "p-31", post: "narrchan-x/31", url: "https://x.com/narrsubject/status/31", text: OWN_TEXT,
+ media: [{ src: "posts-media/narrchan-x/12/12_1.png", kind: "image", width: 320, height: 180 }],
+ screens: [{ id: "s1", media: 0, kind: "dm", read: "none", lines: [{ who: "ferryfan", text: "Is it the BRT dock?" }, { who: "narrsubject", text: "Yes, pier four." }] }],
+ narration: { script: OWN_TEXT, takes: [{ file: OWN_TAKE, engine: "orpheus", voice: "zac", seconds: 2, script: OWN_TEXT, at: "2026-11-02T00:00:00.000Z" }], pick: 0 },
+ });
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ mkdirSync(path.join(DIR, "narration", "posts", "31"), { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=300:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", path.join(DIR, OWN_TAKE)]);
+}
+
+/** What the bench's card frame DRAWS of the item: its words, its blocks (their keys and words), its tiles' modes. */
+async function drawnCard(page: Page) {
+ const frame = page.frameLocator('[data-post-card-frame="read"]');
+ await expect(frame.locator("[data-post-words]")).toContainText("ferry", { timeout: 15_000 });
+ return frame.locator("body").evaluate((b) => ({
+ words: b.querySelector("[data-post-words]")?.textContent ?? null,
+ blocks: [...b.querySelectorAll("[data-post-block]")].map((x) => [x.getAttribute("data-post-block"), x.textContent]),
+ tiles: [...b.querySelectorAll("[data-thread-tile]")].map((x) => [x.getAttribute("data-thread-tile"), x.getAttribute("data-thread-mode")]),
+ follow: b.getAttribute("data-post-follow"),
+ }));
+}
+
+test("READ AGAIN (lane line-rerun): the next reading unpicked and heard as it lands, the edited text read, Pick -- and the card draws exactly what it drew", async ({ page }) => {
+ addOwnItem();
+ // Every play the page starts, recorded (a new read plays as it lands).
+ await page.addInitScript(() => {
+ const w = window as unknown as { __played: string[] };
+ w.__played = [];
+ const play = HTMLMediaElement.prototype.play;
+ HTMLMediaElement.prototype.play = function (this: HTMLMediaElement) {
+ w.__played.push(this.src);
+ return play.call(this).catch(() => undefined) as Promise<void>;
+ };
+ });
+ await page.setViewportSize({ width: 1440, height: 1400 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-31"));
+ const panel = page.locator('[data-post-narration="p-31"]');
+ await expect(panel.locator("[data-post-take]")).toHaveCount(1);
+ // Every new control, by its name.
+ for (const label of ["Read again", "Read the edited text", "Tune this line only", "Read again with this tuning", "Tuning back to the defaults", "Play new reads when they land", "temperature, this line only", "top p, this line only", "top k, this line only", "min p, this line only", "repeat penalty, this line only", "takes, this line only", "Pick take 1"]) {
+ await expect(panel.locator(`[aria-label="${label}"]`), label).toHaveCount(1);
+ }
+ const before = await drawnCard(page);
+
+ // READ AGAIN: reading 1, a new take NOT picked, marked new, played as it lands.
+ await expect(panel.locator('[aria-label="Read the edited text"]')).toBeDisabled();
+ // A DOUBLE PRESS is one read (review 1, finding 4): one ask of the editor, one take.
+ const asks31 = () => (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; out?: string }[]).filter((r) => r.route === "tts" && String(r.out ?? "").includes("/narration/posts/31/")).length;
+ const asked0 = asks31();
+ await panel.locator('[aria-label="Read again"]').dblclick();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 20_000 });
+ expect(asks31()).toBe(asked0 + 1);
+ expect(narr("p-31").takes![1]).toMatchObject({ file: "narration/posts/31/take-2.orpheus-zac.wav", script: OWN_TEXT, reading: 1 });
+ expect(narr("p-31").pick).toBe(0);
+ await expect(panel.locator('[data-post-take-new="2"]')).toBeVisible();
+ await expect(panel.locator('[data-post-take-made="2"]')).toHaveText("reading 1");
+ await expect.poll(() => page.evaluate(() => (window as unknown as { __played: string[] }).__played.some((u) => u.includes(encodeURIComponent("take-2.orpheus-zac.wav"))))).toBe(true);
+ // Again, tuned for this line only: reading 2, the tuning sent and recorded.
+ await panel.locator('[data-read-tune] summary').click();
+ await panel.locator('[aria-label="temperature, this line only"]').fill("0.7");
+ await panel.locator('[aria-label="Read again with this tuning"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 20_000 });
+ expect(narr("p-31").takes![2]).toMatchObject({ reading: 2, tuning: { temperature: 0.7 } });
+ expect(narr("p-31").pick).toBe(0);
+ // The take list says each take's words.
+ await expect(panel.locator('[data-post-take-text="3"]')).toContainText("The ferry runs at noon.");
+
+ // READ EDITED TEXT: the words changed for reading only -- saved (marked for reading), then read (reading 0).
+ const spoken = "The ferry runs at twelve noon. Bring a warm coat for the crossing.";
+ await panel.locator("[data-post-script]").fill(spoken);
+ await panel.locator('[aria-label="Read the edited text"]').click();
+ await expect(panel.locator("[data-post-take]")).toHaveCount(4, { timeout: 20_000 });
+ const n = timeline().find((e) => e.id === "p-31")!.narration as Record<string, unknown> & { takes: Array<Record<string, unknown>> };
+ expect(n.script).toBe(spoken);
+ expect(n.forReading).toBe(true);
+ expect(n.takes[3]).toMatchObject({ script: spoken });
+ expect(n.takes[3].reading ?? 0).toBe(0);
+ expect(n.pick).toBe(0);
+
+ // PICK the edited read: it plays now -- and the card draws exactly what it drew before any of this.
+ await panel.locator('[aria-label="Pick take 4"]').click();
+ await expect(panel.locator('[data-post-take="4"]')).toHaveAttribute("data-post-take-picked", "1");
+ expect(narr("p-31").pick).toBe(3);
+ await page.reload();
+ expect(await drawnCard(page)).toEqual(before);
+ // The previous pick, one press away.
+ await page.locator('[data-post-narration="p-31"] [aria-label="Pick take 1"]').click();
+ await expect.poll(() => narr("p-31").pick).toBe(0);
+ // A READ WHOSE JOB CANNOT BE FOLLOWED fails in place, never "reading…" for ever (review 1, finding 5).
+ await page.route(/\/api\/report\/post-narration\?.*[?&]job=/, (route) => route.abort());
+ await page.locator('[data-post-narration="p-31"] [aria-label="Read again"]').click();
+ await expect(page.locator('[data-post-narration="p-31"] [data-post-take-failed]')).toContainText("did not answer", { timeout: 20_000 });
+ await expect(page.locator('[data-post-narration="p-31"] [aria-label="Read again"]')).toBeEnabled();
+ // The bench back: Check again lands the take the editor made meanwhile (review 2, finding 2) -- nothing lost.
+ await page.unroute(/\/api\/report\/post-narration\?.*[?&]job=/);
+ const had = narr("p-31").takes!.length;
+ await page.locator('[data-post-narration="p-31"] [aria-label="Check again"]').click();
+ await expect.poll(() => narr("p-31").takes!.length, { timeout: 20_000 }).toBe(had + 1);
+ // A lost read is found again on load too: its marker is gone once its take is kept.
+ expect(existsSync(path.join(DIR, "narration", "posts", "31", ".reading.json"))).toBe(false);
+});
+
+test("READ A SCREEN LINE AGAIN (lane line-rerun): said as, read again alone, its readings listed and picked -- the controls by name; the narration page's too", async ({ page }) => {
+ addOwnItem();
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ const e = m.timeline.find((x: { id: string }) => x.id === "p-31");
+ e.screens[0].read = "all";
+ e.screens[0].saidAs = { 0: "Is it the B R T dock?" };
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ await page.setViewportSize({ width: 1440, height: 1400 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-31"));
+ const line = page.locator('[data-post-screen-line="0"]');
+ for (const label of ["said as, line 0", "Read line 0 again", "Read line 0 as edited", "Tune line 0 only"]) await expect(line.locator(`[aria-label="${label}"]`), label).toHaveCount(1);
+ await expect(line.locator('[aria-label="said as, line 0"]')).toHaveValue("Is it the B R T dock?");
+ // The first read with the screens: made, picked (the bench's Make the read).
+ await page.locator("[data-post-screens-make-read]").click();
+ await expect.poll(() => (narr("p-31").takes ?? []).length, { timeout: 60_000 }).toBe(2);
+ const first = narr("p-31").takes![1] as Take & { parts?: Array<{ role?: string; text?: string; reading?: number }> };
+ expect(first.parts!.find((p) => p.role === "screen:s1:0")!.text).toContain("B R T");
+ await page.reload();
+ // Line 0 again: only it is read anew (reading 1), a new take unpicked.
+ await page.locator('[data-post-screen-line="0"] [aria-label="Read line 0 again"]').click();
+ await expect.poll(() => (narr("p-31").takes ?? []).length, { timeout: 60_000 }).toBe(3);
+ const again = narr("p-31").takes![2] as Take & { parts?: Array<{ role?: string; reading?: number }>; read?: { tuned?: Record<string, { reading?: number }> } };
+ expect(again.parts!.find((p) => p.role === "screen:s1:0")!.reading).toBe(1);
+ expect(again.parts!.find((p) => p.role === "screen:s1:1")!.reading).toBeUndefined();
+ expect(again.read!.tuned!["screen:s1:0"].reading).toBe(1);
+ expect(narr("p-31").pick).toBe(1);
+ await expect(page.locator('[data-post-screen-reading-pick="0:3"]')).toBeVisible({ timeout: 15_000 });
+ await page.locator('[aria-label="Pick take 3 for line 0"]').click();
+ await expect.poll(() => narr("p-31").pick).toBe(2);
+ // ONE "play when ready" for every line on the page (review 1, finding 9): off on the post's, off on the line's.
+ const postAuto = page.locator('[data-post-narration="p-31"] [aria-label="Play new reads when they land"]');
+ const lineAuto = page.locator('[data-post-screen-line="0"] [aria-label="Play new reads when they land"]');
+ await expect(lineAuto).toBeChecked();
+ await postAuto.uncheck();
+ await expect(lineAuto).not.toBeChecked();
+ await lineAuto.check();
+ await expect(postAuto).toBeChecked();
+});
+
+test("READ THE THREAD AGAIN (lane line-rerun): its controls by name on a threaded item, and one press makes a new thread read, unpicked, every synthesized piece one reading on", async ({ page }) => {
+ // p-32 of this test's own: a reply, its thread read (the post it answers, then his words) picked.
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ const base = m.timeline.find((x: { id: string }) => x.id === "p-13");
+ const file = "narration/posts/32/take-1.orpheus-thread.wav";
+ m.timeline.push({
+ ...base, id: "p-32", post: "narrchan-x/32", url: "https://x.com/narrsubject/status/32", text: "Yes, every morning at nine.", date: "2026-10-30T11:00:00.000Z",
+ parents: [{ id: "3201", handle: "ferryfan", author: "Ferry Fan", text: "Does the early boat still run?", date: "2026-10-30T10:30:00.000Z" }],
+ narration: {
+ script: "Yes, every morning at nine.", pick: 0,
+ takes: [{ file, engine: "orpheus", voice: "leo+zac", seconds: 4, script: "Does the early boat still run?\n\nYes, every morning at nine.", read: { kind: "thread", parents: "0" }, parts: [
+ { n: 1, para: 0, text: "Does the early boat still run?", voice: "leo", role: "parent:0", start: 0, seconds: 1.8 },
+ { n: 2, para: 100, text: "Yes, every morning at nine.", voice: "zac", role: "post", start: 2.6, seconds: 1.4 },
+ ] }],
+ },
+ });
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ mkdirSync(path.join(DIR, "narration", "posts", "32"), { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=300:sample_rate=48000:duration=4", "-ac", "1", "-c:a", "pcm_s16le", path.join(DIR, file)]);
+ await page.setViewportSize({ width: 1440, height: 1400 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-32"));
+ const thread = page.locator("[data-post-thread-panel]");
+ for (const label of ["Read the thread again", "Tune the thread only", "Read the thread again with this tuning", "Play new reads when they land"]) await expect(thread.locator(`[aria-label="${label}"]`), label).toHaveCount(1);
+ await thread.locator('[aria-label="Read the thread again"]').click();
+ await expect(thread.locator("[data-read-note]")).toContainText("take 2 made, not picked", { timeout: 60_000 });
+ const t2 = narr("p-32").takes![1] as Take & { parts?: Array<{ role?: string; reading?: number }>; read?: { kind?: string } };
+ expect(t2.read?.kind).toBe("thread");
+ expect(t2.parts!.map((p) => [p.role, p.reading])).toEqual([["parent:0", 1], ["post", 1]]);
+ expect(narr("p-32").pick).toBe(0);
+});
+
+test("THE NARRATION PAGE's cards carry the same controls, by name", async ({ page }) => {
+ await page.goto(urls.section("reports/narration-review-fixture", "narration"));
+ await page.locator("[data-narration-link]").click();
+ for (const label of ["Read the card again", "Read the card as edited", "Tune the card only"]) await expect(page.locator(`[aria-label="${label}"]`).first(), label).toBeVisible();
+});
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -285,6 +285,20 @@ export const GROUPS = [
],
},
{
+ cmd: "narration",
+ usage: [
+ " umtool narration <project> [<card>] [--list] [--json] a CARD's NARRATION (spoken only; no card draws it): its",
+ " words, reading and tuning, and its READINGS kept beside the build (out/narration/)",
+ " umtool narration <project> <card> --read [--text \"…\"] [--reading N|next] [tuning flags] one reading asked of",
+ " the editor and kept, the card NOT changed · --pick <key>: the card made that reading",
+ " umtool narration <project> <card> [--text \"…\"] [--reading N] [tuning flags | --tuning-off] set them",
+ ],
+ docs: [
+ ["`narration <project> [<card>] [--list] [--json]` · `<card> --read [--text \"…\"] [--reading N\|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` · `<card> --pick <key>` · `<card> [--text \"…\"] [--reading N] [tuning flags \| --tuning-off]`",
+ "a **card's narration** and its readings ([knobs.md](knobs.md#a-cards-narration-read-again), `lib/report/cardNarrationCli.mjs`): the words a stock voice says over a card (spoken only — no card draws them), its reading and Orpheus tuning; `--read` asks the editor for one reading (a job; it waits while render mode holds the machine) and keeps it in `out/narration/` without changing the card (`--reading next`: one past the highest these words were read at); `--pick <key>` makes the card play a kept reading (its words, reading and tuning; nothing synthesized) — a verdict on the same words is kept; without either, the card's words, reading and tuning are set. The narration page's Read again, Read edited text, Tune and Pick run these."],
+ ],
+ },
+ {
cmd: "present",
usage: [
" umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] PRESENT MODE: the cut as slides,",
@@ -1036,12 +1050,13 @@ export const GROUPS = [
" a re-run adds only posts not already in the cut",
" umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [media.<i>.start=<s>]",
" [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off] [media.<i>.push=on|off] [--json]",
- " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"] [--reading n]",
- " [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]]",
+ " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"] [--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] [k=v …]",
" | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]",
- " [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date",
+ " [--voice-for <handle>=<voice>]… [--reading n|next [--for <role>]] [--tuned <role>=reading:n,…]… [--no-pick]",
+ " [--dry-run] [--json] a THREAD READ: its context and his words in date",
" order, each in its author's voice, parts cached, one take saved and picked (exit 0 / 1)",
" umtool posts set-item | roles | narrate | reread | fx … --in-take <take> the same edit on a TAKE of the project:",
" its manifest read as the take's, the write in takes/<take>/take.json's patch (an undo point of the take's,",
@@ -1085,13 +1100,13 @@ export const GROUPS = [
"**one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it \"choppy\"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: \"revoice\", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2**"],
["`posts progress <project> [auto\\|on\\|off\\|default] [--json]`",
"the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it"],
- ["`posts screen <project> <item> list\\|add\\|set\\|rm\\|check\\|read\\|record …` (add: `--media <i> [--at <from>,<to>] --kind dm\\|email\\|post\\|text [--id <id>] [--title \"…\"] [--from <file>] [--line \"who: words\"]… [--read all\\|none\\|<n>,…] [--unread omit\\|dim] [--ref <channel>/<postId>]` or `--from-read [--media <i>] [--kind …]`; record: `<id> <line> --recording <file> [--as <the speaker's character>] [--no-clean\\|--clean] [--no-trim\\|--trim] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events]`; set: `<id> kind= title= media= at=<a>,<b>\\|off unread= ref= read=all\\|none\\|<n>,… read.<n>=\"excerpt\"\\|on\\|off line.add=\"who: words\" line.<n>=off line.<n>.who= line.<n>.side=left\\|right\\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\\|off take.<n>=<take n>\\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`)",
- "a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \\| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2**"],
+ ["`posts screen <project> <item> list\\|add\\|set\\|rm\\|check\\|read\\|record …` (add: `--media <i> [--at <from>,<to>] --kind dm\\|email\\|post\\|text [--id <id>] [--title \"…\"] [--from <file>] [--line \"who: words\"]… [--read all\\|none\\|<n>,…] [--unread omit\\|dim] [--ref <channel>/<postId>]` or `--from-read [--media <i>] [--kind …]`; record: `<id> <line> --recording <file> [--as <the speaker's character>] [--no-clean\\|--clean] [--no-trim\\|--trim] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events]`; set: `<id> kind= title= media= at=<a>,<b>\\|off unread= ref= read=all\\|none\\|<n>,… read.<n>=\"excerpt\"\\|on\\|off line.add=\"who: words\" line.<n>=off line.<n>.who= line.<n>.side=left\\|right\\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\\|off take.<n>=<take n>\\|off said.<n>=\"…\"\\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--reading N\\|next] [tuning flags] [--for screen:<id>:<line>] [--tuned <role>=reading:N,…]… [--no-pick] [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`)",
+ "a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \\| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `said.<n>=` is what the voice SAYS for line n (`saidAs`: an acronym spelled out, a typo said right) -- never drawn, never the line's identity; one that says a masked shape or a redacted line is refused. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2**"],
["`posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]`",
"a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**)"],
- ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--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= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`",
+ ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--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= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"] [--reading N\\|next] [--no-pick]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`",
"a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."],
- ["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`",
+ ["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--reading N\\|next] [tuning flags] [--for <role>] [--tuned <role\\|*>=reading:N,…]… [--no-pick] [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`",
"a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: 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 pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own"],
["`posts say <project> [ls] [--item <id>]` · `add <word\\|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"]` · `remove <word\\|n> [--item <id>]` · `try \"<text>\" [--item <id>]` · `stale` `[--json]`",
"**THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2**"],
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -233,6 +233,12 @@ export const VERBS = Object.freeze([
form("review-pass verdict", "project", "the draft's verdict at the pass's end: its parent's when only review fields differ, else saved as a version and judged", [
project(), pick("verdict", ["like", "maybe", "no", "clear"], { required: true }), opt("--note", { type: "text", help: "the verdict's note" }),
], { shape: "review-pass <project> verdict <verdict>" }),
+ // A card's narration and its readings (lane line-rerun, lib/report/cardNarrationCli.mjs): the narration page's twin.
+ form("narration", "draft", "a card's narration: its words, reading and tuning; a reading made, or picked", [
+ project(), arg("card", { required: false, help: "the card (none: every narrated card)" }), bool("--read", "one reading asked of the editor, the card not changed"),
+ opt("--text", { type: "text" }), opt("--reading", { help: "0-99999, or next (with --read)" }), opt("--pick", { help: "a kept reading's key" }),
+ num("--temperature"), num("--top-p"), num("--top-k"), num("--min-p"), num("--repeat-penalty"), num("--chunk-takes"), bool("--tuning-off"), bool("--list"),
+ ]),
form("present", "project", "present mode's address and slides", [project(), takeOpt({ help: "that take's cut (default the latest)" }), bool("--cut", "the manifest alone"), bool("--public", "as a public page would carry it")]),
form("set", "draft", "a clip's knobs: claim, marks, audio, blur, fx …", [project(), clip(), pairs({ help: "key=value, one per line (claim.at=190.2, audio.gain=-3, `key=` clears)" }), opt("--mark", { help: "the mark the claim.* keys set" }), takeOpt()], B(["clip"], { clip: "{id}" })),
form("intro", "draft", "the intro the cut opens on (render.intro)", [project(), pairs({ required: false, help: "key=value, one per line (style=boot-dark, seconds=4); none: print it" }), bool("--off", "take the intro off"), takeOpt({ help: "a version: --off opens it on no intro, --on on the cut's" }), bool("--on")], B(["intro"], {})),
@@ -539,10 +545,11 @@ function posts() {
p("narrate", "draft", "a post item's narration: script, takes, pick, approve, mix", [
item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"),
opt("--voice"), opt("--engine"), num("--speed"),
- num("--reading", { help: "with --take: another reading of the same words, 0-99999 (0 = the first)" }), num("--temperature", { help: "with --take: Orpheus's tuning, 0.1-1.5" }),
+ opt("--reading", { help: "with --take: another reading of the same words, 0-99999 (0 = the first), or next" }), num("--temperature", { help: "with --take: Orpheus's tuning, 0.1-1.5" }),
num("--top-p", { help: "with --take: 0.05-1" }), num("--top-k", { help: "with --take: 0-200" }), num("--min-p", { help: "with --take: 0-0.5" }),
num("--repeat-penalty", { help: "with --take: 1-2" }), num("--chunk-takes", { help: "with --take: the tries a sentence gets, 1-6" }),
- num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"),
+ num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"), bool("--no-pick", "with --take: the new take joins the list unpicked"),
+ opt("--for", { help: "with --thread: the piece the reading and tuning are for (screen:<id>:<line>, post, …)" }), many("--tuned", { repeat: true, item: "role=reading:N,…", help: "with --thread: each piece's reading and tuning" }),
bool("--thread", "with --take: a thread read"), opt("--parents"), num("--post-take", { help: "with --thread: his own line is this take of the item (as --list numbers them)" }), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"),
num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"),
pick("--pitch", ["target", "source", "contour"], { help: "a convert's pitch (--recording, --derive)" }), num("--semitones", { help: "-12…12, moves a followed pitch" }), dry(),
@@ -558,6 +565,8 @@ function posts() {
many("--line", { repeat: true, item: "line", help: "add: a line `who: words`, one per line" }),
opt("--read", { help: "add: all, none or line numbers" }), pick("--unread", ["omit", "dim"]), opt("--by", { help: "check: who checked it" }), bool("--undo", "check: not checked"),
num("--post-take", { help: "read: her own line is this take of the item" }), many("--line-take", { repeat: true, item: "role=n", help: "read: screen:<id>:<line>=<take n>, one per line" }),
+ opt("--reading", { help: "read: 0-99999 or next" }), num("--temperature"), num("--top-p"), num("--top-k"), num("--min-p"), num("--repeat-penalty"), num("--chunk-takes"),
+ opt("--for", { help: "read: the piece they are for (screen:<id>:<line>)" }), bool("--no-pick", "read: the new take joins the list unpicked"),
pairs({ required: false, help: "set: kind= title= at= read= read.<n>=\"excerpt\" line.<n>.who= …, one per line" }), dry(), inTake(),
], { shape: "posts screen <project> <item> <op>", ...POST_ITEM }),
p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }),
diff --git a/umtool/lib/report/cardNarration.test.mjs b/umtool/lib/report/cardNarration.test.mjs
@@ -0,0 +1,125 @@
+// `umtool narration` (cardNarrationCli.mjs; lane line-rerun): a card's narration read again, kept beside the build
+// without changing the card, picked, and its verdict kept on the same words. A stub for the editor; temp dirs.
+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 { cardNarrationCommand, cardReadings, nextCardReading } from "./cardNarrationCli.mjs";
+import { keepNarration } from "umtool-report-to-video/narration-store";
+import { readNarrationReview, reviewState, setNarrationReview } from "umtool-report-to-video/narration-review";
+import { narrationsOf } from "umtool-report-to-video/narration";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-card-narration-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+const CARD = { type: "card", id: "c1", seconds: "auto", heading: "The crossing", narration: { text: "Six months later, the ferry ran again.", engine: "orpheus", voice: "tara" } };
+
+async function project(name) {
+ 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 }, timeline: [CARD],
+ }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+/** The editor, stubbed: a tone kept as the editor's result would be (narration-store.mjs keepNarration). */
+const narrate = (asked) => async ({ narrations, dir }) => {
+ const recs = new Map();
+ for (const n of narrations) {
+ asked.push(n);
+ const wav = path.join(ROOT, `${n.key}.src.wav`);
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=330:d=1.4", "-ar", "48000", "-ac", "1", wav]);
+ recs.set(n.id, await keepNarration(dir, n, { wav, engine: n.engine, voice: n.voice, reading: n.reading ?? 0, ...(n.tuning ? { tuning: n.tuning } : {}) }, { jobId: `job-${asked.length}` }));
+ }
+ return recs;
+};
+const run = async (args, asked = []) => {
+ const lines = [];
+ const code = await cardNarrationCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s), narrate: narrate(asked) });
+ return { code, out: lines.join("\n"), json: () => JSON.parse(lines.join("\n")) };
+};
+
+test("--read keeps a reading WITHOUT changing the card; --reading next is one past the highest of these words; --pick plays it, a verdict on the same words kept", async () => {
+ const p = await project("read");
+ const asked = [];
+ let r = await run([p.id, "c1", "--read", "--json"], asked);
+ assert.equal(r.code, 0, r.out);
+ assert.equal(r.json().plays, true);
+ r = await run([p.id, "c1", "--read", "--reading", "next", "--temperature", "0.7", "--json"], asked);
+ assert.equal(r.code, 0, r.out);
+ assert.deepEqual([asked[1].reading, asked[1].tuning], [1, { temperature: 0.7 }]);
+ assert.equal(r.json().plays, false);
+ assert.deepEqual((await manifest(p)).timeline[0].narration, CARD.narration, "the card is not changed by a reading");
+ const readings = await cardReadings(p.dir, "c1");
+ assert.equal(readings.length, 2);
+ assert.equal(nextCardReading(readings, CARD.narration.text), 2);
+ // Approved as it plays now; picking reading 1 of the same words keeps the verdict.
+ const now = narrationsOf(await manifest(p))[0];
+ await setNarrationReview(p.dir, "c1", { verdict: "approved", key: now.key, text: now.text });
+ r = await run([p.id, "c1", "--pick", readings[1].key, "--json"]);
+ assert.equal(r.code, 0, r.out);
+ assert.equal(r.json().verdictKept, true);
+ const after1 = (await manifest(p)).timeline[0].narration;
+ assert.deepEqual([after1.reading, after1.tuning], [1, { temperature: 0.7 }]);
+ const n1 = narrationsOf(await manifest(p))[0];
+ assert.equal(n1.key, readings[1].key, "the card plays the picked reading's file");
+ assert.equal(reviewState(n1, (await readNarrationReview(p.dir)).rows.c1), "approved");
+ // Back to the first: one press, nothing synthesized.
+ r = await run([p.id, "c1", "--pick", readings[0].key.slice(0, 12)], asked);
+ assert.equal(r.code, 0, r.out);
+ assert.equal(asked.length, 2);
+ assert.equal("reading" in (await manifest(p)).timeline[0].narration, false);
+});
+
+test("--read --text reads other words (the card keeps its own until a pick); setting the words, a reading and the tuning; refusals", async () => {
+ const p = await project("set");
+ const asked = [];
+ const r = await run([p.id, "c1", "--read", "--text", "Six months on, the ferry ran.", "--reading", "next", "--json"], asked);
+ assert.equal(r.code, 0, r.out);
+ assert.equal(asked[0].reading ?? 0, 0, "new words: the first reading");
+ assert.equal((await manifest(p)).timeline[0].narration.text, CARD.narration.text);
+ assert.equal((await run([p.id, "c1", "--reading", "3"])).code, 0);
+ assert.equal((await manifest(p)).timeline[0].narration.reading, 3);
+ assert.equal((await run([p.id, "c1", "--tuning-off"])).code, 0);
+ assert.equal((await run([p.id, "c1", "--reading", "next"])).code, 1);
+ assert.equal((await run([p.id, "c1", "--pick", "0000000000"])).code, 1);
+ assert.equal((await run([p.id, "nope", "--read"])).code, 1);
+ const list = await run([p.id, "--list", "--json"]);
+ assert.equal(list.json().cards[0].readings.length, 1);
+});
+
+test("AN ENGINE WITH NO SEED (Kokoro reports no reading): a reading asked is kept under it, listed as it, and picked back to its key", async () => {
+ const p = await project("kokoro");
+ const m = await manifest(p);
+ m.timeline[0].narration = { text: CARD.narration.text, engine: "kokoro", voice: "af_heart" };
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ const asked = [];
+ const noSeed = async ({ narrations, dir }) => {
+ const recs = new Map();
+ for (const n of narrations) {
+ asked.push(n);
+ const wav = path.join(ROOT, `${n.key}.k.wav`);
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=330:d=1.2", "-ar", "48000", "-ac", "1", wav]);
+ recs.set(n.id, await keepNarration(dir, n, { wav, engine: n.engine, voice: n.voice }, { jobId: "job" }));
+ }
+ return recs;
+ };
+ const go = async (args) => {
+ const lines = [];
+ const code = await cardNarrationCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s), narrate: noSeed });
+ return { code, out: lines.join("\n") };
+ };
+ assert.equal((await go([p.id, "c1", "--read"])).code, 0);
+ assert.equal((await go([p.id, "c1", "--read", "--reading", "next"])).code, 0);
+ assert.equal(asked[1].reading, 1);
+ const readings = await cardReadings(p.dir, "c1");
+ const second = readings.find((x) => x.key === asked[1].key);
+ const r = await go([p.id, "c1", "--pick", second.key]);
+ assert.equal(r.code, 0, r.out);
+ assert.equal((await manifest(p)).timeline[0].narration.reading, 1);
+ assert.equal(narrationsOf(await manifest(p))[0].key, second.key);
+});
diff --git a/umtool/lib/report/cardNarrationCli.mjs b/umtool/lib/report/cardNarrationCli.mjs
@@ -0,0 +1,183 @@
+// `umtool narration` -- A CARD's NARRATION from the CLI (report-to-video/narration.mjs; lane line-rerun, S3 of the
+// Orpheus re-tune plan): its words, its reading and its tuning, and its READINGS -- every voice kept for it beside the
+// build (out/narration/<key>.{wav,json}, narration-store.mjs) -- read again, compared and picked, with no agent. A
+// card's narration is SPOKEN ONLY: no card draws its words (narration.mjs), so an edit changes what is said and the
+// card's length, never what is shown.
+//
+// umtool narration <project> [--list] [--json] every narrated card: its words, reading, tuning, readings
+// umtool narration <project> <card> [--json] one card's
+// umtool narration <project> <card> --read [--text "…"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k]
+// [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--json]
+// ONE READING asked of the editor (its tts op, a job; waits)
+// and kept beside the build -- the card NOT changed
+// umtool narration <project> <card> --pick <key> [--json] the card made that reading: its words, reading, tuning
+// umtool narration <project> <card> [--text "…"] [--reading N] [tuning flags | --tuning-off] [--json] set them
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readFile, readdir, stat } from "node:fs/promises";
+import path from "node:path";
+import { narrationKey, narrationTuningOf, narrationsOf, resolveNarration } from "umtool-report-to-video/narration";
+import { narrationDir, narrationWavPath } from "umtool-report-to-video/narration-store";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { StaleToken, StructureRefused, manifestToken, updateCardNarration } from "./manifest.mjs";
+import { NarrateError, tuningFlags } from "./postNarrationCli.mjs";
+
+export const CARD_NARRATION_USAGE = [
+ "usage: umtool narration <project> [--list] [--json]",
+ " umtool narration <project> <card> [--json]",
+ " umtool narration <project> <card> --read [--text \"…\"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k]",
+ " [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--json]",
+ " umtool narration <project> <card> --pick <key> [--json]",
+ " umtool narration <project> <card> [--text \"…\"] [--reading N] [tuning flags | --tuning-off] [--json]",
+ " A CARD's NARRATION: the words a stock synthetic voice says over a card (spoken only -- no card draws them), its",
+ " READING (0 the first; 1, 2, … the same words read anew) and Orpheus's TUNING (umtool posts narrate --help). Its",
+ " READINGS are the voices kept for it beside the build (out/narration/<key>.wav): each its words, reading, tuning.",
+ " --read: one reading asked of the editor (its tts op, a job; it waits while render mode holds the machine) and",
+ " kept -- the card is NOT changed; --text reads other words, --reading next one past the highest these words were",
+ " read at. --pick <key>: the card made that reading (its words, reading and tuning; nothing synthesized). Without",
+ " --read or --pick: the card's words (--text), reading and tuning set (--tuning-off: none). A verdict on the card's",
+ " words (the narration review) is kept by a pick of another reading of the same words.",
+].join("\n");
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const spacing = (t) => String(t ?? "").replace(/\s+/g, " ").trim();
+
+/** Every reading kept beside the build (its record and its sound there), by card id, each oldest first -- read once. */
+export async function allCardReadings(projectDir) {
+ const dir = narrationDir(path.join(projectDir, "out"));
+ const names = await readdir(dir).catch(() => []);
+ const out = new Map();
+ for (const f of names) {
+ if (!/^[0-9a-f]{64}\.json$/.test(f)) continue;
+ const rec = await readFile(path.join(dir, f), "utf8").then(JSON.parse, () => null);
+ if (!isObj(rec) || typeof rec.id !== "string" || `${rec.key}.json` !== f) continue;
+ if (!(await stat(narrationWavPath(dir, rec.key)).catch(() => null))?.isFile()) continue;
+ out.set(rec.id, [...(out.get(rec.id) ?? []), rec]);
+ }
+ for (const list of out.values()) list.sort((a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? "")));
+ return out;
+}
+
+/** Every reading kept for `cardId` beside the build, oldest first. */
+export async function cardReadings(projectDir, cardId) {
+ return (await allCardReadings(projectDir)).get(cardId) ?? [];
+}
+
+/** The reading a record was asked at (`askedReading`; an engine with no seed reports none), else the one reported. */
+export const readingOfRecord = (r) => (Number.isInteger(r?.askedReading) ? r.askedReading : Number.isInteger(r?.reading) ? r.reading : 0);
+
+/** One past the highest reading `text` was kept at (a record with none: 0), or 0 when it never was. */
+export function nextCardReading(readings, text) {
+ let hi = -1;
+ for (const r of readings) if (spacing(r.text) === spacing(text)) hi = Math.max(hi, readingOfRecord(r));
+ return hi + 1;
+}
+
+/** A reading as a line: its key, words, reading, tuning, length -- and whether the card plays it. */
+const readingLine = (r, current) => ` ${r.key === current ? "▶" : " "} ${r.key.slice(0, 12)} ${Number(r.seconds).toFixed(2)} s reading ${readingOfRecord(r)}${r.askedTuning ? ` ${Object.entries(r.askedTuning).map(([k, v]) => `${k} ${v}`).join(", ")}` : ""} "${spacing(r.text).slice(0, 70)}"`;
+
+/** `umtool narration <project> …` */
+export async function cardNarrationCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), narrate = null } = {}) {
+ const flags = new Map();
+ const words = [];
+ const VALUED = new Set(["--text", "--reading", "--pick", "--temperature", "--top-p", "--top-k", "--min-p", "--repeat-penalty", "--chunk-takes"]);
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (VALUED.has(a)) {
+ flags.set(a, args[i + 1] ?? "");
+ i += 1;
+ } else if (a.startsWith("--")) flags.set(a, true);
+ else words.push(a);
+ }
+ const str = (k) => (flags.has(k) && typeof flags.get(k) === "string" ? flags.get(k) : null);
+ const json = flags.has("--json");
+ const [projectArg, cardId] = words;
+ if (!projectArg || flags.has("--help")) {
+ out(CARD_NARRATION_USAGE);
+ return projectArg ? 0 : 2;
+ }
+ try {
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new NarrateError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new NarrateError(`no project matches "${projectArg}"`);
+ const project = r.project;
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new NarrateError(`${project.id} has no manifest`);
+ const all = narrationsOf(manifest);
+ if (!cardId || flags.has("--list")) {
+ const rows = [];
+ for (const n of all) rows.push({ ...n, readings: await cardReadings(project.dir, n.id) });
+ if (json) out(JSON.stringify({ ok: true, cards: rows }, null, 2));
+ else {
+ out(`${project.id}: ${rows.length} narrated card(s)`);
+ for (const n of rows) out([`${n.id} ${n.engine} · ${n.voice} reading ${n.reading ?? 0}${n.tuning ? ` ${JSON.stringify(n.tuning)}` : ""} "${spacing(n.text).slice(0, 70)}"`, ...n.readings.map((x) => readingLine(x, n.key))].join("\n"));
+ }
+ return 0;
+ }
+ const e = (manifest.timeline ?? []).find((x) => x?.id === cardId);
+ const now = all.find((x) => x.id === cardId);
+ if (!e || !now) throw new NarrateError(`${cardId} is not a card with a narration (umtool narration ${project.id} --list)`);
+ const readings = await cardReadings(project.dir, cardId);
+ const tuned = tuningFlags(str);
+ const write = async (patch) => withEditNotes(project, async () => updateCardNarration(project.dir, cardId, patch, { token: await manifestToken(project.dir) }));
+
+ if (flags.has("--read")) {
+ // ONE READING, the card not changed: its words (--text, else its own), the reading and tuning asked (else its own).
+ const text = str("--text") !== null ? String(str("--text")).trim() : now.text;
+ if (!text) throw new NarrateError("--text needs words");
+ const reading = tuned?.reading === "next" ? nextCardReading(readings, text) : tuned?.reading ?? (now.reading ?? 0);
+ const tuning = tuned?.tuning ? narrationTuningOf({ ...(now.tuning ?? {}), ...tuned.tuning }) : now.tuning ?? null;
+ const ask = resolveNarration({ ...e, narration: { ...e.narration, text, ...(reading > 0 ? { reading } : { reading: undefined }), ...(tuning ? { tuning } : { tuning: undefined }) } }, manifest.render);
+ const n = { id: cardId, ...ask, key: narrationKey(ask) };
+ const run = narrate ?? (await import("umtool-report-to-video/narrate-via-editor")).narrateCut;
+ const recs = await run({ narrations: [n], dir: narrationDir(path.join(project.dir, "out")), emit: (_ev, f) => !json && f?.message && out(f.message) });
+ const rec = recs.get(cardId);
+ if (json) out(JSON.stringify({ ok: true, id: cardId, key: n.key, reading: n.reading ?? 0, tuning: n.tuning ?? null, text: n.text, seconds: rec?.seconds ?? null, plays: n.key === now.key }, null, 2));
+ else out(`${cardId}: reading ${n.reading ?? 0} kept (${n.key.slice(0, 12)}, ${rec?.seconds ?? "?"} s)${n.key === now.key ? " -- the one the card plays" : ` -- the card plays another; pick it: umtool narration ${project.id} ${cardId} --pick ${n.key}`}`);
+ return 0;
+ }
+ if (str("--pick") !== null) {
+ const key = String(str("--pick")).trim();
+ const rec = readings.find((x) => x.key === key || (key.length >= 8 && x.key.startsWith(key)));
+ if (!rec) throw new NarrateError(`${cardId} has no reading ${key} kept (umtool narration ${project.id} ${cardId})`);
+ const patch = { text: rec.text, reading: readingOfRecord(rec) > 0 ? readingOfRecord(rec) : null, tuning: rec.askedTuning ?? null };
+ const want = resolveNarration({ ...e, narration: { ...e.narration, text: patch.text, reading: patch.reading ?? undefined, tuning: patch.tuning ?? undefined } }, manifest.render);
+ if (narrationKey(want) !== rec.key) throw new NarrateError(`${cardId}: reading ${rec.key.slice(0, 12)} was made with another voice or speed than the card's now -- read it again (--read)`);
+ const { result } = await write(patch);
+ // A VERDICT ON THESE WORDS IS KEPT (lane line-rerun ruling): the review keys a verdict by the narration's key,
+ // which a reading moves -- a verdict given on the card as it played, on the same words, moves with the pick.
+ const { readNarrationReview, setNarrationReview } = await import("umtool-report-to-video/narration-review");
+ const row = (await readNarrationReview(project.dir)).rows?.[cardId];
+ const kept = !!row?.verdict && row.key === now.key && spacing(row.text) === spacing(rec.text);
+ if (kept) await setNarrationReview(project.dir, cardId, { verdict: row.verdict, key: rec.key, text: rec.text });
+ if (json) out(JSON.stringify({ ok: true, id: cardId, key: rec.key, narration: result.entry.narration, verdictKept: kept, token: result.token ?? null }, null, 2));
+ else out(`${cardId}: plays reading ${readingOfRecord(rec)} (${rec.key.slice(0, 12)})${kept ? ` -- still ${row.verdict} (the same words)` : ""}`);
+ return 0;
+ }
+ const patch = {};
+ if (str("--text") !== null) patch.text = String(str("--text"));
+ if (tuned?.reading === "next") throw new NarrateError("--reading next goes with --read (a reading is made, then picked)");
+ if (tuned?.reading !== undefined && tuned?.reading !== null) patch.reading = tuned.reading;
+ if (tuned?.tuning) patch.tuning = narrationTuningOf({ ...(e.narration.tuning ?? {}), ...tuned.tuning });
+ if (flags.has("--tuning-off")) patch.tuning = null;
+ if (!Object.keys(patch).length) {
+ if (json) out(JSON.stringify({ ok: true, id: cardId, narration: e.narration, key: now.key, readings }, null, 2));
+ else out([`${cardId} ${now.engine} · ${now.voice} reading ${now.reading ?? 0}${now.tuning ? ` ${JSON.stringify(now.tuning)}` : ""}`, ` "${now.text}"`, ...readings.map((x) => readingLine(x, now.key))].join("\n"));
+ return 0;
+ }
+ const { result } = await write(patch);
+ if (json) out(JSON.stringify({ ok: true, id: cardId, narration: result.entry.narration, token: result.token ?? null }, null, 2));
+ else out(`${cardId}: ${JSON.stringify(result.entry.narration)}`);
+ return 0;
+ } catch (e) {
+ if (e instanceof NarrateError || e instanceof StructureRefused || e instanceof StaleToken) {
+ const msg = e instanceof StructureRefused ? e.errors.join("; ") : e.message;
+ if (json) out(JSON.stringify({ ok: false, error: msg }, null, 2));
+ else err(`umtool narration: ${msg}`);
+ return 1;
+ }
+ throw e;
+ }
+}
diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs
@@ -243,7 +243,7 @@ test("rereadPlan: a thread read's own options kept, the changed author's overrid
assert.equal(plan.skipped[0].id, "p-8");
});
-test("rereadPlan: a single take's own tuning and reading are asked again (lane orpheus-tuning); defaults and thread reads add nothing", () => {
+test("rereadPlan: a single take's own tuning and reading are asked again (lane orpheus-tuning) -- its recorded takes always (lane line-rerun: the settings' default may not be 3); thread reads add nothing", () => {
const made = (o) => ({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...o });
const m = { timeline: [
{ type: "post", id: "p-1", handle: "x", narration: { takes: [{ file: "a.wav", engine: "orpheus", voice: "zac", tuning: made({ temperature: 0.7 }), reading: 2 }], pick: 0 } },
@@ -254,8 +254,8 @@ test("rereadPlan: a single take's own tuning and reading are asked again (lane o
const drift = (id, thread = false) => ({ id, handle: "x", role: "post", reads: "orpheus:zac", want: "orpheus:leah", kind: "tts", thread });
const plan = rereadPlan("p", m, [drift("p-1"), drift("p-2"), drift("p-3"), drift("p-4", true)], ["x"]);
assert.deepEqual(plan.items.map((x) => x.argv.slice(4)), [
- ["--take", "--reading", "2", "--temperature", "0.7"],
- ["--take"],
+ ["--take", "--reading", "2", "--temperature", "0.7", "--chunk-takes", "3"],
+ ["--take", "--chunk-takes", "3"],
["--take", "--speed", "1.2", "--top-k", "40", "--chunk-takes", "5"],
["--take", "--thread"],
]);
diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs
@@ -198,6 +198,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/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -67,8 +67,8 @@ import {
variantsProblems, verdictOfInput,
} from "./knobs.mjs";
import { validateNarration } from "umtool-report-to-video/narration";
-import { postReadText, validatePostItem, validatePostItems } from "umtool-report-to-video/post-item";
-import { threadReadErrors } from "umtool-report-to-video/post-thread";
+import { postReadText, saysShownDraft, shownDraftOf, takeIsEditedRead, validatePostItem, validatePostItems } from "umtool-report-to-video/post-item";
+import { spokenSaysHiddenErrors, threadReadErrors } from "umtool-report-to-video/post-thread";
import { planContext } from "umtool-report-to-video/post-conversation";
import { followKnobs } from "umtool-report-to-video/read-follow";
import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars";
@@ -3410,7 +3410,7 @@ export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine"
* what was approved was that take on those words. Refused in the build's
* words (validatePostItem).
*/
-export function postNarrationIn(m, id, patch) {
+export function postNarrationIn(m, id, patch, { forReading = false } = {}) {
const i = entryIndex(m.timeline, id);
const e = m.timeline[i];
if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
@@ -3426,7 +3426,25 @@ export function postNarrationIn(m, id, patch) {
if (v === null || v === undefined || v === false && (k === "excerpt" || k === "approved" || k === "off")) delete n[k];
else n[k] = typeof v === "number" && k !== "pick" ? round2(v) : typeof v === "string" && k === "script" ? v.trim() : v;
}
+ // THE SCRIPT AS A SPOKEN EDIT (lane line-rerun; ruling 3): saved by the one writer (`forReading`: a single item's
+ // script -- the bench's Save, `posts narrate --script`, a take that carries one), it is marked for reading when it
+ // differs from his words as drafted, so the card's layout follows the shown text; undo restores it with the script.
+ // A spoken edit saying what the item's screens hide is refused here, never kept to be refused at the build.
+ if (forReading && "script" in patch) {
+ const s = typeof n.script === "string" ? n.script.trim() : "";
+ if (s && String(shownDraftOf(e) ?? "").trim() && !saysShownDraft(e, s)) n.forReading = true;
+ else delete n.forReading;
+ if (s && (before?.script ?? "") !== n.script) {
+ const hid = spokenSaysHiddenErrors(e, n.script, "the script");
+ if (hid.length) throw new StructureRefused(hid);
+ }
+ }
if (isObj(patch.addTake)) {
+ // STAMPED WHEN IT IS MADE (review 1, finding 3; the orchestrator's ruling): a take whose words are not the post's
+ // as drafted is a read edited for reading -- while it plays the card follows the shown text, whatever the script
+ // says later (post-item.mjs readEditOf).
+ // (A thread read decides its own when it is made: postThreadRead.mjs, from its post piece's written words.)
+ if (patch.addTake.forReading === undefined && patch.addTake.read?.kind !== "thread" && takeIsEditedRead(e, patch.addTake)) patch.addTake.forReading = true;
n.takes.push(patch.addTake);
if (patch.keepPick !== true) n.pick = n.takes.length - 1;
}
@@ -3542,7 +3560,7 @@ export async function updatePostFx(dir, id, op, { token = null } = {}) {
*/
export async function updatePostNarration(dir, id, patch, { token = null } = {}) {
if (!isObj(patch) || !Object.keys(patch).length) throw new Error("a narration patch is an object of knobs");
- return structural(dir, "post-narration", token, (m) => postNarrationIn(m, id, patch));
+ return structural(dir, "post-narration", token, (m) => postNarrationIn(m, id, patch, { forReading: true }));
}
/**
@@ -4448,6 +4466,33 @@ export async function updateNarration(dir, id, text, { token = null, at = null }
}
/**
+ * A CARD's NARRATION -- its words, its reading, its tuning -- through the manifest (lane line-rerun; `umtool narration
+ * <p> <card>`): `patch` any of `text` (words), `reading` (0 or null: the first), `tuning` (null: none). A structural
+ * write (an undo point), refused in the build's words. The words are spoken only: no card draws them.
+ */
+export async function updateCardNarration(dir, id, patch, { token = null } = {}) {
+ if (!isObj(patch) || !Object.keys(patch).length) throw new Error("a card narration patch is { text?, reading?, tuning? }");
+ for (const k of Object.keys(patch)) if (!["text", "reading", "tuning"].includes(k)) throw new Error(`${k} is not a card narration's (text, reading, tuning)`);
+ return structural(dir, "narration", token, (m) => {
+ const e = m.timeline[entryIndex(m.timeline, id)];
+ if (e.type !== "card" || !e.narration || typeof e.narration !== "object") throw new Error(`${id} is not a card with a narration`);
+ const before = JSON.stringify(e.narration);
+ if (typeof patch.text === "string") e.narration.text = patch.text.trim();
+ if ("reading" in patch) {
+ if (patch.reading === null || patch.reading === 0) delete e.narration.reading;
+ else e.narration.reading = patch.reading;
+ }
+ if ("tuning" in patch) {
+ if (patch.tuning === null || !Object.keys(patch.tuning ?? {}).length) delete e.narration.tuning;
+ else e.narration.tuning = patch.tuning;
+ }
+ const errors = validateNarration({ render: m.render, timeline: [e] });
+ if (errors.length) throw new StructureRefused(errors);
+ return { id, entry: e, changed: before !== JSON.stringify(e.narration) };
+ });
+}
+
+/**
* A drafted field's whole value, written as THE OPERATOR's (release 28, M0):
* what umtool's "Use this" under an alternative (`<task>-draft.json`) runs.
* Checked as the field's own editor checks it; a structural write (snapshot
diff --git a/umtool/lib/report/narration-review.mjs b/umtool/lib/report/narration-review.mjs
@@ -13,6 +13,7 @@ import { stat } from "node:fs/promises";
import { estimatedNarratedCardSeconds, narrationWords } from "umtool-report-to-video/narration";
import { DRAFTS_REVIEW_FILE, readNarrationReview, reviewRows } from "umtool-report-to-video/narration-review";
import { narrationDir, narrationWavPath, readNarrationRecord } from "umtool-report-to-video/narration-store";
+import { allCardReadings, readingOfRecord } from "./cardNarrationCli.mjs";
/**
* @param {string} projectDir
@@ -23,6 +24,8 @@ export async function narrationReviewView(projectDir, manifest) {
const dir = narrationDir(path.join(projectDir, "out"));
const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
const rows = [];
+ // Every card's readings, the store read once for the view (review 1, a nit).
+ const kept = await allCardReadings(projectDir);
for (const r of reviewRows(manifest, review)) {
const at = timeline.findIndex((e) => e?.id === r.id);
const e = timeline[at] ?? {};
@@ -53,6 +56,12 @@ export async function narrationReviewView(projectDir, manifest) {
judgedText: r.row?.text ?? "",
judgedAt: r.row?.at ?? "",
kept: rec ? { seconds: rec.seconds, disclosure: rec.disclosure, mtimeMs: wav ? Math.round(wav.mtimeMs) : 0 } : null,
+ // Its reading and tuning now, and every reading kept for it (lane line-rerun: Read again, Pick).
+ key: r.key,
+ reading: Number.isInteger(e.narration?.reading) ? e.narration.reading : 0,
+ tuning: e.narration?.tuning ?? null,
+ madeWith: rec?.tuning ?? null,
+ readings: (kept.get(r.id) ?? []).map((x) => ({ key: x.key, text: x.text, reading: readingOfRecord(x), tuning: x.askedTuning ?? null, seconds: x.seconds, createdAt: x.createdAt ?? null })),
});
}
const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 };
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 { LEGACY_EDIT_TEXT, excerptSpansOf, legacyReadOf, postItemPlan, postReadText, readEditOf, takeIsEditedRead } 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",
@@ -197,9 +202,13 @@ export async function importPatches(manifest, rows, measure) {
...(typeof t.note === "string" ? { note: t.note } : {}),
// A take composed of parts (a long post, paragraph by paragraph): the row's, else take-<n>.parts.json beside it.
// Each part's ROLE stored as it comes in (post-thread.mjs): the text it reads, its own or inferred.
+ // Its STAMP decided FIRST (review 2, finding 6): an imported read of words edited for reading is his post's,
+ // part by part (Rule B, as a made take's) -- never a role inferred from the edited words.
...(() => {
const parts = normalizeParts(Array.isArray(t.parts) ? t.parts : m.parts);
- return parts ? { parts: withPartRoles(e, parts) } : {};
+ const script = typeof t.script === "string" ? t.script : String(row.script ?? "");
+ const edited = takeIsEditedRead(e, { script, ...(parts ? { parts } : {}) });
+ return { ...(edited ? { forReading: true } : {}), ...(parts ? { parts: edited ? parts : withPartRoles(e, parts) } : {}) };
})(),
});
files.add(t.file);
@@ -274,8 +283,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)"}`,
];
+ // ITS PLAYING TAKE PREDATES THE RULE (post-item.mjs legacyReadOf): its card follows what that take says.
+ if (legacyReadOf(e)) 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 +298,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 = LEGACY_EDIT_TEXT;
+
/** `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 +376,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 +461,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 +507,60 @@ 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 };
}
+/** A piece of a read, as a part's role names it (post-narration.mjs's part roles; `media:` is never synthesized). */
+const TUNED_ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/;
+
+/** 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 && !TUNED_ROLE_RE.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})`);
+ if (m[1] !== "*" && !TUNED_ROLE_RE.test(m[1])) throw new NarrateError(`--tuned ${m[1]}: not a piece of a read (* or post, quoted, parent:<i>, linked:<i>, screen:<id>:<line>)`);
+ 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 +589,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 +640,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, ...(legacyReadOf(e) ? { readEdit: "legacy" } : readEditOf(e) === "reading" ? { readEdit: "reading" } : {}) })) }, 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 +839,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"), events: flags.has("--events"),
});
}
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,213 @@
+// 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("A PLAYING TAKE FROM BEFORE THE RULE: --list (and --json) says which items play a take read from other words with no stamp -- read it again to move it", async () => {
+ const old = (script) => ({ script, pick: 0, takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1, script }] });
+ const p = await project("legacy", [item({ narration: old("Something else entirely.") }), { ...item({ narration: old(shownDraftOf(item())) }), id: "p-2", post: "ferry-x/2" }, { ...item({ narration: { script: "Unread other words." } }), id: "p-3", post: "ferry-x/3" }]);
+ 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.readEdit ?? null), ["legacy", null, null], "an item with no take playing is not flagged");
+});
+
+// ---------------------------------------------------------------------------
+// THE PLAYING TAKE DECIDES (review 1, finding 3; the orchestrator's ruling): a take is stamped `forReading` when it is
+// made from words that are not the post's as drafted, and the card follows the shown text while a stamped take plays --
+// whatever the script says afterwards. `narration.forReading` decides only with no take playing.
+// ---------------------------------------------------------------------------
+
+test("RULING 3 HOLDS when the script is saved back to the post's words while an edited take still plays, when an older edited take is picked again, and after --draft-scripts --force", async () => {
+ const { postNarrationIn } = await import("./manifest.mjs");
+ const { FIXTURES, drawn, singleItem, threadItem } = await import("../../report-to-video/post-reading-pin.fixtures.mjs");
+ void FIXTURES;
+ const drafted = shownDraftOf(singleItem());
+ const edited = "The council met on Tuesday about the new bridge.";
+ const m = { timeline: [singleItem({ parents: [threadItem().parents[0]], thread: { parent: "excerpt" } })] };
+ const base = drawn(m.timeline[0]);
+ // Edited, read, picked.
+ postNarrationIn(m, "p-7003", { script: edited, addTake: { file: "narration/posts/7003/take-2.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 3, script: edited } }, { forReading: true });
+ assert.equal(m.timeline[0].narration.takes[1].forReading, true, "the take is stamped when it is made");
+ assert.deepEqual(drawn(m.timeline[0]), base);
+ // The script saved back to the post's words, no read: the edited take still plays -- the card as before.
+ postNarrationIn(m, "p-7003", { script: drafted }, { forReading: true });
+ assert.deepEqual(drawn(m.timeline[0]), base);
+ // A read of the post's words (no stamp), picked; then the older edited take picked again.
+ postNarrationIn(m, "p-7003", { addTake: { file: "narration/posts/7003/take-3.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: drafted } }, { forReading: true });
+ assert.equal("forReading" in m.timeline[0].narration.takes[2], false, "a take of the post's words is not stamped");
+ assert.deepEqual(drawn(m.timeline[0]), base);
+ postNarrationIn(m, "p-7003", { pick: 1 }, { forReading: true });
+ assert.deepEqual(drawn(m.timeline[0]), base);
+ // --all --draft-scripts --force (the plural writer) while the edited take plays.
+ postNarrationIn(m, "p-7003", { script: drafted });
+ assert.deepEqual(drawn(m.timeline[0]), base);
+});
+
+// ---------------------------------------------------------------------------
+// AN UNEDITED READ IS NOT "EDITED" (review 2, finding 1): a paragraph over 60 words read in several parts, the parts
+// saying a lexicon word, an anonymous handle said as its shown name -- none is an edit for reading: no stamp, no notice.
+// ---------------------------------------------------------------------------
+
+test("AN UNEDITED READ in several parts of one long paragraph is neither stamped nor flagged (probe 5)", async () => {
+ const { postNarrationIn } = await import("./manifest.mjs");
+ const { singleItem } = await import("../../report-to-video/post-reading-pin.fixtures.mjs");
+ const { draftScript, scriptParts } = await import("umtool-report-to-video/post-narration");
+ const { legacyReadOf, readEditOf } = await import("umtool-report-to-video/post-item");
+ const long = Array.from({ length: 9 }, (_, i) => `The council met on day ${i + 1} about the new bridge and nobody came.`).join(" ");
+ const e = singleItem({ text: long });
+ const d = draftScript(long).script;
+ let t = 0;
+ const parts = scriptParts(d).map((p) => {
+ const q = { n: p.n, para: p.para, text: p.text, start: t, seconds: 5 };
+ t += 5.25;
+ return q;
+ });
+ assert.ok(parts.length > 1 && d.split("\n\n").length === 1, "one paragraph, read in several parts");
+ const take = { file: "narration/posts/7003/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: t, script: d, parts };
+ // A take from before the rule: no notice.
+ assert.equal(legacyReadOf({ ...e, narration: { script: d, pick: 0, takes: [take] } }), false);
+ // A take made now: no stamp.
+ const m = { timeline: [{ ...e, narration: { script: d, takes: [] } }] };
+ postNarrationIn(m, e.id, { addTake: { ...take } });
+ assert.equal("forReading" in m.timeline[0].narration.takes[0], false);
+ assert.equal(readEditOf(m.timeline[0]), null);
+ // Its parts' words without its script (an imported take): rebuilt into the paragraph, still not an edit.
+ const { script: _s, ...noScript } = take;
+ void _s;
+ assert.equal(legacyReadOf({ ...e, narration: { script: d, pick: 0, takes: [noScript] } }), false);
+});
+
+test("A LEXICON WORD or AN ANONYMOUS HANDLE said another way is not an edit: a single read's written script decides; a thread read's post piece's written words", async () => {
+ const { postNarrationIn } = await import("./manifest.mjs");
+ const { singleItem, threadItem } = await import("../../report-to-video/post-reading-pin.fixtures.mjs");
+ const { legacyReadOf } = await import("umtool-report-to-video/post-item");
+ const { postWrittenEdited } = await import("./postThreadRead.mjs");
+ const e = singleItem();
+ const d = shownDraftOf(e);
+ // Lexicon: its parts say "the B R I D G E" where the post says "the bridge"; its script is the post's words.
+ const said = d.replace("bridge", "B R I D G E");
+ const lex = { file: "narration/posts/7003/take-2.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: d, parts: said.split("\n\n").map((text, i) => ({ n: i + 1, para: i, text, start: i * 3, seconds: 3 })), lexicon: [{ word: "bridge", say: "B R I D G E" }] };
+ // An anonymous handle said as its shown name (`said`), the script the post's words.
+ const anon = { file: "narration/posts/7003/take-3.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: d, said: d.replace("council", "Anon 1") };
+ for (const t of [lex, anon]) {
+ const m = { timeline: [{ ...e, narration: { script: d, takes: [] } }] };
+ postNarrationIn(m, e.id, { addTake: { ...t } });
+ assert.equal("forReading" in m.timeline[0].narration.takes[0], false, t.file);
+ assert.equal(legacyReadOf({ ...e, narration: { script: d, pick: 0, takes: [t] } }), false, t.file);
+ }
+ // A thread read: stamped from its post piece's WRITTEN words, not its spoken ones.
+ const th = threadItem();
+ assert.equal(postWrittenEdited(th, { pieces: [{ role: "post", written: shownDraftOf(th), text: "the B R I D G E said" }] }), false);
+ assert.equal(postWrittenEdited(th, { pieces: [{ role: "post", written: "Other words entirely.", text: "Other words entirely." }] }), true);
+ // An unstamped thread read whose parts say a lexicon word, its script the post's: no notice.
+ assert.equal(legacyReadOf(th), false);
+});
+
+test("AN IMPORTED READ of words edited for reading is stamped FIRST and its parts are his post's, never a role inferred from the edited words (review 2, finding 6)", async () => {
+ const { importPatches } = await import("./postNarrationCli.mjs");
+ const { singleItem, threadItem } = await import("../../report-to-video/post-reading-pin.fixtures.mjs");
+ const e = singleItem({ parents: [threadItem().parents[0]] });
+ const parentWords = "Does anyone know why the tolls on the old crossing keep rising?";
+ const script = `The council met on Tuesday about the new bridge.\n\n${parentWords}`;
+ const rows = [{ id: "7003", entry: e.id, script, takes: [{ file: "narration/posts/7003/take-5.orpheus-zac.wav", script, seconds: 6, parts: script.split("\n\n").map((text, i) => ({ n: i + 1, para: i, text, start: i * 3, seconds: 3 })) }] }];
+ const measure = async () => ({ seconds: 6, at: "2026-11-17T00:00:00.000Z", parts: null });
+ const { patches } = await importPatches({ timeline: [e] }, rows, measure);
+ const t = patches.find((p) => p.patch.addTake)?.patch.addTake;
+ assert.equal(t.forReading, true);
+ assert.ok(t.parts.every((p) => p.role === undefined), JSON.stringify(t.parts));
+});
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),",
@@ -55,11 +57,16 @@ export const SCREEN_USAGE = [
" set keys: kind= title=|off media= at=<a>,<b>|off unread= ref=|off read=all|none|<n>,… read.<n>=\"excerpt\"|on|off",
" line.add=\"who: words\" line.<n>=off line.<n>.who=|off line.<n>.side=left|right|auto line.<n>.text=",
" line.<n>.time=|off line.<n>.redact=on|off take.<n>=<take n>|off (the recording read in line n's place)",
+ " said.<n>=\"…\"|off (what the voice SAYS for line n -- an acronym spelled out, a typo said right; never drawn;",
+ " `off` or empty clears it, so the word \"off\" alone cannot be said: say it as \"Off.\"; line.<n>.redact=on drops it)",
" check: the transcription read against the screenshot (by you, now); --undo takes it back. A screen not checked is a",
" lint WARNING. An e-mail address, a phone number, an order or reference number in a line is masked whatever you do.",
" 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",
@@ -178,7 +185,15 @@ export function applyPairs(screen, pairs, { takeId = null } = {}) {
else if (!SCREEN_SIDES.includes(v)) fail(`${key}= takes left, right or auto`);
else l.side = v;
} else if (f === "redact") {
- if (v === "on") l.redact = true;
+ if (v === "on") {
+ l.redact = true;
+ // A redacted line is never read: its "said as" goes with it (review 1, finding 7).
+ const n = Number(m[1]);
+ if (isObj(sc.saidAs) && sc.saidAs[String(n)] !== undefined) {
+ delete sc.saidAs[String(n)];
+ if (!Object.keys(sc.saidAs).length) delete sc.saidAs;
+ }
+ }
else if (v === "off") delete l.redact;
else fail(`${key}= takes on or off`);
} else if (f === "text") l.text = v;
@@ -196,6 +211,15 @@ export function applyPairs(screen, pairs, { takeId = null } = {}) {
}
if (Object.keys(lt).length) sc.lineTakes = lt;
else delete sc.lineTakes;
+ } else if ((m = /^said\.(\d{1,2})$/.exec(key))) {
+ // What line n is SAID AS (saidAs; never drawn -- the card shows the line as written); off: its own words.
+ const n = Number(m[1]);
+ lineAt(n);
+ const sa = isObj(sc.saidAs) ? { ...sc.saidAs } : {};
+ if (off) delete sa[String(n)];
+ else sa[String(n)] = v;
+ if (Object.keys(sa).length) sc.saidAs = sa;
+ else delete sc.saidAs;
} else fail(`${key} is not a screen's knob (posts screen --help)`);
}
// Lines removed: the read's line numbers follow them (a dropped line's read goes too) -- the bench's rule too.
@@ -220,7 +244,8 @@ export function screenListing(e, sc) {
const ex = r && (r.cutBefore || r.cutAfter) ? ` [reads: "${str(l.text).slice(r.start, r.end)}"]` : "";
const recs = recordings.find((L) => L.screen === sc.id && L.n === n);
const rec = recs ? ` [recorded: ${recs.takes.map((x) => `take ${x.n}${x.chosen ? " (chosen)" : ""}${x.current ? "" : " (line changed since)"}`).join(", ")}]` : "";
- return ` ${mark} ${String(n).padStart(2)} ${(l?.side ? `[${l.side}] ` : "") + (l?.who ? `${l.who}: ` : "- ")}${l?.redact ? "(redacted)" : str(l?.text)}${l?.time ? ` | ${l.time}` : ""}${ex}${rec}`;
+ const as = isObj(sc.saidAs) && typeof sc.saidAs[String(n)] === "string" ? ` [said as: "${sc.saidAs[String(n)]}"]` : "";
+ return ` ${mark} ${String(n).padStart(2)} ${(l?.side ? `[${l.side}] ` : "") + (l?.who ? `${l.who}: ` : "- ")}${l?.redact ? "(redacted)" : str(l?.text)}${l?.time ? ` | ${l.time}` : ""}${ex}${as}${rec}`;
});
return [head, ...rows];
}
@@ -353,7 +378,9 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js
} });
// Words changed: what was checked is not what is there now.
if (JSON.stringify(next.lines) !== JSON.stringify(sc.lines)) delete next.checked;
- return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}`);
+ // A line redacted drops its "said as": said in the answer.
+ const dropped = Object.keys(isObj(sc.saidAs) ? sc.saidAs : {}).filter((k) => !(isObj(next.saidAs) && k in next.saidAs) && next.lines?.[Number(k)]?.redact === true);
+ return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}${dropped.length ? ` (line ${dropped.join(", ")} redacted: its said-as dropped -- a redacted line is never read)` : ""}`);
}
if (verb === "rm") {
const sc = byId(words[0]);
@@ -369,13 +396,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"), events: flags.has("--events"),
});
}
if (verb === "record") {
@@ -445,6 +475,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
@@ -59,12 +59,13 @@ import path from "node:path";
import { promisify } from "node:util";
import { POST_PART_GAP, draftScript, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, scriptParts, takeFileOf, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
import { chosenLineTakes, chronoPieces, lineTakesOf } from "umtool-report-to-video/post-thread";
-import { cardText, parentsOf } from "umtool-report-to-video/post-item";
+import { cardText, parentsOf, saysShownDraft, shownDraftOf } from "umtool-report-to-video/post-item";
import { planContext } from "umtool-report-to-video/post-conversation";
import { spokenRead, termsFor } from "umtool-report-to-video/post-redact";
import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say";
import { SCREEN_LINE_GAP, parseScreenRole, screenWho, screensOf, shapeSpans } from "umtool-report-to-video/post-screens";
import { readManifest } from "../projects/report.mjs";
+import { ORPHEUS_DEFAULT_TAKES, TTS_TUNING_FIELDS, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
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,45 @@ 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 Orpheus's defaults left out, in the fields' order; null when none is left. `takes` equal to the code's
+ * default (3) is left out too (review 1, a nit): `--chunk-takes 3` keys as an untuned part does -- an untuned part's key
+ * never held the settings' takes either.
+ */
+export function tuningOf(tuning) {
+ const n = normalizeTtsTuning(tuning, { takes: ORPHEUS_DEFAULT_TAKES });
+ 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 +203,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;
@@ -231,8 +268,10 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i
}
const sw = screenWho(p.who, e, names);
const handle = sw.self ? str(e.handle) : sw.handle;
+ // `written`: the line as SHOWN (its identity: a take is this line's while it said these); what is SAID is its
+ // "said as" (post-screens.mjs saidAs) when it has one.
const written = draftScript(p.text).script;
- const said = spokenRead(written, e, red, { voice: slurVoice });
+ const said = spokenRead(p.spoken ? draftScript(p.spoken).script : written, e, red, { voice: slurVoice });
if (!norm(said.text)) {
skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" });
continue;
@@ -292,6 +331,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 {
@@ -400,12 +452,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,
@@ -422,7 +475,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;
});
@@ -430,7 +483,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 }),
@@ -443,6 +499,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 } : {}),
};
}
@@ -458,8 +515,17 @@ export function upToDate(e, plan) {
if (JSON.stringify(Object.entries(lines).sort()) !== JSON.stringify(Object.entries(had).sort())) return false;
// A take whose parts say their voices: each piece in the same engine and voice, at the same speed.
const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : [];
- if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number");
- return voiceSig(parts, t.engine ?? "orpheus") === voiceSig(plan.pieces, plan.engine);
+ if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number" || p.reading || p.tuning);
+ if (voiceSig(parts, t.engine ?? "orpheus") !== voiceSig(plan.pieces, plan.engine)) return false;
+ // EACH PIECE's READING AND TUNING (review 1, finding 2): per piece, never through the voices' set -- two lines of one
+ // voice at readings 1 and 0 are not the same read as 0 and 1.
+ for (const pc of plan.pieces) {
+ if (pc.take) continue;
+ const mine = parts.filter((p) => p.role === pc.role && !p.take);
+ if (mine.length && mine.some((p) => tuneSig(p) !== tuneSig(pc))) return false;
+ if (!mine.length && (pc.reading || pc.tuning)) return false;
+ }
+ return true;
}
const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile();
@@ -483,7 +549,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`);
@@ -508,8 +574,19 @@ 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;
+ // A READING OR TUNING ASKED FOR A PIECE (review 1, finding 2): of a piece the read has, synthesized -- a piece read
+ // from a take (a recording, his line from --post-take, a line's chosen or re-attached take) is never "read again".
+ for (const role of Object.keys(tuned ?? {})) {
+ if (role === "*") {
+ if (!plan.pieces.some((pc) => !pc.take)) throw new ThreadReadError(`${e.id}: every piece of this read is a take (a recording): there is nothing synthesized to read again -- record it again`);
+ continue;
+ }
+ const pc = plan.pieces.find((x) => x.role === role);
+ if (!pc) throw new ThreadReadError(`${e.id}: this read has no piece ${role} (its pieces: ${plan.pieces.map((x) => x.role).join(", ")})`);
+ if (pc.take) throw new ThreadReadError(`${e.id}: ${role} is read from take ${pc.take.n} (${pc.take.file}), not synthesized -- to read it again, record it again, or choose "synthesized" for it`);
+ }
const parts = readParts(plan);
const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/"));
const wavOf = (p) => (p.take ? path.join(project.dir, ...p.file.split("/")) : path.join(cacheDir, `${p.key}.wav`));
@@ -574,7 +651,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`);
@@ -620,9 +697,13 @@ 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 }),
+ // STAMPED FOR READING when his post piece was WRITTEN as other words than the post's as drafted (review 2,
+ // finding 1: never judged from its parts, which hold the words as spoken -- a lexicon word is not an edit).
+ ...(postWrittenEdited(e, plan) ? { forReading: true } : {}),
};
- 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);
@@ -632,6 +713,13 @@ export async function threadTake(project, e, opts = {}) {
return { ...base, upToDate: false, fresh, jobs, lane, take, result, editNotes };
}
+/** Whether a thread read's post piece was written as other words than the post's as drafted (its stamp). */
+export function postWrittenEdited(e, plan) {
+ const pc = plan.pieces.find((x) => x.role === "post");
+ if (!pc) return false;
+ return !!String(shownDraftOf(e) ?? "").trim() && !saysShownDraft(e, pc.written);
+}
+
/** The guard on the item as it is now (postThreadCli.mjs readListing): what the card would refuse, and its warnings. */
async function guardOf(project, id) {
const { readListing } = await import("./postThreadCli.mjs");
@@ -645,18 +733,25 @@ async function guardOf(project, id) {
/** `umtool posts narrate <p> <item> --take --thread …` (postNarrationCli.mjs routes it here). */
export async function threadCommand(project, e, o) {
- const { json = false, out = (s) => console.log(s) } = o;
- const say = (s) => !json && out(s);
+ const { json = false, events = false, out = (s) => console.log(s) } = o;
+ const say = (s) => !json && !events && out(s);
let r;
try {
r = await threadTake(project, e, { ...o, signals: true, emit: (_ev, f) => f?.message && say(f.message) });
} catch (err) {
- if (json && err instanceof ThreadReadError) {
- out(JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2));
+ if ((json || events) && err instanceof ThreadReadError) {
+ out(events ? JSON.stringify({ ev: "result", ok: false, id: e.id, error: err.message }) : JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2));
return 1;
}
throw err;
}
+ // --events (the bench's Read again, review 1 finding 2): ONE line, the take MADE (its file and number) or none, and
+ // why -- the bench plays and names only the take this job made, never the list's last.
+ if (events) {
+ const n = r.take ? (r.result?.narration?.takes ?? []).findIndex((t) => t?.file === r.take.file) + 1 : null;
+ out(JSON.stringify({ ev: "result", ok: true, id: e.id, upToDate: !!r.upToDate, dryRun: !!r.dryRun, take: r.take ? { file: r.take.file, n, parts: (r.take.parts ?? []).map((p) => ({ role: p.role ?? null, file: p.file ?? null, reading: p.reading ?? 0 })) } : null, picked: r.take ? r.result?.narration?.pick === n - 1 : false, ...(r.upToDate ? { why: "the playing take already reads this, in these voices, at these readings" } : {}) }));
+ return 0;
+ }
const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, ...(p.take ? { take: p.take } : {}), ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.character ? { character: p.character } : {}), words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) }));
const guard = r.take ? await guardOf(project, e.id) : null;
// RECORDINGS OF ITS LINES NOBODY CHOSE (screenLine takes): said, never read in -- the operator chooses.
@@ -684,7 +779,7 @@ export async function threadCommand(project, e, o) {
return 0;
}
if (r.dryRun) return 0;
- out(` ${r.take.file} ${r.take.seconds} s, ${r.fresh} part(s) synthesized${r.jobs.length ? ` (editor jobs ${r.jobs.join(", ")})` : ""}, picked`);
+ out(` ${r.take.file} ${r.take.seconds} s, ${r.fresh} part(s) synthesized${r.jobs.length ? ` (editor jobs ${r.jobs.join(", ")})` : ""}, ${o.keepPick ? "not picked (--pick to play it)" : "picked"}`);
if (r.result.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`);
if (guard?.errors?.length) out(` the card would REFUSE it:\n${guard.errors.map((x) => ` ${x}`).join("\n")}\n (umtool posts roles ${project.id} ${e.id})`);
for (const w of guard?.warnings ?? []) out(` warning: ${w}`);
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/readTuning.mjs b/umtool/lib/report/readTuning.mjs
@@ -3,7 +3,7 @@
// take's own --speed. The ranges and the defaults are the editor's (yt-dlp-transcript-common/lib/ttsTuning.mjs).
//
// Plain ESM, pure.
-import { ORPHEUS_DEFAULT_TAKES, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
/** The flags that make a read's tuning, and the tuning field each sets. */
export const TUNING_FLAGS = Object.freeze({
@@ -11,14 +11,15 @@ export const TUNING_FLAGS = Object.freeze({
});
/**
- * The flags that ask a take's tuning and reading again: `--reading N` when it was not the first reading, and a flag
- * for each tuning value that is not Orpheus's default (the take records every value; `takes` against the settings'
- * default). `[]` for a take made with the defaults, or one that records neither (another engine, an older take).
+ * The flags that ask a take's tuning and reading again: `--reading N` when it was not the first reading, a flag for
+ * each sampler value that is not Orpheus's default, and the takes it recorded ALWAYS (`--chunk-takes`: the settings'
+ * default may differ from the code's 3, and the editor drops a value equal to its settings' own -- the same key).
+ * `[]` for a take that records neither (another engine, an older take).
*/
export function tuningArgvOf(take) {
const a = [];
if (Number.isInteger(take?.reading) && take.reading > 0) a.push("--reading", String(take.reading));
- const off = normalizeTtsTuning(take?.tuning, { takes: ORPHEUS_DEFAULT_TAKES });
+ const off = normalizeTtsTuning(take?.tuning);
for (const [flag, field] of Object.entries(TUNING_FLAGS)) if (off[field] !== undefined) a.push(flag, String(off[field]));
return a;
}
diff --git a/umtool/lib/report/readTuning.test.mjs b/umtool/lib/report/readTuning.test.mjs
@@ -0,0 +1,28 @@
+// readTuning.mjs: the flags that ask a take's tuning and reading again (lane line-rerun: its recorded takes always).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { tuningArgvOf } from "./readTuning.mjs";
+import { nextReadingOf } from "umtool-report-to-video/post-narration";
+
+const made = (o) => ({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...o });
+
+test("tuningArgvOf: the takes a take recorded are asked again even when they are the code's 3 (the settings' default may differ); a sampler default is not", () => {
+ assert.deepEqual(tuningArgvOf({ tuning: made({}), reading: 0 }), ["--chunk-takes", "3"]);
+ assert.deepEqual(tuningArgvOf({ tuning: made({ takes: 4, top_p: 0.9 }), reading: 2 }), ["--reading", "2", "--top-p", "0.9", "--chunk-takes", "4"]);
+ assert.deepEqual(tuningArgvOf({ engine: "kokoro" }), []);
+});
+
+test("nextReadingOf: one past the highest reading of THESE words among the synthesized takes; new words read first (0)", () => {
+ const takes = [
+ { file: "a", script: "One line.", reading: 0 },
+ { file: "b", script: "One line.", reading: 2 },
+ { file: "c", script: "One line." },
+ { file: "d", script: "Other words.", reading: 7 },
+ { file: "e", engine: "recorded", script: "One line." },
+ { file: "f", script: "One line.", reading: 9, read: { kind: "thread" } },
+ ];
+ assert.equal(nextReadingOf(takes, "One line."), 3);
+ assert.equal(nextReadingOf(takes, "Other words."), 8);
+ assert.equal(nextReadingOf(takes, "Never read."), 0);
+ assert.equal(nextReadingOf([], "x"), 0);
+});
diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs
@@ -49,6 +49,19 @@ export function renderModeFile(env = process.env) {
* @param {{ url: string, token: string, fetch?: typeof fetch }} cfg
* @returns {import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderModeLanes | null}
*/
+/**
+ * WHILE RENDER MODE GIVES THE MACHINE TO A RENDER (lane line-rerun): the sentence a read pressed now says in place of
+ * "running" -- its synthesis waits at the heavy slot's door until the render ends -- or null when render mode is off.
+ */
+export function renderWaitSentence(env = process.env, { file = renderModeFile(env) } = {}) {
+ try {
+ const s = readRenderPriority(file);
+ return s.held && s.state ? `waiting for the render (${describeRenderPriority(s.state)}): render mode gives it the machine, and this read is made when it ends` : null;
+ } catch {
+ return null;
+ }
+}
+
export function editorLanes(cfg) {
if (!cfg?.token) return null;
const ask = async (route, body) => {
diff --git a/umtool/lib/report/screenLineRecord.mjs b/umtool/lib/report/screenLineRecord.mjs
@@ -26,7 +26,7 @@ import { characterOf, projectCharactersOf } from "umtool-report-to-video/cast";
import { draftScript, isNarrated, pickedTake, postIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
import { spokenRead, termsFor } from "umtool-report-to-video/post-redact";
import { handleKey } from "umtool-report-to-video/post-say";
-import { parseScreenRole, screenLineSaid, screenOf, screenReadLines, screenWho, shapeSpans } from "umtool-report-to-video/post-screens";
+import { parseScreenRole, screenLineSaid, screenLineSpoken, screenOf, screenReadLines, screenWho, shapeSpans } from "umtool-report-to-video/post-screens";
import { readManifest } from "../projects/report.mjs";
const str = (v) => (typeof v === "string" ? v : "");
@@ -58,10 +58,12 @@ export function lineToRecord(e, role, { red = null, names = {} } = {}) {
if (l.redact === true) throw new LineRecordError(`line ${p.n} of screen ${p.id} is redacted: it is never read`);
if (!screenReadLines(sc).some((r) => r.n === p.n)) throw new LineRecordError(`line ${p.n} of screen ${p.id} is not read by the screen: tick it first (umtool posts screen <p> ${e.id} set ${p.id} read.${p.n}=on)`);
const written = draftScript(screenLineSaid(sc, p.n)).script;
+ // What is SAID: its "said as" (post-screens.mjs saidAs) when it has one -- the prompt you read is what the voice says.
+ const say = draftScript(screenLineSpoken(sc, p.n)).script || written;
// A beep needs the slur's time in the read; a joined read is not word-timed as it is made (postThreadRead.mjs): skipped.
const voice = red?.slurs?.voice === "beep" ? "skip" : undefined;
- const script = str(spokenRead(written, e, red, { voice }).text).replace(/\s+/g, " ").trim();
- const prompt = str(spokenRead(written, e, red ? { ...red, say: [] } : red, { voice }).text).replace(/\s+/g, " ").trim();
+ const script = str(spokenRead(say, e, red, { voice }).text).replace(/\s+/g, " ").trim();
+ const prompt = str(spokenRead(say, e, red ? { ...red, say: [] } : red, { voice }).text).replace(/\s+/g, " ").trim();
if (!script) throw new LineRecordError(`line ${p.n} of screen ${p.id} has nothing left to say (all of it masked or redacted)`);
const sw = screenWho(l.who, e, names);
return { role, screen: p.id, n: p.n, written, script, prompt, speaker: str(l.who), handle: sw.self ? str(e.handle).replace(/^@/, "") || null : sw.handle, self: sw.self };
diff --git a/umtool/lib/report/screenSaidAs.test.mjs b/umtool/lib/report/screenSaidAs.test.mjs
@@ -0,0 +1,93 @@
+// A SCREEN LINE's "SAID AS" (lane line-rerun; operator ruling 3, 15 Nov 2026: every edit is for READING only): what the
+// voice says for a read line (`screens[j].saidAs`), never what the card draws, never the line's identity.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { saidAsOf, screenLineSaid, screenLineSpoken, screenReadLines, screenRows, validateScreens, withoutLines } from "umtool-report-to-video/post-screens";
+import { screenLineChanged } from "umtool-report-to-video/post-thread";
+import { validatePostItem } from "umtool-report-to-video/post-item";
+import { draftScript } from "umtool-report-to-video/post-narration";
+import { applyPairs } from "./postScreensCli.mjs";
+import { threadReadPlan } from "./postThreadRead.mjs";
+import { lineToRecord } from "./screenLineRecord.mjs";
+import { FIXTURES, PINNED_SHAS, drawn } from "../../report-to-video/post-reading-pin.fixtures.mjs";
+
+const NO_RED = { terms: [], markup: {}, slurs: null };
+const DM = {
+ id: "s1", media: 0, kind: "dm", read: "all", lines: [
+ { who: "rivertalk", text: "Did the BRT plan pass?" },
+ { who: "bridgefan", text: "Ask the clerk, rm 4." },
+ { who: "rivertalk", text: "Thanks." },
+ ],
+};
+const IMG = { src: "posts-media/bridge-x/7003/7003_1.png", kind: "image", width: 900, height: 1400 };
+const item = (sc) => ({ type: "post", id: "p-1", post: "bridge-x/1", platform: "x", handle: "bridgefan", author: "Bridge Fan", date: "2026-10-02T10:00:00.000Z", text: "Here it is.", media: [IMG], screens: [sc] });
+
+test("saidAs: what the voice says, never what is shown -- shown, screenLineSaid, the drawn rows and the read runs identical with and without it", () => {
+ const as = { ...DM, saidAs: { 0: "Did the B R T plan pass?", 1: "Ask the clerk, room four." } };
+ assert.equal(saidAsOf(as, 0), "Did the B R T plan pass?");
+ assert.equal(saidAsOf(as, 2), null);
+ for (const n of [0, 1, 2]) assert.equal(screenLineSaid(as, n), screenLineSaid(DM, n));
+ assert.equal(screenLineSpoken(as, 0), "Did the B R T plan pass?");
+ assert.equal(screenLineSpoken(as, 2), screenLineSaid(DM, 2));
+ assert.deepEqual(screenRows(as), screenRows(DM));
+ assert.deepEqual(screenReadLines(as), screenReadLines(DM));
+});
+
+test("saidAs: a take of the line as shown is still the line's when only its said-as changes (screenLineChanged reads the shown words)", () => {
+ const parts = [0, 1, 2].map((n) => ({ n: n + 1, para: (n + 1) * 100, text: screenLineSaid(DM, n), role: `screen:s1:${n}`, line: draftScript(screenLineSaid(DM, n)).script, speaker: DM.lines[n].who, start: n * 2, seconds: 1.5 }));
+ const narrated = (sc) => ({ ...item(sc), narration: { script: "Here it is.", pick: 0, takes: [{ file: "narration/posts/1/take-1.orpheus-thread.wav", seconds: 6, script: "x", parts, read: { kind: "thread" } }] } });
+ const before = narrated(DM);
+ const after = narrated({ ...DM, saidAs: { 0: "Did the B R T plan pass?" } });
+ for (const n of [0, 1, 2]) assert.equal(screenLineChanged(after, `screen:s1:${n}`), screenLineChanged(before, `screen:s1:${n}`));
+ assert.equal(screenLineChanged(after, "screen:s1:0"), false);
+});
+
+test("saidAs: refused for a line it does not have, a redacted line, no words, or a shape the card would mask; a line removed takes its said-as with it", () => {
+ const bad = (saidAs) => validateScreens(item({ ...DM, saidAs }));
+ assert.deepEqual(bad({ 0: "Did the B R T plan pass?" }), []);
+ assert.ok(bad({ 7: "x" }).some((m) => /has no line 7/.test(m)));
+ assert.ok(validateScreens(item({ ...DM, lines: [...DM.lines.slice(0, 2), { text: "secret", redact: true }], saidAs: { 2: "secret" } })).some((m) => /redacted/.test(m)));
+ assert.ok(bad({ 0: " " }).some((m) => /must be words/.test(m)));
+ assert.ok(bad({ 1: "write to clerk@example.org" }).some((m) => /an e-mail address the card would mask/.test(m)));
+ assert.ok(bad({ 1: "call 5551234567" }).some((m) => /a number the card would mask/.test(m)));
+ assert.deepEqual(withoutLines({ ...DM, saidAs: { 0: "a", 2: "c" } }, [1]).saidAs, { 0: "a", 1: "c" });
+ assert.equal("saidAs" in withoutLines({ ...DM, saidAs: { 1: "b" } }, [1]), false);
+});
+
+test("saidAs: a said-as that says what another line masks is refused by the item's validator", () => {
+ const sc = { ...DM, lines: [...DM.lines, { who: "rivertalk", text: "my number is 555 123 4567" }] };
+ const hit = validatePostItem({ ...item(sc), screens: [{ ...sc, saidAs: { 0: "it is 5551234567 then" } }] });
+ assert.ok(hit.some((m) => /a number/.test(m)), hit.join("\n"));
+});
+
+test("said.<n>= (posts screen set): sets and clears a line's said-as", () => {
+ const sc = applyPairs(DM, ['said.0="Did the B R T plan pass?"']);
+ assert.deepEqual(sc.saidAs, { 0: "Did the B R T plan pass?" });
+ assert.equal("saidAs" in applyPairs(sc, ["said.0=off"]), false);
+ assert.throws(() => applyPairs(DM, ["said.9=x"]), /line 9/);
+});
+
+test("saidAs: the thread read SAYS it (a part's text) and keeps the line as shown (`line`, the identity); the record prompt says it too", () => {
+ const e = { ...item({ ...DM, saidAs: { 0: "Did the B R T plan pass?" } }), narration: { script: "Here it is." } };
+ const plan = threadReadPlan({ timeline: [e], render: {} }, e, { red: NO_RED, map: {}, cast: {}, item: null, names: {} });
+ const p0 = plan.pieces.find((p) => p.role === "screen:s1:0");
+ assert.match(p0.text, /B R T/);
+ assert.doesNotMatch(p0.line, /B R T/);
+ const r = lineToRecord(e, "screen:s1:0", { red: NO_RED, names: {} });
+ assert.match(r.prompt, /B R T/);
+ assert.doesNotMatch(r.written, /B R T/);
+});
+
+test("THE READING PIN with a said-as: a thread item's card draws as before", () => {
+ const e = structuredClone(FIXTURES.thread);
+ e.screens[0].saidAs = { 0: "Are the tolls going up again, yes or no?" };
+ assert.deepEqual(drawn(e), PINNED_SHAS.thread);
+});
+
+test("A LINE REDACTED drops its said-as (review 1, finding 7): line.<n>.redact=on is never refused for a said-as it had", () => {
+ const sc = applyPairs({ ...DM, saidAs: { 0: "Did the B R T plan pass?", 1: "Ask the clerk, room four." } }, ["line.1.redact=on"]);
+ assert.equal(sc.lines[1].redact, true);
+ assert.deepEqual(sc.saidAs, { 0: "Did the B R T plan pass?" });
+ assert.deepEqual(validateScreens(item(sc)), []);
+ assert.equal("saidAs" in applyPairs({ ...DM, saidAs: { 1: "x" } }, ["line.1.redact=on"]), false);
+});
diff --git a/umtool/lib/report/threadTuned.test.mjs b/umtool/lib/report/threadTuned.test.mjs
@@ -0,0 +1,139 @@
+// 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 { ThreadReadError, nextPartReading, partKey, threadReadPlan, threadTake, tuneSig, upToDate } 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({ "multi:--tuned": ["bogus=reading:2"] })), /not a piece of a read/);
+ const ld = flags({ "--for": "linked:12", "--reading": "1" });
+ assert.throws(() => threadTunedOf(tuningFlags(ld.str), ld), /--for names one piece/, "a part's role names one digit for linked");
+ assert.equal(tuneSig({ tuning: { takes: 3, temperature: 0.7 } }), '|t{"temperature":0.7}', "takes 3 keys as an untuned part's");
+ 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"]);
+});
+
+test("UP TO DATE IS PER PIECE (review 1, finding 2): a line asked at another reading is never 'up to date' because another line already has that reading", () => {
+ const mk = (r) => ["screen:s1:0", "screen:s1:1", "screen:s1:2"].map((role, i) => ({ role, voice: "leo", engine: "orpheus", text: `line ${i}`, file: `x${i}`, start: i, seconds: 1, ...(r[i] ? { reading: r[i] } : {}) }));
+ const post = { role: "post", voice: "zac", engine: "orpheus", text: "his words", file: "p", start: 9, seconds: 1 };
+ const want = "his words\n\nline 0\n\nline 1\n\nline 2";
+ const e = { narration: { pick: 0, takes: [{ file: "t.wav", seconds: 5, script: want, voice: "zac+leo", engine: "orpheus", parts: [post, ...mk([0, 1, 0])], read: { kind: "thread" } }] } };
+ assert.equal(nextPartReading(e, "screen:s1:2", "line 2"), 1);
+ assert.equal(upToDate(e, { want, voice: "zac+leo", engine: "orpheus", pieces: [post, ...mk([0, 1, 1])] }), false);
+ assert.equal(upToDate(e, { want, voice: "zac+leo", engine: "orpheus", pieces: [post, ...mk([0, 1, 0])] }), true);
+});
+
+test("A RECORDED PIECE asked to be read again is refused in a sentence; a read with nothing synthesized to read again too; an unknown piece too", async () => {
+ const p = await project("recorded");
+ const asked = [];
+ await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS });
+ const e = (await read(p)).timeline[0];
+ // His line from take 1 (a recording of his words would be read in his piece's place).
+ await wavOf(path.join(p.dir, "narration/posts/7/take-9.recorded-me.wav"));
+ const rec = { file: "narration/posts/7/take-9.recorded-me.wav", engine: "recorded", voice: "me", seconds: 1, script: "Here is what they sent.", source: { kind: "recorded", voice: "me" } };
+ const withRec = { ...e, narration: { ...e.narration, takes: [...e.narration.takes, rec] } };
+ await assert.rejects(() => threadTake(p, withRec, { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS, postTake: 2, tuned: { post: { reading: "next" } } }), (err) => err instanceof ThreadReadError && /is read from take 2/.test(err.message));
+ await assert.rejects(() => threadTake(p, e, { red: NO_RED, ask: stubAsk(asked), lanes: null, ...LAYERS, tuned: { "screen:s9:0": { reading: "next" } } }), (err) => err instanceof ThreadReadError && /no piece screen:s9:0/.test(err.message));
+});
diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs
@@ -121,6 +121,11 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) {
// What Orpheus made it with, as the editor says (every tuning value, the reading, its seed base), so the reading
// can be made again exactly. Absent for another engine, and in a record kept before (it still reads).
...madeWith(result),
+ // The tuning it was ASKED with (lane line-rerun): what the card says to ask this file again -- its key -- when
+ // another reading is picked (umtool narration <p> <card> --pick <key>).
+ ...(n.tuning && typeof n.tuning === "object" && Object.keys(n.tuning).length ? { askedTuning: n.tuning } : {}),
+ // ...and the reading it was ASKED at: an engine with no seed (Kokoro) reports none, yet the key holds it.
+ ...(Number.isInteger(n.reading) && n.reading > 0 ? { askedReading: n.reading } : {}),
editor: {
jobId,
cached: result.cached === true,
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -30,13 +30,13 @@
// and the card's HTML.
import {
- isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration,
+ draftScript, isNarrated, narrationSchedule, pickedTake, postNarrationFiles, postNarrationKnobs, validatePostNarration,
} from "./post-narration.mjs";
import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactSceneRef, redactionOn, validatePostsRender } from "./post-redact.mjs";
import { blurErrors, blurOn, censorEntry } from "./post-censor.mjs";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs";
import { FOLLOW_MIN_SIZE, followBlocks, followKnobs, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs";
-import { panelSchedule, pictureBeats, threadLayout, validatePostThread } from "./post-thread.mjs";
+import { panelSchedule, pictureBeats, spokenSaysHiddenErrors, threadLayout, validatePostThread } from "./post-thread.mjs";
import { isPictureOnly, pictureBeatSeconds, pictureHasSound, pictureMediaOf, pictureRuleEntry, validatePictureOnly, validatePictureReplyRender } from "./post-picture.mjs";
import { joinLayerHtml, validatePostJoin, validatePostJoinRender } from "./post-join.mjs";
import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from "./post-link-visit.mjs";
@@ -170,6 +170,85 @@ export function postReadText(entry) {
return spans && excerptRanges(cardText(entry), spans) ? spans.map((x) => x.trim()).join(POST_EXCERPT_JOIN) : cardText(entry);
}
+/** What a script says when nobody edited it: what is read of the post, drafted to be spoken (draftScript). */
+export const shownDraftOf = (entry) => draftScript(postReadText(entry)).script;
+
+/** A script's words as compared: each paragraph's spacing collapsed, the paragraphs kept (a merge is an edit). */
+const spacing = (t) => str(t).split(/\n\s*\n/).map((x) => x.replace(/\s+/g, " ").trim()).filter(Boolean).join("\n\n");
+
+/** Whether `script` says his words as drafted (shownDraftOf), paragraph for paragraph: not an edit for reading. */
+export const saysShownDraft = (entry, script) => spacing(script) === spacing(shownDraftOf(entry));
+
+/** What an item whose playing take predates the rule is told (`posts narrate --list`, the bench), and what moves it. */
+export const LEGACY_EDIT_TEXT = "its playing take was read before reads were kept apart from the card, so the card follows what that take says -- read it again to move it to the new rule";
+
+/**
+ * Whether a script is the post's words EDITED FOR READING (lane line-rerun; operator ruling 3, 15 Nov 2026: an edit
+ * changes only what is spoken) -- `script` the one to judge (default: the item's own). What it decides is only an
+ * item with NO playing take (a preview from the script); with one, the take decides (readEditOf):
+ * null no script, no words on the card, or the script says the shown text as drafted
+ * "reading" edited, and `narration.forReading` set by the writer
+ * "legacy" edited, no marker
+ */
+export function scriptEditOf(entry, script = entry?.narration?.script) {
+ const own = spacing(script);
+ const shown = spacing(shownDraftOf(entry));
+ if (!own || !shown || own === shown) return null;
+ return entry?.narration?.forReading === true ? "reading" : "legacy";
+}
+
+/**
+ * The post's words a take READ, as written (review 2, finding 1): a single read's `script` (the words before the
+ * lexicon, the redaction or an anonymous handle changed what was said), else its parts -- his post's ("post") when
+ * they store roles -- rebuilt into paragraphs (a paragraph over 60 words is read in several parts: they join with a
+ * space; a thread read's part is in paragraph `para` % 100 of its piece).
+ */
+export function takePostWords(take) {
+ const parts = Array.isArray(take?.parts) ? take.parts : [];
+ const roled = parts.some((p) => typeof p?.role === "string");
+ if (!roled && str(take?.script).trim()) return str(take.script);
+ const own = roled ? parts.filter((p) => p?.role === "post") : parts;
+ if (!own.length) return str(take?.script);
+ const paras = [];
+ let last;
+ for (const p of own) {
+ const k = Number.isInteger(p?.para) ? (roled ? p.para % 100 : p.para) : null;
+ if (paras.length && k !== null && k === last) paras[paras.length - 1] += ` ${str(p?.text).trim()}`;
+ else paras.push(str(p?.text).trim());
+ last = k;
+ }
+ return paras.join("\n\n");
+}
+
+/**
+ * Whether a take is stamped FOR READING when it is made (the writer, postNarrationIn): the words it read are not the
+ * post's as drafted. False with no shown text. A THREAD read decides its own when it is made, from the words its post
+ * piece was WRITTEN as (postThreadRead.mjs: its parts hold the words as spoken) -- the writer leaves it as it comes.
+ */
+export const takeIsEditedRead = (entry, take) => !!spacing(shownDraftOf(entry)) && !!spacing(takePostWords(take)) && !saysShownDraft(entry, takePostWords(take));
+
+/**
+ * THE RULE FOR THE CARD's LAYOUT (lane line-rerun; review 1, finding 3, the orchestrator's ruling): the take that PLAYS
+ * decides. `take` (default: the picked one):
+ * "reading" stamped `forReading` when it was made: the card follows the SHOWN text (read-follow.mjs followParts,
+ * post-thread.mjs partRoles), never the read's words
+ * null it says the post's words as drafted: the card follows it, as ever (the same thing)
+ * "legacy" made before the rule (no stamp) from other words: the card follows them, as it always did -- read it
+ * again to move it to the rule
+ * With no take playing, the script decides (scriptEditOf: `narration.forReading`).
+ */
+/** Whether the PLAYING take predates the rule and reads other words than the post's (`--list`, the bench say so). */
+export const legacyReadOf = (entry) => !!pickedTake(entry) && readEditOf(entry) === "legacy";
+
+export function readEditOf(entry, take = pickedTake(entry)) {
+ if (!take) return scriptEditOf(entry);
+ if (take.forReading === true) return "reading";
+ // An unstamped THREAD read's parts hold its words as SPOKEN (the lexicon, the redaction): it is legacy only when the
+ // script it read from was edited too -- a lexicon word alone is not an edit.
+ if (take.read?.kind === "thread" && (!str(entry?.narration?.script).trim() || saysShownDraft(entry, entry.narration.script))) return null;
+ return takeIsEditedRead(entry, take) ? "legacy" : null;
+}
+
/** The card's word indices (cardTokens') that the excerpt does NOT read (drawn dimmed), or null with no excerpt. */
export function excerptCutWords(entry) {
const spans = excerptSpansOf(entry);
@@ -784,6 +863,11 @@ export function validatePostItem(e) {
errors.push(...validatePictureOnly(e));
// Its screens (post-screens.mjs): the text screenshots it carries, transcribed, and what of them is read.
errors.push(...validateScreens(e));
+ // A line's "said as" (saidAs) that says what another line masks or a redacted line holds: refused when written.
+ for (const sc of Array.isArray(e?.screens) ? e.screens : []) {
+ if (!isObj(sc?.saidAs)) continue;
+ for (const [k, v] of Object.entries(sc.saidAs)) if (typeof v === "string") errors.push(...spokenSaysHiddenErrors(e, v, `line ${k} of screen ${sc.id}'s "said as"`));
+ }
return errors;
}
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -192,20 +192,26 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz",
// `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim.
const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]);
// `character`: the character THIS item's own read is made with (cast.mjs: the project's own, else the cast's) -- absent: by its author's handle.
-const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "character", "takes", "pick", "approved", "off", "window"]);
+// `forReading` (lane line-rerun): the script is his words EDITED FOR READING -- the card follows the shown text
+// (post-item.mjs scriptEditOf). Set and cleared by the one writer that saves the script, never by hand.
+const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "character", "takes", "pick", "approved", "off", "window", "forReading"]);
// `said`: what a synthesized read SAID when an anonymous handle made it differ from its script (post-anon.mjs; the
// lint reads it); `speedAsked`: where its speed came from -- true (the command's --speed: kept as asked), "item" (the
// item's own), "preset" (its character's: drift when that changes). Absent: unknown -- never speed drift.
// `tuning`, `reading` (lane orpheus-tuning): what an Orpheus take was made with, as the editor's result said it --
// every tuning value (the defaults included) and the reading (0 = the first) -- so it can be made again exactly.
-const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading"]);
+// `forReading` (lane line-rerun): the take was made from words that are not the post's as drafted -- stamped by the
+// writer when it is made; while it plays the card follows the shown text (post-item.mjs readEditOf).
+const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading", "forReading"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
// `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's;
// `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs).
// `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"];
@@ -242,6 +248,24 @@ export function pickedTake(entry) {
return isObj(t) && typeof t.file === "string" && fin(t.seconds) && t.seconds > 0 ? { ...t, index: i } : null;
}
+/** Whitespace collapsed: two texts that differ only in their spacing are the same text to a read. */
+const sameText = (t) => String(t ?? "").replace(/\s+/g, " ").trim();
+
+/**
+ * THE NEXT READING of `text` (lane line-rerun, "Read again"): one past the highest `reading` among the takes that
+ * SYNTHESIZED those words (a missing reading is 0, the first), or 0 when none did -- the first reading of new words.
+ * Pure: the bench, its route and `--reading next` share it.
+ */
+export function nextReadingOf(takes, text) {
+ const want = sameText(text);
+ let hi = -1;
+ for (const t of Array.isArray(takes) ? takes : []) {
+ if (!isObj(t) || takeSourceOf(t).kind !== "tts" || t.read?.kind === "thread" || sameText(t.script) !== want) continue;
+ hi = Math.max(hi, Number.isInteger(t.reading) && t.reading >= 0 ? t.reading : 0);
+ }
+ return hi + 1;
+}
+
/** The read's speed for a post (its `rate`, else the cut's, else 1), held to its limits. */
export function narrationRateOf(entry, render) {
const r = Number(postNarrationKnobs(entry, render).rate);
@@ -615,6 +639,7 @@ export function validatePostNarration(e) {
for (const k of Object.keys(n)) if (!ITEM_KEYS.has(k)) errors.push(`${w}.${k} is not a narration key`);
if (n.script !== undefined) errors.push(...scriptErrors(n.script, `${w}.script`));
for (const k of ["excerpt", "approved", "off"]) if (n[k] !== undefined && typeof n[k] !== "boolean") errors.push(`${w}.${k} must be true or false`);
+ if (n.forReading !== undefined && n.forReading !== true) errors.push(`${w}.forReading must be true (or absent)`);
if (n.speed !== undefined && !numIn(n.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${w}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`);
if (n.character !== undefined && !(typeof n.character === "string" && /^[a-z0-9][a-z0-9_-]{0,47}$/.test(n.character))) errors.push(`${w}.character must be a character's id (umtool posts character)`);
if (n.window !== undefined) {
@@ -661,6 +686,7 @@ export function validatePostNarration(e) {
if (t.said !== undefined && (typeof t.said !== "string" || t.said.length > 50000)) errors.push(`${tw}.said must be the words its read said`);
if (t.speedAsked !== undefined && t.speedAsked !== true && t.speedAsked !== "item" && t.speedAsked !== "preset") errors.push(`${tw}.speedAsked must be true, "item" or "preset"`);
errors.push(...tuningProblems(t.tuning, t.reading, tw));
+ if (t.forReading !== undefined && t.forReading !== true) errors.push(`${tw}.forReading must be true (or absent)`);
if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`);
// A RECORDING OF ONE SCREEN LINE (postScreensCli.mjs `posts screen … record`, post-screens.mjs): the line it was
// recorded for -- its screen, its index, its words as a read writes them, its speaker. Never the item's read.
@@ -729,6 +755,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)`);
diff --git a/umtool/report-to-video/post-reading-pin.fixtures.mjs b/umtool/report-to-video/post-reading-pin.fixtures.mjs
@@ -0,0 +1,104 @@
+// The reading pin's fixtures and what it hashes (post-reading-pin.test.mjs; lane/line-rerun): imported by the
+// tests that hold an edit to a read to the card main drew (lib/report/screenSaidAs.test.mjs too).
+import { createHash } from "node:crypto";
+import { postCardHtml, postItemPlan } from "./post-item.mjs";
+import { drawnScreens, threadLayout } from "./post-thread.mjs";
+import { followBlocks } from "./read-follow.mjs";
+import { screenLineSaid } from "./post-screens.mjs";
+import { draftScript } from "./post-narration.mjs";
+
+const sha = (v) => createHash("sha1").update(typeof v === "string" ? v : JSON.stringify(v)).digest("hex");
+
+const POST = "The council met on Tuesday about the new bridge.\n\nNobody from the ministry came to explain the delay.";
+const QUOTED = { id: "7002", handle: "harbourwatch", author: "Harbour Watch", text: "Bridge works paused again, the notice says.", date: "2026-10-01T09:00:00.000Z" };
+const PARENT = {
+ id: "7001", handle: "rivertalk", author: "River Talk", date: "2026-10-01T08:00:00.000Z",
+ text: "Does anyone know why the tolls on the old crossing keep rising?\n\nA second paragraph nobody reads aloud in this cut.",
+};
+const IMG = { src: "posts-media/bridge-x/7003/7003_1.png", kind: "image", width: 900, height: 1400 };
+const DM = {
+ id: "s1", media: 0, kind: "dm", read: "all", lines: [
+ { who: "rivertalk", text: "Are the tolls going up again?" },
+ { who: "bridgefan", text: "Not this year, they said." },
+ ],
+};
+const base = (o = {}) => ({
+ type: "post", id: "p-7003", post: "bridge-x/7003", platform: "x", author: "Bridge Fan", handle: "bridgefan", date: "2026-10-02T10:00:00.000Z",
+ text: POST, subjects: ["bridgefan"], ...o,
+});
+const drafted = draftScript(POST).script;
+
+/** A single read of his words: one file, its script his words as drafted. */
+export function singleItem(o = {}) {
+ return base({
+ quoted: QUOTED, ...o,
+ narration: { script: drafted, pick: 0, takes: [{ file: "narration/posts/7003/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6.2, script: drafted }] },
+ });
+}
+
+/** A thread read: the parent's first paragraph only (its tile an excerpt), the quoted post, his words, the screen's lines. */
+export function threadItem(o = {}) {
+ const e = base({ parents: [PARENT], quoted: QUOTED, thread: { parent: "excerpt" }, media: [IMG], screens: [DM], ...o });
+ const parts = [];
+ let t = 0;
+ const add = (text, role, piece, gap, more = {}) => {
+ t += parts.length ? gap : 0;
+ const sec = Math.round((text.split(/\s+/).length / 3) * 100) / 100;
+ parts.push({ n: parts.length + 1, para: piece * 100 + (more.para ?? 0), text, voice: role === "post" ? "zac" : "leo", role, start: Math.round(t * 1000) / 1000, seconds: sec, ...(more.line ? { line: more.line, speaker: more.speaker } : {}) });
+ t += sec;
+ };
+ add(draftScript(PARENT.text.split("\n\n")[0]).script, "parent:0", 0, 0);
+ add(draftScript(QUOTED.text).script, "quoted", 1, 0.8);
+ const [p1, p2] = drafted.split("\n\n");
+ add(p1, "post", 2, 0.8);
+ add(p2, "post", 2, 0.6, { para: 1 });
+ DM.lines.forEach((l, n) => {
+ const said = screenLineSaid(DM, n);
+ add(draftScript(said).script, `screen:s1:${n}`, 3 + n, n ? 0.35 : 0.8, { line: draftScript(said).script, speaker: l.who });
+ });
+ return {
+ ...e,
+ narration: {
+ script: drafted, pick: 0,
+ takes: [{ file: "narration/posts/7003/take-1.orpheus-thread.wav", engine: "orpheus", voice: "zac+leo", seconds: Math.round(t * 1000) / 1000, script: parts.map((p) => p.text).join("\n\n"), parts, read: { kind: "thread", parents: "0" } }],
+ },
+ };
+}
+
+/** What the card DRAWS of an item: never what its read sounds like (no timing). */
+export function drawn(e) {
+ const render = { postNarration: { lead: 0.4 } };
+ const plan = postItemPlan(e, render);
+ const box = { width: 1600, height: 900 };
+ const fb = followBlocks(e);
+ return {
+ plain: sha(postCardHtml(e, { ...box })),
+ follow: sha(postCardHtml(e, { ...box, follow: true, thread: plan.follow?.thread ?? null })),
+ // The blocks: their words, their scope, the screen line they are -- and whether a part reads them at all (an
+ // excerpt tile hides the ones none does).
+ blocks: sha(fb.blocks.map((b) => [b.k, b.scope, b.from, b.to, b.line ?? null, b.part === null])),
+ tiles: sha(Array.isArray(e.parents) || e.quoted ? (threadLayout(e, render).tiles ?? []).map((x) => [x.scope, x.mode, x.above ?? null, x.inside ?? null]) : []),
+ screens: sha(drawnScreens(e).map((s) => s.id)),
+ };
+}
+
+export const FIXTURES = { single: singleItem(), thread: threadItem() };
+
+// Recorded on main (19fb842b5), before the S3 code.
+export const PINNED_SHAS = {
+ single: {
+ plain: "b2d58c132a00371da7ae824538067737551a4e3f",
+ follow: "80b1456aff9178519d0def976396c9a4e5d61047",
+ blocks: "6dd74f6c9ca620ed3d2ec690fd229fc848dc5a59",
+ tiles: "b22e780f2eed98b5f9cefe21828d3600bd5af3c0",
+ screens: "97d170e1550eee4afc0af065b78cda302a97674c",
+ },
+ thread: {
+ plain: "2bbb8717d3cad9f607463c969f5f7df622133cdf",
+ follow: "b0574d9a6149c221f3ed675ce748c98b48f6316b",
+ blocks: "3d085f775b916acd294b454fafde7bc770e72b85",
+ tiles: "68c08a31d2d1eaaac527741a5e83eaf5093d1b51",
+ screens: "2d021c30467f8a663cbd09eb672c85a6c484355a",
+ },
+};
+
diff --git a/umtool/report-to-video/post-reading-pin.test.mjs b/umtool/report-to-video/post-reading-pin.test.mjs
@@ -0,0 +1,122 @@
+// THE READING PIN (lane/line-rerun, S3 of the Orpheus re-tune plan; operator ruling 3, 15 Nov 2026: "every edit is for
+// READING only -- the original text is always what is shown on screen"). An item whose read says its shown text as
+// drafted draws BYTE-IDENTICALLY to main (19fb842b5) before a line of S3 was written: its plain card, its followed
+// card (the blocks the read lights, the paragraphs an excerpt tile hides), its thread tiles' modes and the screens it
+// draws. A change that moves one of these hashes changes what a card made before S3 draws.
+//
+// Recorded on main: PIN_RECORD=1 node --test report-to-video/post-reading-pin.test.mjs
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createHash } from "node:crypto";
+import { draftScript } from "./post-narration.mjs";
+import { postItemPlan } from "./post-item.mjs";
+import { FIXTURES, PINNED_SHAS, drawn, singleItem, threadItem } from "./post-reading-pin.fixtures.mjs";
+
+test("THE READING PIN: an item whose read says its shown text as drafted draws as it did on main", () => {
+ const got = Object.fromEntries(Object.entries(FIXTURES).map(([k, e]) => [k, drawn(e)]));
+ if (process.env.PIN_RECORD) {
+ console.log(JSON.stringify(got, null, 2));
+ return;
+ }
+ assert.deepEqual(got, PINNED_SHAS);
+});
+
+// ---------------------------------------------------------------------------
+// EDITED FOR READING (lane line-rerun): the read's words edited -- an acronym spelled out, a tag, paragraphs merged,
+// a sentence left out, words that match nothing on the card -- and a new take of them picked. The card draws exactly
+// what it drew before the edit: the same hashes as the pin above.
+// ---------------------------------------------------------------------------
+
+const EDITS = {
+ respelled: "The council met on Tuesday about the new bridge, the B R I D G E.\n\nNobody from the ministry <sigh> came to explain the delay.",
+ merged: "The council met on Tuesday about the new bridge. Nobody from the ministry came to explain the delay.",
+ shortened: "The council met on Tuesday about the new bridge.",
+ unrelated: "Completely different words that the card never shows.\n\nAnd a second paragraph of them.\n\nAnd a third.",
+};
+
+/** A single item whose script is `script`, saved for reading, and a take of it picked. */
+function editedSingle(script) {
+ const e = singleItem();
+ return { ...e, narration: { ...e.narration, script, forReading: true, pick: 1, takes: [...e.narration.takes, { file: "narration/posts/7003/take-2.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 5.1, script, reading: 1, forReading: true }] } };
+}
+
+/** A thread item whose post piece reads `script` (its paragraphs its parts), saved for reading, picked. */
+function editedThread(script) {
+ const e = threadItem();
+ const t = e.narration.takes[0];
+ const own = draftScript(script).script.split("\n\n");
+ const before = t.parts.filter((p) => p.role !== "post");
+ const at = t.parts.findIndex((p) => p.role === "post");
+ let start = t.parts[at].start;
+ const post = own.map((text, i) => {
+ const sec = Math.round((text.split(/\s+/).length / 3) * 100) / 100;
+ const p = { n: 0, para: 200 + i, text, voice: "zac", role: "post", start: Math.round(start * 1000) / 1000, seconds: sec };
+ start += sec + 0.6;
+ return p;
+ });
+ const parts = [...before.slice(0, at), ...post, ...before.slice(at)].map((p, i) => ({ ...p, n: i + 1 }));
+ const take = { ...t, file: "narration/posts/7003/take-2.orpheus-thread.wav", parts, script: parts.map((p) => p.text).join("\n\n"), reading: 1, forReading: true };
+ return { ...e, narration: { ...e.narration, script, forReading: true, pick: 1, takes: [t, take] } };
+}
+
+for (const [name, script] of Object.entries(EDITS)) {
+ test(`EDITED FOR READING (${name}): a single read's card draws as before the edit`, () => {
+ assert.deepEqual(drawn(editedSingle(script)), PINNED_SHAS.single);
+ });
+ test(`EDITED FOR READING (${name}): a thread read's card draws as before the edit -- the excerpt tile hides what it hid, the tiles keep their modes`, () => {
+ assert.deepEqual(drawn(editedThread(script)), PINNED_SHAS.thread);
+ });
+}
+
+test("EDITED BEFORE (a playing take made before the rule: no stamp): the card follows its words, as it always did", () => {
+ const e = editedSingle(EDITS.unrelated);
+ delete e.narration.forReading;
+ delete e.narration.takes[1].forReading;
+ assert.notDeepEqual(drawn(e), PINNED_SHAS.single);
+});
+
+// ---------------------------------------------------------------------------
+// WHEN THE TILES ARE DRAWN (review 1, finding 1): a spoken edit never moves when a thread tile shows. The tiles' t0/t1
+// of the unedited items, hashed as main (19fb842b5) schedules them -- recorded by running main's report-to-video on
+// these fixtures -- and every edited variant schedules them the same.
+// ---------------------------------------------------------------------------
+
+const RENDER = { postNarration: { lead: 0.4 } };
+const tilesOf = (e) => (postItemPlan(e, RENDER).follow?.thread?.tiles ?? []).map((t) => [t.scope, t.mode, t.t0, t.t1, t.from, t.to]);
+const sha = (v) => createHash("sha1").update(JSON.stringify(v)).digest("hex");
+// Main's: thread [["parent:0","excerpt",4.8,5.5,…],["quoted","full",4.8,5.5,…],["post","full",7.93,8.63,…],["screen:s1","full",15.33,16.03,…]].
+const TILE_SHAS_MAIN = { single: "d1021365f7f764ec2d5fb30a8b089d2ba6ddfe54", thread: "ee8b33368446e02103771de890cb8b9f9c060583" };
+
+test("THE TILES' TIMES: the unedited items schedule their tiles as main does", () => {
+ assert.deepEqual(Object.fromEntries(Object.entries(FIXTURES).map(([k, e]) => [k, sha(tilesOf(e))])), TILE_SHAS_MAIN);
+});
+
+for (const [name, script] of Object.entries(EDITS)) {
+ test(`THE TILES' TIMES (${name}): an edit to his words read moves no tile's time -- the parent, the quoted post, his post, the screen`, () => {
+ assert.equal(sha(tilesOf(editedThread(script))), TILE_SHAS_MAIN.thread, JSON.stringify(tilesOf(editedThread(script))));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// A SINGLE READ IN PARTS, its parts storing no role (Rule B: his post's, part by part; Rule A: the shown paragraphs).
+// ---------------------------------------------------------------------------
+
+/** A single read of `script` in parts (a paragraph each), no roles, stamped for reading, picked. */
+function editedSingleParts(script) {
+ const e = singleItem();
+ let t = 0;
+ const parts = draftScript(script).script.split("\n\n").map((text, i) => {
+ const sec = Math.round((text.split(/\s+/).length / 3) * 100) / 100;
+ const p = { n: i + 1, para: i, text, start: Math.round(t * 1000) / 1000, seconds: sec };
+ t += sec + 0.5;
+ return p;
+ });
+ const take = { file: "narration/posts/7003/take-2.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: Math.round(t * 100) / 100, script, parts, reading: 1, forReading: true };
+ return { ...e, narration: { ...e.narration, script, forReading: true, pick: 1, takes: [...e.narration.takes, take] } };
+}
+
+for (const [name, script] of Object.entries(EDITS)) {
+ test(`A SINGLE READ IN PARTS, NO ROLES (${name}): the card draws as before the edit`, () => {
+ assert.deepEqual(drawn(editedSingleParts(script)), PINNED_SHAS.single);
+ });
+}
diff --git a/umtool/report-to-video/post-screens.mjs b/umtool/report-to-video/post-screens.mjs
@@ -14,7 +14,7 @@
// ref?: "<channel>/<postId>", unread?: "omit" | "dim",
// lines: [{ who?, side?: "left" | "right", text, time?, redact?: true }],
// read: "all" | "none" | [{ line, text? }],
-// lineTakes?: { "<n>": "<take id>" } }]
+// lineTakes?: { "<n>": "<take id>" }, saidAs?: { "<n>": "<what the voice says>" } }]
//
// - `media` names the attachment (an index into the item's `media`); `at` the source span a video or GIF shows it.
// - `read`: every line ("all"), none ("none": transcribed only -- not drawn, not read), or the lines listed, each read
@@ -26,6 +26,9 @@
// - `lineTakes`: the take the operator CHOSE for a line (a recording of it: `posts screen … record`, the bench's per-line
// Record), by its id -- read in that line's place by every read of the item (postThreadRead.mjs); never chosen for
// it by anything else.
+// - `saidAs` (lane line-rerun; operator ruling 3, 15 Nov 2026: every edit is for READING only): what the voice SAYS
+// for a read line, in place of its words -- an acronym spelled out, a typo said right. Never drawn: the card shows
+// the line as written. A line's identity (is a take still this line?) is its shown words, never what it is said as.
// - `who`: a handle or a name; it is the post's author (her own lines, on the right), or another speaker, voiced through
// the project's characters and the cast as a thread read's pieces are (post-say.mjs) and drawn under the item's
// privacy rule (a subject, or `redact: false`, shown; else blurred), an anonymous one under its shown name.
@@ -236,7 +239,7 @@ const VIEWS = new WeakMap();
function viewOf(screen) {
if (!isObj(screen)) return { reads: [], broken: [] };
const lines = Array.isArray(screen.lines) ? screen.lines : [];
- const key = JSON.stringify([screen.read, lines]);
+ const key = JSON.stringify([screen.read, lines, isObj(screen.saidAs) ? screen.saidAs : null]);
const had = VIEWS.get(screen);
if (had && had.key === key) return had;
const r = screen.read;
@@ -263,7 +266,9 @@ function viewOf(screen) {
}
const masked = maskShapes(t).text;
const cut = masked.slice(span.start, span.end);
- reads.push({ n: x.line, start: span.start, end: span.end, cutBefore: span.start > all.start, cutAfter: span.end < all.end, said: cut.includes(REDACT_MARK) ? dropMarks(cut) : cut.trim(), shown: cut });
+ const said = cut.includes(REDACT_MARK) ? dropMarks(cut) : cut.trim();
+ const as = saidAsOf(screen, x.line);
+ reads.push({ n: x.line, start: span.start, end: span.end, cutBefore: span.start > all.start, cutAfter: span.end < all.end, said, shown: cut, spoken: as ?? said });
}
reads.sort((a, b) => a.n - b.n);
const v = { key, reads, broken };
@@ -277,17 +282,31 @@ function viewOf(screen) {
* redacted line, a line with no words, or an EXCERPT NOT IN ITS LINE: none (never the whole line instead).
*/
export function screenReadLines(screen) {
- return viewOf(screen).reads.map(({ said: _s, shown: _w, ...r }) => r);
+ return viewOf(screen).reads.map(({ said: _s, shown: _w, spoken: _p, ...r }) => r);
+}
+
+/** A line's "said as" (`saidAs`), trimmed, or null when it has none. */
+export function saidAsOf(screen, n) {
+ const v = isObj(screen?.saidAs) ? screen.saidAs[String(n)] : undefined;
+ return typeof v === "string" && v.trim() ? v.trim() : null;
}
/** The screens the DATA says are read (a read line or more), in order. */
export const readScreens = (entry) => screensOf(entry).filter((s) => viewOf(s).reads.length > 0);
-/** What a read line SAYS (before the thread read's spokenRead): its read run, its shapes left out ("" when not read). */
+/**
+ * A read line's words as SHOWN, ready to be said (before the thread read's spokenRead): its read run, its shapes left
+ * out ("" when not read). The line's identity -- a take is this line's while it said these -- never its "said as".
+ */
export function screenLineSaid(screen, n) {
return viewOf(screen).reads.find((x) => x.n === n)?.said ?? "";
}
+/** What the voice SAYS for a read line: its "said as" (`saidAs`), else screenLineSaid ("" when not read). */
+export function screenLineSpoken(screen, n) {
+ return viewOf(screen).reads.find((x) => x.n === n)?.spoken ?? "";
+}
+
/**
* A screen with lines `drops` (their indices) REMOVED, pure (a copy): its read follows them -- a removed line's read
* goes, the later lines' numbers move down (the CLI's `line.<n>=off`, the post bench's ×: one rule). A read the take
@@ -304,6 +323,12 @@ export function withoutLines(screen, drops) {
if (Object.keys(lt).length) out.lineTakes = lt;
else delete out.lineTakes;
}
+ // So do their "said as" (saidAs): a removed line's goes, the later ones' keys move down.
+ if (isObj(screen?.saidAs)) {
+ const sa = Object.fromEntries(Object.entries(screen.saidAs).filter(([k]) => /^\d{1,2}$/.test(k) && !gone.has(Number(k))).map(([k, v]) => [String(to(Number(k))), v]));
+ if (Object.keys(sa).length) out.saidAs = sa;
+ else delete out.saidAs;
+ }
return out;
}
@@ -500,7 +525,7 @@ export function validateScreens(e) {
errors.push(`${at} must be an object`);
return;
}
- const known = new Set(["id", "media", "at", "kind", "title", "source", "checked", "ref", "unread", "lines", "read", "lineTakes"]);
+ const known = new Set(["id", "media", "at", "kind", "title", "source", "checked", "ref", "unread", "lines", "read", "lineTakes", "saidAs"]);
for (const k of Object.keys(sc)) if (!known.has(k)) errors.push(`${at}.${k} is not a screen's field (${[...known].join(", ")})`);
if (!SCREEN_ID_RE.test(str(sc.id))) errors.push(`${at}.id must be a short name (lower-case letters, digits, -)`);
else if (ids.has(sc.id)) errors.push(`${at}.id "${sc.id}" is the id of another screen of the item`);
@@ -559,6 +584,19 @@ export function validateScreens(e) {
else if (!isObj(t.screenLine) || t.screenLine.screen !== sc.id) errors.push(`${at}.lineTakes.${k}: take ${takes.indexOf(t) + 1} is not a recording of a line of screen ${sc.id}${isObj(t.screenLine) ? ` (it is of screen ${t.screenLine.screen})` : ""}`);
}
}
+ // What a line is SAID AS (never drawn): a line it has, not redacted, words -- and no shape (an e-mail, a number the
+ // card would mask is never said, however it is typed).
+ if (sc.saidAs !== undefined) {
+ const sa = sc.saidAs;
+ if (!isObj(sa) || Object.keys(sa).length > SCREEN_LINES_MAX) errors.push(`${at}.saidAs must be { "<line>": "<what the voice says>" }`);
+ else for (const [k, v] of Object.entries(sa)) {
+ const n = /^\d{1,2}$/.test(k) ? Number(k) : -1;
+ if (n < 0 || !isObj(lines?.[n])) errors.push(`${at}.saidAs.${k}: the screen has no line ${k}`);
+ else if (lines[n].redact === true) errors.push(`${at}.saidAs.${k}: line ${k} is redacted -- it is never read`);
+ if (typeof v !== "string" || !v.trim() || v.length > SCREEN_LINE_MAX) errors.push(`${at}.saidAs.${k} must be words (at most ${SCREEN_LINE_MAX} characters)`);
+ else if (shapeSpans(v).length) errors.push(`${at}.saidAs.${k} says ${shapeSpans(v)[0].kind === "email" ? "an e-mail address" : "a number"} the card would mask -- a read never says one: say it another way`);
+ }
+ }
const r = sc.read;
if (r === "all" || r === "none") return;
if (!Array.isArray(r)) {
@@ -612,7 +650,9 @@ export function screenPieces(entry) {
for (const sc of readScreens(entry)) {
for (const r of screenReadLines(sc)) {
const text = screenLineSaid(sc, r.n);
- if (text.trim()) out.push({ role: screenRole(sc.id, r.n), who: str(sc.lines[r.n].who) || null, text, screen: sc.id });
+ // `spoken`: its "said as" (saidAs), only when it has one -- `text` stays the line as shown (its identity).
+ const as = saidAsOf(sc, r.n);
+ if (text.trim()) out.push({ role: screenRole(sc.id, r.n), who: str(sc.lines[r.n].who) || null, text, screen: sc.id, ...(as ? { spoken: as } : {}) });
}
}
return out;
diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs
@@ -48,14 +48,14 @@
// PURE and dependency-free (but its siblings): the plan, the build, Play, the
// bench, the writers and the lint all read the same rules from here.
-import { POST_PARENTS_MAX, cardText, contextText, linksOf, parentsOf, refMediaOf, refShown } from "./post-item.mjs";
+import { POST_PARENTS_MAX, cardText, contextText, linksOf, parentsOf, readEditOf, refMediaOf, refShown } from "./post-item.mjs";
import { draftScript, isNarrated, isOnlyUrls, joinSplitLinks, pickedTake, postNarrationKnobs, scriptParts, spokenUrls } from "./post-narration.mjs";
import { normWord, scriptWordsOf } from "./word-zoom.mjs";
import { followKnobs } from "./read-follow.mjs";
import { planContext } from "./post-conversation.mjs";
import { branchMapOf, mapKnobs, mapTimes } from "./post-branch-map.mjs";
import { isPictureOnly, pictureBeatSeconds } from "./post-picture.mjs";
-import { isScreenScope, parseScreenRole, readScreens, screenLineProblem, screenLineSaid, screenOrder, screenPieces, screenReadLines, screenRole, screenScope, screenWarnings, screensOf as screensOfEntry, shapeSpans, tileOfRole } from "./post-screens.mjs";
+import { isScreenScope, parseScreenRole, readScreens, screenLineProblem, screenLineSaid, screenLineSpoken, screenOrder, screenPieces, screenReadLines, screenRole, screenScope, screenWarnings, screensOf as screensOfEntry, shapeSpans, tileOfRole } from "./post-screens.mjs";
/** What a context tile may be. */
export const THREAD_MODES = Object.freeze(["auto", "full", "excerpt", "context", "carry", "hidden"]);
@@ -166,7 +166,7 @@ export function readTexts(entry) {
});
add("post", [cardText(entry), str(entry?.narration?.script), spoken(cardText(entry))]);
// ITS SCREENS' read lines (post-screens.mjs): each its own text (a take's stored roles name them; a long line is matched).
- for (const sc of readScreens(entry)) for (const r of screenReadLines(sc)) add(screenRole(sc.id, r.n), [screenLineSaid(sc, r.n)]);
+ for (const sc of readScreens(entry)) for (const r of screenReadLines(sc)) add(screenRole(sc.id, r.n), [screenLineSaid(sc, r.n), screenLineSpoken(sc, r.n)]);
return out;
}
@@ -223,6 +223,9 @@ export function partRoles(entry, take = undefined) {
parts = scriptParts(script).map((p) => ({ text: p.text, para: p.para * 100 }));
}
if (!parts.length) return [];
+ // HIS WORDS EDITED FOR READING (post-item.mjs readEditOf: the take's stamp; ruling 3): a read of them that stores
+ // no roles is his post's, part by part -- never inferred from the edited words as a parent, the quoted post or a picture.
+ if (t && readEditOf(entry, t) === "reading" && !parts.some((p) => typeof p?.role === "string")) return parts.map(() => ({ role: "post", source: "inferred" }));
const texts = readTexts(entry);
const orderOf = roleOrderOf(entry);
const images = (Array.isArray(entry?.media) ? entry.media : []).map((m, i) => ({ m, i })).filter((x) => x.m?.kind === "image");
@@ -659,6 +662,19 @@ export function readSaysHiddenErrors(e) {
return out;
}
+/**
+ * WHAT A SPOKEN EDIT WOULD SAY THAT ITS SCREENS HIDE, pure (lane line-rerun): readSaysHiddenErrors over `text` as the
+ * read's words -- the script saved for reading, a screen line's "said as" -- so a spoken edit the build would refuse is
+ * refused when it is WRITTEN, and never reaches a take (whose refusal would drop the read from the preview).
+ */
+// It judges the text as WRITTEN, not as spokenRead would say it (the lexicon, the redaction): refusing more is the safe
+// side -- a word the lexicon would say another way is still refused if written as a masked shape (review 1: no change).
+export function spokenSaysHiddenErrors(e, text, where = "the read") {
+ if (!str(text).trim() || !screensOfEntry(e).length) return [];
+ const probe = { ...e, narration: { pick: 0, takes: [{ file: "narration/probe.wav", seconds: 1, script: str(text) }] } };
+ return readSaysHiddenErrors(probe).map((m) => m.replace("its picked take", where).replace(/: make the read again \(umtool posts screen <p> [^)]*\)$/, ": say it another way"));
+}
+
// ---------------------------------------------------------------------------
// WHAT A PREVIEW PLAYS (Play, Present, the post bench's player, the card page): never a read the build refuses.
// ---------------------------------------------------------------------------
@@ -903,7 +919,11 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat
const roles = layout.roles;
// Each read piece's start on the item's clock: its first block's start.
const startOfPart = new Map();
- for (const b of blocks) if (b.part !== null && b.start !== null && !startOfPart.has(b.part)) startOfPart.set(b.part, b.start);
+ // Keyed by the TAKE's part (`takePart` when read-follow's part stands for one: his words edited for reading).
+ for (const b of blocks) {
+ const n = b.part === null ? null : b.takePart ?? b.part;
+ if (n !== null && b.start !== null && (!startOfPart.has(n) || b.start < startOfPart.get(n))) startOfPart.set(n, b.start);
+ }
// A PICTURE-ONLY context post's BEAT (pictureBeats) is a piece of its own, before the read's first.
const beatOf = new Map((Array.isArray(beats) ? beats : []).map((b) => [b.scope, b]));
const pieces = [...beatOf.values()].map((b) => ({ role: b.scope, parts: [], start: b.t0, beat: b.scope !== "post" })).concat(tilePieces(readPieces(entry, roles)).map((p) => {
@@ -1313,7 +1333,7 @@ export function panelReadErrors(follow, panel, { id = "?", settle = 0.35 } = {})
const show = (panel?.shows ?? []).find((sh) => sh.scope === b.scope);
const a = b.start + settle;
const z = Math.max(a, (fin(b.end) ? b.end : b.start) - 0.4);
- if (!show || show.t0 > a + 1e-6 || show.t1 < z - 1e-6) errors.push(`${id}: part ${b.part + 1} reads the picture of ${b.scope}, which the panel does not show while it is said (${r3(b.start)}–${r3(fin(b.end) ? b.end : b.start)} s)`);
+ if (!show || show.t0 > a + 1e-6 || show.t1 < z - 1e-6) errors.push(`${id}: part ${(b.takePart ?? b.part) + 1} reads the picture of ${b.scope}, which the panel does not show while it is said (${r3(b.start)}–${r3(fin(b.end) ? b.end : b.start)} s)`);
}
return errors;
}
@@ -1340,6 +1360,6 @@ export function chronoPieces(entry, { skip = [] } = {}) {
add("post", entry, cardText(entry));
out.sort((a, b) => order(a.role) - order(b.role));
// ITS SCREENS' read lines (post-screens.mjs), after everything else, in the screens' order: `who` as written.
- for (const p of screenPieces(entry)) if (!skip.includes(p.role)) out.push({ role: p.role, date: null, author: null, handle: null, who: p.who, screen: p.screen, text: p.text });
+ for (const p of screenPieces(entry)) if (!skip.includes(p.role)) out.push({ role: p.role, date: null, author: null, handle: null, who: p.who, screen: p.screen, text: p.text, ...(p.spoken ? { spoken: p.spoken } : {}) });
return out;
}
diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs
@@ -43,7 +43,7 @@
// sets it on the page -- in the build per frame before a screenshot
// (post-render.mjs), in Play per tick (PostItemPlayer).
-import { cardText, contextReadSeconds, contextText, linksOf, parentsOf, readSeconds } from "./post-item.mjs";
+import { cardText, contextReadSeconds, contextText, linksOf, parentsOf, readEditOf, readSeconds, shownDraftOf } from "./post-item.mjs";
import { isNarrated, narrationSchedule, partStartOnItem, pickedTake, scriptParts } from "./post-narration.mjs";
import { cardTokens, easeOf, normWord, scriptWordsOf } from "./word-zoom.mjs";
import { partRoles, threadGeoAt, threadKnobs, threadLayout, threadSchedule, threadStateAt } from "./post-thread.mjs";
@@ -203,11 +203,17 @@ function fitMatch(a, b, lo, hi) {
export function followParts(entry) {
if (isNarrated(entry)) {
const t = pickedTake(entry);
+ // HIS WORDS EDITED FOR READING (post-item.mjs readEditOf: the playing take's stamp; ruling 3): the card follows
+ // the SHOWN text -- his post's blocks are made from his words as drafted, never from the edited ones, so no edit
+ // to what is said moves, dims for good or hides a drawn word. The edited read only times them.
+ const forReading = readEditOf(entry, t) === "reading";
if (Array.isArray(t?.parts) && t.parts.length) {
// Each part's ROLE (post-thread.mjs): the text it reads -- a context post, his words, an attachment's.
const roles = partRoles(entry);
- return { source: "take", parts: t.parts.map((p, k) => ({ text: str(p.text), start: fin(p.start) ? p.start : null, ...(roles[k]?.role ? { scope: roles[k].role } : {}) })) };
+ const parts = t.parts.map((p, k) => ({ text: str(p.text), start: fin(p.start) ? p.start : null, ...(roles[k]?.role ? { scope: roles[k].role } : {}) }));
+ return { source: "take", parts: forReading ? shownPostParts(entry, parts, t.parts) : parts };
}
+ if (forReading) return { source: "script", parts: scriptParts(shownDraftOf(entry)).map((p) => ({ text: p.text, scope: "post" })) };
const script = str(t?.script).trim() ? t.script : str(entry?.narration?.script);
const roles = partRoles(entry);
return { source: "script", parts: scriptParts(script).map((p, k) => ({ text: p.text, ...(roles[k]?.role ? { scope: roles[k].role } : {}) })) };
@@ -218,6 +224,37 @@ export function followParts(entry) {
}
/**
+ * His post's parts of a take (scope "post", one run of them) REPLACED by his words as drafted (the shown text's
+ * paragraphs), each `shown: true` and timed from the read: one for one when the read kept as many parts, else shared
+ * by words over the span his parts were read in -- every block read in turn, none left unread by an edit.
+ */
+function shownPostParts(entry, parts, takeParts) {
+ const at = parts.map((p, i) => (p.scope === "post" ? i : -1)).filter((i) => i >= 0);
+ if (!at.length || at.some((i, j) => j && i !== at[j - 1] + 1)) return parts;
+ // Each shown part keeps the take's part it stands for (`at`: one for one, else his first part for the first, his
+ // last for the rest) -- the thread schedule finds a piece's start by the take's parts (review 1, finding 1).
+ const shown = scriptParts(shownDraftOf(entry)).map((q, j) => ({ text: q.text, scope: "post", shown: true, at: at[Math.min(j, at.length - 1)] }));
+ if (!shown.length) return parts;
+ const own = at.map((i) => parts[i]);
+ let timed;
+ if (shown.length === own.length) timed = shown.map((q, j) => ({ ...q, start: own[j].start }));
+ else {
+ const last = takeParts[at[at.length - 1]];
+ const t0 = own[0].start;
+ const t1 = fin(t0) && fin(last?.start) && fin(last?.seconds) ? last.start + last.seconds : null;
+ const total = shown.reduce((n, q) => n + Math.max(1, wordsIn(q.text)), 0);
+ let w = 0;
+ timed = shown.map((q) => {
+ const start = fin(t0) && fin(t1) ? Math.round((t0 + ((t1 - t0) * w) / total) * 1000) / 1000 : null;
+ w += Math.max(1, wordsIn(q.text));
+ return { ...q, start };
+ });
+ }
+ // Every other part keeps the take's part it is (`at`): the schedule times them by it.
+ return [...parts.slice(0, at[0]).map((p, j) => ({ ...p, at: j })), ...timed, ...parts.slice(at[at.length - 1] + 1).map((p, j) => ({ ...p, at: at[at.length - 1] + 1 + j }))];
+}
+
+/**
* THE BLOCK MAP, pure, from the entry alone: `{ source, blocks: [{ k, scope,
* from, to, part }], parts }` -- each block a run of one card text's words
* (card word indices, inclusive), `part` the index of the part that reads it
@@ -320,7 +357,10 @@ export function followBlocks(entry) {
blocks.push(...segs);
}
blocks.push(...media);
- return { source, parts: parts.length, blocks: blocks.map((b, k) => ({ k, ...b })) };
+ // A block read by a part that stands for a take's part (shownPostParts): that take part's index (`takePart`) --
+ // the thread schedule and the lint name a piece by the take's parts.
+ const takeAt = (b) => (b.part !== null && Number.isInteger(parts[b.part]?.at) ? { takePart: parts[b.part].at } : {});
+ return { source, parts: parts.length, blocks: blocks.map((b, k) => ({ k, ...b, ...takeAt(b) })) };
}
/** A block map's runs for one scope, as wordsHtml wraps them: `[{ from, to, k }]`. */
@@ -362,7 +402,8 @@ export function followSchedule(entry, render = undefined, { hold = null, narrati
readEnd = r3(sch.at + sch.seconds);
const take = pickedTake(entry);
const timed = map.source === "take" && parts.every((p) => fin(p.start));
- if (timed) take.parts.forEach((p, i) => (starts[i] = partStartOnItem(sch, p)));
+ // A part of his words as drafted (shownPostParts) is timed by its own start; every other by the take's part.
+ if (timed) parts.forEach((p, i) => (starts[i] = partStartOnItem(sch, p.shown ? p : take.parts[p.at ?? i])));
else {
// No parts: the read's seconds shared by words.
const total = parts.reduce((n, p) => n + wordsIn(p.text), 0) || 1;
@@ -823,7 +864,7 @@ export function readInViewErrors(follow, geo, stateAt, { total = null, id = "?"
}
const secs = times.length > 1 ? bad * T.step : bad ? Math.max(0.1, bEnd - b.start) : 0;
if (bad && secs > T.slack + 1e-9) {
- errors.push(`${id}: part ${b.part + 1} (${tileName(b.scope)}, block ${b.k}) is not in full view for ${secs.toFixed(2)} s of its read (${r3(b.start)}–${r3(bEnd)} s) -- at ${worst.s} s ${worst.why.join("; ")}`);
+ errors.push(`${id}: part ${(b.takePart ?? b.part) + 1} (${tileName(b.scope)}, block ${b.k}) is not in full view for ${secs.toFixed(2)} s of its read (${r3(b.start)}–${r3(bEnd)} s) -- at ${worst.s} s ${worst.why.join("; ")}`);
}
}
// A CONTEXT tile is never larger nor stronger than its context size; a carried or scene tile, once it has given way.