Archilyzer · Source

archilyzer

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

commit 9e8f687cf202be5c7a9908519e70d640df6b6cc9
parent 200646d65b3437a6e672d95c4a3e7333fb18798c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 03:47:24 -0500

Merge lane/screens-2: a screen line in your own voice, and a screen from a post's read -- umtool posts screen record keeps a recording of one screen line (recorded, cleaned, converted to its speaker's stock voice), read only where it is chosen, by its words and speaker, and said to be heard or not heard; add --from-read makes a picture-only post's read its screen, never read twice; the post bench records, chooses and makes the read; no preview, Play or Present plays a read the build refuses, a read may not say what a screen masks, and Present's public payload carries only what the card draws

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

Diffstat:
Meditor/CHANGELOG.md | 3+++
Mumtool/app/api/report/post-item/inspector/route.ts | 3+++
Mumtool/app/api/report/post-item/route.ts | 8+++++++-
Mumtool/app/api/report/post-narration/route.ts | 107++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/PostBench.tsx | 16++++++++++++++--
Mumtool/components/projects/PostScreensPanel.tsx | 112++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Aumtool/components/projects/ScreenLineVoice.tsx | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PostItemPlayer.tsx | 24+++++++++++++++++++-----
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 5++++-
Mumtool/docs/report-video.md | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/e2e/post-screens.spec.ts | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/cli/groups.mjs | 7++++---
Mumtool/lib/cli/verbs.mjs | 6+++++-
Mumtool/lib/report/manifest.mjs | 3++-
Mumtool/lib/report/playView.mjs | 9++++++++-
Mumtool/lib/report/postBenchData.ts | 4+++-
Mumtool/lib/report/postNarrationCli.mjs | 28+++++++++++++++++++++-------
Mumtool/lib/report/postRecord.mjs | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/postScreensCli.mjs | 130++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Aumtool/lib/report/postScreensReview3.test.mjs | 364+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postScreensRound2.test.mjs | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postThreadRead.mjs | 44++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/present.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/recordPreview.mjs | 22++++++++++++++--------
Aumtool/lib/report/screenLineRecord.mjs | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-item.mjs | 23+++++++++++++++--------
Mumtool/report-to-video/post-narration.mjs | 16+++++++++++++++-
Aumtool/report-to-video/post-screens-pin2.test.mjs | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-screens.mjs | 102++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/post-thread.mjs | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
31 files changed, 2432 insertions(+), 107 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **umtool: a picture-only post's read can become its screen, and a screen line can be read in your own voice.** `umtool posts screen <p> <item> add --from-read` (the post bench's "From its read") turns the script of a picture-only post into a screen: one line per line of the script, not checked, and with no speaker split out of a line. That screen *is* the post's read, so the thread read no longer reads the same words twice. `posts screen … record <id> <n> --recording <file>` (the bench's per-line Record / Stop / Keep) records one line as the read says it, with masked numbers and redacted words left out of what you read. It is kept as new takes: recorded, cleaned, and converted to the line's speaker's character's stock voice. None of them is picked. A line take is read only when you choose it, with the bench's per-line select or `set <id> take.<n>=<take>`. A choice follows its line when lines move, and is refused when the line's words or speaker changed. `--check-words` (CLI only) transcribes the recording first and refuses it if it says a number, a handle, an anonymous author's name or a redacted term. The lint flags every chosen take that was not heard this way. +- **umtool: no preview plays a read the build refuses.** After a screen line is edited, removed, redacted or no longer read, the build refuses the old read. Play, Present (including the public payload), the card page and the post bench's player now refuse it too: they play the item silent and say why, until the read is made again. Present's public payload carries a post's screens the way the card draws them (masked, blurred speakers nameless), never the raw lines. +- **umtool: no part of a read may say what the item's screens mask.** A build refuses a read in which any part says a number or e-mail one of the item's screens masks, or the words of a redacted line. That covers the post's own words, a context post and a screen line. Two recordings kept at the same moment never take the same file: a recorded take's name is now claimed with an exclusive create. - **A local-only Archilyzer in one command: `./docker/demo.sh up`.** On a machine with only docker (compose v2.24 or newer), it starts the editor, umtool and a local model server (ollama) in Docker, connects a published archive as a source (https://jeralyzer.pages.dev unless `--archive`), pulls the model (`--model`, default qwen2.5:7b) and routes every AI task to it. Every step is one printed line; `--dry-run` prints every command and changes nothing; a missing prerequisite (docker, compose, the daemon, 12 GB of RAM, 25 GB free, a port) is one sentence and exit 1. The GPU is found by itself (a render node: ollama on Vulkan; NVIDIA; else the CPU, said so), and ollama's own line about the device it uses is printed. A host ollama already holding a model on the GPU is warned about. The choices are kept in `.env.demo` (mode 600) and reused, so a second `up` changes nothing. A step that fails after the start (the start itself, the editor's first answer, the pull, the settings) ends with one sentence saying the demo is partly up and that `./docker/demo.sh down` stops it. `down` keeps the volumes unless `--volumes`, and stops the stack even when `.env.demo` is gone; `status` shows the stack; `voice` says what Orpheus needs. Nothing is opened off this machine: every value written to `.env.demo` is checked character by character (a newline cannot be smuggled in through `--archive`), a `.env.demo` line it did not write or a bind other than 127.0.0.1 (in the file or the shell) is refused, and the exposure guard is handed the binds compose really publishes on (docker-compose.yml, for every stack). RUNNING_IN_DOCKER.md, "A local-only demo". - **Local only: `ARCHILYZER_LOCAL_ONLY=1` (the demo sets it).** With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is sent or any process started — every call to the Claude API, every Claude Code answer (a task routed to `code`, or `answers` posted by a session), the digest's `claude` CLI lane, and every call to an ollama model that is a cloud model (a `-cloud` tag, or one whose /api/show names a remote host) or that is served from anywhere but this machine (a loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model may read (its web_search and fetch tools), the published site's in-browser Ask, or remote transcription workers, which are not language models. A settings change (on the ops route or the editor's own pages) that would route a task off the local model or name a model server elsewhere is refused, an LLM worker elsewhere is not saved and is skipped, and `reports import-sweep` and `import-local-runs` are refused. A refused job or write says so in one sentence; the digest's metered lane says "refused: local only", not "is the claude CLI installed". `archilyzer gen local-check` (and `./docker/demo.sh check`) checks it afterwards by counts and host names: the flag on, every route local, every model server a local route asks on this machine, no API key present, no call off the local route in the usage ledger or the per-call logs since a date, and no imported iteration; it exits 1 when any fails, says NOTHING TO PROVE YET (not PASS) while no call is recorded, and never prints a key or a home path. The editor's boot log says `models: LOCAL ONLY`, says as an ERROR when the flag holds a value it does not understand, and gives one line on whether ollama answers. umtool makes no model call itself. Unset, nothing changes. Needs a restart of the editor. - **`archilyzer gen model api|local|extractor <model>` sets the model a route runs** (settings.generation.models), from a terminal or a container; bare, it shows the three. diff --git a/umtool/app/api/report/post-item/inspector/route.ts b/umtool/app/api/report/post-item/inspector/route.ts @@ -2,6 +2,7 @@ import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { cardText, excerptErrors, excerptRanges, excerptSpansOf } from "umtool-report-to-video/post-item"; import { pickedTake } from "umtool-report-to-video/post-narration"; +import { itemReadRefusals } from "umtool-report-to-video/post-thread"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs"; import { attachmentOf } from "@/lib/report/postsCli.mjs"; @@ -74,6 +75,8 @@ export async function GET(request: Request) { takes: takes.map((t, i) => ({ i, file: String(t.file ?? ""), engine: typeof t.engine === "string" ? t.engine : null, voice: typeof t.voice === "string" ? t.voice : null, seconds: typeof t.seconds === "number" ? t.seconds : null })), picked: picked ? picked.index : null, off: e.narration?.off === true, + // A read the build refuses (post-thread.mjs itemReadRefusals): not played anywhere until it is made again. + refused: itemReadRefusals(e) as string[], }, token: await manifestToken(r.project.dir), }, diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -7,6 +7,7 @@ import { jobState, startJob } from "@/lib/research/case-editor"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, updatePostFx, updatePostItem, updatePostNarration } from "@/lib/report/manifest.mjs"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; +import { playableAsWritten } from "umtool-report-to-video/post-thread"; import { scriptWordTimes } from "umtool-report-to-video/word-zoom"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { threadLayout } from "umtool-report-to-video/post-thread"; @@ -83,6 +84,8 @@ async function anonymised(project: { dir: string }, m: Record<string, unknown>, async function itemOf(project: { dir: string }, manifest: Record<string, unknown>, id: string, take: string | null, { anon = false }: { anon?: boolean } = {}) { let m = manifest; if (take) m = (await resolveTakeManifest(project.dir, take, { base: manifest })).manifest as Record<string, unknown>; + // The item AS WRITTEN (before the anonymity pass): what the build's enforced lint judges its read on. + const written = ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).find((e) => e?.type === "post" && e.id === id) ?? null; if (anon) m = await anonymised(project, m, manifest); const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[]; const at = tl.findIndex((e) => e?.type === "post" && e.id === id); @@ -91,7 +94,7 @@ async function itemOf(project: { dir: string }, manifest: Record<string, unknown const ctx = planContext(tl, at, (m.render ?? {}) as Record<string, unknown>) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null; join: { seconds: number } | null }; // THE JOIN (post-join.mjs): the item before's own context, so its post's size is known (the carried post drawn alike). const prevCtx = at > 0 && ctx.join ? (planContext(tl, at - 1, (m.render ?? {}) as Record<string, unknown>) as Record<string, unknown>) : null; - return { item: at >= 0 ? tl[at] : null, prev: ctx.prev, ctx, prevCtx, manifest: m }; + return { item: at >= 0 ? tl[at] : null, written, prev: ctx.prev, ctx, prevCtx, manifest: m }; } /** How the item before draws its post (post-item.mjs joinCarryOf), as the build draws the carried post alike. */ @@ -273,6 +276,9 @@ export async function GET(request: Request) { const w = Math.round(Number(q.get("w")) || 0); const h = Math.round(Number(q.get("h")) || 0); if (!(w >= 160 && w <= 3840 && h >= 90 && h <= 2160)) return new Response("w and h are the footage box, in px", { status: 400 }); + // NEVER A READ THE BUILD REFUSES (post-thread.mjs playableEntry): a read older than its screen draws as no read at all. + // Judged on the item AS WRITTEN, applied to the one drawn (post-thread.mjs playableAsWritten): the build's verdict. + found.item = playableAsWritten(found.written ?? found.item, found.item) as Entry; const base = `/api/report/post-item?project=${encodeURIComponent(r.project.id)}`; const parentShot = typeof found.item.parentShot === "string" ? `${base}&file=${encodeURIComponent(found.item.parentShot)}` : null; // The authors' pictures (post-avatars.mjs), served as the project's files. diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -1,4 +1,4 @@ -import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +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, @@ -24,6 +24,8 @@ import { spokenRead } from "umtool-report-to-video/post-redact"; import { recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast"; 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"; export const dynamic = "force-dynamic"; @@ -67,6 +69,14 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // a reread, set or fit + inTake: <take> the same, scoped to the take's patch (takeScope.mjs, the CLI's // --in-take); every other op refuses inTake // POST {project, op: "undo"} the last structural write undone +// POST multipart {project, id, line: "screen:<id>:<n>", label?, part (audio)} +// ONE SCREEN LINE recorded (lib/report/screenLineRecord.mjs): a umtool +// 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) +// GET ?project&id&screenJob=<job> either job: its state, its result, and -- ended -- the entry as it is const noStore = { "cache-control": "no-store" }; type Entry = Record<string, unknown> & { id: string; type?: string; narration?: Record<string, unknown> }; @@ -88,6 +98,33 @@ export async function GET(request: Request) { const render = (m.render ?? {}) as Record<string, unknown>; const id = q.get("id"); const job = q.get("job"); + if (id && q.get("linePrompts") !== null) { + // What each read screen line says, as the read says it (screenLineRecord.mjs lineToRecord): the bench's prompt. + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const { lineToRecord } = await import("@/lib/report/screenLineRecord.mjs"); + const { characterNames } = await import("@/lib/report/postThreadRead.mjs"); + const { screensOf, screenReadLines } = await import("umtool-report-to-video/post-screens"); + const red = await projectRedaction(r.project.dir, m); + const names = characterNames(await readLayers(r.project.dir).catch(() => null)); + const prompts: Record<string, string> = {}; + for (const sc of screensOf(e) as Array<{ id: string }>) { + for (const rl of screenReadLines(sc) as Array<{ n: number }>) { + const role = `screen:${sc.id}:${rl.n}`; + try { + prompts[role] = String(lineToRecord(e, role, { red, names: names as Record<string, string> }).prompt); + } catch { + // a line with nothing left to say: no prompt + } + } + } + return Response.json({ ok: true, prompts }, { 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 }); + } 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). const e = postsOf(m).find((x) => x.id === id); @@ -240,6 +277,15 @@ 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. + 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 }); + return Response.json({ ok: true, job: { id: j.id, state: j.state } }, { headers: noStore }); + } if (body.op === "undo") { const { result } = await withEditNotes(r.project, () => undoStructural(r.project.dir, { token })); return Response.json({ ok: true, ...result }, { headers: noStore }); @@ -414,10 +460,13 @@ async function record(request: Request) { if (!RECORD_LABEL_RE.test(label)) return Response.json({ error: `"${label}" is not a voice label (a-z, 0-9, - and _)` }, { status: 400 }); const blobs = form.getAll("part").filter((x): x is File => typeof x === "object" && x !== null && "arrayBuffer" in x); if (!blobs.length) return Response.json({ error: "nothing was recorded" }, { status: 400 }); + // ONE SCREEN LINE (the screens section's per-line Record): kept by the CLI's own command, as a umtool job. + if (form.get("line") !== null) return recordLine(r.project, e, String(form.get("line")), label, blobs[0]); const texts = form.getAll("text").map(String); const paras = form.getAll("para").map((x) => Number(x)); - const up = path.join(r.project.dir, ...takesDirOf(postIdOf(e)).split("/"), `.upload-${Date.now()}`); - await mkdir(up, { recursive: true }); + const takesDir = path.join(r.project.dir, ...takesDirOf(postIdOf(e)).split("/")); + await mkdir(takesDir, { recursive: true }); + const up = await mkdtemp(path.join(takesDir, ".upload-")); try { const parts = []; for (const [k, b] of blobs.entries()) { @@ -439,3 +488,55 @@ async function record(request: Request) { await rm(up, { recursive: true, force: true }); } } + +/** The umtool CLI (bin/umtool.mjs). */ +const cliPath = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); +/** 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}`]; + +/** A screens job as the bench reads it: its state, the CLI's result (its last word), and -- ended -- the entry. */ +async function screenJobView(dir: string, id: string, j: Job) { + const result = [...j.events].reverse().find((x) => x.ev === "result") ?? null; + const said = j.log.filter((l) => !l.startsWith("**") && !l.startsWith("$ ") && !l.startsWith("---")); + const ended = j.state !== "running"; + let entry: Entry | null = null; + let token: string | null = null; + if (ended) { + const m = (await readManifest(dir)) as Record<string, unknown> | null; + entry = m ? postsOf(m).find((x) => x.id === id) ?? null : null; + token = await manifestToken(dir); + } + const err = j.state === "failed" ? String((result as { error?: string } | null)?.error ?? said.at(-1) ?? j.error ?? "failed") : null; + return { ok: true, state: j.state, result, error: err, message: said.at(-1) ?? null, ...(ended ? { entry, token } : {}) }; +} + +/** + * ONE SCREEN LINE RECORDED (lib/report/screenLineRecord.mjs): the upload kept in a scratch dir beside the post's takes, + * `umtool posts screen <p> <item> record <id> <n> --recording <it> --events` run as a umtool job, the scratch dir + * removed when the job ends (whatever its state). + */ +async function recordLine(project: { id: string; dir: string }, e: Entry, role: string, label: string, blob: File) { + const m = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/.exec(role); + if (!m) return Response.json({ error: "line must be screen:<id>:<n>" }, { status: 400 }); + if (blob.size > 200 * 1024 * 1024) return Response.json({ error: "the recording is larger than 200 MB" }, { status: 413 }); + const running = runningJob(); + if (running) return Response.json({ error: `umtool is running another job (${running.kind}): keep it when that is done`, busy: true }, { status: 409 }); + // A scratch dir of its own (mkdtemp: unique, never another upload's). + const takesDir = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/")); + await mkdir(takesDir, { recursive: true }); + const up = await mkdtemp(path.join(takesDir, ".line-upload-")); + const own = /\.(wav|mp3|m4a|aac|ogg|opus|flac|webm)$/i.exec(typeof blob.name === "string" ? blob.name : "")?.[1]?.toLowerCase(); + const file = path.join(up, `line.${own ?? (/ogg/.test(blob.type) ? "ogg" : /wav/.test(blob.type) ? "wav" : "webm")}`); + await writeFile(file, new Uint8Array(await blob.arrayBuffer())); + try { + const j = startUmtoolJob(screenJobKinds(project.id, e.id)[0], [{ + label: `${e.id}: line ${m[2]} of screen ${m[1]} recorded, cleaned, converted (none picked)`, + argv: [process.execPath, cliPath(), "posts", "screen", project.id, e.id, "record", m[1], m[2], "--recording", file, "--label", label, "--events"], + cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000, ndjson: true, + }], { project: project.id, onEnd: () => rm(up, { recursive: true, force: true }) }); + return Response.json({ ok: true, job: { id: j.id, state: j.state } }, { headers: noStore }); + } catch (err) { + await rm(up, { recursive: true, force: true }); + return fail(err); + } +} diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -12,6 +12,7 @@ import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import PostThreadPanel from "./PostThreadPanel"; import PostScreensPanel from "./PostScreensPanel"; +import { playableEntry } from "umtool-report-to-video/post-thread"; import BlurBoxPad, { type Band } from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; import PostComboPanel from "./PostComboPanel"; @@ -142,7 +143,8 @@ export default function PostBench({ : savedScene, [entry, savedScene], ); - const shown = useMemo(() => panelEntry(sceneEntry(entry, scene), render) as Entry, [entry, scene, render]); + // What plays: never a read the build refuses (post-thread.mjs playableEntry) -- the item silent, the reason said. + const shown = useMemo(() => playableEntry(panelEntry(sceneEntry(entry, scene), render)) as Entry, [entry, scene, render]); const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, scene: conversation, mediaScene: conversation ? null : scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene, conversation]); // Its progress bar (post-progress.mjs): the read's span and its parts' ticks. const progressP = useMemo(() => progressPlan(shown, render, plan as never), [shown, render, plan]); @@ -431,7 +433,17 @@ 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)} /> - <PostScreensPanel project={project} entry={entry} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> + <PostScreensPanel + project={project} + entry={entry} + saved={saved} + setEntry={(f) => setEntry((e) => f(e) as Entry)} + onEntry={(e, t) => { + setEntry(e as Entry); + setSaved(e as Entry); + setToken(t); + }} + /> <PostNarrationPanel project={project} entry={entry} diff --git a/umtool/components/projects/PostScreensPanel.tsx b/umtool/components/projects/PostScreensPanel.tsx @@ -1,10 +1,12 @@ "use client"; import { useMemo, useRef, useState } from "react"; -import { SCREEN_KINDS, lineOfText, screenReadLines, screenWarnings, shapeSpans, validateScreens, withoutLines } from "umtool-report-to-video/post-screens"; +import { SCREEN_KINDS, lineOfText, screenFromRead, screenReadLines, screenWarnings, shapeSpans, validateScreens, withoutLines } from "umtool-report-to-video/post-screens"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; -import { partRoles, threadReadErrors } from "umtool-report-to-video/post-thread"; +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"; // --------------------------------------------------------------------------- // A POST's SCREENS ON THE BENCH (report-to-video/post-screens.mjs; docs/report-video.md, "Screens"; operator, 12 Nov: @@ -13,12 +15,19 @@ import { postFileUrl } from "./review/PostItemPlayer"; // email, a post, text), its lines transcribed by hand (pasted as `who: words | time`), who says each and on which side, // which lines are read (a line's excerpt trimmed to the words read), and whether a person checked the transcription. // No model: everything here is typed. The bench's Save writes it (updatePostItem's `screens`); the read is made with -// `umtool posts screen <p> <item> read` (the line shown here). +// `umtool posts screen <p> <item> read` (the line shown here, and its button). A read line may be RECORDED in the +// operator's voice (ScreenLineVoice: `posts screen … record`) and that take CHOSEN for it (`lineTakes`). // --------------------------------------------------------------------------- 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 }; +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 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 }) => { + const st = t.steps?.[0]; + return st?.op === "convert" ? `converted to ${String(st.voice ?? "a stock voice").split(":").pop()}` : st?.op === "enhance" ? "cleaned" : "recorded"; +}; type Media = { src: string; kind: string; seconds?: number }; type Entry = Record<string, unknown> & { id: string; media?: Media[]; screens?: Screen[] }; @@ -27,8 +36,15 @@ const r2 = (v: number) => Math.round(v * 100) / 100; /** The read as a list of `{ line, text? }` (all: every line not redacted; none: none). */ const readList = (sc: Screen): Array<{ line: number; text?: string }> => (sc.read === "all" ? sc.lines.map((l, i) => (l.redact ? null : { line: i })).filter((x): x is { line: number } => !!x) : sc.read === "none" ? [] : sc.read); -export default function PostScreensPanel({ project, entry, setEntry }: { project: string; entry: Entry; setEntry: (f: (e: Entry) => Entry) => void }) { +export default function PostScreensPanel({ project, entry, saved, setEntry, onEntry }: { project: string; entry: Entry; saved: Entry; setEntry: (f: (e: Entry) => Entry) => void; onEntry: (e: Entry, token: string | null) => void }) { const screens = useMemo(() => (Array.isArray(entry.screens) ? entry.screens : []), [entry.screens]); + // THE OPERATOR's VOICE for a line: one mic, one job; a line is recorded as SAVED (the draft differing: Save first). + const dirty = JSON.stringify(entry) !== JSON.stringify(saved); + const dirtyNow = useRef(dirty); + dirtyNow.current = dirty; + const voice = useScreenVoice({ project, id: entry.id, onEntry: onEntry as (e: VoiceEntry, t: string | null) => void, unsaved: () => dirtyNow.current }); + const recs = useMemo(() => lineTakesOf(entry) as LineRecs, [entry]); + const lineWarnings = useMemo(() => lineTakeWarnings(entry) as string[], [entry]); const media = Array.isArray(entry.media) ? entry.media : []; const errors = useMemo(() => validateScreens(entry) as string[], [entry]); // The build's guard on the read as it is (post-thread.mjs): a line edited, removed or moved under a read is refused @@ -51,12 +67,24 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project void _c; return { ...rest, lines: f(s.lines) }; }); - const add = () => { + const nextId = () => { const have = new Set(screens.map((s) => s.id)); let n = 1; while (have.has(`s${n}`)) n += 1; + return `s${n}`; + }; + // A PICTURE-ONLY post's read made its screen (post-screens.mjs screenFromRead: `posts screen … add --from-read`). + const pictureOnly = ownPictureOnly(entry) as boolean; + const script = typeof (entry.narration as { script?: unknown } | undefined)?.script === "string" ? String((entry.narration as { script: string }).script) : ""; + const [fromReadError, setFromReadError] = useState<string | null>(null); + const addFromRead = () => { + const made = screenFromRead(entry, { pictureOnly, id: nextId() }) as { screen?: Screen; error?: string }; + setFromReadError(made.error ?? null); + if (made.screen) setScreens((list) => [...list, made.screen as Screen]); + }; + const add = () => { const m = media[0]; - const sc: Screen = { id: `s${n}`, media: 0, kind: "dm", source: "transcribed", lines: [], read: "all", ...(m && (m.kind === "video" || m.kind === "gif") ? { at: [0, r2(Math.min(5, m.seconds ?? 5))] as [number, number] } : {}) }; + const sc: Screen = { id: nextId(), media: 0, kind: "dm", source: "transcribed", lines: [], read: "all", ...(m && (m.kind === "video" || m.kind === "gif") ? { at: [0, r2(Math.min(5, m.seconds ?? 5))] as [number, number] } : {}) }; setScreens((list) => [...list, sc]); }; if (!media.length) return null; @@ -68,7 +96,17 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project <button type="button" className="ink-link ml-auto" onClick={add} data-post-screens-add=""> Add a screen </button> + {pictureOnly && script.trim() && ( + <button type="button" className="ink-link" onClick={addFromRead} title="its script, a line per line, on its picture -- not checked" data-post-screens-from-read=""> + From its read + </button> + )} </div> + {fromReadError && ( + <p className="m-0 mb-1 text-[var(--color-bad,#e5484d)]" data-post-screens-from-read-error=""> + {fromReadError} + </p> + )} {screens.map((sc) => ( <ScreenEditor key={sc.id} @@ -81,11 +119,35 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project setScreen={(f) => setScreen(sc.id, f)} setLines={(f) => setLines(sc.id, f)} remove={() => setScreens((list) => list.filter((s) => s.id !== sc.id))} + voice={voice} + dirty={dirty} + recs={recs} /> ))} {screens.length > 0 && ( - <p className="m-0 mt-2 font-mono text-text-2" data-post-screens-read-cmd=""> - umtool posts screen {project} {entry.id} read + <div className="mt-2 flex flex-wrap items-center gap-2"> + <button type="button" className="ink-link disabled:opacity-40" disabled={dirty || voice.job?.state === "running" || !isNarrated(entry)} title={dirty ? "Save first" : "umtool posts screen … read, as a job"} onClick={() => void voice.makeRead()} data-post-screens-make-read=""> + Make the read + </button> + <span className="font-mono text-text-2" data-post-screens-read-cmd=""> + umtool posts screen {project} {entry.id} read + </span> + </div> + )} + {voice.job && ( + <p className={`m-0 mt-1 ${voice.job.state === "failed" ? "text-[var(--color-bad,#e5484d)]" : "text-text-2"}`} data-post-screens-job={voice.job.what} data-post-screens-job-state={voice.job.state}> + {voice.job.what === "line" ? `${voice.job.role}: ` : "the read: "} + {voice.job.state === "running" ? voice.job.message ?? "running…" : voice.job.state === "failed" ? voice.job.error ?? "failed" : "done"} + </p> + )} + {voice.status && ( + <p className="m-0 mt-1 text-text-2" data-post-screens-voice-status=""> + {voice.status} + </p> + )} + {voice.mic.error && ( + <p className="m-0 mt-1 text-[var(--color-bad,#e5484d)]" data-post-screens-mic-error=""> + {voice.mic.error} </p> )} {errors.length > 0 && ( @@ -102,9 +164,9 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project ))} </ul> )} - {warnings.length > 0 && ( + {warnings.length + lineWarnings.length > 0 && ( <ul className="m-0 mt-1 list-disc pl-4 text-text-2" data-post-screens-warnings=""> - {warnings.map((w, i) => ( + {[...warnings, ...lineWarnings].map((w, i) => ( <li key={i}>{w}</li> ))} </ul> @@ -114,8 +176,11 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project } function ScreenEditor({ - project, entry, sc, media, paste, setPaste, setScreen, setLines, remove, + project, entry, sc, media, paste, setPaste, setScreen, setLines, remove, voice, dirty, recs, }: { + voice: ScreenVoice; + dirty: boolean; + recs: LineRecs; project: string; entry: Entry; sc: Screen; @@ -240,6 +305,7 @@ function ScreenEditor({ <th>words (the excerpt read below, when trimmed)</th> <th className="w-20">time</th> <th className="w-14">redact</th> + <th className="w-48">your voice</th> </tr> </thead> <tbody> @@ -280,6 +346,28 @@ function ScreenEditor({ × </button> </td> + <td> + {d && !l.redact && ( + <ScreenLineVoice + role={`screen:${sc.id}:${n}`} + n={n} + voice={voice} + 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)]} + onChoose={(id) => + setScreen((s) => { + const lt = { ...(s.lineTakes ?? {}) }; + if (id) lt[String(n)] = id; + else delete lt[String(n)]; + const { lineTakes: _l, ...rest } = s; + void _l; + return Object.keys(lt).length ? { ...rest, lineTakes: lt } : rest; + }) + } + /> + )} + </td> </tr> ); })} diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx @@ -0,0 +1,188 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { useMic, ls } from "./useMic"; + +// --------------------------------------------------------------------------- +// A SCREEN LINE IN THE OPERATOR's VOICE, on the post bench's screens section (lib/report/screenLineRecord.mjs; the +// CLI's `umtool posts screen <p> <item> record <id> <n> --recording <file>`): Record / Stop / play back / Redo / Keep +// per read line -- Keep one umtool JOB (recorded, cleaned, converted to the speaker's character's stock voice, none +// picked) -- and the select that CHOOSES which take, if any, is read in the line's place (the screen's `lineTakes`, +// saved with the bench's Save: `set <id> take.<n>=`). "Make the read" is `posts screen <p> <item> read`, as a job. +// Recording is off while the draft differs from what is saved: a line is recorded as it is SAVED. +// --------------------------------------------------------------------------- + +const LABEL_KEY = "umtool.post-narration.label"; + +type Job = { id: string; what: string; role?: string; state: string; message?: string | null; error?: string | null }; +export type VoiceEntry = Record<string, unknown> & { id: string }; + +/** The section's voice: one microphone, one take at a time, one job at a time. */ +export function useScreenVoice({ project, id, onEntry, unsaved }: { project: string; id: string; onEntry: (e: VoiceEntry, token: string | null) => void; unsaved: () => boolean }) { + const mic = useMic(); + const [at, setAt] = useState<string | null>(null); + const [phase, setPhase] = useState<"idle" | "recording">("idle"); + const [takes, setTakes] = useState<Record<string, { blob: Blob; url: string }>>({}); + const [job, setJob] = useState<Job | null>(null); + const [status, setStatus] = useState<string | null>(null); + const [prompts, setPrompts] = useState<Record<string, string>>({}); + const poll = useRef<ReturnType<typeof setTimeout> | null>(null); + useEffect(() => () => { + if (poll.current) clearTimeout(poll.current); + }, []); + // What each read line says, as the read says it (the server's: its masks, the redaction, an anonymous handle's shown name). + const loadPrompts = useCallback(async () => { + const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&linePrompts=1`, { cache: "no-store" }).catch(() => null); + const j = r && r.ok ? ((await r.json().catch(() => null)) as { prompts?: Record<string, string> } | null) : null; + setPrompts(j?.prompts ?? {}); + }, [project, id]); + useEffect(() => { + void loadPrompts(); + }, [loadPrompts]); + const follow = useCallback( + (j: Job) => { + 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 }); + if (state === "running") { + poll.current = setTimeout(tick, 1500); + return; + } + // The entry as the job left it -- never over edits made meanwhile (they are kept; Save, then reload to see it). + const kept = unsaved(); + if (v.entry && !kept) onEntry(v.entry, v.token ?? null); + if (state === "done") { + if (j.what === "line" && j.role) { + setTakes((t) => { + const { [j.role as string]: gone, ...rest } = t; + if (gone) URL.revokeObjectURL(gone.url); + return rest; + }); + 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)"); + if (kept) setStatus((x) => `${x ?? ""} -- your unsaved edits are kept: Save, then reload the bench to see it`); + void loadPrompts(); + } + }; + poll.current = setTimeout(tick, 800); + }, + [project, id, onEntry, loadPrompts, unsaved], + ); + const record = async (role: string) => { + if (phase !== "idle" || job?.state === "running") return; + if (!(await mic.start())) return; + setAt(role); + setPhase("recording"); + }; + const stop = async () => { + if (phase !== "recording" || !at) return; + const blob = await mic.stop(); + setPhase("idle"); + if (!blob) return; + const role = at; + setTakes((t) => { + if (t[role]) URL.revokeObjectURL(t[role].url); + return { ...t, [role]: { blob, url: URL.createObjectURL(blob) } }; + }); + }; + const redo = (role: string) => + setTakes((t) => { + const { [role]: gone, ...rest } = t; + if (gone) URL.revokeObjectURL(gone.url); + return rest; + }); + const keep = async (role: string) => { + const t = takes[role]; + if (!t) return; + setStatus(null); + const fd = new FormData(); + fd.set("project", project); + fd.set("id", id); + fd.set("line", role); + fd.set("label", ls.get(LABEL_KEY) ?? "operator"); + fd.append("part", t.blob, `line${/ogg/.test(t.blob.type) ? ".ogg" : ".webm"}`); + const r = await fetch("/api/report/post-narration", { method: "POST", body: fd }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string }; + if (!r.ok || !j.job) { + setJob({ id: "", what: "line", role, state: "failed", error: j.error ?? `HTTP ${r.status}` }); + return; + } + follow({ id: j.job.id, what: "line", role, state: j.job.state }); + }; + 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 }) }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string }; + if (!r.ok || !j.job) { + setJob({ id: "", what: "read", state: "failed", error: j.error ?? `HTTP ${r.status}` }); + return; + } + follow({ id: j.job.id, what: "read", state: j.job.state }); + }; + return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead }; +} + +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 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 }) { + const mine = voice.at === role && voice.phase === "recording"; + const t = voice.takes[role]; + const busy = voice.job?.state === "running"; + const other = voice.phase === "recording" && voice.at !== role; + const btn = "ink-link disabled:opacity-40"; + return ( + <div className="flex flex-col gap-0.5" data-post-screen-voice={n}> + {voice.prompts[role] && ( + <span className="text-text-2" title="what you read: the line as the read says it" data-post-screen-prompt={n}> + “{voice.prompts[role]}” + </span> + )} + <div className="flex flex-wrap items-center gap-1.5"> + {!mine ? ( + <button type="button" className={btn} disabled={dirty || busy || other} title={dirty ? "Save first: a line is recorded as it is saved" : "record this line in your voice"} onClick={() => void voice.record(role)} data-post-screen-record={n}> + {t ? "Redo" : "Record"} + </button> + ) : ( + <button type="button" className={btn} onClick={() => void voice.stop()} data-post-screen-record-stop={n}> + Stop + </button> + )} + {mine && <span className="text-[var(--color-bad,#e5484d)]" data-post-screen-recording={n}>● recording</span>} + {t && !mine && ( + <> + <audio src={t.url} controls className="h-6 w-36" data-post-screen-record-playback={n} /> + <button type="button" className={btn} disabled={busy} onClick={() => voice.redo(role)} data-post-screen-record-redo={n}> + Discard + </button> + <button type="button" className={btn} disabled={busy || dirty} onClick={() => void voice.keep(role)} data-post-screen-record-keep={n}> + Keep + </button> + </> + )} + {dirty && <span className="text-text-2" data-post-screen-record-save-first={n}>save first</span>} + </div> + {options.length > 0 && ( + <label className="flex items-center gap-1"> + reads + <select value={chosen ?? ""} onChange={(e) => onChoose(e.target.value || undefined)} data-post-screen-line-take={n}> + <option value="">synthesized</option> + {options.map((o) => ( + <option key={o.id} value={o.id}> + {o.label} + {o.current ? "" : " (line changed since)"} + </option> + ))} + </select> + </label> + )} + </div> + ); +} diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -5,7 +5,8 @@ import { POST_ENTER_FADE, POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes import { applyJoinState, endMediaOf, joinClockOf, joinEase, joinFrameAt } from "umtool-report-to-video/post-join"; import { applyVisitState } from "umtool-report-to-video/post-link-visit"; import { applyMapState, mapHtml, mapPlace, mapSize } from "umtool-report-to-video/post-branch-map"; -import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; +import { dryGainAt, mixPhaseAt, wetGainAt } from "umtool-report-to-video/post-narration"; +import { READ_REFUSED_REASON, itemReadRefusals, playableTake } from "umtool-report-to-video/post-thread"; import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow"; import { scrollAt, showOpacityAt } from "umtool-report-to-video/post-thread"; import { blurCqw, blurOf, labelBoxOf, pixelGrid } from "umtool-report-to-video/post-censor"; @@ -220,7 +221,7 @@ export function postItemAssets({ project, take = null, entry, plan, box, publish if (postLayout(entry, box).mode === "stack") docs.push(page(entry.id, "media")); if (joinFrom && (plan.follow?.join?.seconds ?? 0) > 0) docs.push(page(joinFrom.entry.id, "read")); const files: string[] = []; - const voice = plan.narration ? (pickedTake(entry) as { file?: string } | null) : null; + const voice = plan.narration ? (playableTake(entry) as { file?: string } | null) : null; if (voice?.file) files.push(takeFileUrl(project, voice.file)); for (const st of plan.steps) { for (const m of st.items) { @@ -629,9 +630,16 @@ export default function PostItemPlayer({ }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); + // NEVER A READ THE BUILD REFUSES (post-thread.mjs playableEntry; itemReadRefusals for an entry handed in as written): + // the item plays silent and says why. + const readRefused = useMemo(() => { + const own = (entry as { readRefused?: { reason: string } }).readRefused; + if (own) return own; + return (itemReadRefusals(entry) as string[]).length ? { reason: READ_REFUSED_REASON as string } : null; + }, [entry]); // Narrated (post-narration.mjs): the picked take on the item's clock, from `at`. - const mix = plan.narration ?? null; - const voiceTake = useMemo(() => (mix ? pickedTake(entry) : null), [mix, entry]); + const mix = readRefused ? null : plan.narration ?? null; + const voiceTake = useMemo(() => (mix ? playableTake(entry) : null), [mix, entry]); const voice = useRef<HTMLAudioElement | null>(null); const local = mix ? s - mix.at : -1; const speaking = !!mix && local >= 0 && local < mix.seconds; @@ -671,7 +679,7 @@ export default function PostItemPlayer({ const [ahead] = useState(() => { const here = (u: string) => postPreload.urlOf(u) !== u; if (postPreload.docOf(pageUrl("read")) === null) return false; - const take = plan.narration ? (pickedTake(entry) as { file?: string } | null) : null; + const take = plan.narration ? (playableTake(entry) as { file?: string } | null) : null; if (take?.file && !here(takeFileUrl(project, take.file))) return false; return (plan.steps[0]?.items ?? []).every((m) => here(postFileUrl(project, String(m.src)))); }); @@ -1199,8 +1207,14 @@ export default function PostItemPlayer({ data-post-scene={scene ? scene.key : undefined} data-post-scene-n={scene ? `${scene.n + 1}/${scene.of}` : undefined} data-post-thread-tiles={followNow?.tiles ? Object.entries(followNow.tiles).map(([sc, v]) => `${sc}=${v[0]}/${v[1]}`).join(" ") : undefined} + data-post-read-refused={readRefused ? "1" : undefined} className="pointer-events-none absolute inset-0 overflow-hidden" > + {readRefused && ( + <div className="absolute left-2 top-2 z-20 max-w-[70%] rounded bg-black/80 px-2 py-1 text-[11px] text-[var(--color-bad,#e5484d)]" data-post-read-refused-reason=""> + {readRefused.reason} + </div> + )} {mix && voiceTake && ( // eslint-disable-next-line jsx-a11y/media-has-caption <audio ref={voice} src={fileOf(takeFileUrl(project, voiceTake.file))} preload="auto" muted={!voiceOn} data-post-narration-audio={voiceTake.file} data-post-narration-rate={String(speed * readRate)} /> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -132,7 +132,7 @@ 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 …` (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>]`; 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 [--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). 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 [--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 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; `--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 | @@ -366,7 +366,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `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] [--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 [<screen>] [key=value…] [--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 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 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 @@ -1852,7 +1852,10 @@ lint says so. Nothing in a screen is drawn that is not read, unless `unread: "di | `unread` -- the lines not read: `"omit"` (default: left out, a "⋯" row where they were) or `"dim"` (drawn dim, never lit) | **lines not read** | `… set s1 unread=dim` | same | | `title` (the header's word in place of the kind's), `ref` (a screenshot of a post: the archived post it pictures) | **title** | `… set s1 title="Refund email"` · `ref=<channel>/<postId>` | same | | `checked: { by, at }` -- the transcription read against the screenshot (a screen not checked is a lint WARNING; new words take it away) | **checked** | `… check s1 [--by <name>]` · `--undo` | same | -| THE READ -- her words, then each read line in its speaker's voice; her own line from the take that plays (never made again); a line from an existing take | the command shown under the screens | `umtool posts screen <p> <item> read [--post-take n] [--line-take screen:s1:3=4]… [--dry-run]` (= `posts narrate <p> <item> --take --thread`, `--no-screens` leaves them out) | — | +| THE READ -- her words, then each read line in its speaker's voice; her own line from the take that plays (never made again); a line from an existing take; a line's CHOSEN take in its place | **Make the read** (a job), the command shown beside it | `umtool posts screen <p> <item> read [--post-take n] [--line-take screen:s1:3=4]… [--dry-run]` (= `posts narrate <p> <item> --take --thread`, `--no-screens` leaves them out) | `POST /api/report/post-narration {project, op: "screen-read", id}` (a job; `GET ?project&id&screenJob=<job>`) | +| a screen from a PICTURE-ONLY post's read -- its `narration.script` a line per line, on its picture, read whole, not checked | **From its read** (a picture-only post with a script) | `umtool posts screen <p> <item> add --from-read [--media i] [--kind text] [--id] [--title]` | same as `screens[]` | +| A LINE IN YOUR VOICE -- the line as the read says it recorded, cleaned, converted to its speaker's character's stock voice, each a new take with `screenLine`, none picked ([report-video.md](report-video.md#a-line-in-your-own-voice)) | each read line's **Record** / **Stop** / play back / **Discard** / **Keep** (a job; off while the draft is unsaved) | `umtool posts screen <p> <item> record s1 2 --recording my-read.wav [--as <the speaker's character>] [--no-clean] [--no-trim] [--no-convert] [--pitch …] [--semitones n] [--label l]` · `--check-words` (the editor's transcribe op: refused on a number -- in digits or words --, a handle, an anonymous author's name or a redacted term heard; the take keeps what was heard; CLI only. Without it nothing hears the recording: the lint warns, the bench says "not heard") | `POST /api/report/post-narration` multipart `{project, id, line: "screen:s1:2", label?, part}` (a job) | +| `lineTakes` -- `{ "<n>": "<take id>" }`, the take CHOSEN to be read in line n's place (a recording that says that line as it is now: its screen, words and speaker; a removed line above it moves the key); none: synthesized | each read line's **reads** select, each recording marked heard / not heard (saved with Save) | `… set s1 take.2=5` (`take.2=off`) | `POST /api/report/post-item {op: "set", patch: {screens}}` | What is never drawn nor said, marked or not -- in a line, a speaker, a time or a title: an e-mail address, a phone-style run of nine digits or more or a local number, an order / confirmation / tracking / account / card / code value, a diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1578,11 +1578,82 @@ build refused up front (`screenDrawErrors`, in the enforced lint; again in the s take does not read ("make the read"); screens on an item not narrated (not drawn: a screen is drawn and read with the item's read); a speaker blurred by the privacy rule; a screenshot of a post naming an archived one. +**A screen from a picture-only post's read** (`posts screen <p> <item> add --from-read`; the bench's **From its +read**; `post-screens.mjs linesOfRead`, `screenFromRead`). A PICTURE-ONLY post whose picture is text already has its +words typed once -- its read's script (`narration.script`). `--from-read` makes them its screen: a line per line of the +script (blank lines and Orpheus emotion tags dropped, a line past 600 characters split at its sentence ends), on its +picture (its first image; a GIF or a video visible its whole length; `--media` another), kind `text` (`--kind`), read +whole, NOT checked (the lint says so until a person reads it against the picture), `source: "read"`. A "who:" is never +parsed out of a read -- a shape or a heading would become a speaker ("Order number: 4419"); set the speakers after; +only Orpheus's own tags (`<laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp>`) are left out, any other +`<…>` is words. Refused off a picture-only post or with no script. As any screen, nothing of it is drawn until the read +reads it -- and until then the item plays its read as it was, which the build refuses while it says what the screen +masks (below). Such a screen IS the post's read: the thread read leaves his own piece out (it would say the picture's +words twice), reuses no take of it, and refuses `--post-take`. + +#### A line in your own voice + +A read line of a screen may be RECORDED by the operator (`lib/report/screenLineRecord.mjs`; `umtool posts screen <p> +<item> record <id> <n> --recording <file>`; the bench's per-line **Record**). What he reads is the line AS THE READ SAYS +IT -- its read run, its shapes left out, the redaction left out, an anonymous handle as its shown name (never the raw +line: a masked number is never on the prompt). It is kept through `posts narrate --recording`'s chain as NEW takes of the +item -- recorded (a new `take-<n>.recorded-<label>.wav`, its name CLAIMED by an exclusive create, the next number while +one is there: two recordings kept at once never share a file, and no recording is ever overwritten or renamed over -- +on every recording path, the record page's Keep too), cleaned, converted to the line's SPEAKER's character's STOCK voice +(the author's own lines her character; anyone else the character holding their handle, this video's first then the +cast's; never the narrator; none: kept as recorded, and said; `--as` may name that character and no other) -- each +carrying `screenLine: { screen, n, said, speaker, heard? }`, NONE of them picked, the item's script untouched. Its script is the line's +words as the read says them (the lexicon's spellings in), so the read holds it to the line (`lineTakeProblem`). It is +refused on an item with no read of its own (a line is read inside one). + +A line take is read ONLY WHEN CHOSEN -- nothing is said that the operator did not choose: the screen's `lineTakes` +(`{ "<n>": "<take id>" }`: the bench's per-line select, saved with Save; `posts screen … set <id> take.<n>=<take>|off`) +or `--line-take`. A take is a line's by its CONTENT -- its screen, its words as a read writes them, its speaker -- not by +the index it was recorded at: a line removed above it moves the choice's key and the take still says its line; a take +whose words or speaker are not the line's as it is now is refused. `read` without a choice synthesizes the line and NAMES the recordings nobody chose; the lint warns of +them too, of a chosen take recorded for the line as it was, and of a picked read that does not play its chosen take. +REFUSED: a line take picked as the item's read (the writer), used as `--post-take`, chosen for or named as another line, +read after its line's words or speaker changed (record it again), or deleted while chosen (unchoose it first); a line +removed takes its choice with it. Its disclosure in the read: "a recorded reading converted to a stock voice (engine · +voice)", or "a recorded reading". `--check-words` (opt-in, the CLI only; the editor's transcribe op): the recording is +transcribed before anything is kept and REFUSED when it is heard saying a shape or a number in words ("five five five +two oh one…"), an @handle, an anonymous author's handle or display name (bare, possessive, or spaced: "secret kid"), or a +redacted term; other words are a warning (the transcription may mishear); the take keeps what it was heard saying and +against which words (`screenLine.heard`). WHAT IS VERIFIED: without `--check-words`, NOTHING hears the recording -- the +read holds the take's script (the line's own words, typed) to the line, which is the line compared with itself; the +lint WARNS for every chosen take not heard ("was not heard -- nothing verified what the recording says") and the bench +marks each recording "heard" or "not heard". What is always checked: the prompt never shows what the card masks, the +take is the line's (its screen, words and speaker as they are now), and it is never the item's read. + +On the bench, Record and Make the read are off while the draft differs from what is saved (a line is recorded as it is +saved); Keep and Make the read are each ONE umtool job (`posts screen … record`, `posts screen … read`; the upload in a +scratch dir of its own, mkdtemp), followed on the page; a job's result never replaces edits made meanwhile. + +**No preview plays a read the build refuses** (post-thread.mjs `playableEntry`, the enforced lint's own judgement on the +item as written: `itemReadRefusals`). The writer lets a screen change under its read -- a line's words or speaker +edited, a line removed, redacted or no longer read -- and the build refuses the old read; so do Play, Present (the +public payload too), the card page and the post bench's player: the item plays SILENT, as an item not narrated, no take +of it in the payload, saying why ("the read is older than its screen … make the read again"). One verdict everywhere: +the item AS WRITTEN is judged (the card page too, before its anonymity pass: `playableAsWritten`), and every player, +preview and payload reads an item's take through one accessor, `playableTake` (a source test lists the files and +refuses a direct picked-take read in them). **No part of a read may +say what the item's screens hide** (`readSaysHiddenErrors`, in the enforced lint): his words, a context post, a screen +line or a take with no parts that says a number (four digits or more, however joined) or an e-mail one of the item's +screens masks, or three or more words of a line marked `redact`, refuses the read -- naming the part and the line, never +the value. (The project's own redaction terms are a read's to leave out -- spokenRead -- and an anonymous handle the +anonymity lint's.) Present's PUBLIC payload carries the screens AS THE CARD DRAWS THEM, built from the card's own drawing +(`publicScreens`: post-thread.mjs `drawnScreens`, post-screens.mjs `screenRows` and `screenHeader`, post-item.mjs +`screenSpeakerShown`) -- only the screens the card draws, each as its rows: a read line's read run alone, masked, "…" +where it is cut; a line not read absent (a `{ gap }` row where the card draws "⋯"), or dim when the card draws it dim; +a redacted line never; a speaker the card blurs nameless; no `lines`, no `read` -- never a raw line. + **Byte-identical without.** An item with no `screens` draws, plans and keys exactly as before -(`post-screens-pin.test.mjs`); a segment with screens carries `screens: POST_SCREEN_DRAW_V` in its key. +(`post-screens-pin.test.mjs`); a segment with screens carries `screens: POST_SCREEN_DRAW_V` in its key. An item with +round-1 screens and none of `lineTakes` / `screenLine` draws, plans, keys, validates, guards and lints as before -- its +enforced lint, thread-read warnings and new-read plan too (`post-screens-pin2.test.mjs`). The knobs: [knobs.md](knobs.md#screens-a-posts-text-screenshots); the CLI: `umtool posts screen <p> <item> -list|add|set|rm|check|read` ([cli.md](cli.md)); the post bench's **screens** section. +list|add|set|rm|check|read|record` ([cli.md](cli.md)); the post bench's **screens** section. ### The combo counter diff --git a/umtool/e2e/post-screens.spec.ts b/umtool/e2e/post-screens.spec.ts @@ -1,5 +1,6 @@ import { test, expect, type Page } from "@playwright/test"; -import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; @@ -10,7 +11,11 @@ import * as urls from "./urls"; // - the bench's screens section adds a screen in the post's video, takes pasted lines, a line not read, an excerpt, // the transcription checked -- saved by the bench's Save through the item's one writer, no model anywhere; // - a narrated item whose read reads the screen draws it on the card after its words: typeset, its line being read -// lit, "· transcribed" in its header and on the card's badge while it is up. +// lit, "· transcribed" in its header and on the card's badge while it is up; +// - a read line RECORDED in the operator's voice (lane/screens-2; the fake microphone's tone, never a real voice): +// Record / Stop / play back / Keep (one job: recorded, then converted by the stub editor to the speaker's +// character's stock voice -- none picked), the take CHOSEN for the line in its select and saved, then "Make the +// read" (one job): the read plays the chosen take in the line's place. Recording is off while the draft is unsaved. // Fixture: e2e/fixtures/post-narration-fixture.mjs's p-11 (a 4 s video, a 2 s take), rewritten here. // // POST_SCREENS_SHOTS=<dir> screenshots there @@ -23,21 +28,37 @@ const MANIFEST = path.join(DIR, "video.manifest.json"); const PROJECT = "reports/post-narration-fixture"; const SHOTS = process.env.POST_SCREENS_SHOTS ?? null; +/** The fake microphone's voice: a 1 kHz tone, two seconds (never a real recording). */ +const MIC_WAV = path.join(HERE, "..", ".e2e-song", "post-screens-mic.wav"); +const CHARACTERS = path.join(DIR, "narration", "characters.json"); +if (!existsSync(MIC_WAV)) { + mkdirSync(path.dirname(MIC_WAV), { recursive: true }); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]); +} +test.use({ launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${MIC_WAV}`, "--autoplay-policy=no-user-gesture-required"] } }); + type Line = { who?: string; side?: string; text: string; time?: string; redact?: boolean }; type Screen = { id: string; media: number; at?: number[]; kind: string; lines: Line[]; read: unknown; checked?: { by: string } }; const item = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; screens?: Screen[] }> }).timeline.find((e) => e.id === id); test.beforeAll(() => { if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); + if (existsSync(CHARACTERS) && !existsSync(`${CHARACTERS}.pristine`)) copyFileSync(CHARACTERS, `${CHARACTERS}.pristine`); }); +const restoreCharacters = () => { + if (existsSync(`${CHARACTERS}.pristine`)) copyFileSync(`${CHARACTERS}.pristine`, CHARACTERS); + else rmSync(CHARACTERS, { force: true }); +}; test.beforeEach(() => { test.setTimeout(120_000); copyFileSync(`${MANIFEST}.pristine`, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); + restoreCharacters(); }); test.afterAll(() => { if (existsSync(`${MANIFEST}.pristine`)) copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + restoreCharacters(); }); const panel = (page: Page) => page.locator("[data-post-screens-panel]"); @@ -119,3 +140,88 @@ test("a read that reads the screen draws it on the card after its words: typeset await expect(frame.locator('[data-screen-line="0"] .sname')).toHaveText("TheQuartering"); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-card.png") }); }); + +type Take = { file: string; engine?: string; voice?: string; script?: string; steps?: Array<{ op: string; voice?: string }>; screenLine?: { screen: string; n: number; said: string; speaker: string }; parts?: Array<{ role?: string; take?: string }> }; +type Narr = { pick?: number; script?: string; takes: Take[] }; +const narrOf = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; narration: Narr; screens?: Array<Screen & { lineTakes?: Record<string, string> }> }> }).timeline.find((e) => e.id === id)!; +const idOf = (t: Take) => t.file.split("/").pop()!.replace(/\.wav$/, ""); + +test("a read line in your own voice: Record / Stop / Keep (one job, none picked), the take chosen for the line and saved, Make the read plays it in the line's place", async ({ page }) => { + test.setTimeout(180_000); + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const e = m.timeline.find((x: { id: string }) => x.id === "p-11"); + e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "hop on the scale fatso call 555 201 4477" }, { who: "narrsubject", text: "you first" }] }]; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + // TheQuartering's character in this video: a stock voice to convert to. + mkdirSync(path.dirname(CHARACTERS), { recursive: true }); + writeFileSync(CHARACTERS, JSON.stringify({ format: "umtool-project-characters", version: 1, characters: [{ id: "tq", name: "Jeremy", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:am_michael" } } }] })); + const before = narrOf("p-11").narration; + await page.setViewportSize({ width: 1366, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const sc = page.locator('[data-post-screen="s1"]'); + await expect(sc).toBeVisible({ timeout: 15_000 }); + // What you read: the line as the read says it -- the number masked out. + await expect(sc.locator('[data-post-screen-prompt="0"]')).toContainText("hop on the scale fatso call"); + await expect(sc.locator('[data-post-screen-prompt="0"]')).not.toContainText("555"); + // Unsaved: recording is off (a line is recorded as it is saved). + await sc.locator('[data-post-screen-time="1"]').fill("12:19 PM"); + await expect(sc.locator('[data-post-screen-record="0"]')).toBeDisabled(); + await expect(sc.locator('[data-post-screen-record-save-first="0"]')).toBeVisible(); + await sc.locator('[data-post-screen-time="1"]').fill(""); + await expect(sc.locator('[data-post-screen-record="0"]')).toBeEnabled(); + // Record, Stop, play back, Keep. + await sc.locator('[data-post-screen-record="0"]').click(); + await expect(sc.locator('[data-post-screen-recording="0"]')).toBeVisible(); + await page.waitForTimeout(1200); + await sc.locator('[data-post-screen-record-stop="0"]').click(); + await expect(sc.locator('[data-post-screen-record-playback="0"]')).toHaveCount(1); + await sc.locator('[data-post-screen-record-keep="0"]').click(); + await expect(panel(page).locator('[data-post-screens-job="line"]')).toHaveAttribute("data-post-screens-job-state", "done", { timeout: 90_000 }); + const n1 = narrOf("p-11").narration; + const made = n1.takes.slice(before.takes.length); + expect(made.length).toBeGreaterThanOrEqual(2); + expect(made.every((t) => t.screenLine?.screen === "s1" && t.screenLine?.n === 0 && t.screenLine?.speaker === "TheQuartering")).toBe(true); + expect(made.every((t) => !/555|4477/.test(String(t.script)))).toBe(true); + expect(made.at(-1)!.steps?.[0]?.op).toBe("convert"); + expect(n1.pick ?? 0).toBe(before.pick ?? 0); + await expect(panel(page).locator("[data-post-screens-voice-status]")).toContainText("none picked"); + // Not chosen: the lint says so; choose the converted take, Save. + await expect(panel(page).locator("[data-post-screens-warnings]")).toContainText("has a recording no read uses"); + const converted = idOf(made.at(-1)!); + await sc.locator('[data-post-screen-line-take="0"]').selectOption(converted); + await page.locator("[data-post-bench-save]").click(); + await expect.poll(() => narrOf("p-11").screens?.[0]?.lineTakes?.["0"] ?? null).toBe(converted); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-voice.png"), fullPage: true }); + // Make the read: the chosen take in the line's place, the rest synthesized (the stub editor's tts). + await panel(page).locator("[data-post-screens-make-read]").click(); + await expect(panel(page).locator('[data-post-screens-job="read"]')).toHaveAttribute("data-post-screens-job-state", "done", { timeout: 120_000 }); + const n2 = narrOf("p-11").narration; + const playing = n2.takes[n2.pick ?? 0]; + expect(playing.parts?.find((p) => p.role === "screen:s1:0")?.take).toBe(converted); + expect(playing.parts?.some((p) => p.role === "screen:s1:1" && !p.take)).toBe(true); +}); + +test("a read older than its screen is not played on the bench: the item plays silent and says why (review round 1, M1)", async ({ page }) => { + // Its read reads the screen's two lines; then line 0's words are edited under it (the writer takes it). + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const e = m.timeline.find((x: { id: string }) => x.id === "p-11"); + e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "call me at 555 201 4477 fatso" }, { who: "narrsubject", text: "you first" }] }]; + e.narration.script = "The video speaks for itself."; + e.narration.takes[0].parts = [ + { n: 1, para: 0, text: "The video speaks for itself.", start: 0, seconds: 0.6, role: "post" }, + { n: 2, para: 100, text: "hop on the scale fatso", start: 0.8, seconds: 0.5, role: "screen:s1:0", line: "hop on the scale fatso", speaker: "TheQuartering" }, + { n: 3, para: 200, text: "you first", start: 1.5, seconds: 0.5, role: "screen:s1:1", line: "you first", speaker: "narrsubject" }, + ]; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + await page.setViewportSize({ width: 1366, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const player = page.locator('[data-post-play="p-11"]').first(); + await expect(player).toHaveAttribute("data-post-read-refused", "1", { timeout: 15_000 }); + await expect(player.locator("[data-post-read-refused-reason]")).toContainText("make the read again"); + await expect(player).not.toHaveAttribute("data-post-narrated", "1"); + await expect(player.locator("[data-post-narration-audio]")).toHaveCount(0); + // The card page draws no screen (no read reads it) and never the old lit lines. + const frame = page.frameLocator('[data-post-card-frame="read"]'); + await expect(frame.locator("body")).toHaveAttribute("data-post-ready", "1", { timeout: 15_000 }); + await expect(frame.locator('[data-post-screen="s1"]')).toHaveCount(0); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -1009,7 +1009,8 @@ export const GROUPS = [ " `umtool timeline <p> --take <take> undo`), the project's manifest untouched; set-item/roles/reread/fx", " take --take <take> for it too (narrate's --take is a new read)", " umtool posts screen <project> <item> list | add --media <i> [--at a,b] --kind dm|email|post|text [--from <file>] [--line …]…", - " | set <id> <key>=<value>… | rm <id> | check <id> [--by n] [--undo] | read [--post-take n] [--line-take r=n]…", + " | add --from-read | set <id> <key>=<value>… | rm <id> | check <id> [--by n] [--undo] | read [--post-take n] [--line-take r=n]…", + " | record <id> <line> --recording <file> [--as c] [--no-clean] [--no-convert] [--check-words]", " a post's SCREENS: its text screenshots transcribed, drawn on its card and read after its words", " umtool posts say <project> ls | add <word> \"<spoken>\" [--case] [--item <id>] | remove <word> | try \"<text>\" | stale", " the PRONUNCIATION LEXICON every synthesized read applies (stale: picked reads that say it the old way)", @@ -1045,8 +1046,8 @@ 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 …` (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>]`; 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 [--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). 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 [--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 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>…`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -507,7 +507,11 @@ function posts() { pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(), ], { ...Q, ...POST_ITEM }), p("screen", "draft", "a post item's text screenshots: transcribed, drawn, read", [ - item(), pick("op", ["list", "add", "set", "rm", "check", "read"], { required: true }), arg("screen", { required: false, help: "the screen's id (set, rm, check)" }), + item(), pick("op", ["list", "add", "set", "rm", "check", "read", "record"], { required: true }), arg("screen", { required: false, help: "the screen's id (set, rm, check, record)" }), + arg("line", { required: false, help: "record: the line's number" }), bool("--from-read", "add: a picture-only post's read made its screen"), + file("--recording", { help: "record: your read of the line (a sound file)" }), opt("--as", { help: "record: the character to convert to (default: the line's speaker's)" }), + bool("--no-clean"), bool("--no-convert"), pick("--pitch", ["target", "source", "contour"], { help: "record: a convert's pitch" }), num("--semitones", { help: "record: -12…12" }), + bool("--check-words", "record: transcribed first, refused when it says a number, a handle or a redacted term"), num("--media", { help: "add: the attachment it is in" }), opt("--at", { help: "add: <from>,<to> seconds of a video" }), pick("--kind", ["dm", "email", "post", "text"]), opt("--title"), 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"), diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -3114,7 +3114,8 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { const had = new Set(guard(was)); // A SCREEN's line the picked take reads that the screen no longer reads (post-screens.mjs) is the build's to refuse, // not this write's: the read is re-made FROM the screens (umtool posts screen <p> <item> read), so they change first. - const now = guard(e).filter((x) => !had.has(x) && !/ reads (?:line \d+ of )?screen [a-z0-9-]+,/.test(x)); + // So is a line whose words or speaker CHANGED under the read (screenLineChanged): the build refuses the old read. + const now = guard(e).filter((x) => !had.has(x) && !/ reads (?:line \d+ of )?screen [a-z0-9-]+,/.test(x) && !/: line \d+ of screen [a-z0-9-]+ changed since the read /.test(x)); if (now.length) throw new StructureRefused(now); } return { id, at: i, entry: e }; diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -17,6 +17,7 @@ import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; import { panelEntry, postDay, postItemPlan } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; +import { playableEntry } from "umtool-report-to-video/post-thread"; import { clockPlan } from "umtool-report-to-video/post-clock"; import { progressPlan } from "umtool-report-to-video/post-progress"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; @@ -67,6 +68,8 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu date: day || null, quote: words || null, post: panelEntry(sceneEntry(e, mediaScene), render), + // Its read, NOT played (post-thread.mjs playableEntry): why -- Play and Present say so. + ...(e.readRefused ? { readRefused: e.readRefused } : {}), // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: the // posts its run left on screen (post-conversation.mjs: one conversation played as one scene) -- it wins the card. postPlan: plan, @@ -199,7 +202,11 @@ export async function playViewWith(project, { take = null, bare = false, postFor : { combos: {}, groups: [] }; const entries = await Promise.all( timeline.map(async (e, i) => { - if (e.type === "post") return postPlayEntry(post ? post(e) : e, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, render)); + // Never a read the build refuses (post-thread.mjs playableEntry, judged on the item as written): it plays silent. + if (e.type === "post") { + const pe = playableEntry(e); + return postPlayEntry(post ? post(pe) : pe, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, render)); + } if (e.type === "video") return videoPlayEntry(e, D); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); diff --git a/umtool/lib/report/postBenchData.ts b/umtool/lib/report/postBenchData.ts @@ -2,6 +2,7 @@ import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; import { postItemPlan, panelEntry } from "umtool-report-to-video/post-item"; +import { playableEntry } from "umtool-report-to-video/post-thread"; import { planContext } from "umtool-report-to-video/post-conversation"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; @@ -71,7 +72,8 @@ export async function postBenchData(dir: string, id: string): Promise<PostBenchD entry, token, box: { width: box.width, height: box.height }, - plan: postItemPlan(panelEntry(sceneEntry(entry, scene), render), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan, + // Never a read the build refuses (post-thread.mjs playableEntry): planned as the bench's player plays it. + plan: postItemPlan(playableEntry(panelEntry(sceneEntry(entry, scene), render)), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan, scene, render, before: ctx.prev, diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -37,6 +37,7 @@ import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs"; const execFileP = promisify(execFile); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; @@ -947,8 +948,10 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}), // Its audio is its source's words at its source's speed: what it said and where that speed came from, copied. ...(typeof t.speed === "number" ? { speed: t.speed } : {}), ...(t.speedAsked !== undefined ? { speedAsked: t.speedAsked } : {}), ...(typeof t.said === "string" ? { said: t.said } : {}), + // A recording of a screen line stays that line's (and, as it, never picked). + ...(isObj(t.screenLine) ? { screenLine: { ...t.screenLine } } : {}), }; - const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take, ...(isObj(t.screenLine) ? { keepPick: true } : {}) }, { token: await manifestToken(project.dir) })); return { take, result }; } @@ -969,7 +972,7 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = * kept either side), `pitch` / `semitones`. Each step a new take, the last one picked, with the disclosure line the * cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, direction }`. */ -export async function importRecording(project, e0, file, { as = null, label = "operator", clean = undefined, convert = true, trim = undefined, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null } = {}) { +export async function importRecording(project, e0, file, { as = null, label = "operator", clean = undefined, convert = true, trim = undefined, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null, screenLine = null, script = null, character: given = undefined } = {}) { const abs = path.resolve(String(file ?? "")); if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`); const { keepRecording } = await import("./postRecord.mjs"); @@ -977,16 +980,20 @@ export async function importRecording(project, e0, file, { as = null, label = "o const { convertPitchLabel, recordedPresetOf, shownNameOf } = await import("umtool-report-to-video/cast"); const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration"); const layers = await readLayers(project.dir); - const who = layers.characterForRead(e0, as); + // A SCREEN LINE's recording (screenLineRecord.mjs) is made into its SPEAKER's character, which the caller found + // (`character`: null -- none, kept as recorded); a read of the item into the item's (characterForRead). + const who = given !== undefined ? (given ? { character: given, layer: "line" } : null) : layers.characterForRead(e0, as); const character = who?.character ?? null; - if (as && !character) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`); + if (as && !character && given === undefined) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`); const preset = character ? recordedPresetOf(character) : null; const doClean = clean ?? preset?.enhance ?? true; const doTrim = trim ?? (preset ? preset.trim : undefined); const notes = []; const takes = []; const fresh = async () => findPostItem(await readManifest(project.dir), e0.id); - const kept = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${shownNameOf(character)}` : ""}`, ...(doTrim ? { trim: doTrim } : {}) }); + const kept = screenLine + ? await keepRecording(project, e0, [{ file: abs, text: String(script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `line ${screenLine.n} of screen ${screenLine.screen} recorded${character ? ` for ${shownNameOf(character)}` : ""}`, script: String(script ?? ""), screenLine, ...(doTrim ? { trim: doTrim } : {}) }) + : await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${shownNameOf(character)}` : ""}`, ...(doTrim ? { trim: doTrim } : {}) }); takes.push({ step: "recorded", file: kept.take.file }); emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB${doTrim?.on === false ? ", its edges not trimmed" : ""})` }); let e = await fresh(); @@ -1005,7 +1012,8 @@ export async function importRecording(project, e0, file, { as = null, label = "o } else if (clean === undefined) notes.push(`not cleaned: ${character.id}'s recorded preset says so (enhance off)`); if (convert) { const target = character ? preset.convert : null; - if (!character) notes.push("not converted: no character to convert to (--as <character>, the item's own, or the post's author or a narrator in the cast: umtool cast add …)"); + if (!character && screenLine) notes.push(`not converted: line ${screenLine.n}'s speaker has no character to convert to -- kept as recorded (umtool cast add … --handle <the speaker's handle>, or --as <character>)`); + else if (!character) notes.push("not converted: no character to convert to (--as <character>, the item's own, or the post's author or a narrator in the cast: umtool cast add …)"); else if (!target.voice) notes.push(`not converted: ${character.id} has no stock voice to convert to (umtool cast ${who.layer === "cast" || who.layer === "narrator" ? "" : `project ${project.id} `}set ${character.id} --convert-voice <engine:voice>)`); else { // The pitch asked for this read, else the character's; semitones asked of the target's own pitch are dropped @@ -1022,8 +1030,11 @@ export async function importRecording(project, e0, file, { as = null, label = "o } } } + // A line's: none picked; its disclosure the one its line will carry in the read (a recorded reading, converted or not). + const conv = screenLine ? (e?.narration?.takes ?? []).find((t) => t.file === takes.at(-1).file)?.steps?.find((st) => st?.op === "convert") : null; return { - takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null, + takes, picked: screenLine ? null : takes.at(-1).file, notes, + disclosure: screenLine ? (conv ? `a recorded reading converted to a stock voice (${conv.engine ?? "?"} · ${conv.voice ?? "?"})` : "a recorded reading") : e ? postNarrationDisclosure(e) : null, character: character ? { id: character.id, name: shownNameOf(character), voice: character.voice ?? null, layer: who.layer } : null, ...(preset?.direction ? { direction: preset.direction } : {}), }; @@ -1043,6 +1054,9 @@ export async function deleteTake(project, e, index) { const id = takeIdOf(t); const users = takes.map((x, i) => ({ x, n: i + 1 })).filter(({ x }) => x !== t && ((Array.isArray(x?.parts) && x.parts.some((p) => p?.take === id || (p?.take && p?.file === t.file))) || (x?.source?.kind === "take" && x.source.from === id))); if (users.length) throw new NarrateError(`take ${index + 1} (${t.file}) is a part of ${users.map(({ x, n }) => `take ${n} (${x.file})`).join(", ")}: delete ${users.length === 1 ? "that take" : "those takes"} first -- nothing moved`); + // A take a screen CHOSE for one of its lines (`lineTakes`): unchosen first. + const chooser = (Array.isArray(e.screens) ? e.screens : []).flatMap((sc) => Object.entries(isObj(sc?.lineTakes) ? sc.lineTakes : {}).filter(([, v]) => v === id).map(([k]) => ({ sc: sc.id, k })))[0]; + if (chooser) throw new NarrateError(`take ${index + 1} (${t.file}) is chosen for line ${chooser.k} of screen ${chooser.sc}: unchoose it first (umtool posts screen <p> ${e.id} set ${chooser.sc} take.${chooser.k}=off) -- nothing moved`); const trash = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/"), ".trash"); await mkdir(trash, { recursive: true }); const stamp = new Date().toISOString().replace(/[:.]/g, "-"); diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -98,6 +98,58 @@ export async function decodePart(src, out) { return { seconds: r3(seconds ?? 0), silences }; } +/** + * A NEW RECORDED TAKE's NAME, CLAIMED (review round 1, b): `take-<n>.recorded-<label>.wav` created EMPTY with an + * exclusive create (`wx`), the next n tried while one is there -- so two recordings kept at once never write the same + * file, and no recording already there is ever overwritten or renamed over. `{ n, rel, abs }`; the caller writes the + * take there (a rename over its own empty claim) or, failing, gives the claim back (releaseClaim). + * + * @param {string} projectDir + * @param {Record<string, any>} entry + * @param {string} label + */ +export async function claimRecordedTake(projectDir, entry, label) { + const pid = postIdOf(entry); + const dir = path.join(projectDir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + let n = nextTakeNumber(entry, await readdir(dir).catch(() => [])); + for (let tries = 0; tries < 1000; tries += 1, n += 1) { + const rel = `${takesDirOf(pid)}/take-${n}.recorded-${label}.wav`; + const abs = path.join(projectDir, ...rel.split("/")); + try { + const fh = await open(abs, "wx"); + await fh.close(); + return { n, rel, abs }; + } catch (err) { + if (err?.code !== "EEXIST") throw err; + } + } + throw new Error(`no free take number for a recording of ${entry.id}`); +} + +/** Any take file's name claimed the same way: `makeRel(n)` for n from `n0` on, the first created exclusively. `{ n, rel, abs }`. */ +export async function claimTakeName(projectDir, makeRel, n0) { + for (let n = n0, tries = 0; tries < 1000; tries += 1, n += 1) { + const rel = makeRel(n); + const abs = path.join(projectDir, ...rel.split("/")); + await mkdir(path.dirname(abs), { recursive: true }); + try { + const fh = await open(abs, "wx"); + await fh.close(); + return { n, rel, abs }; + } catch (err) { + if (err?.code !== "EEXIST") throw err; + } + } + throw new Error("no free take number"); +} + +/** A claim given back: its file removed only while it is still the empty claim (never a recording). */ +export async function releaseClaim(abs) { + const st = await stat(abs).catch(() => null); + if (st?.isFile() && st.size === 0) await rm(abs, { force: true }); +} + /** The room kept either side of a part's words: a preset's `trim.padMs`, else the recorder's own. */ export const roomOf = (trim) => (trim && Number.isFinite(trim.padMs) ? { head: trim.padMs / 1000, tail: trim.padMs / 1000 } : RECORD_ROOM); @@ -172,20 +224,27 @@ export const partsIn = (parts, relDir) => parts.map((p) => ({ n: p.n, para: p.pa * @param {Array<{ file: string, text?: string, para?: number }>} parts * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null, trim?: { on?: boolean, padMs?: number | null } | null, spans?: Array<{ from: number, to: number } | null> | null }} [o] */ -export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null, spans = null } = {}) { +export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null, spans = null, screenLine = null } = {}) { // A character's recorded preset (cast.mjs recordedPresetOf): its edges left as recorded (`trim.on` false), or the // room kept either side of the words (`trim.padMs`); none: trimmed, RECORD_ROOM. const room = roomOf(trim); if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`); if (!parts.length) throw new Error("nothing was recorded"); const pid = postIdOf(entry); - const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); - await mkdir(dir, { recursive: true }); - const n = nextTakeNumber(entry, await readdir(dir).catch(() => [])); - const base = `take-${n}.recorded-${label}`; - const rel = `${takesDirOf(pid)}/${base}.wav`; - const partsRel = `${takesDirOf(pid)}/${base}.parts`; + // Its name CLAIMED (claimRecordedTake): never another recording's, kept at the same moment or before. + const claim = await claimRecordedTake(project.dir, entry, label); + const rel = claim.rel; + const partsRel = rel.replace(/\.wav$/, ".parts"); const partsDir = path.join(project.dir, ...partsRel.split("/")); + try { + return await keepClaimed(project, entry, parts, { label, manifest, note, script, trim, spans, screenLine, room, pid, rel, partsRel, partsDir }); + } catch (err) { + await releaseClaim(claim.abs); + throw err; + } +} + +async function keepClaimed(project, entry, parts, { label, manifest, note, script, trim, spans, screenLine, room, rel, partsRel, partsDir }) { await mkdir(partsDir, { recursive: true }); // Each part: decoded, measured, cut to its marks or trimmed of its silence at either end. const sources = []; @@ -204,9 +263,11 @@ export async function keepRecording(project, entry, parts, { label = "operator", file: rel, engine: "recorded", voice: label, label, seconds: j.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""), at: new Date().toISOString(), ...(Number.isFinite(j.lufs) ? { lufs: j.lufs } : {}), ...(note ? { note } : {}), ...(partsOut.length > 1 ? { parts: partsOut } : {}), + // A RECORDING OF ONE SCREEN LINE (screenLineRecord.mjs): the line it is of; its script the line's words. + ...(screenLine ? { screenLine } : {}), }; - const { result, editNotes } = await withEditNotes(project, async () => - updatePostNarration(project.dir, entry.id, { addTake: take, ...(script !== null && script !== entry.narration?.script ? { script } : {}) }, { token: await manifestToken(project.dir) }), - ); + // A line's recording is never the item's read: not picked, and the item's script left as it is. + const patch = screenLine ? { addTake: take, keepPick: true } : { addTake: take, ...(script !== null && script !== entry.narration?.script ? { script } : {}) }; + const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, entry.id, patch, { token: await manifestToken(project.dir) })); return { take, gain: j.gain, target, result, editNotes }; } diff --git a/umtool/lib/report/postScreensCli.mjs b/umtool/lib/report/postScreensCli.mjs @@ -6,10 +6,13 @@ // umtool posts screen <p> <item> add --media <i> [--at <from>,<to>] --kind dm|email|post|text [--id <id>] [--title "…"] // [--from <file>] [--line "who: words"]… [--read all|none|<n>,<n>…] [--unread omit|dim] // [--ref <channel>/<postId>] [--json] +// umtool posts screen <p> <item> add --from-read [--media <i>] [--kind …] [--id <id>] [--title "…"] [--json] // umtool posts screen <p> <item> set <id> <key>=<value>… [--from <file>] [--json] // umtool posts screen <p> <item> rm <id> [--json] // umtool posts screen <p> <item> check <id> [--by <name>] [--undo] [--json] // umtool posts screen <p> <item> read [--post-take <n>] [--line-take screen:<id>:<n>=<take n>]… [--force] [--dry-run] [--json] … +// umtool posts screen <p> <item> record <id> <n> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] +// [--no-convert] [--pitch …] [--semitones n] [--label l] [--check-words [--worker w]] [--events] [--json] // // Every write goes through the post item's one writer (manifest.mjs updatePostItem, `screens`: the whole list, under // the manifest's token), refused in the build's words. `read` is the thread read (postThreadRead.mjs) with the screens: @@ -22,33 +25,46 @@ // Plain ESM: the CLI runs it under bare node. import { readFile } from "node:fs/promises"; import path from "node:path"; -import { draftScript } from "umtool-report-to-video/post-narration"; +import { draftScript, takeIdOf } from "umtool-report-to-video/post-narration"; +import { chosenLineTakes, lineTakeCurrent, lineTakesOf as lineRecordingsOf } from "umtool-report-to-video/post-thread"; import { voiceOverridesOf } from "umtool-report-to-video/post-say"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostItem } from "./manifest.mjs"; -import { SCREEN_KINDS, SCREEN_SIDES, SCREEN_UNREAD, lineOfText, screenLineSaid, screenReadLines, withoutLines, screenRows, screenWarnings, screensOf, validateScreens } from "umtool-report-to-video/post-screens"; +import { ownPictureOnly } from "umtool-report-to-video/post-item"; +import { SCREEN_KINDS, SCREEN_SIDES, SCREEN_UNREAD, lineOfText, screenFromRead, screenLineSaid, screenReadLines, withoutLines, screenRows, screenWarnings, screensOf, validateScreens } from "umtool-report-to-video/post-screens"; export const SCREEN_USAGE = [ "usage: umtool posts screen <project> <item> list [--json]", " umtool posts screen <project> <item> add --media <i> [--at <from>,<to>] --kind dm|email|post|text [--id <id>] [--title \"…\"]", " [--from <file>] [--line \"who: words\"]… [--read all|none|<n>,<n>…] [--unread omit|dim] [--ref <channel>/<postId>] [--json]", + " umtool posts screen <project> <item> add --from-read [--media <i>] [--kind dm|email|post|text] [--id <id>] [--title \"…\"] [--json]", " umtool posts screen <project> <item> set <id> <key>=<value>… [--from <file>] [--json]", " 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]", + " 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),", " transcribed once, drawn on its card and read in the voices of the people in them, each line lit while it is said.", " --media: the attachment it is in (its index); --at: the seconds of a video it is visible in. --read: the lines read", " (all; none: transcribed only, not drawn); --unread: the lines not read left out (omit) or drawn dim. --from: a JSON", " screen, or text lines `[right] who: words | time` (`- words`: no speaker; `[redact] …`: never drawn nor read).", + " --from-read: a PICTURE-ONLY post's read made its screen -- its script (narration.script) a line per line, on its", + " picture (--media: another attachment), kind text (--kind), read whole, NOT checked; no speakers (set them after).", " 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", + " line.<n>.time=|off line.<n>.redact=on|off take.<n>=<take n>|off (the recording read in line n's place)", " 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.", + " (--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.", + " 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", + " (the editor's transcribe op): 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. Without it nothing hears the recording.", ].join("\n"); export class ScreenUsageError extends Error { @@ -104,7 +120,7 @@ const readOf = (v) => (v === "all" || v === "none" ? v : numList(v, "read").map( * A screen with `key=value` pairs laid on (the `set` keys, SCREEN_USAGE), pure; a copy. Throws ScreenUsageError for a * key it does not know or a value it cannot read; what the build refuses is the writer's to say. */ -export function applyPairs(screen, pairs) { +export function applyPairs(screen, pairs, { takeId = null } = {}) { const sc = JSON.parse(JSON.stringify(screen)); sc.lines = Array.isArray(sc.lines) ? sc.lines : []; const lineAt = (n) => { @@ -168,6 +184,18 @@ export function applyPairs(screen, pairs) { } else if (f === "text") l.text = v; else if (off) delete l[f]; else l[f] = v; + } else if ((m = /^take\.(\d{1,2})$/.exec(key))) { + // The take CHOSEN for a line (a recording of it): its number as --list counts, made its id; off unchooses. + const n = Number(m[1]); + lineAt(n); + const lt = isObj(sc.lineTakes) ? { ...sc.lineTakes } : {}; + if (off) delete lt[String(n)]; + else { + if (!takeId) fail(`${key}= takes a take's number (posts screen <p> <item> list shows the line's recordings)`); + lt[String(n)] = takeId(v, n); + } + if (Object.keys(lt).length) sc.lineTakes = lt; + else delete sc.lineTakes; } 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. @@ -183,13 +211,16 @@ export function nextScreenId(e) { /** One screen as listing lines (text). */ export function screenListing(e, sc) { const reads = new Map(screenReadLines(sc).map((r) => [r.n, r])); + const recordings = lineRecordingsOf(e); const m = (Array.isArray(e.media) ? e.media : [])[sc.media]; const head = `${sc.id} ${sc.kind}${sc.title ? ` "${sc.title}"` : ""} attachment ${sc.media}${m ? ` (${m.kind})` : ""}${Array.isArray(sc.at) ? ` at ${sc.at[0]}–${sc.at[1]} s` : ""} read ${sc.read === "all" ? "all" : sc.read === "none" ? "none (transcribed only)" : `${reads.size} line(s)`}${sc.unread === "dim" ? ", the rest dim" : ""} ${sc.checked ? `checked by ${sc.checked.by} ${String(sc.checked.at).slice(0, 10)}` : "NOT CHECKED"}`; const rows = sc.lines.map((l, n) => { const r = reads.get(n); const mark = l?.redact ? "x" : r ? (r.cutBefore || r.cutAfter ? "~" : "*") : " "; const ex = r && (r.cutBefore || r.cutAfter) ? ` [reads: "${str(l.text).slice(r.start, r.end)}"]` : ""; - 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}`; + 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}`; }); return [head, ...rows]; } @@ -217,14 +248,16 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js const entry = result.entry; const { pickedTake, isNarrated } = await import("umtool-report-to-video/post-narration"); const { partRoles } = await import("umtool-report-to-video/post-thread"); - const warnings = screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? partRoles(entry).map((r) => r.role) : [] }); + const { lineTakeWarnings } = await import("umtool-report-to-video/post-thread"); + const warnings = [...screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? partRoles(entry).map((r) => r.role) : [] }), ...lineTakeWarnings(entry)]; const { threadReadErrors } = await import("umtool-report-to-video/post-thread"); const { followKnobs } = await import("umtool-report-to-video/read-follow"); const { planContext } = await import("umtool-report-to-video/post-conversation"); const m2 = await readManifest(project.dir); const i = (m2?.timeline ?? []).findIndex((x) => x?.id === e.id); const at = i >= 0 ? m2.timeline[i] : null; - const refused = at && isNarrated(at) ? threadReadErrors(at, m2.render ?? {}, { ...planContext(m2.timeline, i, m2.render ?? {}), followOn: followKnobs(at, m2.render ?? {}).on }) : []; + const { readSaysHiddenErrors } = await import("umtool-report-to-video/post-thread"); + const refused = at && isNarrated(at) ? [...threadReadErrors(at, m2.render ?? {}, { ...planContext(m2.timeline, i, m2.render ?? {}), followOn: followKnobs(at, m2.render ?? {}).on }), ...readSaysHiddenErrors(at)] : []; if (json) { out(JSON.stringify({ ok: true, id: e.id, what, screens: entry.screens ?? [], warnings, refusedUntilRead: refused, token: result.token, editNotes }, null, 2)); return 0; @@ -252,6 +285,24 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js for (const sc of screens) for (const l of screenListing(e, sc)) out(l); return 0; } + if (verb === "add" && flags.has("--from-read")) { + // A PICTURE-ONLY post's read made its screen (post-screens.mjs screenFromRead): typed once, as its script. + if (flag("--from") !== null || multi("--line").length) fail("--from-read makes the lines from the read: not with --from or --line"); + const id = flag("--id") ?? nextScreenId(e); + if (screens.some((s) => s.id === id)) fail(`${e.id} has a screen ${id} already (set changes it)`); + const mi = flag("--media"); + if (mi !== null && !/^\d$/.test(String(mi))) fail("--media takes the attachment's index"); + const made = screenFromRead(e, { pictureOnly: ownPictureOnly(e), id, media: mi === null ? null : Number(mi), kind: flag("--kind") }); + if (made.error) fail(made.error); + const sc = { ...made.screen, ...(flag("--title") !== null ? { title: flag("--title") } : {}) }; + if (dryRun) { + const errs = validateScreens({ ...e, screens: [...screens, sc] }); + out(json ? JSON.stringify({ ok: !errs.length, dryRun: true, screen: sc, errors: errs }, null, 2) : [`would add ${sc.id} from its read:`, ...screenListing(e, sc).map((l) => ` ${l}`), ...errs.map((x) => ` refused: ${x}`)].join("\n")); + return errs.length ? 1 : 0; + } + // What is true now: the screen is not drawn and its read is the old one until the read is made again. + return write([...screens, sc], `added screen ${sc.id} from its read (${sc.lines.length} line(s), not checked) -- not drawn, and the item still plays its read as it was (its script, every word of it), until the read is made again: umtool posts screen ${project.id} ${e.id} read (its lines are then the read, the masked parts never said)`); + } if (verb === "add") { const from = flag("--from") ? await readFrom(path.resolve(String(flag("--from")))) : {}; const base = from.screen ?? {}; @@ -290,7 +341,16 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js } const pairs = words.slice(1); if (!pairs.length && !flag("--from")) fail("set <id> <key>=<value>… (posts screen --help)"); - next = applyPairs(next, pairs); + next = applyPairs(next, pairs, { takeId: (v, n) => { + const takes = Array.isArray(e.narration?.takes) ? e.narration.takes : []; + const k = Number(v); + if (!/^\d{1,3}$/.test(String(v)) || k < 1 || k > takes.length) fail(`take.${n}= takes a take's number (1–${takes.length}) or off`); + const t = takes[k - 1]; + if (!isObj(t?.screenLine) || t.screenLine.screen !== sc.id) fail(`take ${k} is not a recording of a line of screen ${sc.id}${isObj(t?.screenLine) ? ` (it is of screen ${t.screenLine.screen})` : ""}: record it (posts screen <p> ${e.id} record ${sc.id} ${n} --recording <file>)`); + // Owned by its CONTENT: it must say line n as it is now (its words, its speaker), whatever line it was recorded as. + if (lineTakeCurrent(e, t, sc.id, n) !== true) fail(`take ${k} does not say line ${n} of screen ${sc.id} as it is now (it was recorded for line ${t.screenLine.n}: other words or another speaker): record it (posts screen <p> ${e.id} record ${sc.id} ${n} --recording <file>)`); + return takeIdOf(t); + } }); // 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}`); @@ -314,10 +374,54 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js 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, - postTake, lineTakes: { ...defaultLineTakes(e), ...lineTakesOf(multi("--line-take")) }, + // 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")) }, }); } - fail(`posts screen ${verb}: list, add, set, rm, check or read`); + if (verb === "record") { + // ONE LINE in a person's voice (screenLineRecord.mjs): new takes, none picked; chosen for its line by hand. + const sc = byId(words[0]); + if (!/^\d{1,2}$/.test(String(words[1] ?? ""))) fail(`record ${sc.id} <line>: which line (0–${sc.lines.length - 1})?`); + const file = flag("--recording"); + if (!file) fail("record takes --recording <file> (a sound file: your read of the line)"); + const { recordScreenLine, LineRecordError } = await import("./screenLineRecord.mjs"); + const events = flags.has("--events"); + const role = `screen:${sc.id}:${Number(words[1])}`; + let r; + try { + r = await recordScreenLine(project, e.id, role, path.resolve(String(file)), { + as: flag("--as"), label: flag("--label") ?? "operator", + clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined, + ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}), + convert: !flags.has("--no-convert"), note: flag("--note"), + ...(flag("--pitch") !== null ? { pitch: flag("--pitch") } : {}), ...(flag("--semitones") !== null ? { semitones: Number(flag("--semitones")) } : {}), + checkWords: flags.has("--check-words"), worker: flag("--worker"), + emit: (ev, f) => (events ? out(JSON.stringify({ ev, ...f })) : !json && f?.message && out(f.message)), + }); + } catch (err) { + const { NarrateError } = await import("./postNarrationCli.mjs"); + if (err instanceof LineRecordError || err instanceof NarrateError) { + if (events || json) out(JSON.stringify({ ...(events ? { ev: "result" } : {}), ok: false, id: e.id, role, error: err.message })); + else out(`refused: ${err.message}`); + return 1; + } + throw err; + } + const m2 = await readManifest(project.dir); + const after = (m2?.timeline ?? []).find((x) => x?.id === e.id); + const numbers = r.takes.map((x) => 1 + (after?.narration?.takes ?? []).findIndex((t) => t.file === x.file)); + const res = { ok: true, id: e.id, role, takes: r.takes.map((x, i) => ({ ...x, n: numbers[i] })), notes: r.notes, disclosure: r.disclosure, character: r.character, prompt: r.line.prompt }; + if (events) out(JSON.stringify({ ev: "result", ...res })); + else if (json) out(JSON.stringify(res, null, 2)); + else { + out(`${e.id}: line ${words[1]} of screen ${sc.id} recorded -- ${r.takes.map((x, i) => `take ${numbers[i]} ${x.step}`).join(", ")}; none picked`); + for (const n of r.notes) out(` ${n}`); + out(` disclosure in the read: ${r.disclosure}`); + out(` choose it for the line: umtool posts screen ${project.id} ${e.id} set ${sc.id} take.${words[1]}=${numbers.at(-1)} then: umtool posts screen ${project.id} ${e.id} read`); + } + return 0; + } + fail(`posts screen ${verb}: list, add, set, rm, check, read or record`); return 2; } @@ -327,6 +431,8 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js * from the parts cache when it was before). */ export function defaultPostTake(e) { + // A screen made from its read IS his read (postThreadRead.mjs): no take of his words stands in for it. + if (screensOf(e).some((sc) => sc.source === "read")) return null; const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; const k = Number.isInteger(e?.narration?.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0; const t = takes[k]; @@ -355,6 +461,8 @@ export function defaultLineTakes(e) { const m = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/.exec(role); const sc = m ? screensOf(e).find((s) => s.id === m[1]) : null; const now = sc ? lineWritten(screenLineSaid(sc, Number(m[2]))) : ""; + // A RECORDING OF A LINE (`screenLine`) is read in only while the screen CHOOSES it (chosenLineTakes): never re-attached here. + if (at >= 0 && isObj(takes[at]?.screenLine)) continue; if (at >= 0 && typeof x?.line === "string" && now && norm(x.line) === norm(now)) out[role] = at + 1; } return out; diff --git a/umtool/lib/report/postScreensReview3.test.mjs b/umtool/lib/report/postScreensReview3.test.mjs @@ -0,0 +1,364 @@ +// lane/screens-2, review round 1: what the review found, each pinned by a test made failing first. +// M1 a read the build refuses is never played by a preview: playableEntry, Play's view, Present (operator and public) +// M2 a screen made from its read IS the post's read (the post part not read twice); no part of a read says what the +// item's screens hide (the enforced lint); `add --from-read` says only what is true +// i the public payload carries the screens as the card draws them, never raw +// Temp dirs only; no audio is made (the takes are placeholders the payloads only name). +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { draftScript } from "umtool-report-to-video/post-narration"; +import { screenLineSaid, withoutLines } from "umtool-report-to-video/post-screens"; +import { itemReadRefusals, playableEntry, readSaysHiddenErrors, validateScreenReads } from "umtool-report-to-video/post-thread"; +import { presentPayload } from "./present.mjs"; +import { playViewWith } from "./playView.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { threadReadPlan } from "./postThreadRead.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-screens-review3-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const DM = { id: "s1", media: 0, kind: "dm", read: "all", checked: { by: "op", at: "2026-11-12T10:00:00.000Z" }, lines: [ + { who: "TheQuartering", text: "what is your address so I can send it" }, + { who: "MadamSavvy", text: "it is 12 Elm Street Springfield" }, + { who: "TheQuartering", text: "You can't be this dumb" }, +] }; +const THREAD = "narration/posts/2117/take-1.orpheus-thread.wav"; +function narrated(e) { + const parts = [{ n: 1, para: 0, text: "Hey, you told me.", voice: "tara", role: "post", start: 0, seconds: 1 }]; + let t = 1.5; + e.screens[0].lines.forEach((l, n) => { + const said = screenLineSaid(e.screens[0], n); + parts.push({ n: parts.length + 1, para: 100 * (n + 1), text: said, voice: "leo", role: `screen:s1:${n}`, start: t, seconds: 1, line: draftScript(said).script, speaker: l.who }); + t += 1.5; + }); + return { ...e, narration: { script: "Hey, you told me.", pick: 0, takes: [{ file: THREAD, engine: "orpheus", voice: "tara+leo", seconds: t, script: "x", parts, read: { kind: "thread", parents: "0" } }] } }; +} +const ITEM = narrated({ type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", text: "Hey, you told me.", subjects: ["MadamSavvy"], media: [IMG], screens: [structuredClone(DM)] }); +// The g1 probe's edits: each made UNDER the read (the writer takes them; the build refuses the old read). +const EDITS = { + "words of line 1 edited": (sc) => ({ ...sc, lines: sc.lines.map((l, i) => (i === 1 ? { ...l, text: "it is somewhere in town" } : l)) }), + "line 0 gets a phone number": (sc) => ({ ...sc, lines: sc.lines.map((l, i) => (i === 0 ? { ...l, text: "what is your address call 555 201 4477" } : l)) }), + "line 2 gets an anonymous handle": (sc) => ({ ...sc, lines: sc.lines.map((l, i) => (i === 2 ? { ...l, text: "ask @secretkid about it" } : l)) }), + "line 1 given to someone else": (sc) => ({ ...sc, lines: sc.lines.map((l, i) => (i === 1 ? { ...l, who: "Stranger" } : l)) }), + "line 0 removed": (sc) => withoutLines(sc, [0]), + "line 1 redacted": (sc) => ({ ...sc, lines: sc.lines.map((l, i) => (i === 1 ? { ...l, redact: true } : l)) }), + "line 1 no longer read": (sc) => ({ ...sc, read: [{ line: 0 }, { line: 2 }] }), +}; +const edited = (f) => ({ ...ITEM, screens: [f(structuredClone(ITEM.screens[0]))] }); + +async function project(name, 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 }, timeline: [item] }, null, 2)); + return { id: name, dir }; +} + +test("M1 playableEntry: the read as made plays; after each g1 edit the item plays WITHOUT its read (no narration, no take), the reason said", () => { + assert.equal(playableEntry(ITEM), ITEM, "a read the build plays: the item itself"); + for (const [name, f] of Object.entries(EDITS)) { + const e = edited(f); + assert.ok(itemReadRefusals(e).length > 0, name); + const p = playableEntry(e); + assert.equal(p.narration, undefined, name); + assert.ok(!JSON.stringify(p).includes(THREAD), `${name}: no reference to the old take`); + assert.match(p.readRefused.reason, /make the read again/); + } +}); + +test("M1 Play and Present: a refused read is in no view and no payload -- operator or public -- and Present's public data carries no raw line (i)", async () => { + for (const [name, f] of Object.entries(EDITS)) { + const p = await project(`m1-${Object.keys(EDITS).indexOf(name)}`, edited(f)); + const view = await playViewWith(p, {}); + assert.ok(!view.error, String(view.error)); + const pe = view.view.entries.find((x) => x.id === "p-2117"); + assert.equal(pe.post.narration, undefined, `${name}: Play`); + assert.equal(pe.postPlan.narration ?? null, null, `${name}: Play's plan`); + assert.ok(pe.readRefused, `${name}: Play says why`); + for (const canUncensor of [true, false]) { + const pay = await presentPayload(p, { canUncensor }); + assert.ok(!pay.error, String(pay.error)); + const s = pay.slides.find((x) => x.kind === "post"); + assert.equal(s.narration, null, `${name}: Present ${canUncensor ? "operator" : "public"}`); + assert.ok(!JSON.stringify(pay).includes(THREAD), `${name}: no stale audio in the payload`); + if (!canUncensor) { + const raw = JSON.stringify(s.post.screens); + assert.ok(!/555|4477/.test(raw), `${name}: a phone number never in the public data`); + } + } + } + // The read as made: played, in both. + const ok = await project("m1-ok", ITEM); + const pay = await presentPayload(ok, { canUncensor: false }); + assert.equal(pay.slides.find((x) => x.kind === "post").narration.file, THREAD); +}); + +test("i: an item whose read draws no screen carries no screen in the public payload (the card draws none)", async () => { + const sc = { id: "s1", media: 0, kind: "dm", title: "Mail to savvy@gmail.com", read: "all", lines: [{ who: "Stranger", text: "my email is jane.doe@example.com", time: "555-201-4477" }] }; + const p = await project("i-pub", { ...ITEM, narration: undefined, screens: [sc] }); + const pay = await presentPayload(p, { canUncensor: false }); + assert.deepEqual(pay.slides.find((x) => x.kind === "post").post.screens, []); + assert.ok(!/jane\.doe|savvy@gmail|4477/.test(JSON.stringify(pay))); + const op = await presentPayload(p, { canUncensor: true }); + assert.ok(JSON.stringify(op.slides.find((x) => x.kind === "post").post.screens).includes("jane.doe@example.com"), "the operator's own screen, as written"); +}); + +test("M2 the enforced lint: no part of an item's read says a number or an e-mail its screens mask, nor a redacted line's words -- whoever's part it is", () => { + const sc = { id: "s1", media: 0, kind: "text", source: "read", read: "all", lines: [{ text: "I never said that." }, { text: "Order number: 4419283 was refunded." }, { text: "my secret plan for the house", redact: true }] }; + const plain = (script) => ({ type: "post", id: "p-7", post: "kir-x/7", platform: "x", author: "K", handle: "kirsche", date: "2026-11-02T01:40:36.000Z", text: "@thequartering", media: [IMG], screens: [sc], narration: { script, takes: [{ file: "narration/posts/7/take-1.kokoro-af_heart.wav", engine: "kokoro", voice: "af_heart", seconds: 3, script }], pick: 0 } }); + assert.ok(readSaysHiddenErrors(plain("I never said that. Order number: 4419283 was refunded.")).some((x) => /its picked take says a number that line 1 of screen s1 masks/.test(x))); + assert.ok(readSaysHiddenErrors(plain("the order was 4419 283")).length > 0, "its digits however they are joined"); + assert.ok(readSaysHiddenErrors(plain("here is my secret plan for the house")).some((x) => /line 2 of screen s1, which is redacted/.test(x))); + assert.deepEqual(readSaysHiddenErrors(plain("I never said that.")), []); + assert.deepEqual(readSaysHiddenErrors(plain("I paid $99.95 on 11/02/2026")), [], "amounts and dates are never shapes"); + // Through the cut: the build's enforced lint (validateScreenReads) refuses it; a cut without screens is untouched. + assert.ok(validateScreenReads({ timeline: [plain("Order number: 4419283 was refunded.")] }).length > 0); + const { screens: _s, ...noScreens } = plain("Order number: 4419283 was refunded."); + assert.deepEqual(validateScreenReads({ timeline: [noScreens] }), []); + // A message names the part and the line, never the value. + assert.ok(readSaysHiddenErrors(plain("Order number: 4419283")).every((x) => !x.includes("4419283"))); +}); + +test("M2 --from-read: its screen IS the post's read -- the post part is not read again, no take of it reused, a --post-take refused; `add` says only what is true (probe f2)", async () => { + const take = { file: "narration/posts/7/take-1.kokoro-af_heart.wav", engine: "kokoro", voice: "af_heart", seconds: 3, script: "I never said that.\nOrder number: 4419283 was refunded." }; + const item = { type: "post", id: "p-7", post: "kir-x/7", platform: "x", author: "Kirsche", handle: "kirsche", date: "2026-11-02T01:40:36.000Z", text: "@thequartering", media: [IMG], narration: { script: take.script, takes: [take], pick: 0 } }; + await project("fr", item); + const lines = []; + const posts = async (args) => { + lines.length = 0; + const code = await postsCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + return { code, text: lines.join("\n") }; + }; + let r = await posts(["screen", "fr", "p-7", "add", "--from-read"]); + assert.equal(r.code, 0, r.text); + assert.match(r.text, /the item still plays its read as it was/); + assert.match(r.text, /the build REFUSES the read as it is .*says a number that line 1 of screen s1 masks/); + r = await posts(["screen", "fr", "p-7", "read", "--dry-run", "--json"]); + assert.equal(r.code, 0, r.text); + const j = JSON.parse(r.text); + assert.deepEqual(j.parts.map((p) => p.role), ["screen:s1:0", "screen:s1:1"], "the post part is not read: the screen's lines are its read"); + assert.ok(j.parts.every((p) => !p.take), "no take reused"); + assert.ok(j.parts.every((p) => !/4419283/.test(p.text)), "the masked number never said"); + assert.ok(j.skipped.some((s) => s.role === "post" && /screen s1's lines/.test(s.why))); + r = await posts(["screen", "fr", "p-7", "read", "--dry-run", "--post-take", "1"]); + assert.notEqual(r.code, 0); + assert.match(r.text, /own words are its screen s1's lines/); + // A typed screen (not from its read) reads his words as before. + const typed = { ...item, screens: [{ id: "s1", media: 0, kind: "text", source: "transcribed", read: "all", lines: [{ text: "hello" }] }] }; + assert.deepEqual(threadReadPlan({ render: {}, timeline: [typed] }, typed, {}).pieces.map((p) => p.role), ["post", "screen:s1:0"]); +}); + +// --------------------------------------------------------------------------- +// SHOULD-FIXES (b, d, e, f, j) -- a is in postScreensRound2.test.mjs (content-based ownership). +// --------------------------------------------------------------------------- +import { readFile, readdir, stat } from "node:fs/promises"; +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { claimRecordedTake, keepRecording } from "./postRecord.mjs"; +import { heardProblem, recordScreenLine } from "./screenLineRecord.mjs"; +import { lineTakeProblem } from "./postThreadRead.mjs"; +import { linesOfRead } from "umtool-report-to-video/post-screens"; +import { lineTakeWarnings } from "umtool-report-to-video/post-thread"; + +const tone = async (file, voice = VOICE_A, seconds = 1) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: 0.1, after: 0.1 }))); +}; +const OWN_TAKE = { file: "narration/posts/2117/take-1.kokoro-af_heart.wav", engine: "kokoro", voice: "af_heart", seconds: 1, script: "Hey, you told me." }; +const plainItem = () => ({ ...ITEM, narration: { script: "Hey, you told me.", takes: [OWN_TAKE], pick: 0 } }); + +test("b: two recordings kept at once never write one file; a recording already there is never overwritten (an exclusive claim, the next number)", async () => { + const p = await project("b-claim", plainItem()); + // A recording already on disk at the number the item would give next (not in the manifest: a crash, another session). + const there = path.join(p.dir, "narration/posts/2117/take-2.recorded-operator.wav"); + await tone(there, VOICE_B, 0.5); + const before = await readFile(there); + const a = path.join(ROOT, "b-a.wav"); + const b = path.join(ROOT, "b-b.wav"); + await tone(a, VOICE_A, 1); + await tone(b, VOICE_B, 1.3); + const e = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")).timeline[0]; + const got = await Promise.allSettled([keepRecording(p, e, [{ file: a, text: "x" }]), keepRecording(p, e, [{ file: b, text: "x" }])]); + const files = got.filter((x) => x.status === "fulfilled").map((x) => x.value.take.file); + assert.ok(files.length >= 1); + assert.ok(!files.includes("narration/posts/2117/take-2.recorded-operator.wav"), "the file already there was not taken"); + assert.deepEqual(await readFile(there), before, "never overwritten"); + const names = (await readdir(path.join(p.dir, "narration/posts/2117"))).filter((f) => /^take-\d+\.recorded-operator\.wav$/.test(f)); + assert.equal(new Set(names).size, names.length); + assert.ok(names.length >= 3, `both recordings kept in files of their own: ${names}`); + for (const f of names) assert.ok((await stat(path.join(p.dir, "narration/posts/2117", f))).size > 0, `${f} is a recording, not an empty claim`); + // The claim itself: exclusive, the next number while one is there. + const c1 = await claimRecordedTake(p.dir, e, "operator"); + const c2 = await claimRecordedTake(p.dir, e, "operator"); + assert.notEqual(c1.rel, c2.rel); +}); + +test("d: --check-words refuses an anonymous author's handle or name in any spoken form, and a number said in words (probe h1)", () => { + const o = { handles: ["secretkid"], names: ["Jeremy Smith"], terms: ["Jenny"], lineTakeProblem }; + for (const heard of ["ask secretkid about it", "ask secretkid's mom about it", "ask secret kid about it", "ask Secret Kid about it", "ask SecretKid. about it", "ask @secretkid about it", + "call five five five two oh one four four seven seven", "my number is 555 201 4477", "email jane at gmail dot com", "ask Jeremy Smith about it", "ask jeremysmith's dog", "ask jenny about it"]) { + assert.ok(heardProblem(heard, "ask Kid A about it", o).refused, heard); + } + assert.deepEqual(heardProblem("ask Kid A about it", "ask Kid A about it", o), { refused: null, warning: null }); + assert.ok(heardProblem("about it ask Kid A", "ask Kid A about it", o).warning, "other words: a warning"); + assert.equal(heardProblem("one or two of them", "one or two of them", o).refused, null, "a few number words are words"); +}); + +test("e: linesOfRead leaves out only Orpheus's tags -- any other <word> is the picture's words (probe f1 e)", () => { + assert.deepEqual(linesOfRead("I never said that. <sigh> Press <1> to call <b>a</b> <c>"), [{ text: "I never said that. Press <1> to call <b>a</b> <c>" }]); + assert.deepEqual(linesOfRead("<laugh> ok <gasp>"), [{ text: "ok" }]); +}); + +const CHARS = { format: "umtool-project-characters", version: 1, characters: [ + { id: "tq", name: "Jeremy", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:am_michael" } } }, + { id: "other", name: "Other", handles: ["someoneelse"], synthetic: { voice: "kokoro:af_sky" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:af_sky" } } }, +] }; +const stubOps = (heard = null) => async (route, body) => { + if (route === "/api/ops/transcribe") { + await writeFile(body.out, JSON.stringify({ words: String(heard ?? "").split(/\s+/).filter(Boolean).map((w, i) => ({ w, start: i * 0.3, end: i * 0.3 + 0.25 })) })); + return { jobId: "t", result: {} }; + } + await tone(body.out, VOICE_B, 1); + return { jobId: "j", result: route.endsWith("voice-convert") ? { op: "convert", engine: "openvoice", voice: String(body.voice ?? "").split(":").pop() } : { op: "enhance", engine: "deepfilternet" } }; +}; + +test("f: record --as only names the line's speaker's character -- another character or the narrator is refused (probe a1)", async () => { + const p = await project("f-as", plainItem()); + await writeFile(path.join(p.dir, "narration", "characters.json"), JSON.stringify(CHARS)); + await mkdir(path.join(p.dir, ".umtool"), { recursive: true }); + await writeFile(path.join(p.dir, ".umtool", "cast.json"), JSON.stringify({ format: "umtool-cast", version: 1, characters: [{ id: "me", name: "Me", handles: ["operator"], voice: "kokoro:bm_george", convert: { engine: "openvoice" }, narrator: true }] })); + const f = path.join(ROOT, "f.wav"); + await tone(f); + await assert.rejects(() => recordScreenLine(p, "p-2117", "screen:s1:0", f, { as: "other", ask: stubOps() }), /not the character of line 0's speaker \(that is tq\)/); + await assert.rejects(() => recordScreenLine(p, "p-2117", "screen:s1:0", f, { as: "me", ask: stubOps() }), /the narrator is never a screen line's voice/); + const ok = await recordScreenLine(p, "p-2117", "screen:s1:0", f, { as: "tq", ask: stubOps(), clean: false }); + assert.match(ok.disclosure, /am_michael/); +}); + +test("j: an unheard line take is said to be one -- the record's note, the lint per chosen take; a heard one records what it was heard saying, against which words", async () => { + const p = await project("j-heard", plainItem()); + await writeFile(path.join(p.dir, "narration", "characters.json"), JSON.stringify(CHARS)); + const f = path.join(ROOT, "j.wav"); + await tone(f); + const r = await recordScreenLine(p, "p-2117", "screen:s1:2", f, { ask: stubOps(), clean: false, convert: false }); + assert.ok(r.notes.some((x) => /not heard: nothing checked what the recording says/.test(x))); + const h = await recordScreenLine(p, "p-2117", "screen:s1:2", f, { ask: stubOps("You can't be this dumb"), clean: false, convert: false, checkWords: true }); + assert.equal(h.heard, true); + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + const e = m.timeline[0]; + const [unheard, heard] = e.narration.takes.slice(1); + assert.equal(unheard.screenLine.heard, undefined); + assert.deepEqual([heard.screenLine.heard.against, heard.screenLine.heard.words], ["You can't be this dumb", "You can't be this dumb"]); + const chose = (id) => ({ ...e, screens: [{ ...e.screens[0], lineTakes: { 2: id } }] }); + assert.ok(lineTakeWarnings(chose("take-2.recorded-operator")).some((x) => /line take 2 of screen s1 line 2 was not heard -- nothing verified what the recording says/.test(x))); + assert.ok(!lineTakeWarnings(chose("take-3.recorded-operator")).some((x) => /was not heard/.test(x))); +}); + +// --------------------------------------------------------------------------- +// RE-CHECK: the public payload is built from what the card draws (M); one verdict on the item as written (b); one +// accessor for an item's playable read (e). +// --------------------------------------------------------------------------- +import { publicScreens } from "./present.mjs"; +import { playableAsWritten, playableTake } from "umtool-report-to-video/post-thread"; +import { postCardHtml, postItemPlan } from "umtool-report-to-video/post-item"; + +/** Every string anywhere in a value (keys too), any depth. */ +const strings = (v, out = []) => { + if (typeof v === "string") out.push(v); + else if (Array.isArray(v)) v.forEach((x) => strings(x, out)); + else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) strings(x, out.concat(k)); + return out; +}; +const MARKED = { + type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", text: "Hey, you told me.", subjects: ["MadamSavvy"], media: [IMG], + screens: [ + { id: "s1", media: 0, kind: "dm", title: "Mail to TITLEMARK@example.com", read: [{ line: 0, text: "keep this part" }, { line: 1 }, { line: 4 }], lines: [ + { who: "MadamSavvy", text: "keep this part CUTREMAINDER words", time: "call 555 201 4477" }, + { who: "TheQuartering", text: "ring 555 777 8888 now", time: "11:32 AM" }, + { who: "TheQuartering", text: "OMITTEDLINE never chosen" }, + { who: "TheQuartering", text: "REDACTEDWORDS alpha beta gamma", redact: true }, + { who: "secretkid", text: "ask @secretkid about it" }, + ] }, + { id: "s2", media: 0, kind: "text", read: "all", lines: [{ text: "UNREADSCREEN its words" }] }, + ], +}; +const narratedMarked = () => { + const e = structuredClone(MARKED); + const parts = [{ n: 1, para: 0, text: "Hey, you told me.", voice: "tara", role: "post", start: 0, seconds: 1 }]; + let t = 1.5; + for (const n of [0, 1, 4]) { + const said = screenLineSaid(e.screens[0], n); + parts.push({ n: parts.length + 1, para: 100 * (n + 1), text: said, voice: "leo", role: `screen:s1:${n}`, start: t, seconds: 1, line: draftScript(said).script, speaker: e.screens[0].lines[n].who }); + t += 1.5; + } + return { ...e, narration: { script: "Hey, you told me.", pick: 0, takes: [{ file: THREAD, engine: "orpheus", voice: "tara+leo", seconds: t, script: "x", parts, read: { kind: "thread", parents: "0" } }] } }; +}; + +test("M (re-check): the WHOLE public payload holds nothing the card does not draw -- an excerpt's remainder, a line not read, a screen not read, a redacted line, a masked number, a title's or a time's shape, an anonymous handle; the operator payload as before", async () => { + const p = await project("m-public", narratedMarked()); + await writeFile(path.join(p.dir, "narration", "characters.json"), JSON.stringify({ format: "umtool-project-characters", version: 1, characters: [{ id: "kid", name: "Secret Kid", handles: ["secretkid"], anonymous: true }] })); + const pub = await presentPayload(p, { canUncensor: false }); + assert.ok(!pub.error, String(pub.error)); + const all = strings(pub).join("\n"); + for (const marker of ["CUTREMAINDER", "OMITTEDLINE", "UNREADSCREEN", "REDACTEDWORDS", "alpha beta", "555 201 4477", "4477", "555 777 8888", "8888", "TITLEMARK", "secretkid", "Secret Kid"]) { + assert.ok(!all.toLowerCase().includes(marker.toLowerCase()), `${marker} is nowhere in the public payload`); + } + // What the card draws IS there: the excerpt's run cut "…", a "⋯" row for the lines left out, the read lines masked. + const sc = pub.slides.find((x) => x.kind === "post").post.screens; + assert.deepEqual(sc.map((x) => x.id), ["s1"], "only the screens the card draws"); + const rows = sc[0].rows; + assert.equal(rows[0].text, "keep this part…"); + assert.ok(rows.some((r) => r.gap), "the lines left out are a gap row, not their words"); + assert.ok(rows.some((r) => /^ring\b/.test(r.text) && !/\d/.test(r.text)), "a read line, its number masked"); + assert.equal("lines" in sc[0], false, "no lines to draw from but the rows drawn"); + // The card itself draws none of the markers either (the payload and the card agree). + const e = narratedMarked(); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow?.thread ?? null }); + for (const marker of ["CUTREMAINDER", "OMITTEDLINE", "UNREADSCREEN", "REDACTEDWORDS"]) assert.ok(!html.includes(marker), `${marker} not on the card`); + // The operator's payload: the screens as written, unchanged. + const op = await presentPayload(p, { canUncensor: true }); + const opScreens = op.slides.find((x) => x.kind === "post").post.screens; + assert.deepEqual(opScreens.map((x) => x.lines.map((l) => l.text)), MARKED.screens.map((x) => x.lines.map((l) => l.text.replace("@secretkid", "@Anon_1"))), "every line as written (the anonymity pass as before)"); + assert.deepEqual(opScreens.map((x) => x.read), MARKED.screens.map((x) => x.read)); + // A read refused: no screen drawn, none in the public data. + assert.deepEqual(publicScreens(MARKED, { roles: [] }), []); +}); + +test("b (re-check): the card page's verdict is the item AS WRITTEN's, applied to the item as drawn (playableAsWritten)", async () => { + const stale = edited(EDITS["words of line 1 edited"]); + // The drawn copy may differ (the anonymity pass, the censor): the verdict is the written one's either way. + const drawnLooksFine = { ...stale, screens: ITEM.screens }; + const out = playableAsWritten(stale, drawnLooksFine); + assert.equal(out.narration, undefined); + assert.ok(out.readRefused); + const fine = playableAsWritten(ITEM, { ...ITEM, screens: stale.screens }); + assert.equal(fine.narration.takes[0].file, THREAD, "written fine: the drawn copy plays"); + // The route calls it with the item as written. + const src = await readFile(new URL("../../app/api/report/post-item/route.ts", import.meta.url), "utf8"); + assert.match(src, /playableAsWritten\(found\.written \?\? found\.item, found\.item\)/); + assert.match(src, /const written = .*before the anonymity pass|The item AS WRITTEN \(before the anonymity pass\)/); +}); + +test("e (re-check): every player, preview and payload reads an item's take through playableTake -- no direct picked-take read outside the allow-list", async () => { + assert.equal(playableTake(edited(EDITS["line 1 redacted"])), null); + assert.equal(playableTake(ITEM).file, THREAD); + assert.equal(playableTake({ ...ITEM, readRefused: { reason: "x" } }), null); + const root = new URL("../../", import.meta.url); + // The files that play, preview or ship an item's read. + const files = ["lib/report/present.mjs", "lib/report/playView.mjs", "lib/report/postBenchData.ts", "components/projects/review/PostItemPlayer.tsx", "components/projects/present/PresentView.tsx", "app/api/report/post-item/route.ts"]; + for (const dir of ["components/projects/review/playEngine"]) for (const f of await readdir(new URL(dir, root))) if (/\.(ts|tsx|mjs)$/.test(f) && !/\.test\./.test(f)) files.push(`${dir}/${f}`); + // Allowed: the card route's word-timing ops, which time the take on record (a write), never play it. + const ALLOW = [/const take = pickedTake\(found\.item\) as .*script\?: string; parts\?: unknown\[\]/, /const take = found\.item \? \(pickedTake\(found\.item\) as .*\{ file: string \}\) \| null\) : null;/]; + const bad = []; + for (const f of files) { + const lines = (await readFile(new URL(f, root), "utf8")).split("\n"); + lines.forEach((l, i) => { + if (/^\s*(\/\/|\*)/.test(l)) return; + if ((/\bpickedTake\(/.test(l) || /\bnarration\??\.takes\b/.test(l)) && !ALLOW.some((re) => re.test(l))) bad.push(`${f}:${i + 1}: ${l.trim().slice(0, 120)}`); + }); + } + assert.deepEqual(bad, [], "read an item's take through playableTake (post-thread.mjs)"); +}); diff --git a/umtool/lib/report/postScreensRound2.test.mjs b/umtool/lib/report/postScreensRound2.test.mjs @@ -0,0 +1,321 @@ +// A post's SCREENS, round 2 (lane/screens-2): a screen made from a picture-only post's READ (`posts screen … add +// --from-read`, post-screens.mjs linesOfRead / screenFromRead) and a LINE RECORDED by the operator (`posts screen … +// record`, the bench's per-line Record): kept as new takes of the item that are never its read, converted only to the +// speaker's character's stock voice, chosen for a line by hand (`--line-take`, the screen's `lineTakes`), refused when +// they are another line's or the line changed. No editor (stub ops), no real audio (synthetic tones), temp dirs. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, 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_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { linesOfRead, maskShapes, screenFromRead } from "umtool-report-to-video/post-screens"; +import { ownPictureOnly, validatePostItem } from "umtool-report-to-video/post-item"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-screens2-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const wavOf = async (file, voice, seconds = 1.2) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: 0.1, after: 0.1 }))); +}; +const IMG = { src: "posts-media/kir-x/7/7_1.jpg", kind: "image", width: 900, height: 1400 }; +const GIF = { src: "posts-media/kir-x/7/7_2.mp4", kind: "gif", width: 480, height: 270, seconds: 2.53 }; +const PIC = { + type: "post", id: "p-7", post: "kir-x/7", platform: "x", author: "Kirsche", handle: "kirsche", date: "2026-11-02T01:40:36.000Z", + text: "@thequartering", media: [IMG], + narration: { script: "I never said that.\n\nOrder number: 4419283 was refunded <sigh> on 11/02/2026.\n", takes: [{ file: "narration/posts/7/take-1.kokoro-af_heart.wav", engine: "kokoro", voice: "af_heart", seconds: 3, script: "I never said that." }], pick: 0 }, +}; +async function project(name, item) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + for (const t of item.narration?.takes ?? []) await wavOf(path.join(dir, t.file), VOICE_A, 1); + 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: "kokoro", voice: "af_heart" } }, + 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 posts = async (args) => { + const lines = []; + const code = await postsCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + return { code, text: lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; + +// --------------------------------------------------------------------------- +// ITEM 3: --from-read +// --------------------------------------------------------------------------- + +test("linesOfRead: a line per line of the script, blank lines and emotion tags dropped, a long line split at its sentences -- never a speaker parsed out", () => { + assert.deepEqual(linesOfRead("I never said that.\n\n \nOrder number: 4419283 was refunded <sigh> today."), [{ text: "I never said that." }, { text: "Order number: 4419283 was refunded today." }]); + // A "who: words" is words: a shape or a heading is never a speaker (round 1's p7). + for (const raw of ["Order number: 4419", "Ref: AB-1234", "savvy@gmail.com: hi there", "Phone: 555 201 4477", "TheQuartering: hi"]) assert.deepEqual(linesOfRead(raw), [{ text: raw }], raw); + const long = Array.from({ length: 30 }, (_, i) => `Sentence number ${i} goes on for a little while.`).join(" "); + const out = linesOfRead(long); + assert.ok(out.length > 1 && out.every((l) => l.text.length <= 600 && /\.$/.test(l.text)), "split at sentence ends"); + assert.equal(out.map((l) => l.text).join(" "), long); + const noStop = "word ".repeat(200).trim(); + assert.ok(linesOfRead(noStop).every((l) => l.text.length <= 600 && !/^ | $/.test(l.text))); + assert.throws(() => linesOfRead(" \n <sigh> \n"), /no words/); + assert.throws(() => linesOfRead(Array.from({ length: 61 }, (_, i) => `line ${i}`).join("\n")), /at most 60/); +}); + +test("screenFromRead: a picture-only post's script made a screen on its picture, read whole, NOT checked; refused for any other post", () => { + const made = screenFromRead(PIC, { pictureOnly: ownPictureOnly(PIC), id: "s1" }); + assert.deepEqual(made.screen, { id: "s1", media: 0, kind: "text", source: "read", lines: [{ text: "I never said that." }, { text: "Order number: 4419283 was refunded on 11/02/2026." }], read: "all" }); + assert.deepEqual(validatePostItem({ ...PIC, screens: [made.screen] }), []); + // Its shapes are masked like any line's (the order number drawn as a bar, never said); its date stays. + assert.ok(!maskShapes(made.screen.lines[1].text).text.includes("4419283")); + assert.ok(maskShapes(made.screen.lines[1].text).text.includes("11/02/2026")); + // A GIF: visible its whole length. + const gif = screenFromRead({ ...PIC, media: [GIF] }, { pictureOnly: true, id: "s1", kind: "dm" }); + assert.deepEqual([gif.screen.at, gif.screen.kind], [[0, 2.53], "dm"]); + assert.match(screenFromRead({ ...PIC, media: [{ ...GIF, seconds: undefined }] }, { pictureOnly: true, id: "s1" }).error, /--at/); + assert.match(screenFromRead({ ...PIC, text: "a whole sentence of words" }, { pictureOnly: false, id: "s1" }).error, /not a picture-only post/); + assert.match(screenFromRead({ ...PIC, narration: { ...PIC.narration, script: "" } }, { pictureOnly: true, id: "s1" }).error, /no words/); + assert.match(screenFromRead(PIC, { pictureOnly: true, id: "s1", kind: "chat" }).error, /--kind takes/); + assert.match(screenFromRead(PIC, { pictureOnly: true, id: "s1", media: 4 }).error, /--media 4/); +}); + +test("the CLI: posts screen … add --from-read writes one screen from narration.script (not checked; the lint says so); refused off a picture-only post", async () => { + const p = await project("fromread", PIC); + let r = await posts(["screen", "fromread", "p-7", "add", "--from-read", "--dry-run"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens, undefined, "a dry run writes nothing"); + r = await posts(["screen", "fromread", "p-7", "add", "--from-read", "--title", "A statement", "--json"]); + assert.equal(r.code, 0, r.text); + const j = r.json(); + assert.deepEqual(j.screens[0].lines.map((l) => l.text), ["I never said that.", "Order number: 4419283 was refunded on 11/02/2026."]); + assert.equal(j.screens[0].title, "A statement"); + assert.equal(j.screens[0].checked, undefined); + assert.ok(j.warnings.some((w) => /screen s1's transcription not checked/.test(w))); + assert.ok(j.warnings.some((w) => /does not read screen s1/.test(w)), "nothing drawn until the read reads it"); + r = await posts(["screen", "fromread", "p-7", "add", "--from-read", "--line", "a: b"]); + assert.equal(r.code, 2); + await project("fromread2", { ...PIC, text: "A post with words of its own." }); + r = await posts(["screen", "fromread2", "p-7", "add", "--from-read"]); + assert.equal(r.code, 2); + assert.match(r.text, /not a picture-only post/); +}); + +// --------------------------------------------------------------------------- +// ITEM 1: a screen line recorded by the operator +// --------------------------------------------------------------------------- + +const DM = { id: "s1", media: 0, kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order" }, + { who: "MadamSavvy", text: "call me at 555 201 4477 tonight" }, + { who: "TheQuartering", text: "You can't be this dumb" }, + { who: "Stranger", text: "who is this" }, + { who: "TheQuartering", text: "ask @secretkid about it" }, +] }; +const OWN = { file: "narration/posts/2117/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", label: "operator", seconds: 1.4, script: "Hey, you told me. Your turn.", source: { kind: "recorded", voice: "operator" } }; +const SAVVY = { + type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", + text: "Hey, you told me. Your turn.", subjects: ["MadamSavvy"], media: [IMG], screens: [DM], + narration: { script: "Hey, you told me. Your turn.", takes: [OWN], pick: 0 }, +}; +// This video's characters: TheQuartering converts to a stock voice; Savvy (the author) to hers; the narrator is never a line's. +const CHARS = { format: "umtool-project-characters", version: 1, characters: [ + { id: "tq", name: "Jeremy", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:am_michael" } } }, + { id: "savvy", name: "Savvy", handles: ["madamsavvy"], synthetic: { voice: "kokoro:af_bella" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:af_bella" } } }, + { id: "kid", name: "Secret Kid", handles: ["secretkid"], anonymous: true, shown: "Kid A" }, +] }; +async function savvy(name, item = SAVVY, chars = CHARS) { + const p = await project(name, item); + await mkdir(path.join(p.dir, "narration"), { recursive: true }); + if (chars) await writeFile(path.join(p.dir, "narration", "characters.json"), JSON.stringify(chars)); + return p; +} +/** The editor's ops, stubbed: each writes its out file as a tone and answers as the editor does. */ +const stubOps = (asked, heard = null) => async (route, body) => { + asked.push({ route, body }); + if (route === "/api/ops/transcribe") { + await writeFile(body.out, JSON.stringify({ words: String(heard ?? "").split(/\s+/).filter(Boolean).map((w, i) => ({ w, start: i * 0.3, end: i * 0.3 + 0.25 })) })); + return { jobId: `job-t${asked.length}`, result: {} }; + } + await wavOf(body.out, VOICE_B, 1); + return { jobId: `job-${asked.length}`, result: route.endsWith("voice-convert") ? { op: "convert", engine: body.engine ?? "openvoice", voice: String(body.voice ?? "").split(":").pop() } : { op: "enhance", engine: "deepfilternet" } }; +}; +const stubTts = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out, VOICE_B, 0.6); + return { jobId: `tts-${asked.length}`, result: { wav: body.out } }; +}; +const recording = async (p, name = "rec.wav") => { + const f = path.join(ROOT, `${p.id}-${name}`); + await wavOf(f, VOICE_A, 1.2); + return f; +}; +const NO_RED = { terms: [], markup: {}, slurs: null }; + +test("lineToRecord: the line as the read says it -- its shapes left out, an anonymous handle as its shown name, the lexicon only in the script; a line not read or redacted refused", async () => { + const { lineToRecord } = await import("./screenLineRecord.mjs"); + const red = { terms: [], markup: {}, slurs: null, say: [{ word: "dumb", say: "dumm" }], anon: new Map([["secretkid", "Kid A"]]) }; + const a = lineToRecord(SAVVY, "screen:s1:2", { red }); + assert.equal(a.prompt, "You can't be this dumb"); + assert.equal(a.script, "You can't be this dumm", "the script says it the lexicon's way: what the read holds the take to"); + assert.equal(a.written, "You can't be this dumb"); + assert.deepEqual([a.speaker, a.handle, a.self], ["TheQuartering", "TheQuartering", false]); + const b = lineToRecord(SAVVY, "screen:s1:1", { red }); + assert.ok(!/555|4477/.test(b.prompt + b.script + b.written), "a masked number is never in the prompt nor the script (R2 #2)"); + assert.equal(b.self, true); + const c = lineToRecord(SAVVY, "screen:s1:4", { red }); + assert.ok(!/secretkid/i.test(c.prompt + c.script) && /Kid A/.test(c.script), "an anonymous handle said as its shown name"); + const unread = { ...SAVVY, screens: [{ ...DM, read: [{ line: 0 }] }] }; + assert.throws(() => lineToRecord(unread, "screen:s1:2", { red }), /not read by the screen/); + const redacted = { ...SAVVY, screens: [{ ...DM, lines: DM.lines.map((l, n) => (n === 2 ? { ...l, redact: true } : l)) }] }; + assert.throws(() => lineToRecord(redacted, "screen:s1:2", { red }), /redacted/); + assert.throws(() => lineToRecord(SAVVY, "screen:s9:0", { red }), /no screen s9/); + assert.throws(() => lineToRecord(SAVVY, "screen:s1:9", { red }), /no line 9/); +}); + +test("record: recorded, cleaned, converted to the SPEAKER's character's stock voice -- each a new take, none picked, the item's script untouched; a line take, never the item's read", async () => { + const { recordScreenLine } = await import("./screenLineRecord.mjs"); + const p = await savvy("rec"); + const asked = []; + const r = await recordScreenLine(p, "p-2117", "screen:s1:2", await recording(p), { ask: stubOps(asked) }); + assert.deepEqual(asked.map((x) => x.route), ["/api/ops/voice-enhance", "/api/ops/voice-convert"]); + assert.equal(asked[1].body.voice, "kokoro:am_michael", "TheQuartering's character's stock voice"); + assert.equal(r.picked, null); + assert.equal(r.disclosure, "a recorded reading converted to a stock voice (openvoice · kokoro:am_michael)"); + assert.equal(r.line.prompt, "You can't be this dumb"); + const n = (await read(p)).timeline[0].narration; + assert.equal(n.pick, 0, "his own read still plays"); + assert.equal(n.script, SAVVY.narration.script, "the item's script untouched"); + assert.equal(n.takes.length, 4); + for (const t of n.takes.slice(1)) { + assert.deepEqual(t.screenLine, { screen: "s1", n: 2, said: "You can't be this dumb", speaker: "TheQuartering" }); + assert.equal(t.script, "You can't be this dumb"); + } + assert.match(n.takes[1].file, /take-2\.recorded-operator\.wav$/, "a NEW recorded file"); + assert.equal(n.takes[3].steps[0].op, "convert"); + // The original recording of his words is untouched (never rewritten). + assert.equal(n.takes[0].file, OWN.file); + // Picking a line take is refused in the build's words. + const { updatePostNarration } = await import("./manifest.mjs"); + await assert.rejects(() => updatePostNarration(p.dir, "p-2117", { pick: 3 }), /take 4 is a recording of line 2 of screen s1/); +}); + +test("record: a speaker with no character is kept as recorded (a note); the author's own line converts to HER character, never the narrator", async () => { + const { recordScreenLine } = await import("./screenLineRecord.mjs"); + const p = await savvy("rec-who"); + const asked = []; + const a = await recordScreenLine(p, "p-2117", "screen:s1:3", await recording(p, "a.wav"), { ask: stubOps(asked) }); + assert.ok(a.notes.some((x) => /line 3's speaker has no character to convert to -- kept as recorded/.test(x))); + assert.ok(!asked.some((x) => x.route.endsWith("voice-convert"))); + assert.equal(a.disclosure, "a recorded reading"); + const b = await recordScreenLine(p, "p-2117", "screen:s1:1", await recording(p, "b.wav"), { ask: stubOps(asked) }); + assert.equal(asked.at(-1).body.voice, "kokoro:af_bella"); + assert.match(b.disclosure, /af_bella/); + // A cast narrator is never a line's character. + const p2 = await savvy("rec-narr", SAVVY, null); + await mkdir(path.join(p2.dir, ".umtool"), { recursive: true }); + await writeFile(path.join(p2.dir, ".umtool", "cast.json"), JSON.stringify({ format: "umtool-cast", version: 1, characters: [{ id: "me", name: "Me", handles: ["operator"], voice: "kokoro:bm_george", convert: { engine: "openvoice" }, narrator: true }] })); + const asked2 = []; + const c = await recordScreenLine(p2, "p-2117", "screen:s1:0", await recording(p2), { ask: stubOps(asked2) }); + assert.ok(!asked2.some((x) => x.route.endsWith("voice-convert")), "no convert to the narrator"); + assert.ok(c.notes.some((x) => /no character/.test(x))); +}); + +test("record is refused on an item with no read of its own; --check-words refuses a recording heard saying a number or a handle (nothing kept) and warns on other words", async () => { + const { recordScreenLine } = await import("./screenLineRecord.mjs"); + const bare = await savvy("rec-bare", { ...SAVVY, narration: undefined }); + await assert.rejects(() => recordScreenLine(bare, "p-2117", "screen:s1:2", path.join(ROOT, "nope.wav"), { ask: stubOps([]) }), /no read of its own yet/); + const p = await savvy("rec-check"); + const file = await recording(p); + for (const heard of ["call me at 555 201 4477 tonight", "you can't be this dumb @secretkid", "you can't be secretkid this dumb"]) { + await assert.rejects(() => recordScreenLine(p, "p-2117", "screen:s1:2", file, { ask: stubOps([], heard), checkWords: true }), /--check-words: .* refused -- it is heard saying/, heard); + } + assert.equal((await read(p)).timeline[0].narration.takes.length, 1, "a refusal keeps nothing"); + assert.equal((await readdir(path.join(p.dir, "narration/posts/2117"))).filter((f) => f.startsWith(".line-check")).length, 0, "its scratch is gone"); + const w = await recordScreenLine(p, "p-2117", "screen:s1:2", file, { ask: stubOps([], "you can this be dumb"), checkWords: true, convert: false, clean: false }); + assert.ok(w.notes.some((x) => /not the line's in order/.test(x))); + const ok = await recordScreenLine(p, "p-2117", "screen:s1:2", file, { ask: stubOps([], "You can't be this dumb"), checkWords: true, convert: false, clean: false }); + assert.ok(ok.notes.some((x) => /heard saying the line/.test(x))); +}); + +test("a line take is read ONLY when chosen: the screen's lineTakes (set <id> take.<n>=) or --line-take; another line's or a stale one refused; the disclosure says what it is", async () => { + const { recordScreenLine } = await import("./screenLineRecord.mjs"); + const { threadTake, postTakeOf } = await import("./postThreadRead.mjs"); + const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration"); + const { lineTakeWarnings, threadReadErrors } = await import("umtool-report-to-video/post-thread"); + const p = await savvy("choose"); + await recordScreenLine(p, "p-2117", "screen:s1:2", await recording(p), { ask: stubOps([]) }); + let e = (await read(p)).timeline[0]; + // Not chosen: synthesized, and said so. + const tts = []; + let r = await posts(["screen", "choose", "p-2117", "read", "--dry-run"]); + assert.equal(r.code, 0, r.text); + assert.match(r.text, /screen:s1:2 is synthesized: its recordings take 2, take 3, take 4 not chosen -- --line-take screen:s1:2=4/); + assert.ok(lineTakeWarnings(e).some((x) => /line 2 of screen s1 has a recording no read uses/.test(x))); + // Chosen by number; another line's take refused; off unchooses. + r = await posts(["screen", "choose", "p-2117", "set", "s1", "take.0=4"]); + assert.equal(r.code, 2); + assert.match(r.text, /take 4 does not say line 0 of screen s1 as it is now \(it was recorded for line 2/); + r = await posts(["screen", "choose", "p-2117", "set", "s1", "take.2=4"]); + assert.equal(r.code, 0, r.text); + e = (await read(p)).timeline[0]; + assert.deepEqual(e.screens[0].lineTakes, { 2: "take-4.convert-openvoice" }); + r = await posts(["screen", "choose", "p-2117", "list"]); + assert.match(r.text, /2 TheQuartering: You can't be this dumb {3}\[recorded: take 2, take 3, take 4 \(chosen\)\]/); + const made = await threadTake(p, e, { red: NO_RED, ask: stubTts(tts), lanes: null, postTake: 1 }); + const parts = made.take.parts; + assert.equal(parts.find((x) => x.role === "screen:s1:2").take, "take-4.convert-openvoice"); + assert.ok(!tts.some((b) => /dumb/.test(b.text)), "the chosen line is not synthesized"); + const after1 = (await read(p)).timeline[0]; + assert.deepEqual(threadReadErrors(after1, {}), []); + assert.deepEqual(lineTakeWarnings(after1).filter((x) => !/was not heard/.test(x)), [], "only that nothing heard it"); + // The disclosure names the converted recording (and the synthetic voices of the rest). + assert.match(postNarrationDisclosure(after1), /a recorded reading converted to a stock voice \(openvoice · kokoro:am_michael\)/); + // A line take is never his words, and never another line's. + assert.throws(() => postTakeOf(after1, 4), /a recording of line 2 of screen s1: it is read in that line's place/); + assert.throws(() => postTakeOf(after1, 4, { line: "screen:s9:0" }), /a recording of a line of screen s1, not of screen:s9:0/); + // Another line's words: refused by its content (owned by what it says, not by its index). + await assert.rejects(() => threadTake(p, after1, { red: NO_RED, ask: stubTts([]), lanes: null, postTake: 1, lineTakes: { "screen:s1:0": 4 }, force: true }), /does not say line 0 of screen s1 as it is now/); + // The line edited since it was recorded: the chosen take is refused, never played under new words (R1 #1). + r = await posts(["screen", "choose", "p-2117", "set", "s1", "line.2.text=You cannot be this dumb"]); + assert.equal(r.code, 0, r.text); + const edited = (await read(p)).timeline[0]; + assert.ok(lineTakeWarnings(edited).some((x) => /its chosen take \(take 4\) was recorded for the line as it was/.test(x))); + await assert.rejects(() => threadTake(p, edited, { red: NO_RED, ask: stubTts([]), lanes: null, postTake: 1, force: true }), /does not say line 2 of screen s1 as it is now/); + // Given to another speaker since: the same. + r = await posts(["screen", "choose", "p-2117", "set", "s1", "line.2.text=You can't be this dumb", "line.2.who=Stranger"]); + assert.equal(r.code, 0, r.text); + const given = (await read(p)).timeline[0]; + await assert.rejects(() => threadTake(p, given, { red: NO_RED, ask: stubTts([]), lanes: null, postTake: 1, force: true }), /does not say line 2 of screen s1 as it is now/); + r = await posts(["screen", "choose", "p-2117", "set", "s1", "take.2=off"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens[0].lineTakes, undefined); + // A chosen take cannot be deleted until it is unchosen. + const q = await savvy("choose-del"); + await recordScreenLine(q, "p-2117", "screen:s1:0", await recording(q), { ask: stubOps([]), clean: false, convert: false }); + assert.equal((await posts(["screen", "choose-del", "p-2117", "set", "s1", "take.0=2"])).code, 0); + r = await posts(["narrate", "choose-del", "p-2117", "--delete", "2"]); + assert.notEqual(r.code, 0); + assert.match(r.text, /chosen for line 0 of screen s1: unchoose it first/); + assert.equal((await read(q)).timeline[0].narration.takes.length, 2, "nothing moved"); +}); + +test("the data: lineTakes names a recording of a line of that screen; a line removed takes its choice with it, the later ones' keys move down -- and the choice still plays (owned by content, l1 #1b)", async () => { + const { withoutLines, validateScreens } = await import("umtool-report-to-video/post-screens"); + const { lineTakesOf } = await import("umtool-report-to-video/post-thread"); + const rec = (n, file, screen = "s1") => ({ file, engine: "recorded", voice: "operator", seconds: 1, script: "x", screenLine: { screen, n, said: n === 2 ? "You can't be this dumb" : "ask Kid A about it", speaker: "TheQuartering" } }); + const e = { ...SAVVY, narration: { ...SAVVY.narration, takes: [OWN, rec(2, "narration/posts/2117/take-2.recorded-operator.wav"), rec(4, "narration/posts/2117/take-3.recorded-operator.wav"), rec(0, "narration/posts/2117/take-4.recorded-operator.wav", "s9")] } }; + const sc = { ...DM, lineTakes: { 2: "take-2.recorded-operator", 4: "take-3.recorded-operator" } }; + assert.deepEqual(validateScreens({ ...e, screens: [sc] }), []); + assert.ok(validateScreens({ ...e, screens: [{ ...DM, lineTakes: { 0: "take-4.recorded-operator" } }] }).some((x) => /take 4 is not a recording of a line of screen s1 \(it is of screen s9\)/.test(x))); + // Line 0 removed above line 2's chosen take: the choice moves to key 1 and the take still says that line (current). + const moved = { ...e, screens: [withoutLines(sc, [0])] }; + assert.deepEqual(validateScreens(moved), []); + const L = lineTakesOf(moved).find((x) => x.role === "screen:s1:1"); + assert.deepEqual(L.takes.map((t) => [t.n, t.current, t.chosen]), [[2, true, true]]); + assert.ok(validateScreens({ ...e, screens: [{ ...DM, lineTakes: { 2: "take-9.nope" } }] }).some((x) => /must be the id of one of the item's takes/.test(x))); + assert.ok(validateScreens({ ...e, screens: [{ ...DM, lineTakes: { 7: "take-2.recorded-operator" } }] }).some((x) => /has no line 7/.test(x))); + assert.deepEqual(withoutLines(sc, [2]).lineTakes, { 3: "take-3.recorded-operator" }); + assert.deepEqual(withoutLines(sc, [0]).lineTakes, { 1: "take-2.recorded-operator", 3: "take-3.recorded-operator" }); + assert.equal("lineTakes" in withoutLines({ ...DM, lineTakes: { 2: "x" } }, [2]), false); +}); diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -58,12 +58,12 @@ import { mkdir, readdir, stat, writeFile } from "node:fs/promises"; 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 { chronoPieces } from "umtool-report-to-video/post-thread"; +import { chosenLineTakes, chronoPieces, lineTakesOf } from "umtool-report-to-video/post-thread"; import { cardText, parentsOf } 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, shapeSpans } from "umtool-report-to-video/post-screens"; +import { SCREEN_LINE_GAP, parseScreenRole, screenWho, screensOf, shapeSpans } from "umtool-report-to-video/post-screens"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -181,7 +181,16 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i const script = own ? null : draftScript(cardText(e)).script || null; const pieces = []; const skipped = []; + // A SCREEN MADE FROM ITS READ (`posts screen … add --from-read`: `source: "read"`) IS that read: its lines are what + // the picture says, so his own piece is not read as well (it would say the picture's words twice, and what the card + // masks once) -- and no take of his words stands in for it. + const fromRead = screensOf(e).find((sc) => sc.source === "read" && screens) ?? null; + if (fromRead && postTake) throw new ThreadReadError(`--post-take: ${e.id}'s own words are its screen ${fromRead.id}'s lines (made from its read): no take reads them as well -- leave --post-take out`); for (const p of chronoPieces(e)) { + if (p.role === "post" && fromRead) { + skipped.push({ role: "post", why: `its read is screen ${fromRead.id}'s lines (made from its read)` }); + continue; + } const m = /^parent:(\d)$/.exec(p.role); if (m) { const at = Number(m[1]); @@ -229,6 +238,13 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i continue; } const lt = lineTakes?.[p.role] ?? null; + // A RECORDING OF A LINE (`screenLine`: posts screen … record) is that line's as it was recorded: another line's, or + // a line whose words or speaker changed since, is refused -- the old audio never plays under new lit text. + const sl = lt?.take?.screenLine; + if (sl && typeof sl === "object" && (str(sl.said).replace(/\s+/g, " ").trim() !== norm(written) || str(sl.speaker).trim().toLowerCase() !== str(p.who).trim().toLowerCase())) { + const sp = /^screen:([a-z0-9-]+):(\d+)$/.exec(p.role); + throw new ThreadReadError(`--line-take ${p.role}=${lt.n}: that take does not say line ${sp[2]} of screen ${sp[1]} as it is now (it was recorded for line ${sl.n} as it was: other words or another speaker) -- record the line again (umtool posts screen <p> ${e.id} record ${sp[1]} ${sp[2]} --recording <file>), or unchoose it (set ${sp[1]} take.${sp[2]}=off)`); + } if (lt) { // THE LINE FROM A TAKE (--line-take): that take's file is the line's piece, and its words are what the TAKE says // (`said`, else its script -- as --post-take's are), so every check that reads a read's words reads the audio's. @@ -263,7 +279,8 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: p.role === "post" ? e.narration?.speed ?? null : null, engine: v.engine }); pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) }); } - if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); + if (!fromRead && !pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); + if (!pieces.length) throw new ThreadReadError(`${e.id} has nothing to read (its screen ${fromRead?.id ?? ""} reads no line)`); // HIS LINE FROM A TAKE (--post-take): the take's file is the post's piece, its script its words; nothing synthesized. if (postTake) { const at = pieces.findIndex((p) => p.role === "post"); @@ -360,7 +377,7 @@ export function takeVoiceOf(t) { * THE TAKE A THREAD READ's own line may be (--post-take n, as --list numbers them), checked: `{ n, take }`. Refused: no * such take, a THREAD take (its own context in it), one with no file. */ -export function postTakeOf(e, n) { +export function postTakeOf(e, n, { line = null } = {}) { const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; const k = Number(n); if (!Number.isInteger(k) || k < 1) throw new ThreadReadError(`--post-take takes a take's number as --list shows it (1 = the first), not ${n}`); @@ -368,6 +385,11 @@ export function postTakeOf(e, n) { const t = takes[k - 1]; if (!t || typeof t.file !== "string" || !t.file) throw new ThreadReadError(`--post-take ${k}: that take has no file`); if (/-thread\.wav$/.test(t.file) || t.read?.kind === "thread") throw new ThreadReadError(`--post-take ${k} is a thread read itself (${t.file}): name a take of his line alone`); + // A RECORDING OF A SCREEN LINE (`screenLine`) is that line's alone: never his words, never another line. + const sl = t.screenLine && typeof t.screenLine === "object" ? t.screenLine : null; + if (sl && line === null) throw new ThreadReadError(`--post-take ${k} is a recording of line ${sl.n} of screen ${sl.screen}: it is read in that line's place (--line-take screen:${sl.screen}:${sl.n}=${k}), never as his words`); + // Owned by its CONTENT (its screen, words and speaker -- threadReadPlan holds it to the line as it is), not its index. + if (sl && line !== null && parseScreenRole(line)?.id !== sl.screen) throw new ThreadReadError(`--post-take ${k} is a recording of a line of screen ${sl.screen}, not of ${line}`); return { n: k, take: t }; } @@ -474,10 +496,12 @@ export async function threadTake(project, e, opts = {}) { const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null; const postTake = postTakeN === null || postTakeN === undefined ? null : postTakeOf(e, postTakeN); // A screen line from a take (--line-take): checked as --post-take's is. - const lineTakes = Object.fromEntries(Object.entries(lineTakesN ?? {}).map(([role, n]) => { + // The takes the screens CHOSE for their lines (`lineTakes`, the operator's: the bench's select, `set <id> take.<n>=`), + // under the ones the command names -- never one nobody chose. + const lineTakes = Object.fromEntries(Object.entries({ ...chosenLineTakes(e), ...(lineTakesN ?? {}) }).map(([role, n]) => { if (!parseScreenRole(role)) throw new ThreadReadError(`--line-take names a screen's line as screen:<id>:<n> (got ${role})`); try { - return [role, postTakeOf(e, n)]; + return [role, postTakeOf(e, n, { line: role })]; } catch (err) { throw new ThreadReadError(String(err instanceof Error ? err.message : err).replace(/--post-take/g, `--line-take ${role}=`)); } @@ -635,9 +659,13 @@ export async function threadCommand(project, e, o) { } 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. + const used = new Set(r.plan.pieces.filter((p) => p.take && p.role !== "post").map((p) => p.role)); + const notChosen = lineTakesOf(e).filter((L) => !used.has(L.role) && r.plan.pieces.some((p) => p.role === L.role)).map((L) => ({ role: L.role, takes: L.takes.filter((x) => x.current).map((x) => x.n) })).filter((L) => L.takes.length); if (json) { out(JSON.stringify({ ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped, + ...(notChosen.length ? { lineTakesNotChosen: notChosen } : {}), parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.take ? { take: p.take, file: p.file } : { key: p.key }), cached: p.cached, text: p.text })), fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane, ...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}), @@ -647,6 +675,10 @@ export async function threadCommand(project, e, o) { out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`); for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.take ? p.voice : p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.take ? `(take ${p.take.n}: ${p.take.file}) ` : ""}${p.from === "cast" ? "(cast) " : p.from === "item" ? `(the item's character: ${p.character}) ` : p.from === "project" && p.character ? `(this video's character: ${p.character}) ` : ""}${p.speed !== undefined ? `×${p.speed} ` : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`); + for (const L of notChosen) { + const m = /^screen:([a-z0-9-]+):(\d+)$/.exec(L.role); + out(` (${L.role} is synthesized: its recording${L.takes.length > 1 ? "s" : ""} take ${L.takes.join(", take ")} not chosen -- --line-take ${L.role}=${L.takes.at(-1)}, or umtool posts screen ${project.id} ${e.id} set ${m[1]} take.${m[2]}=${L.takes.at(-1)})`); + } if (r.upToDate) { out(` up to date: the picked take already reads this, in these voices (--force makes it again)`); return 0; diff --git a/umtool/lib/report/present.mjs b/umtool/lib/report/present.mjs @@ -25,12 +25,14 @@ // `canUncensor: false` (a public export, step 4) carries the CENSORED posts only -- every redacted span already // marked, every masked slur masked, every blurred author's name and handle gone from the data -- and no reveal // data at all. A public page can add censoring, never remove it. -import { cardAuthors, cardText, excerptRanges, excerptSpansOf, postDay } from "umtool-report-to-video/post-item"; +import { cardAuthors, cardText, excerptRanges, excerptSpansOf, postDay, screenSpeakerShown } from "umtool-report-to-video/post-item"; +import { maskedField, screenHeader, screenIsExcerpt, screenRows, screenSide } from "umtool-report-to-video/post-screens"; +import { drawnScreens, partRoles, playableTake } from "umtool-report-to-video/post-thread"; +import { followKnobs } from "umtool-report-to-video/read-follow"; import { REDACT_MARK, redactEntry, redactionOn } from "umtool-report-to-video/post-redact"; import { maskFor, slurMatches, slursOn } from "umtool-report-to-video/post-slurs"; import { blurOf, censorEntry } from "umtool-report-to-video/post-censor"; import { clockZoneOf } from "umtool-report-to-video/post-clock"; -import { pickedTake } from "umtool-report-to-video/post-narration"; import { estimateSchedule } from "umtool-report-to-video/deck"; import { gapsOf, keptSpans } from "umtool-report-to-video/gaps"; import { clipBlurOf } from "umtool-report-to-video/clip-blur"; @@ -188,7 +190,7 @@ export function censorData(entry, red) { * @param {Record<string, any>} entry * @param {import("umtool-report-to-video/post-redact").Redaction | null} red */ -export function publicPostEntry(entry, red) { +export function publicPostEntry(entry, red, render = undefined) { const out = /** @type {Record<string, any>} */ (structuredClone(redactEntry(entry, red))); // A blurred author keeps a handle that names nobody: the card's rule still blurs it, and a mention of it in any // words is drawn blurred too (wordsHtml) -- the real handle is nowhere in the data. @@ -226,12 +228,58 @@ export function publicPostEntry(entry, red) { if (typeof out.replyingTo === "string" && blurred.has(out.replyingTo.replace(/^@/, "").toLowerCase())) out.replyingTo = NOBODY; if (Array.isArray(out.subjects)) out.subjects = out.subjects.filter((h) => !blurred.has(String(h).replace(/^@/, "").toLowerCase())); } - const take = pickedTake(entry); + // Its read as a preview may play it (post-thread.mjs playableTake: none when the build refuses it). + const take = playableTake(entry); if (isObj(out.narration)) out.narration = take ? { takes: [{ file: take.file, seconds: take.seconds, ...(fin(take.rate) ? { rate: take.rate } : {}) }], pick: 0 } : { off: true }; delete out.notes; + // ITS SCREENS AS THE CARD DRAWS THEM (re-check M): built from the card's drawing, never a raw line in the data. + if (Array.isArray(out.screens)) { + out.screens = publicScreens(out, { authorHidden: cardAuthors(entry).some((a) => a.where === "author" && a.redact), roles: take ? partRoles(entry) : [], follow: followKnobs(entry, render ?? {}).on }); + } + // A read not played: why, without the build's words (they name commands, not what was said). + if (isObj(out.readRefused)) out.readRefused = { reason: String(out.readRefused.reason ?? "") }; return out; } +/** + * A post's SCREENS AS ITS CARD DRAWS THEM, for a payload that cannot uncensor (review round 1, i; re-check M) -- built + * FROM THE CARD's OWN DRAWING, never a second pass over the lines: only the screens the card draws (post-thread.mjs + * drawnScreens: the ones its read reads, with read-follow on), each as its rows (post-screens.mjs screenRows: a read + * line's read run alone, masked, "…" where it is cut; a line not read absent -- a `{ gap }` row where the card draws + * "⋯" -- or dim when the card draws it dim; a redacted line never), its header and badge (screenHeader), each row's + * speaker as the card names it (post-item.mjs screenSpeakerShown; a blurred one `xxxxxxxx`, one a speaker) and its + * time masked. `{ id, kind, media, at?, header, badge, excerpt, rows }` -- no `lines`, no `read`: nothing to draw from + * but what was drawn. + * + * @param {Record<string, any>} entry the post item as the card draws it (its redaction marked, its anonymous authors + * under their names) + * @param {{ authorHidden?: boolean, roles?: Array<{ role: string | null }>, follow?: boolean }} [o] `roles`: its + * picked take's (partRoles); `follow`: read-follow on (off: the card is not threaded, no screen is drawn) + */ +export function publicScreens(entry, { authorHidden = false, roles = [], follow = true } = {}) { + if (!follow) return []; + const hidden = new Map(); + const nobody = (who) => { + const k = String(who).trim().toLowerCase(); + if (!hidden.has(k)) hidden.set(k, hidden.size ? `${NOBODY}${hidden.size + 1}` : NOBODY); + return hidden.get(k); + }; + return drawnScreens(entry, roles).map((sc) => { + const head = screenHeader(entry, sc, { authorHidden }); + const rows = screenRows(sc).map((r) => { + if (r.gap) return { gap: r.lines }; + const l = sc.lines[r.n] ?? {}; + const who = str(l.who).trim(); + return { + n: r.n, text: `${r.cutBefore ? "…" : ""}${r.text}${r.cutAfter ? "…" : ""}`, read: r.read, side: screenSide(l, entry), + ...(who ? { who: screenSpeakerShown(entry, l, { authorHidden }) ? maskedField(who) : nobody(who) } : {}), + ...(str(l.time).trim() ? { time: maskedField(l.time.trim()) } : {}), + }; + }); + return { id: sc.id, kind: sc.kind, media: sc.media, ...(Array.isArray(sc.at) ? { at: sc.at } : {}), header: head.text, badge: head.badge, excerpt: screenIsExcerpt(sc), rows }; + }); +} + // --------------------------------------------------------------------------- // THE SLIDES. // --------------------------------------------------------------------------- @@ -343,10 +391,10 @@ export function presentFrom({ view, manifest, red, canUncensor = true }) { if (e.type === "post" && e.post && e.postPlan) { const post = /** @type {Record<string, any>} */ (e.post); const day = dayIn(post.date, zone); - const take = pickedTake(post); + const take = playableTake(post); const spans = excerptSpansOf(post); const excerpt = spans ? excerptRanges(cardText(post), spans) : null; - const shown = canUncensor ? post : publicPostEntry(post, red); + const shown = canUncensor ? post : publicPostEntry(post, red, manifest.render); slides.push({ id: unique(postSlideId(e)), kind: "post", diff --git a/umtool/lib/report/recordPreview.mjs b/umtool/lib/report/recordPreview.mjs @@ -33,7 +33,7 @@ import { convertAskOf, stepPitchOf } from "./derivePitch.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; import { NarrateError, findPostItem, measureTake } from "./postNarrationCli.mjs"; -import { RECORD_LABEL_RE, decodePart, explicitSpan, joinRecording, partsIn, roomOf, targetLufsOf, trimSpan } from "./postRecord.mjs"; +import { RECORD_LABEL_RE, claimRecordedTake, claimTakeName, decodePart, explicitSpan, joinRecording, partsIn, roomOf, targetLufsOf, trimSpan } from "./postRecord.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -389,7 +389,8 @@ export async function keepPreview(project, entry, { label = "operator", script = const partsRel = rel.replace(/\.wav$/, ".parts"); const from = path.join(dir, made.file.replace(/\.wav$/, ".parts")); if (await stat(from).catch(() => null)) { - await rm(abs(partsRel), { recursive: true, force: true }); + // A parts folder already at that name is another take's: never removed (the claim makes one unlikely; refused). + if (await stat(abs(partsRel)).catch(() => null)) throw Object.assign(new NarrateError(`${partsRel} is there already (another take's parts): nothing of it is touched -- keep it again`), { status: 409 }); await rename(from, abs(partsRel)); } return partsRel; @@ -401,8 +402,11 @@ export async function keepPreview(project, entry, { label = "operator", script = const text = String(script ?? entry.narration?.script ?? ""); const who = doc.character; - // The original. - const rel = `${takesDirOf(pid)}/take-${n}.recorded-${label}.wav`; + // The original -- its name CLAIMED (postRecord.mjs claimRecordedTake): never a recording already there, nor one kept + // at the same moment; each derived one's too (claimTakeName). + const claim = await claimRecordedTake(project.dir, entry, label); + n = claim.n; + const rel = claim.rel; const partsRel = await move(doc.built.raw, rel); const parts = multi ? partsIn(doc.built.raw.parts, partsRel) : null; const recorded = { @@ -419,8 +423,9 @@ export async function keepPreview(project, entry, { label = "operator", script = // The cleaned one. if (doc.built.clean) { - n += 1; - const r2 = derivedFileOf(pid, n, "enhance", "default"); + const c2 = await claimTakeName(project.dir, (k) => derivedFileOf(pid, k, "enhance", "default"), n + 1); + n = c2.n; + const r2 = c2.rel; const p2 = await move(doc.built.clean, r2); const take = derived(r2, doc.built.clean, { op: "enhance", ...(doc.clean?.engine ? { engine: doc.clean.engine } : {}), ranAt: doc.clean?.ranAt ?? at(), ...(doc.clean?.job ? { job: doc.clean.job } : {}) }, label, p2, doc.clean?.job); result = await write({ addTake: take }); @@ -429,9 +434,10 @@ export async function keepPreview(project, entry, { label = "operator", script = } // The converted one -- when it is of these marks (a mark moved after the Filter leaves it behind). if (doc.convert && doc.convert.built === doc.built.key && (await stat(path.join(dir, doc.convert.file)).catch(() => null))?.isFile()) { - n += 1; const c = doc.convert; - const r3 = derivedFileOf(pid, n, "convert", c.asked?.engine ?? c.asked?.voice ?? "default"); + const c3 = await claimTakeName(project.dir, (k) => derivedFileOf(pid, k, "convert", c.asked?.engine ?? c.asked?.voice ?? "default"), n + 1); + n = c3.n; + const r3 = c3.rel; const p3 = await move(c, r3); const pitched = c.pitch ? { pitch: c.pitch, ...(typeof c.semitones === "number" ? { semitones: c.semitones } : {}) } : {}; const take = derived(r3, c, { op: "convert", ...(c.engine ? { engine: c.engine } : {}), voice: c.voice, ...pitched, ranAt: c.ranAt ?? at(), ...(c.job ? { job: c.job } : {}) }, String(c.voice).split(":").pop(), p3, c.job); diff --git a/umtool/lib/report/screenLineRecord.mjs b/umtool/lib/report/screenLineRecord.mjs @@ -0,0 +1,209 @@ +// A SCREEN LINE RECORDED BY THE OPERATOR (lane/screens-2; docs/report-video.md, "Screens" -- "A line in your own +// voice"): one line of a post's screen (post-screens.mjs) read by a person, kept as a NEW take of the item -- recorded, +// cleaned, converted to the line's SPEAKER's character's stock voice -- each step a new take, NONE of them the item's +// read (never picked): a line take is read in its line's place by the item's thread read only once the operator +// CHOOSES it (`--line-take`, the screen's `lineTakes`: the bench's per-line select, `posts screen … set <id> take.<n>=`). +// +// umtool posts screen <p> <item> record <id> <n> --recording <file> [--as <the speaker's character>] [--no-clean|--clean] +// [--no-trim|--trim] [--no-convert] [--pitch …] [--semitones n] [--label l] [--check-words [--worker w]] +// +// WHAT IS READ: the line as the read says it (screenLineSaid: its read run, its shapes left out; draftScript; the +// redaction left out, an anonymous handle said as its shown name: post-redact.mjs spokenRead) -- the PROMPT the person +// reads is that, without the pronunciation lexicon's spellings, and the take's script is it with them (what the read +// holds the take to: postThreadRead.mjs lineTakeProblem). The take carries `screenLine: { screen, n, said, speaker }`: +// the line as a read writes it and its speaker, so a line edited or given to someone else since is refused, never +// played (postThreadRead.mjs threadReadPlan). The recording itself is postNarrationCli.mjs importRecording's chain. +// +// --check-words (opt-in; the editor's transcribe op, a job): the recording TRANSCRIBED before anything is kept -- +// REFUSED when it is heard saying a shape (an e-mail, a number: post-screens.mjs shapeSpans), an @handle, an anonymous +// handle or a redacted term; a warning when its words are not the line's in order. Without it, the recording is the +// operator's: what he reads is what he chose. +// +// Plain ESM: the CLI runs it under bare node. +import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import path from "node:path"; +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 { readManifest } from "../projects/report.mjs"; + +const str = (v) => (typeof v === "string" ? v : ""); + +export class LineRecordError extends Error { + constructor(message) { + super(message); + this.name = "LineRecordError"; + } +} + +/** + * THE LINE TO RECORD, pure: `{ role, screen, n, written, script, prompt, speaker, handle, self }` -- `written` the line + * as a read writes it (the take's `screenLine.said`), `script` what the read says (the take's script), `prompt` what the + * person reads (the same without the lexicon's spellings). Throws LineRecordError: no such screen or line, a line + * redacted or not read, nothing left to say. + * + * @param {Record<string, any>} e the post item + * @param {string} role `screen:<id>:<n>` + * @param {{ red?: any, names?: Record<string, string> }} [o] + */ +export function lineToRecord(e, role, { red = null, names = {} } = {}) { + const p = parseScreenRole(role); + if (!p) throw new LineRecordError(`a screen line is screen:<id>:<n> (got ${role})`); + const sc = screenOf(e, p.id); + if (!sc) throw new LineRecordError(`${e?.id} has no screen ${p.id}`); + const l = sc.lines[p.n]; + if (!l) throw new LineRecordError(`screen ${p.id} has no line ${p.n} (lines 0–${sc.lines.length - 1})`); + 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; + // 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(); + 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 }; +} + +/** + * THE CHARACTER A LINE's RECORDING IS MADE INTO, pure: its SPEAKER's -- the post's author's own lines the item's + * chain (characterForRead: the item's own, this video's for her, the cast's; never the narrator), anyone else's the + * character holding their handle (this video's characters first, then the cast). Null: none (kept as recorded). + */ +export function lineCharacterOf(layers, e, target) { + if (target.self) { + const r = layers.characterForRead(e); + return r && r.layer !== "narrator" ? r.character : null; + } + const h = handleKey(target.handle); + if (!h) return null; + return projectCharactersOf(layers.project).find((c) => (c.handles ?? []).map(handleKey).includes(h)) ?? characterOf(layers.cast, h) ?? null; +} + +/** A digit said as a word (ASR writes numbers both ways). */ +const DIGIT_WORDS = new Set(["zero", "oh", "o", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "double", "triple"]); + +/** + * WHAT A RECORDING IS HEARD SAYING AMISS, pure (--check-words): `{ refused: string | null, warning: string | null }`. + * REFUSED when the words heard hold a shape (an e-mail, a number: post-screens.mjs shapeSpans), a number SAID IN WORDS + * (seven digits or more, as words or digits in a row: "five five five two oh one…"), an @handle, an anonymous author's + * handle (`handles`; bare, possessive "secretkid's", or spaced "secret kid") or display name (`names`, the same forms), + * or a redacted term (`terms`); a warning when its words are not the line's in order (postThreadRead.mjs + * lineTakeProblem's "other words": ASR slack is the person's to judge). Names what, never the words. + */ +export function heardProblem(heard, script, { handles = [], names = [], terms = [], lineTakeProblem }) { + const h = str(heard); + if (shapeSpans(h).length) return { refused: "it is heard saying an e-mail address or a number the card masks", warning: null }; + const raw = h.toLowerCase().replace(/[’‘]/g, "'").split(/\s+/).filter(Boolean); + if (raw.some((w) => /^[^\p{L}\p{N}]*@/u.test(w))) return { refused: "it is heard saying an @handle", warning: null }; + // Each word bare: its edge punctuation and a possessive dropped. + const words = raw.map((w) => w.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}']+$/gu, "").replace(/'s$|'$/u, "").replace(/[^\p{L}\p{N}]/gu, "")).filter(Boolean); + // A number said in words (or in digits a word at a time). + let run = 0; + for (const w of words) { + if (DIGIT_WORDS.has(w)) run += w === "double" ? 1 : w === "triple" ? 2 : 1; + else if (/^\d+$/.test(w)) run += w.length; + else run = 0; + if (run >= 7) return { refused: "it is heard saying a number in words (a number the card masks)", warning: null }; + } + // A handle or a name: a word, or two or three words run together ("secret kid"), or the name's words in a row. + const joined = (i, k) => words.slice(i, i + k).join(""); + const says = (target) => { + const t = String(target).toLowerCase().replace(/^@+/, ""); + const flat = t.replace(/[^\p{L}\p{N}]/gu, ""); + if (!flat) return false; + const tw = t.split(/[^\p{L}\p{N}]+/u).filter(Boolean); + for (let i = 0; i < words.length; i += 1) { + for (let k = 1; k <= 3 && i + k <= words.length; k += 1) if (joined(i, k) === flat) return true; + if (tw.length > 1 && tw.every((x, j) => words[i + j] === x)) return true; + } + return false; + }; + if (handles.some(says)) return { refused: "it is heard saying an anonymous author's handle", warning: null }; + if (names.filter((n) => str(n).trim().length >= 3).some(says)) return { refused: "it is heard saying an anonymous author's name", warning: null }; + const esc = (t) => String(t).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + if (terms.some((t) => new RegExp(`(?<![\\p{L}\\p{N}])${esc(t)}(?![\\p{L}\\p{N}])`, "iu").test(h))) return { refused: "it is heard saying a redacted term", warning: null }; + const why = lineTakeProblem(h, script, { handles, terms }); + return { refused: null, warning: why ? "its words as heard are not the line's in order (the transcription may have misheard: listen to it)" : null }; +} + +/** The anonymous authors' DISPLAY NAMES this video knows (their characters' names, the posts by their handles). */ +export function anonymousNamesOf(manifest, projectDoc, handles) { + const hs = new Set(handles.map((x) => String(x).replace(/^@+/, "").toLowerCase())); + const out = new Set(); + for (const c of Array.isArray(projectDoc?.characters) ? projectDoc.characters : []) if (c?.anonymous === true && str(c.name).trim()) out.add(str(c.name).trim()); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + for (const w of [e, ...(Array.isArray(e?.parents) ? e.parents : []), e?.quoted].filter((x) => x && typeof x === "object")) { + if (hs.has(str(w.handle).replace(/^@+/, "").toLowerCase()) && str(w.author).trim()) out.add(str(w.author).trim()); + } + } + return [...out]; +} + +/** + * RECORD ONE SCREEN LINE of post item `id` (see the head): `file` a sound file; the takes made (`{ takes: [{ step, file + * }], picked: null, notes, disclosure, character, line: { role, prompt } }`). Refused (LineRecordError) on an item with + * no read of its own (a line is read inside one), a line that cannot be read, `as` naming no one, and -- with + * `checkWords` -- a recording heard saying what is never said. `ask` / `editor`: the editor's ops (tests stub them). + */ +export async function recordScreenLine(project, id, role, file, opts = {}) { + const { as = null, label = "operator", clean = undefined, trim = undefined, convert = true, pitch = undefined, semitones = undefined, note = null, checkWords = false, worker = null, emit = () => {}, editor = null, ask = null } = opts; + const manifest = await readManifest(project.dir); + const e = (manifest?.timeline ?? []).find((x) => x?.type === "post" && x.id === id); + if (!e) throw new LineRecordError(`no post item ${id} in ${project.id}`); + const t = pickedTake(e); + if (!isNarrated(e) || t?.screenLine) throw new LineRecordError(`${id} has no read of its own yet: a screen line is read inside the item's read -- make it first (umtool posts narrate <p> ${id} --take, or record it), then record the line`); + const { projectRedaction } = await import("./postRedaction.mjs"); + const red = await projectRedaction(project.dir, manifest); + const { readLayers } = await import("./characterLayers.mjs"); + const layers = await readLayers(project.dir); + const { characterNames, lineTakeProblem } = await import("./postThreadRead.mjs"); + const target = lineToRecord(e, role, { red, names: characterNames(layers) }); + // A line converts ONLY to its SPEAKER's character (operator, 13 Nov): --as may name that one, never another, never + // the narrator. + const character = lineCharacterOf(layers, e, target); + if (as) { + const named = layers.characterForRead(e, as)?.character ?? null; + if (!named) throw new LineRecordError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`); + if (named.narrator === true) throw new LineRecordError(`--as ${as}: the narrator is never a screen line's voice -- a line converts only to its speaker's character`); + if (!character || named.id !== character.id) throw new LineRecordError(`--as ${as}: not the character of line ${target.n}'s speaker${character ? ` (that is ${character.id})` : " (the speaker has none: the line is kept as recorded)"} -- a line converts only to its speaker's character`); + } + const notes = []; + let heardRec = null; + if (checkWords) { + // Heard BEFORE anything is kept: a refusal keeps nothing. + const { decodePart } = await import("./postRecord.mjs"); + const dir = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/")); + await mkdir(dir, { recursive: true }); + const tmp = await mkdtemp(path.join(dir, ".line-check-")); + try { + const wav = path.join(tmp, "heard.wav"); + await decodePart(path.resolve(file), wav); + const out = path.join(tmp, "heard.words.json"); + const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; + emit("note", { message: `${id}: the recording of ${role} transcribed on the editor (--check-words)…` }); + await askOp("/api/ops/transcribe", { path: wav, words: true, out, ...(worker ? { workerId: worker } : {}) }, { ...(editor ? { editor } : {}), emit }); + const doc = JSON.parse(await readFile(out, "utf8").catch(() => "{}")); + const heard = Array.isArray(doc?.words) && doc.words.length ? doc.words.map((w) => str(w?.w)).join(" ") : str(doc?.text); + if (!heard.trim()) throw new LineRecordError(`--check-words: the editor heard no words in the recording of ${role} -- nothing kept`); + const anonHandles = red?.anon instanceof Map ? [...red.anon.keys()] : Object.keys(red?.anon ?? {}).filter((x) => x !== "postIds"); + const p = heardProblem(heard, target.script, { handles: anonHandles, names: anonymousNamesOf(manifest, layers.project, anonHandles), terms: termsFor(e, red).map((x) => x.term), lineTakeProblem }); + if (p.refused) throw new LineRecordError(`--check-words: the recording of ${role} is refused -- ${p.refused}; nothing kept: record the line again`); + if (p.warning) notes.push(`--check-words: ${p.warning}`); + else notes.push("--check-words: heard saying the line"); + // What it was heard saying, against which words: kept with the take (an unheard one says it was not). + heardRec = { at: new Date().toISOString(), against: target.script, words: heard.replace(/\s+/g, " ").trim().slice(0, 2000) }; + } finally { + await rm(tmp, { recursive: true, force: true }); + } + } + const { importRecording } = await import("./postNarrationCli.mjs"); + const r = await importRecording(project, e, file, { + label, clean, trim, convert, pitch, semitones, note, emit, editor, ask, character, + screenLine: { screen: target.screen, n: target.n, said: target.written, speaker: target.speaker, ...(heardRec ? { heard: heardRec } : {}) }, script: target.script, + }); + if (!heardRec) notes.push("not heard: nothing checked what the recording says -- the read takes it as the line's words (--check-words hears it)"); + return { ...r, notes: [...notes, ...r.notes], line: { role, prompt: target.prompt, speaker: target.speaker }, heard: !!heardRec }; +} diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -1235,6 +1235,20 @@ export function pictureHtml(scope, media, { width, maxH, k, mediaUrl = null, pos } /** + * WHETHER A SCREEN LINE's SPEAKER IS NAMED on the card, pure (postCardHtml's screens, and the public payload's: one rule): + * the post's author under the card's rule for her (`authorHidden`: cardAuthors' "author" redact); an anonymous one (the + * pass flagged it) under the shown name; anyone else under the privacy rule -- a subject, or the item's redact: false. + */ +export function screenSpeakerShown(entry, l, { authorHidden = false } = {}) { + const s = screenWho(l?.who, entry); + if (s.self) return !authorHidden; + if (l?.anonymous === true) return true; + if (entry?.redact === true) return false; + if (entry?.redact === false) return true; + return !!s.handle && subjectsOf(entry).some((h) => String(h).replace(/^@/, "").toLowerCase() === String(s.handle).toLowerCase()); +} + +/** * The card's HTML: one page `width` × `height` (the box the item fills), the * card drawn in the deck's palette and faces, the attachments' slot left as a * well for the media to be laid into (the build overlays the files; Play the @@ -1316,14 +1330,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p const menSize = Math.round(22 * k); // A SCREEN's speaker (post-screens.mjs): the post's author under the card's rule for her; an anonymous one (the pass // flagged it) under the shown name; anyone else under the privacy rule -- a subject, or the item's redact: false. - const screenShown = (l) => { - const s = screenWho(l?.who, entry); - if (s.self) return !red("author"); - if (l?.anonymous === true) return true; - if (entry.redact === true) return false; - if (entry.redact === false) return true; - return !!s.handle && subjectsOf(entry).some((h) => String(h).replace(/^@/, "").toLowerCase() === String(s.handle).toLowerCase()); - }; + const screenShown = (l) => screenSpeakerShown(entry, l, { authorHidden: red("author") }); const ownPicMax = Math.max(Math.round(140 * k), L.card.height - 2 * L.pad - Math.round(250 * k) - Math.min(2, parentsOf(entry).length) * Math.round(130 * k) - (isObj(entry.quoted) ? Math.round(170 * k) : 0)); const own = { author: entry.author, handle: entry.handle, ...(entry.anonymous === true ? { anonymous: true } : {}) }; const ownRed = red("author"); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -195,7 +195,7 @@ const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", // `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. -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"]); +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"]); 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). @@ -658,6 +658,16 @@ 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"`); 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. + if (t.screenLine !== undefined) { + const sl = t.screenLine; + // `heard` (--check-words): what the editor's transcription heard it say, against which words, when. + const heardOk = sl?.heard === undefined || (isObj(sl.heard) && typeof sl.heard.at === "string" && typeof sl.heard.against === "string" && sl.heard.against.length <= 2000 && typeof sl.heard.words === "string" && sl.heard.words.length <= 2000 && Object.keys(sl.heard).every((kk) => ["at", "against", "words"].includes(kk))); + if (!(isObj(sl) && typeof sl.screen === "string" && /^[a-z0-9][a-z0-9-]{0,23}$/.test(sl.screen) && Number.isInteger(sl.n) && sl.n >= 0 && sl.n < 60 && typeof sl.said === "string" && sl.said.length <= 2000 && typeof sl.speaker === "string" && sl.speaker.length <= 64 && heardOk && Object.keys(sl).every((kk) => ["screen", "n", "said", "speaker", "heard"].includes(kk)))) { + errors.push(`${tw}.screenLine must be { screen, n, said, speaker, heard? } (the screen line it is a recording of)`); + } + } if (t.words !== undefined) { // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes). const ws = t.words; @@ -726,6 +736,10 @@ export function validatePostNarration(e) { if (n.pick !== undefined && !(Number.isInteger(n.pick) && n.pick >= 0 && Array.isArray(n.takes) && n.pick < n.takes.length)) { errors.push(`${w}.pick must be the index of one of its takes (0–${Math.max(0, (n.takes?.length ?? 1) - 1)})`); } + // A take of ONE SCREEN LINE is a piece of a read (--line-take), never the item's read itself. + const pk = Array.isArray(n.takes) && n.takes.length ? (Number.isInteger(n.pick) && n.pick >= 0 && n.pick < n.takes.length ? n.pick : 0) : -1; + const pt = pk >= 0 ? n.takes[pk] : null; + if (isObj(pt) && isObj(pt.screenLine)) errors.push(`${w}.pick: take ${pk + 1} is a recording of line ${pt.screenLine.n} of screen ${pt.screenLine.screen} -- a line take is read inside the item's read (posts screen <p> ${e?.id ?? "<item>"} read --line-take …), never picked as it: pick another take`); return errors; } diff --git a/umtool/report-to-video/post-screens-pin2.test.mjs b/umtool/report-to-video/post-screens-pin2.test.mjs @@ -0,0 +1,222 @@ +// THE SECOND PIN (lane/screens-2, 13 Nov 2026): an item with ROUND-1 SCREENS and none of the round-2 keys draws, +// plans, keys, validates, guards and lints BYTE-IDENTICALLY to main (7b8f5268) before a line of round 2 was written. A +// change that moves any of these hashes changes what a screen made before round 2 draws, plays or is told. +// +// Covered over a spread of screens: DMs in a video read whole, an image email read in excerpts, a screen with lines +// left out (omit) and drawn dim, a screenshot of a post with typed lines and a `ref`, a picture-only post with a screen +// on its own picture, an item whose screens are not narrated, and a take with line takes (`read.lineTakes`). +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs"; +import { postSegmentKeyOf } from "./post-render.mjs"; +import { partRoles, threadReadErrors } from "./post-thread.mjs"; +import { screenLineSaid, screenWarnings } from "./post-screens.mjs"; +import { draftScript, postNarrationDisclosure } from "./post-narration.mjs"; + +const sha = (v) => createHash("sha1").update(typeof v === "string" ? v : JSON.stringify(v)).digest("hex"); +const VID = { src: "posts-media/savvy-x/2117/2117_1.mp4", kind: "video", width: 1920, height: 1080, seconds: 61.742, audio: true, start: 3.3, end: 8 }; +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const DM = { + id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order", time: "11:32 AM" }, + { who: "MadamSavvy", text: "where is my scale video", time: "11:53 AM" }, + { who: "TheQuartering", text: "you HONESTLY believe that I have lied about weight loss?" }, + { who: "TheQuartering", text: "You can't be this dumb", time: "11:58 AM" }, + ], +}; +const MAIL = { + id: "s2", media: 1, kind: "email", title: "Refund email", checked: { by: "operator", at: "2026-11-12T10:00:00.000Z" }, read: [{ line: 0 }, { line: 1, text: "Total amount refunded: $99.95" }], lines: [ + { who: "coffee brand coffee", text: "Some items in your order have been refunded" }, + { text: "Total amount refunded: $99.95 USD. It may take up to 10 days for this refund to appear in your account." }, + { text: "Order number 4419283 · reply to support@coffeebrand.com" }, + ], +}; +const POST = "Hey, @thequartering You told me your video was ready to go.\n\nYour turn."; +const base = (o = {}) => ({ type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", text: POST, subjects: ["MadamSavvy"], media: [VID, IMG], screens: [DM, MAIL], ...o }); +/** A thread read's take: her words, then each screen line (stored roles, lines and speakers), timed by words. */ +function narrated(e, lines, extra = {}) { + 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, text, voice: role === "post" ? "tara" : "leo", ...more, role, start: Math.round(t * 1000) / 1000, seconds: sec }); + t += sec; + }; + add("Hey, at thequartering You told me your video was ready to go.", "post", 0, 0); + add("Your turn.", "post", 0, 0.6); + lines.forEach(([id, n], i) => { + const sc = e.screens.find((s) => s.id === id); + const said = screenLineSaid(sc, n); + add(said, `screen:${id}:${n}`, 1 + i, i && lines[i - 1][0] === id ? 0.35 : 0.8, { line: draftScript(said).script, speaker: String(sc.lines[n].who ?? "") }); + }); + return { ...e, narration: { script: POST, pick: 0, takes: [{ file: "narration/posts/2117/take-1.orpheus-thread.wav", engine: "orpheus", voice: "tara+leo", seconds: Math.round(t * 1000) / 1000, script: "x", parts, ...extra }] } }; +} +const ALL = [["s1", 0], ["s1", 1], ["s1", 2], ["s1", 3], ["s2", 0], ["s2", 1]]; + +const FIXTURES = { + dmAndMail: narrated(base(), ALL), + omitDim: narrated(base({ screens: [{ ...DM, read: [{ line: 0 }, { line: 3, text: "this dumb" }] }, { ...MAIL, unread: "dim" }] }), [["s1", 0], ["s1", 3], ["s2", 0], ["s2", 1]]), + postShot: narrated(base({ media: [IMG], screens: [{ id: "s1", media: 0, kind: "post", ref: "other-x/9001", read: "all", lines: [{ who: "other", text: "The roof repairs start on Monday." }, { who: "other", text: "Bring gloves." }] }] }), [["s1", 0], ["s1", 1]]), + pictureOnly: narrated(base({ text: "@thequartering", media: [IMG], screens: [{ ...MAIL, media: 0 }] }), [["s2", 0], ["s2", 1]]), + notNarrated: base(), + lineTakes: (() => { + const e = narrated(base(), ALL, { read: { kind: "thread", parents: "0", lineTakes: { "screen:s1:1": { n: 2, file: "narration/posts/2117/take-2.recorded-operator.wav", line: draftScript("where is my scale video").script } } } }); + e.narration.takes.push({ file: "narration/posts/2117/take-2.recorded-operator.wav", engine: "recorded", voice: "operator", label: "operator", seconds: 1.4, source: { kind: "recorded", voice: "operator" }, script: "where is my scale video" }); + e.narration.takes[0].parts[3] = { ...e.narration.takes[0].parts[3], voice: "operator", take: "take-2.recorded-operator", file: "narration/posts/2117/take-2.recorded-operator.wav" }; + return e; + })(), +}; + +/** Every output an item with screens has: its plan, its card pages, its segment key, its validation, guard and lint. */ +function outputs(e) { + const render = { postNarration: { lead: 0.4 } }; + const plan = postItemPlan(e, render); + const box = { width: 1600, height: 900 }; + const narratedNow = Array.isArray(e.narration?.takes); + return { + plan: sha(plan), + plain: sha(postCardHtml(e, { ...box })), + follow: sha(postCardHtml(e, { ...box, follow: true, thread: plan.follow?.thread ?? null })), + key: sha(postSegmentKeyOf({ entry: e, box, render: { fps: 30, palette: null }, plan, take: plan.narration ? {} : null })), + checks: sha([validatePostItem(e), threadReadErrors(e, render), screenWarnings(e, { narrated: narratedNow, takeRoles: narratedNow ? partRoles(e).map((r) => r.role) : [] }), postNarrationDisclosure(e)]), + }; +} + +// Recorded on main (7b8f5268), before the round-2 code: PIN_RECORD=1 node --test this file. +const PINNED = { + "dmAndMail": { + "plan": "25466c15390c7c605b05754660ba297f6bac9699", + "plain": "968fe3cbdf8cc0982f91ea82266277afbdaf627b", + "follow": "7a303b53afbf33f4bf674b147ed5f8229473f438", + "key": "FAKE-TEST-VALUE", + "checks": "58f994d43961a1f976b5fab4778d7b039d45aab6" + }, + "omitDim": { + "plan": "d553ce26ea25e3286010c39bdb4767604a4dcaa9", + "plain": "968fe3cbdf8cc0982f91ea82266277afbdaf627b", + "follow": "66590ec6a12b6017b319b64165951345b4c37c43", + "key": "FAKE-TEST-VALUE", + "checks": "58f994d43961a1f976b5fab4778d7b039d45aab6" + }, + "postShot": { + "plan": "4bed2e5bfe6fb0798c353795d926fad46f480eb2", + "plain": "968fe3cbdf8cc0982f91ea82266277afbdaf627b", + "follow": "c92594bc9a582206416df016c56643e92a75b812", + "key": "FAKE-TEST-VALUE", + "checks": "0b6e6bf545ef5f0a2066a6df455aff903e1a37c1" + }, + "pictureOnly": { + "plan": "6be3de8f69aad67365657a31c73d6b35ec1d8213", + "plain": "ce72a862e6f5d607a150a085ab60f6c9de002d7d", + "follow": "6efbb3bf18f8eae5e3020fcddb0f0543a58a6b1b", + "key": "FAKE-TEST-VALUE", + "checks": "5c8d877bdcee8cbf71658c9ad75d8430757c0a4a" + }, + "notNarrated": { + "plan": "335251e03af67c0374492e8c3530b0b8518b81e7", + "plain": "968fe3cbdf8cc0982f91ea82266277afbdaf627b", + "follow": "0d68eae2fb41c1ab32ef3ff1d702fd0b17eef034", + "key": "FAKE-TEST-VALUE", + "checks": "4615ef4e7c3e3669aebe789aad56c5c25554aaf3" + }, + "lineTakes": { + "plan": "25466c15390c7c605b05754660ba297f6bac9699", + "plain": "968fe3cbdf8cc0982f91ea82266277afbdaf627b", + "follow": "7a303b53afbf33f4bf674b147ed5f8229473f438", + "key": "FAKE-TEST-VALUE", + "checks": "c301b5157774d42623aa191b3416d79e39b89857" + } +}; + +test("an item with round-1 screens and none of the round-2 keys draws, plans, keys and is checked BYTE-IDENTICALLY to main", () => { + const now = Object.fromEntries(Object.entries(FIXTURES).map(([k, e]) => [k, outputs(e)])); + if (process.env.PIN_RECORD === "1") { + console.log(JSON.stringify(now, null, 1)); + return; + } + assert.deepEqual(now, PINNED); +}); + +// THE LINT AND THE READ PLAN (review round 1, h): the build's enforced lint (with and without an anonymous character), +// the drawing's refusals, the lint's thread-read warnings and what a NEW thread read would read, over the same items. +// Recorded at 847224ed, which the reviewer's d1.mjs shows identical to main (7b8f5268) for every one of these. +import { enforcedLint } from "./build-video.mjs"; +import { validateThreadReadWarnings } from "./post-thread.mjs"; +import { screenDrawErrors } from "./post-screens.mjs"; +import { threadReadPlan } from "../lib/report/postThreadRead.mjs"; + +function lintOutputs(e) { + const render = { width: 1920, height: 1080, fps: 30, postNarration: { lead: 0.4 } }; + const manifest = { schemaVersion: 1, slug: "x", title: "x", render, timeline: [e] }; + const anon = { set: new Set(["secretkid"]), doc: { characters: [{ id: "kid", name: "Kid A", handles: ["secretkid"], anonymous: true }] } }; + const plan = (() => { + try { + return threadReadPlan(manifest, e, {}).pieces.map((p) => ({ role: p.role, voice: p.voice, text: p.text, handle: p.handle ?? null, from: p.from ?? null })); + } catch (err) { + return `THROW ${String(err?.message ?? err)}`; + } + })(); + return { + lint: sha(enforcedLint(manifest, { validators: false }, { cut: manifest, anonymity: { set: new Set(), doc: null } })), + lintAnon: sha(enforcedLint(manifest, { validators: false }, { cut: manifest, anonymity: anon })), + draw: sha(screenDrawErrors(e)), + warn: sha(validateThreadReadWarnings(manifest)), + readPlan: sha(plan), + }; +} + +const LINT_PINNED = { + "dmAndMail": { + "lint": "2ba45145f10cbcd18f9f78839ea156686d3df020", + "lintAnon": "2ba45145f10cbcd18f9f78839ea156686d3df020", + "draw": "97d170e1550eee4afc0af065b78cda302a97674c", + "warn": "0001f53272bdf6a9d6a211634657143bdae27be1", + "readPlan": "5d24f6279d52fe58d0c62dfe004d67d66f0a74c4" + }, + "omitDim": { + "lint": "2ba45145f10cbcd18f9f78839ea156686d3df020", + "lintAnon": "2ba45145f10cbcd18f9f78839ea156686d3df020", + "draw": "97d170e1550eee4afc0af065b78cda302a97674c", + "warn": "0001f53272bdf6a9d6a211634657143bdae27be1", + "readPlan": "776b955f61f2c44bd2688daf06ed01375508b067" + }, + "postShot": { + "lint": "cc2cb0cff41dc543477479108d2dbe20ecf90874", + "lintAnon": "cc2cb0cff41dc543477479108d2dbe20ecf90874", + "draw": "97d170e1550eee4afc0af065b78cda302a97674c", + "warn": "7e73eebe078bd9d686c660053fb87b5985f12789", + "readPlan": "e225065294fc39aeb38519833628fa25decc7b93" + }, + "pictureOnly": { + "lint": "93089484fb1ad7bdc6005a5017337ba1e4a3ab89", + "lintAnon": "93089484fb1ad7bdc6005a5017337ba1e4a3ab89", + "draw": "97d170e1550eee4afc0af065b78cda302a97674c", + "warn": "b148a0c52437adc918dafda161cc7fe5c905c2e3", + "readPlan": "a3773d01cc3bb65d42a76f9667fa95515a6b028e" + }, + "notNarrated": { + "lint": "8d3287fcb8a085b6302aa66fe06b2d945e6ffa41", + "lintAnon": "8d3287fcb8a085b6302aa66fe06b2d945e6ffa41", + "draw": "97d170e1550eee4afc0af065b78cda302a97674c", + "warn": "bcd16048b2c13d4d99a4061232aaa05fb2c8d1b3", + "readPlan": "5d24f6279d52fe58d0c62dfe004d67d66f0a74c4" + }, + "lineTakes": { + "lint": "2ba45145f10cbcd18f9f78839ea156686d3df020", + "lintAnon": "2ba45145f10cbcd18f9f78839ea156686d3df020", + "draw": "97d170e1550eee4afc0af065b78cda302a97674c", + "warn": "0001f53272bdf6a9d6a211634657143bdae27be1", + "readPlan": "5d24f6279d52fe58d0c62dfe004d67d66f0a74c4" + } +}; + +test("the same items' enforced lint, drawing refusals, thread-read warnings and new-read plan are BYTE-IDENTICAL to main", () => { + const now = Object.fromEntries(Object.entries(FIXTURES).map(([k, e]) => [k, lintOutputs(e)])); + if (process.env.PIN_RECORD === "1") { + console.log(JSON.stringify(now, null, 1)); + return; + } + assert.deepEqual(now, LINT_PINNED); +}); diff --git a/umtool/report-to-video/post-screens.mjs b/umtool/report-to-video/post-screens.mjs @@ -13,7 +13,8 @@ // screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", title?, source?: "transcribed", checked?: { by, at }, // ref?: "<channel>/<postId>", unread?: "omit" | "dim", // lines: [{ who?, side?: "left" | "right", text, time?, redact?: true }], -// read: "all" | "none" | [{ line, text? }] }] +// read: "all" | "none" | [{ line, text? }], +// lineTakes?: { "<n>": "<take id>" } }] // // - `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 @@ -22,6 +23,9 @@ // drawn dim ("dim"). A line marked `redact: true` is never drawn nor read. // - THE SHAPES: an e-mail address, a phone number, a long run of digits, an order or confirmation number in a line are // MASKED (a bar on the card, never said) whether or not anyone marked them -- the lint says which line held one. +// - `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. // - `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. @@ -55,6 +59,8 @@ export const POST_SCREEN_DRAW_V = 1; export const SCREEN_ROLE_RE = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +/** A take's id (post-narration.mjs takeIdOf: its file's name without .wav -- not imported: that module imports this one's). */ +const takeIdOfFile = (t) => String(t?.file ?? "").split("/").pop().replace(/\.wav$/i, ""); const fin = (v) => typeof v === "number" && Number.isFinite(v); const str = (v) => (typeof v === "string" ? v : ""); const r3 = (v) => Math.round(v * 1000) / 1000; @@ -292,6 +298,12 @@ export function withoutLines(screen, drops) { const to = (n) => n - [...gone].filter((d) => d < n).length; const out = { ...screen, lines: (Array.isArray(screen?.lines) ? screen.lines : []).filter((_, n) => !gone.has(n)) }; if (Array.isArray(screen?.read)) out.read = screen.read.filter((x) => !gone.has(x?.line)).map((x) => ({ ...x, line: to(x.line) })); + // The takes chosen for its lines follow them too: a removed line's choice goes, the later ones' keys move down. + if (isObj(screen?.lineTakes)) { + const lt = Object.fromEntries(Object.entries(screen.lineTakes).filter(([k]) => /^\d{1,2}$/.test(k) && !gone.has(Number(k))).map(([k, v]) => [String(to(Number(k))), v])); + if (Object.keys(lt).length) out.lineTakes = lt; + else delete out.lineTakes; + } return out; } @@ -401,6 +413,73 @@ export function lineOfText(raw) { return { ...(out.who ? { who: out.who } : {}), ...(out.side ? { side: out.side } : {}), text: t.trim(), ...(out.time ? { time: out.time } : {}), ...(out.redact ? { redact: true } : {}) }; } +/** Orpheus's expressive tags (the editor's TTS_EXPRESSIVE_TAGS): how a script is read, never the picture's words. Any other `<…>` is words. */ +const SCRIPT_TAG_RE = /<(?:laugh|chuckle|sigh|cough|sniffle|groan|yawn|gasp)>/g; + +/** + * A PICTURE-ONLY post's READ as a screen's LINES, pure (`posts screen … add --from-read`, the post bench's "From its + * read": one rule): its script (`narration.script`, the words on the picture as the operator wrote them to be read) a + * line per line of it -- blank lines dropped, its emotion tags left out, a line longer than a screen line split at its + * sentence ends (then at a space) -- each `{ text }` alone: a "who:" is NEVER parsed out of a read (a shape or a + * heading would become a speaker: "Order number: 4419"); the speakers are the operator's to set. Throws when it holds + * no words or more lines than a screen takes. + * + * @param {string} script + * @returns {Array<{ text: string }>} + */ +export function linesOfRead(script) { + const out = []; + const push = (t) => { + const v = t.replace(/\s+/g, " ").trim(); + if (v) out.push({ text: v }); + }; + for (const raw of str(script).replace(SCRIPT_TAG_RE, " ").split(/\r?\n/)) { + let t = raw.replace(/\s+/g, " ").trim(); + while (t.length > SCREEN_LINE_MAX) { + const head = t.slice(0, SCREEN_LINE_MAX + 1); + const ends = [...head.matchAll(/[.!?…]["')\]”’]*\s/g)].map((m) => m.index + m[0].length).filter((i) => i <= SCREEN_LINE_MAX); + const sp = head.lastIndexOf(" "); + const cut = ends.length ? ends[ends.length - 1] : sp > 0 ? sp + 1 : SCREEN_LINE_MAX; + push(t.slice(0, cut)); + t = t.slice(cut).trim(); + } + push(t); + } + if (!out.length) throw new Error("its read has no words to make lines of (narration.script is empty)"); + if (out.length > SCREEN_LINES_MAX) throw new Error(`its read is ${out.length} lines -- a screen takes at most ${SCREEN_LINES_MAX}: shorten the script, or add the screen's lines by hand`); + return out; +} + +/** + * A SCREEN MADE FROM A PICTURE-ONLY POST's READ, pure: `{ screen }` -- on its picture (`media`: the index given, else + * its first image, else its first attachment), `kind` (default "text"), its lines linesOfRead's, read whole, NOT + * checked (the lint says so until a person reads it against the picture) -- or `{ error }`: not picture-only + * (`pictureOnly`: the caller's post-item.mjs ownPictureOnly), no script, no attachment, a kind or an index wrong. + * + * @param {Record<string, any>} e + * @param {{ pictureOnly: boolean, id: string, media?: number | null, kind?: string | null }} o + */ +export function screenFromRead(e, { pictureOnly, id, media = null, kind = null }) { + if (!pictureOnly) return { error: `${e?.id ?? "the item"} is not a picture-only post: --from-read makes a screen of a picture-only post's read (its words on the picture); type or paste this one's lines (--from <file>, --line)` }; + const list = Array.isArray(e?.media) ? e.media : []; + if (!list.length) return { error: `${e?.id ?? "the item"} has no attachment for the screen to be in` }; + const at = media !== null && media !== undefined ? media : Math.max(0, list.findIndex((m) => m?.kind === "image")); + if (!Number.isInteger(at) || !isObj(list[at])) return { error: `--media ${media}: ${e?.id} has attachments 0–${list.length - 1}` }; + const k = kind ?? "text"; + if (!SCREEN_KINDS.includes(k)) return { error: `--kind takes ${SCREEN_KINDS.join(", ")}` }; + let lines; + try { + lines = linesOfRead(str(e?.narration?.script)); + } catch (err) { + return { error: `${e?.id}: ${err instanceof Error ? err.message : err}` }; + } + // A GIF's or a video's: visible its whole length (the picture stays in its card), when its length is known. + const m = list[at]; + const timed = m.kind === "video" || m.kind === "gif"; + if (timed && !(fin(m.seconds) && m.seconds >= SCREEN_MIN_SPAN)) return { error: `attachment ${at} is a ${m.kind} of no known length: add the screen with --at <from>,<to>` }; + return { screen: { id, media: at, ...(timed ? { at: [0, r3(m.seconds)] } : {}), kind: k, source: "read", lines, read: "all" } }; +} + // --------------------------------------------------------------------------- // THE VALIDATION. // --------------------------------------------------------------------------- @@ -421,7 +500,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"]); + const known = new Set(["id", "media", "at", "kind", "title", "source", "checked", "ref", "unread", "lines", "read", "lineTakes"]); 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`); @@ -437,7 +516,8 @@ export function validateScreens(e) { } else if (timed) errors.push(`${at}.at must be [from, to]: the seconds of the ${m.kind} it is visible in`); if (!SCREEN_KINDS.includes(sc.kind)) errors.push(`${at}.kind must be one of ${SCREEN_KINDS.join(", ")}`); if (sc.title !== undefined && !(typeof sc.title === "string" && sc.title.trim() && sc.title.length <= SCREEN_TITLE_MAX)) errors.push(`${at}.title must be words (at most ${SCREEN_TITLE_MAX} characters)`); - if (sc.source !== undefined && sc.source !== "transcribed") errors.push(`${at}.source must be "transcribed"`); + // "read": made from a picture-only post's read (--from-read) -- its lines ARE the post's read (postThreadRead.mjs). + if (sc.source !== undefined && sc.source !== "transcribed" && sc.source !== "read") errors.push(`${at}.source must be "transcribed" or "read" (made from its read)`); if (sc.checked !== undefined && !(isObj(sc.checked) && typeof sc.checked.by === "string" && sc.checked.by.trim() && sc.checked.by.length <= 40 && typeof sc.checked.at === "string" && !Number.isNaN(Date.parse(sc.checked.at)))) { errors.push(`${at}.checked must be { by, at }: who checked the transcription and when (ISO)`); } @@ -463,6 +543,22 @@ export function validateScreens(e) { if (l.redact !== undefined && l.redact !== true) errors.push(`${lw}.redact must be true (or absent)`); }); } + // The takes CHOSEN for its lines (a recording of each): a line it has, a take of the item that is a recording of it. + if (sc.lineTakes !== undefined) { + const lt = sc.lineTakes; + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + if (!isObj(lt) || Object.keys(lt).length > SCREEN_LINES_MAX) errors.push(`${at}.lineTakes must be { "<line>": "<take id>" } (the take chosen for each line)`); + else for (const [k, v] of Object.entries(lt)) { + const n = /^\d{1,2}$/.test(k) ? Number(k) : -1; + if (n < 0 || !isObj(lines?.[n])) errors.push(`${at}.lineTakes.${k}: the screen has no line ${k}`); + else if (lines[n].redact === true) errors.push(`${at}.lineTakes.${k}: line ${k} is redacted -- it is never read`); + const t = typeof v === "string" ? takes.find((x) => takeIdOfFile(x) === v) : null; + if (!t) errors.push(`${at}.lineTakes.${k} must be the id of one of the item's takes (a recording of line ${k})`); + // A recording of a line of THIS screen; whether it says this line as it is now is the read's to judge (by its + // words and speaker, not its index: a line removed above it moves the choice, not the take). + 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})` : ""}`); + } + } const r = sc.read; if (r === "all" || r === "none") return; if (!Array.isArray(r)) { diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs @@ -289,6 +289,15 @@ const postIdOf = (e) => String(e?.post ?? "").split("/")[1] ?? ""; export const shownIdOf = (e) => str(e?.originalId) || postIdOf(e); /** + * THE SCREENS A THREADED CARD DRAWS, pure: each screen whose lines the screen reads and the picked take reads a line of, + * in the screens' order (threadLayout's tiles; the public payload's screens: one rule). `roles`: partRoles' (none: not + * narrated -- no screen is drawn). + */ +export function drawnScreens(entry, roles = isNarrated(entry) ? partRoles(entry) : []) { + return readScreens(entry).filter((sc) => roles.some((r) => r?.role && parseScreenRole(r.role)?.id === sc.id)); +} + +/** * THE THREAD LAYOUT, pure: `{ on, tiles: [{ scope, mode, read }], roles, * quotedAt }` -- the tiles top to bottom (the parents oldest first, a quoted * post read first, "post", a quoted post inside it), each with its resolved @@ -356,10 +365,7 @@ export function threadLayout(entry, render = undefined, { prev = null, scene = n // reads them -- a quote read before the post it answers sits above it -- one not read where it stood before the next. orderByRead(tiles, roles); // ITS SCREENS (post-screens.mjs): each screen the take reads a line of, a tile after his post's, in the screens' order. - for (const sc of readScreens(entry)) { - if (!roles.some((r) => r?.role && parseScreenRole(r.role)?.id === sc.id)) continue; - tiles.push({ scope: screenScope(sc.id), mode: "full", read: true, screen: true }); - } + for (const sc of drawnScreens(entry, roles)) tiles.push({ scope: screenScope(sc.id), mode: "full", read: true, screen: true }); const quotedAtOut = tiles.some((t) => t.above) ? "above" : "inside"; // THE SCENE (post-conversation.mjs): what the run had on screen, in the tree's order with this item's own tiles. const scened = withRelations(entry, isNarrated(entry) ? sceneTiles(entry, tiles, scene, k) : tiles, { group: !!scene?.group || !!groupOf(entry) }); @@ -581,18 +587,118 @@ export function screenPartErrors(entry, k, roles = partRoles(entry), changed = n */ export function validateScreenReads(manifest) { const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + return tl.flatMap((e) => itemReadRefusals(e)); +} + +/** + * ONE POST ITEM's READ, REFUSED, pure -- what the build's enforced lint refuses about it (validateScreenReads is this + * over a cut), judged on the item AS WRITTEN: every screen part's errors (screenPartErrors: a line changed since the + * read, not read, gone, a shape said) and every part that SAYS WHAT ITS SCREENS HIDE (readSaysHiddenErrors). Empty + * for an item with no screens, or not narrated. + */ +export function itemReadRefusals(e) { + if (e?.type !== "post" || !Array.isArray(e.screens) || !isNarrated(e)) return []; const out = []; - for (const e of tl) { - if (e?.type !== "post" || !Array.isArray(e.screens) || !isNarrated(e)) continue; - const roles = partRoles(e); - const changed = new Set(); - roles.forEach((r, k) => { - if (r?.role && parseScreenRole(r.role)) out.push(...screenPartErrors(e, k, roles, changed)); + const roles = partRoles(e); + const changed = new Set(); + roles.forEach((r, k) => { + if (r?.role && parseScreenRole(r.role)) out.push(...screenPartErrors(e, k, roles, changed)); + }); + out.push(...readSaysHiddenErrors(e)); + return out; +} + +/** A shape's KEY, to know it said elsewhere: an e-mail lower case; a number its digits (fullwidth ones too). */ +const digitsOf = (t) => str(t).replace(/\p{Nd}/gu, (d) => String(Number.parseInt(d.normalize("NFKC"), 10))).replace(/[^0-9]/g, ""); +const shapeKey = (text, sp) => (sp.kind === "email" ? text.slice(sp.start, sp.end).toLowerCase() : digitsOf(text.slice(sp.start, sp.end))); +/** Every run of digits a text says (its separators between them dropped): `["4419283", "5552014477"]`. */ +const digitRunsOf = (t) => [...str(t).matchAll(/\p{Nd}(?:[\s\-‐‑–—·./()]{0,3}\p{Nd})*/gu)].map((m) => digitsOf(m[0])); + +/** + * WHAT ITS SCREENS HIDE, SAID ANYWHERE IN ITS READ, pure (review round 1, M2: a picture's words read by the post's own + * part and again by its screen): every part of the picked take -- his words, a context post, a screen line, a take with + * no parts as its words -- that says a SHAPE one of the item's screens masks (an e-mail, a number of four digits or + * more: post-screens.mjs shapeSpans, its digits however they are joined) or the words of a line marked `redact` (three + * or more of them in a row). Names the part and the screen's line, never the value. None without screens. + */ +export function readSaysHiddenErrors(e) { + const screens = screensOfEntry(e); + const t = pickedTake(e); + if (!screens.length || !t) return []; + const id = e?.id ?? "<item>"; + const masked = []; + const redacted = []; + for (const sc of screens) { + sc.lines.forEach((l, n) => { + if (!l || typeof l !== "object") return; + const text = str(l.text); + if (l.redact === true) { + const w = sayKeys(text); + if (w.length >= 3) redacted.push({ screen: sc.id, n, w }); + return; + } + for (const sp of shapeSpans(text)) { + const key = shapeKey(text, sp); + if (sp.kind === "email" ? key.length >= 3 : key.length >= 4) masked.push({ screen: sc.id, n, kind: sp.kind, key }); + } }); } + if (!masked.length && !redacted.length) return []; + const parts = Array.isArray(t.parts) && t.parts.length ? t.parts.map((p) => str(p?.text)) : [str(t.said) || str(t.script)]; + const out = []; + parts.forEach((said, k) => { + const where = Array.isArray(t.parts) && t.parts.length ? `its take's part ${k + 1}` : "its picked take"; + const runs = new Set(digitRunsOf(said)); + const low = said.toLowerCase(); + const hit = masked.find((m) => (m.kind === "email" ? low.includes(m.key) : runs.has(m.key) || [...runs].some((r) => r.length >= m.key.length && r.includes(m.key)))); + if (hit) out.push(`timeline ${e?.id ?? "?"}: ${where} says ${hit.kind === "email" ? "an e-mail address" : "a number"} that line ${hit.n} of screen ${hit.screen} masks -- the card never shows it and no read may say it: make the read again (umtool posts screen <p> ${id} read)`); + const w = sayKeys(said); + const red = redacted.find((r) => w.some((_, i) => r.w.every((x, j) => w[i + j] === x))); + if (red) out.push(`timeline ${e?.id ?? "?"}: ${where} says the words of line ${red.n} of screen ${red.screen}, which is redacted -- make the read again (umtool posts screen <p> ${id} read)`); + }); return out; } +// --------------------------------------------------------------------------- +// WHAT A PREVIEW PLAYS (Play, Present, the post bench's player, the card page): never a read the build refuses. +// --------------------------------------------------------------------------- + +/** What a preview says of a read it does not play. */ +export const READ_REFUSED_REASON = "the read is older than its screen, or says what the screen hides -- it is not played: make the read again (umtool posts screen <p> <item> read)"; + +/** + * AN ITEM's PLAYABLE READ, pure: the picked take a preview may play -- none when the item says its read is refused + * (`readRefused`, playableEntry's) or the build would refuse it (itemReadRefusals). EVERY player, preview and payload + * reads the take through this (the source test pins it: lib/report/postScreensReview3.test.mjs, e). + */ +export function playableTake(e) { + if (!e || e.readRefused) return null; + if (itemReadRefusals(e).length) return null; + return pickedTake(e); +} + +/** + * THE ITEM AS A PREVIEW MAY PLAY IT, pure (review round 1, M1): the item itself when the build would play its read; + * else the item WITHOUT its read -- no narration, no take, no part in it (it plays silent, as an item not narrated) -- + * with `readRefused: { reason, errors }` saying why. Judged on the item as written (itemReadRefusals); every player and + * payload goes through it: playView (Play, Present -- the public payload too), the card page, the post bench's player. + */ +export function playableEntry(e) { + return playableAsWritten(e, e); +} + +/** + * THE VERDICT ON THE ITEM AS WRITTEN, APPLIED TO THE ITEM AS DRAWN, pure (re-check b: one verdict everywhere): `drawn` + * (the anonymised, censored copy a page draws) as it may play -- itself, or without its read (`readRefused`) when + * `written` (the same item before those passes: what the build's enforced lint judges) has a read the build refuses. + */ +export function playableAsWritten(written, drawn) { + const errors = itemReadRefusals(written); + if (!errors.length) return drawn; + const { narration: _n, ...rest } = drawn; + return { ...rest, readRefused: { reason: READ_REFUSED_REASON, errors } }; +} + const sayKeys = (t) => str(t).toLowerCase().split(/\s+/).map((x) => x.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean); const normText = (t) => str(t).replace(/\s+/g, " ").trim(); @@ -620,6 +726,111 @@ export function screenLineChanged(entry, role, roles = partRoles(entry)) { return a.length !== b.length || a.some((x, i) => x !== b[i]); } +// --------------------------------------------------------------------------- +// A SCREEN LINE's OWN TAKE (a recording of the line: lib/report/screenLineRecord.mjs, `posts screen … record`). +// --------------------------------------------------------------------------- + +/** A screen line's words AS A READ WRITES THEM (draftScript of what it says): what a part's `line` and a line take's `screenLine.said` hold. */ +export const screenLineWritten = (screen, n) => draftScript(screenLineSaid(screen, n)).script; + +/** A take's id (its file's name without .wav: post-narration.mjs takeIdOf). */ +const idOfTake = (t) => str(t?.file).split("/").pop().replace(/\.wav$/i, ""); + +/** + * Whether a line take (`screenLine`) SAYS line `n` of screen `screenId` AS IT IS NOW -- by its content, not its index: + * the same screen, the line's words as a read writes them, its speaker. (Without `screenId`/`n`: the line it was recorded + * for, by its index.) A take that is no recording of a line: null. + */ +export function lineTakeCurrent(entry, take, screenId = undefined, n = undefined) { + const sl = take?.screenLine; + if (!sl || typeof sl !== "object") return null; + const sid = screenId ?? sl.screen; + const k = n ?? sl.n; + if (sl.screen !== sid) return false; + const sc = screensOfEntry(entry).find((x) => x.id === sid); + if (!sc || !sc.lines[k] || sc.lines[k].redact === true) return false; + return normText(sl.said) === normText(screenLineWritten(sc, k)) && normText(sl.speaker).toLowerCase() === normText(sc.lines[k]?.who).toLowerCase(); +} + +/** + * Each screen line's RECORDINGS, pure, BY CONTENT: `[{ role, screen, n, takes: [{ n, id, take, current, chosen }] }]` -- + * for each line, the item's takes that are recordings of a line of its screen (`screenLine`) and say that line as it is + * now (`current`), or that the screen chose for it (`chosen`, current or not); a recording that says no line now is + * listed under the line it was recorded for, not current. Lines with none are left out. + */ +export function lineTakesOf(entry) { + const takes = Array.isArray(entry?.narration?.takes) ? entry.narration.takes : []; + const recs = takes.map((t, i) => ({ t, i })).filter(({ t }) => t?.screenLine && typeof t.screenLine === "object"); + if (!recs.length) return []; + const out = []; + const placed = new Set(); + for (const sc of screensOfEntry(entry)) { + sc.lines.forEach((_, k) => { + const chosenId = sc.lineTakes && typeof sc.lineTakes === "object" ? sc.lineTakes[String(k)] : undefined; + const mine = recs.filter(({ t }) => t.screenLine.screen === sc.id && (idOfTake(t) === chosenId || lineTakeCurrent(entry, t, sc.id, k) === true)); + if (!mine.length) return; + for (const { i } of mine) placed.add(i); + out.push({ role: screenRole(sc.id, k), screen: sc.id, n: k, takes: mine.map(({ t, i }) => ({ n: i + 1, id: idOfTake(t), take: t, current: lineTakeCurrent(entry, t, sc.id, k) === true, chosen: idOfTake(t) === chosenId })) }); + }); + } + // Recordings that say no line now (the line edited, the screen gone): under the line they were recorded for. + for (const { t, i } of recs) { + if (placed.has(i)) continue; + const sl = t.screenLine; + const role = screenRole(sl.screen, sl.n); + let row = out.find((x) => x.role === role); + if (!row) { + row = { role, screen: sl.screen, n: sl.n, takes: [] }; + out.push(row); + } + row.takes.push({ n: i + 1, id: idOfTake(t), take: t, current: false, chosen: false }); + } + return out; +} + +/** The takes the screens CHOSE for their lines, as --line-take takes them: `{ "<role>": <take number> }` (none: {}). */ +export function chosenLineTakes(entry) { + const takes = Array.isArray(entry?.narration?.takes) ? entry.narration.takes : []; + const out = {}; + for (const sc of screensOfEntry(entry)) { + if (!sc.lineTakes || typeof sc.lineTakes !== "object") continue; + for (const [k, v] of Object.entries(sc.lineTakes)) { + const i = takes.findIndex((t) => idOfTake(t) === v); + if (i >= 0 && /^\d{1,2}$/.test(k)) out[screenRole(sc.id, Number(k))] = i + 1; + } + } + return out; +} + +/** + * THE LINE TAKES' WARNINGS (the lint; never refused here -- the read refuses a stale one when it is made): a chosen take + * recorded for the line as it was, a recording no read uses (not chosen), a chosen take the picked read does not play. + * They name lines and take numbers, never words. + */ +export function lineTakeWarnings(entry) { + const id = entry?.id ?? "?"; + const out = []; + const t = pickedTake(entry); + const parts = Array.isArray(t?.parts) ? t.parts : []; + for (const L of lineTakesOf(entry)) { + const sc = screensOfEntry(entry).find((x) => x.id === L.screen); + if (!sc) continue; + const chosen = L.takes.find((x) => x.chosen); + if (chosen && !chosen.current) out.push(`timeline ${id}: line ${L.n} of screen ${L.screen}: its chosen take (take ${chosen.n}) was recorded for the line as it was -- record it again (umtool posts screen <p> ${id} record ${L.screen} ${L.n} --recording <file>) or unchoose it (umtool posts screen <p> ${id} set ${L.screen} take.${L.n}=off)`); + else if (!chosen && L.takes.some((x) => x.current) && screenReadLines(sc).some((r) => r.n === L.n)) { + out.push(`timeline ${id}: line ${L.n} of screen ${L.screen} has a recording no read uses (take ${L.takes.filter((x) => x.current).map((x) => x.n).join(", take ")}) -- choose one: umtool posts screen <p> ${id} set ${L.screen} take.${L.n}=<take> (or on the post bench), then make the read`); + } + // NOT HEARD (review round 1, j): nothing verified what a recording says unless --check-words heard it -- its words + // are the line's text compared with itself. + if (chosen && !chosen.take?.screenLine?.heard) out.push(`timeline ${id}: line take ${chosen.n} of screen ${L.screen} line ${L.n} was not heard -- nothing verified what the recording says; \`umtool posts screen <p> ${id} record ${L.screen} ${L.n} --recording <file> --check-words\` hears it`); + if (chosen && chosen.current && isNarrated(entry)) { + const mine = parts.filter((p) => p?.role === L.role); + if (mine.length && !mine.every((p) => p.take === chosen.id)) out.push(`timeline ${id}: line ${L.n} of screen ${L.screen}: the picked read does not play its chosen take (take ${chosen.n}) -- make the read: umtool posts screen <p> ${id} read`); + } + } + return out; +} + /** A tile's mode in a layout (null: no such tile). */ export const tileModeOf = (layout, scope) => layout?.tiles?.find((t) => t.scope === scope)?.mode ?? null; @@ -961,6 +1172,8 @@ export function validateThreadReadWarnings(manifest) { return tl.filter((e) => e?.type === "post").flatMap((e) => [ ...threadReadWarnings(e), ...(Array.isArray(e.screens) ? screenWarnings(e, { narrated: isNarrated(e), takeRoles: isNarrated(e) ? partRoles(e).map((r) => r.role) : [], attachAfter: isNarrated(e) && postNarrationKnobs(e, manifest?.render).attach === "after" }) : []), + // Recordings of its screens' lines (screenLine takes): none on an item without them. + ...(Array.isArray(e.screens) ? lineTakeWarnings(e) : []), ]); }