Archilyzer · Source

archilyzer

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

commit ea26a9e74c66a24e9038f434830bda67ea0a92a6
parent e95542d23879ea9346d38f7444b2a0cb8aea6945
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 16:45:50 -0400

report-to-video: montage rulings — the clip deck's verdicts applied at render

<project>/montage-rulings.json, keyed by the source moment (<channel>/<video>@<cutStart>):
a clip ruled cut / not-him / read-aloud is left out of the cut and the wall, a ruled
`match` replaces montage.match, and the counter numbers the kept clips 1…N of N. No file
(or none that changes anything) is the same manifest object: today's render, byte for
byte. build-video and verify-build read it beside the manifest (--no-rulings to build
without); the take maker applies it before windowing, so a window still counts over the
whole kept cut. umtool's lib/report/montageRulings.mjs is the one writer (queue, tmp +
rename, a bad file never overwritten) and maps the seed's edits.json to moments.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/lib/report/montageRulings.mjs | 302++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/montageRulings.test.mjs | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 17+++++++++++++----
Mumtool/lib/report/takeMaker.test.mjs | 26++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 19+++++++++++++++++--
Aumtool/report-to-video/montage-rulings.mjs | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/montage-rulings.test.mjs | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/verify-build.mjs | 11++++++++---
9 files changed, 970 insertions(+), 9 deletions(-)

diff --git a/umtool/lib/report/montageRulings.mjs b/umtool/lib/report/montageRulings.mjs @@ -0,0 +1,302 @@ +// THE CLIP DECK'S STORE (release 34 N1): `<project>/montage-rulings.json`, the +// operator's verdict on each montage instance, written by ear on the clip deck +// (`/projects/<id>/clips`) or `umtool rulings`. The shape, the key rule and how a +// render applies it are report-to-video/montage-rulings.mjs; this is the ONE +// writer. +// +// - every write is queued in-process, read-modify-write, tmp + rename; +// - a file that does not parse (or is not the shape) is an ERROR: never +// overwritten, never read as empty; +// - a ruling is set whole ({verdict, reason, match?}, `at` stamped here) or +// removed (null) -- the deck's undo is "set it back as it was". +// +// IMPORT. Before the deck, the operator ruled in chat and the rulings went into +// the seed's `edits.json` beside the manifest ({exclude: [{videoId, near, why}], +// match: [{videoId, near, match, why}]}, `near` the instance's start). Those map +// to moments: the clip whose video matches and whose cutStart (else start) is +// within 30 s; a moment the seed already left out of the manifest is found in +// the seed's `instances.json` ({slug, videoId, start}) when there is one. An +// exclude becomes not-him / read-aloud / cut by its words; a match keeps the +// clip with the wider phrase. Moments already ruled are left as they are, so +// the offer counts only what is new -- once imported, it is not offered again. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + MONTAGE_RULINGS_FILE, + RULINGS_VERSION, + RULING_MATCH_LIMIT, + RULING_REASON_LIMIT, + RULING_VERDICTS, + clipMomentKey, + isMomentKey, + momentKey, + montageRulingsFileOf, + parseMontageRulings, +} from "umtool-report-to-video/montage-rulings"; + +export const EDITS_FILE = "edits.json"; +export const INSTANCES_FILE = "instances.json"; +/** How far an earlier ruling's `near` may be from the clip's cut start. */ +export const IMPORT_NEAR_SECONDS = 30; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +let queue = Promise.resolve(); +/** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */ +function withRulingsLock(fn) { + const run = queue.then(fn, fn); + queue = run.then( + () => undefined, + () => undefined, + ); + return run; +} + +/** + * The rulings as the page reads them: `{ exists, doc, error }`. A bad file is + * `error` (the page says so and refuses to write), never an empty doc. + * @param {string} projectDir + */ +export async function readRulingsState(projectDir) { + let text = null; + try { + text = await readFile(montageRulingsFileOf(projectDir), "utf8"); + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") return { exists: true, doc: emptyDoc(), error: String(err) }; + } + if (text === null) return { exists: false, doc: emptyDoc(), error: null }; + try { + return { exists: true, doc: parseMontageRulings(JSON.parse(text)), error: null }; + } catch (e) { + return { exists: true, doc: emptyDoc(), error: `${MONTAGE_RULINGS_FILE} does not parse or is not the shape: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +const emptyDoc = () => ({ version: /** @type {1} */ (RULINGS_VERSION), rulings: {} }); + +async function readForWrite(file) { + let text = null; + try { + text = await readFile(file, "utf8"); + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") throw err; + } + if (text === null) return emptyDoc(); + try { + return parseMontageRulings(JSON.parse(text)); + } catch { + throw new Error(`${MONTAGE_RULINGS_FILE} does not parse or is not the shape; not overwriting it`); + } +} + +async function writeDoc(file, doc) { + await mkdir(path.dirname(file), { recursive: true }); + // Keys in order, so the file diffs as the deck walks. + const rulings = Object.fromEntries(Object.entries(doc.rulings).sort(([a], [b]) => a.localeCompare(b))); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify({ version: RULINGS_VERSION, rulings }, null, 2) + "\n", "utf8"); + await rename(tmp, file); +} + +/** + * One ruling, checked and normalised: `{verdict, reason, match?, at}`. Throws a + * sentence. + * @param {unknown} input + * @param {Date} now + */ +export function normaliseRuling(input, now = new Date()) { + if (!isObj(input)) throw new Error("a ruling is { verdict, reason?, match? }"); + const verdict = input.verdict; + if (!RULING_VERDICTS.includes(/** @type {any} */ (verdict))) throw new Error(`verdict must be one of ${RULING_VERDICTS.join(", ")}`); + const reason = input.reason === undefined || input.reason === null ? "" : input.reason; + if (typeof reason !== "string") throw new Error("reason must be a string"); + /** @type {{ verdict: string, reason: string, match?: string, at: string }} */ + const out = { verdict: /** @type {string} */ (verdict), reason: reason.trim().slice(0, RULING_REASON_LIMIT), at: now.toISOString() }; + if (input.match !== undefined && input.match !== null && input.match !== "") { + if (typeof input.match !== "string" || !input.match.trim()) throw new Error("match must be a phrase"); + const m = input.match.trim().replace(/\s+/g, " "); + if (m.length > RULING_MATCH_LIMIT) throw new Error(`match is over ${RULING_MATCH_LIMIT} characters`); + out.match = m; + } + return out; +} + +/** + * Set one moment's ruling (or remove it with `null`). Returns the whole doc. + * @param {string} projectDir + * @param {string} key + * @param {null | { verdict: string, reason?: string, match?: string | null }} ruling + * @param {{ now?: Date }} [opts] + */ +export async function setMontageRuling(projectDir, key, ruling, { now = new Date() } = {}) { + if (!isMomentKey(key)) throw new Error("not a moment key (<channel>/<video>@<seconds>)"); + const next = ruling === null ? null : normaliseRuling(ruling, now); + const file = montageRulingsFileOf(projectDir); + return withRulingsLock(async () => { + const doc = await readForWrite(file); + if (next === null) delete doc.rulings[key]; + else doc.rulings[key] = next; + await writeDoc(file, doc); + return { ruling: doc.rulings[key] ?? null, doc }; + }); +} + +/** Many rulings in one write (the import). Keys already ruled are skipped unless `overwrite`. */ +export async function setMontageRulings(projectDir, entries, { now = new Date(), overwrite = false } = {}) { + const checked = entries.map(({ key, ruling }) => { + if (!isMomentKey(key)) throw new Error(`not a moment key: ${key}`); + return { key, ruling: normaliseRuling(ruling, now) }; + }); + const file = montageRulingsFileOf(projectDir); + return withRulingsLock(async () => { + const doc = await readForWrite(file); + const written = []; + for (const { key, ruling } of checked) { + if (doc.rulings[key] && !overwrite) continue; + doc.rulings[key] = ruling; + written.push(key); + } + if (written.length) await writeDoc(file, doc); + return { written, doc }; + }); +} + +// --------------------------------------------------------------------------- +// The montage clips, and their keys. +// --------------------------------------------------------------------------- + +/** The clips a montage is made of: clips carrying a `montage` object, in order. */ +export const montageClipsOf = (manifest) => + (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.type === "clip" && isObj(e.montage)); + +/** Does the manifest have a montage to rule (any clip with a `montage` object)? */ +export const hasMontageClips = (manifest) => montageClipsOf(manifest).length > 0; + +/** clip id → moment key, for every clip that has one. */ +export function momentKeysOf(manifest) { + const out = new Map(); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + const k = clipMomentKey(e, manifest); + if (k) out.set(e.id, k); + } + return out; +} + +/** + * Resolve a clip id or a key against the manifest to the key a ruling is + * written under. A key that is no clip's is refused: a ruling on a moment the + * cut does not have is a decision nobody made. + */ +export function resolveRulingKey(manifest, idOrKey) { + const keys = momentKeysOf(manifest); + if (keys.has(idOrKey)) return keys.get(idOrKey); + if ([...keys.values()].includes(idOrKey)) return idOrKey; + return null; +} + +// --------------------------------------------------------------------------- +// The import of the seed's edits.json. +// --------------------------------------------------------------------------- + +/** An exclude's words → its verdict. */ +export function verdictFromWhy(why) { + const w = String(why ?? "").toLowerCase(); + if (/\b(another|other|different) speaker|not (him|her|them)|co-?host|guest|caller|someone else/.test(w)) return "not-him"; + if (/read (out|aloud)|reading|tweet|post\b|chat|quote[sd]? (out|aloud)|message/.test(w)) return "read-aloud"; + return "cut"; +} + +const readJsonIf = async (file) => { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch { + return null; + } +}; + +/** + * The earlier rulings in the seed's edits.json, mapped to moments. Pure over + * what it is given. + * + * @param {Record<string, any>} manifest + * @param {unknown} edits edits.json's contents + * @param {unknown} [instances] instances.json's contents (the seed's) + * @returns {{ rulings: { key: string, clip: string | null, ruling: { verdict: string, reason: string, match?: string } }[], unmapped: { videoId: string, near: number, why: string }[] }} + */ +export function mapEarlierRulings(manifest, edits, instances = null) { + const out = { rulings: [], unmapped: [] }; + if (!isObj(edits)) return out; + const clips = (manifest?.timeline ?? []).filter((e) => isObj(e) && e.type === "clip"); + const inst = Array.isArray(instances) ? instances.filter(isObj) : []; + const at = (e) => (Number.isFinite(e.cutStart) ? e.cutStart : e.start); + const find = (videoId, near) => { + const near_ = Number(near); + const c = clips + .filter((e) => e.video === videoId && Number.isFinite(at(e)) && Math.abs(at(e) - near_) < IMPORT_NEAR_SECONDS) + .sort((a, b) => Math.abs(at(a) - near_) - Math.abs(at(b) - near_))[0]; + if (c) { + const key = clipMomentKey(c, manifest); + if (key) return { key, clip: c.id }; + } + const i = inst + .filter((x) => x.videoId === videoId && typeof x.slug === "string" && Number.isFinite(x.start) && Math.abs(x.start - near_) < IMPORT_NEAR_SECONDS) + .sort((a, b) => Math.abs(a.start - near_) - Math.abs(b.start - near_))[0]; + if (i) { + const key = momentKey({ channel: i.slug, video: i.videoId, at: Math.round(i.start * 100) / 100 }); + if (isMomentKey(key)) return { key, clip: null }; + } + return null; + }; + const take = (e, ruling) => { + if (!isObj(e) || typeof e.videoId !== "string" || !Number.isFinite(Number(e.near))) return; + const hit = find(e.videoId, e.near); + if (!hit) { + out.unmapped.push({ videoId: e.videoId, near: Number(e.near), why: String(e.why ?? "") }); + return; + } + out.rulings.push({ ...hit, ruling }); + }; + for (const e of Array.isArray(edits.exclude) ? edits.exclude : []) { + take(e, { verdict: verdictFromWhy(e?.why), reason: String(e?.why ?? "").slice(0, RULING_REASON_LIMIT) }); + } + for (const e of Array.isArray(edits.match) ? edits.match : []) { + if (typeof e?.match !== "string" || !e.match.trim()) continue; + take(e, { verdict: "keep", reason: String(e?.why ?? "").slice(0, RULING_REASON_LIMIT), match: e.match }); + } + return out; +} + +/** + * What the import would write now: the mapped earlier rulings whose moment is + * not ruled yet. `{ exists }` false when the project has no edits.json. + * @param {string} projectDir + * @param {Record<string, any>} manifest + * @param {{ rulings: Record<string, unknown> }} [doc] the current rulings (read when absent) + */ +export async function earlierRulingsOffer(projectDir, manifest, doc) { + const edits = await readJsonIf(path.join(projectDir, EDITS_FILE)); + if (!edits) return { exists: false, rulings: [], unmapped: [] }; + const instances = await readJsonIf(path.join(projectDir, INSTANCES_FILE)); + const current = doc ?? (await readRulingsState(projectDir)).doc; + const mapped = mapEarlierRulings(manifest, edits, instances); + const seen = new Set(); + const rulings = mapped.rulings.filter((r) => { + if (current.rulings[r.key] || seen.has(r.key)) return false; + seen.add(r.key); + return true; + }); + return { exists: true, rulings, unmapped: mapped.unmapped }; +} + +/** + * Write the offer. Returns what was written and what could not be mapped. + * @param {string} projectDir + * @param {Record<string, any>} manifest + * @param {{ now?: Date, dryRun?: boolean }} [opts] + */ +export async function importEarlierRulings(projectDir, manifest, { now = new Date(), dryRun = false } = {}) { + const offer = await earlierRulingsOffer(projectDir, manifest); + if (dryRun || !offer.rulings.length) return { ...offer, written: [] }; + const { written } = await setMontageRulings(projectDir, offer.rulings.map(({ key, ruling }) => ({ key, ruling })), { now }); + return { ...offer, written }; +} diff --git a/umtool/lib/report/montageRulings.test.mjs b/umtool/lib/report/montageRulings.test.mjs @@ -0,0 +1,137 @@ +// The clip deck's store (release 34 N1): one writer, a queue, tmp + rename, a +// bad file never overwritten; the import of the seed's edits.json mapped to +// moments (the clip within 30 s, else the seed's instances.json), offered once. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + earlierRulingsOffer, hasMontageClips, importEarlierRulings, mapEarlierRulings, momentKeysOf, normaliseRuling, + readRulingsState, resolveRulingKey, setMontageRuling, verdictFromWhy, +} from "./montageRulings.mjs"; + +const NOW = new Date("2026-10-18T12:00:00.000Z"); +const clip = (id, channel, video, cutStart) => ({ + type: "clip", id, channel, video, start: cutStart - 2.5, end: cutStart + 5, cutStart, cutEnd: cutStart + 2, montage: { n: 1, of: 3, match: "slow news day" }, +}); +const MANIFEST = { + provenance: { channelSlug: "chan" }, + timeline: [clip("s01", "chan", "aaa", 100), clip("s02", "chan-rumble", "v70yc82", 3597.6), clip("s03", "chan", "bbb", 12.25), { type: "card", id: "k1" }], +}; + +const tmp = () => mkdtemp(path.join(os.tmpdir(), "umtool-rulings-")); +const file = (dir) => path.join(dir, "montage-rulings.json"); + +test("keys: every clip's moment; a clip id or a key resolves, anything else is refused", () => { + assert.deepEqual([...momentKeysOf(MANIFEST)], [["s01", "chan/aaa@100.00"], ["s02", "chan-rumble/v70yc82@3597.60"], ["s03", "chan/bbb@12.25"]]); + assert.equal(resolveRulingKey(MANIFEST, "s02"), "chan-rumble/v70yc82@3597.60"); + assert.equal(resolveRulingKey(MANIFEST, "chan/bbb@12.25"), "chan/bbb@12.25"); + assert.equal(resolveRulingKey(MANIFEST, "chan/zzz@1.00"), null); + assert.equal(hasMontageClips(MANIFEST), true); + assert.equal(hasMontageClips({ timeline: [{ type: "clip", id: "c", video: "v", start: 1, end: 2 }] }), false); +}); + +test("normaliseRuling: checked, trimmed, stamped; a bad one is a sentence", () => { + assert.deepEqual(normaliseRuling({ verdict: "not-him", reason: " guest " }, NOW), { verdict: "not-him", reason: "guest", at: NOW.toISOString() }); + assert.deepEqual(normaliseRuling({ verdict: "keep", match: " it's not that " }, NOW), { verdict: "keep", reason: "", match: "it's not that", at: NOW.toISOString() }); + assert.throws(() => normaliseRuling({ verdict: "maybe" }), /verdict must be one of/); + assert.throws(() => normaliseRuling({ verdict: "cut", reason: 3 }), /reason must be a string/); + assert.throws(() => normaliseRuling(null), /a ruling is/); +}); + +test("setMontageRuling: set, replace, remove; writes queue; no temp file is left; the shape on disk", async () => { + const dir = await tmp(); + try { + assert.deepEqual(await readRulingsState(dir), { exists: false, doc: { version: 1, rulings: {} }, error: null }); + await Promise.all([ + setMontageRuling(dir, "chan/aaa@100.00", { verdict: "cut", reason: "wrong moment" }, { now: NOW }), + setMontageRuling(dir, "chan/bbb@12.25", { verdict: "read-aloud" }, { now: NOW }), + setMontageRuling(dir, "chan-rumble/v70yc82@3597.60", { verdict: "keep", match: "it's not that it's a slow news cycle" }, { now: NOW }), + ]); + let disk = JSON.parse(await readFile(file(dir), "utf8")); + assert.equal(disk.version, 1); + assert.deepEqual(Object.keys(disk.rulings), ["chan-rumble/v70yc82@3597.60", "chan/aaa@100.00", "chan/bbb@12.25"]); + assert.deepEqual(disk.rulings["chan/aaa@100.00"], { verdict: "cut", reason: "wrong moment", at: NOW.toISOString() }); + await setMontageRuling(dir, "chan/aaa@100.00", { verdict: "not-him" }, { now: NOW }); + await setMontageRuling(dir, "chan/bbb@12.25", null); + disk = JSON.parse(await readFile(file(dir), "utf8")); + assert.equal(disk.rulings["chan/aaa@100.00"].verdict, "not-him"); + assert.equal(disk.rulings["chan/bbb@12.25"], undefined); + assert.deepEqual((await readdir(dir)).sort(), ["montage-rulings.json"]); + await assert.rejects(setMontageRuling(dir, "s01", { verdict: "cut" }), /not a moment key/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a file that does not parse is an error: read as such, never overwritten", async () => { + const dir = await tmp(); + try { + await writeFile(file(dir), "{ broken"); + const st = await readRulingsState(dir); + assert.equal(st.exists, true); + assert.match(st.error, /does not parse/); + await assert.rejects(setMontageRuling(dir, "chan/aaa@100.00", { verdict: "cut" }), /not overwriting it/); + assert.equal(await readFile(file(dir), "utf8"), "{ broken"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("verdictFromWhy: an exclude's words", () => { + assert.equal(verdictFromWhy("another speaker"), "not-him"); + assert.equal(verdictFromWhy("the co-host says it"), "not-him"); + assert.equal(verdictFromWhy("a tweet read out, not his own line"), "read-aloud"); + assert.equal(verdictFromWhy("reading chat"), "read-aloud"); + assert.equal(verdictFromWhy("too long"), "cut"); + assert.equal(verdictFromWhy(undefined), "cut"); +}); + +const EDITS = { + exclude: [ + { videoId: "aaa", near: 112, why: "another speaker" }, + { videoId: "gone", near: 454, why: "a tweet read out, not his own line" }, + { videoId: "nowhere", near: 1, why: "x" }, + ], + match: [{ videoId: "v70yc82", near: 3597, match: "it's not that it's a slow news cycle", why: "the rebuttal" }], +}; +const INSTANCES = [{ slug: "chan", videoId: "gone", start: 454.259 }, { slug: "chan", videoId: "aaa", start: 100 }]; + +test("mapEarlierRulings: the clip whose video matches within 30 s; a moment the seed left out, from instances.json; the rest unmapped", () => { + const m = mapEarlierRulings(MANIFEST, EDITS, INSTANCES); + assert.deepEqual(m.rulings, [ + { key: "chan/aaa@100.00", clip: "s01", ruling: { verdict: "not-him", reason: "another speaker" } }, + { key: "chan/gone@454.26", clip: null, ruling: { verdict: "read-aloud", reason: "a tweet read out, not his own line" } }, + { key: "chan-rumble/v70yc82@3597.60", clip: "s02", ruling: { verdict: "keep", reason: "the rebuttal", match: "it's not that it's a slow news cycle" } }, + ]); + assert.deepEqual(m.unmapped, [{ videoId: "nowhere", near: 1, why: "x" }]); + // 30 s is the edge. + assert.equal(mapEarlierRulings(MANIFEST, { exclude: [{ videoId: "aaa", near: 130.1, why: "" }] }).rulings.length, 0); + assert.deepEqual(mapEarlierRulings(MANIFEST, null), { rulings: [], unmapped: [] }); +}); + +test("the import: offered while something is new, written once, then not offered again; a ruled moment is left as it is", async () => { + const dir = await tmp(); + try { + assert.deepEqual(await earlierRulingsOffer(dir, MANIFEST), { exists: false, rulings: [], unmapped: [] }); + await writeFile(path.join(dir, "edits.json"), JSON.stringify(EDITS)); + await writeFile(path.join(dir, "instances.json"), JSON.stringify(INSTANCES)); + await setMontageRuling(dir, "chan/aaa@100.00", { verdict: "keep" }, { now: NOW }); + const offer = await earlierRulingsOffer(dir, MANIFEST); + assert.deepEqual(offer.rulings.map((r) => r.key), ["chan/gone@454.26", "chan-rumble/v70yc82@3597.60"]); + const dry = await importEarlierRulings(dir, MANIFEST, { dryRun: true }); + assert.deepEqual(dry.written, []); + const done = await importEarlierRulings(dir, MANIFEST, { now: NOW }); + assert.deepEqual(done.written, ["chan/gone@454.26", "chan-rumble/v70yc82@3597.60"]); + const disk = (await readRulingsState(dir)).doc.rulings; + assert.equal(disk["chan/aaa@100.00"].verdict, "keep", "the deck's ruling stands"); + assert.equal(disk["chan-rumble/v70yc82@3597.60"].match, "it's not that it's a slow news cycle"); + assert.equal((await earlierRulingsOffer(dir, MANIFEST)).rulings.length, 0); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -42,6 +42,7 @@ import { lstat, mkdir, readFile, rename, rm, stat, symlink, writeFile } from "no import path from "node:path"; import { pathToFileURL } from "node:url"; import { mergePatch } from "umtool-report-to-video/montage-styles"; +import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings"; import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs"; import { replaceManifest } from "./manifest.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -419,18 +420,26 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { const changes = changeLines(base, manifest, patches); const kind = changes.length === 0 ? "reference" : (spec.kind ?? "different"); + // The clip deck's rulings (report-to-video/montage-rulings.mjs), applied to + // the WHOLE cut before it is windowed: a ruled-out clip leaves the window, + // and the counter is numbered over every kept clip, so a window still counts + // #31 of 70. The build applies them again over the render manifest beside + // the project's, where they change nothing more. The take's own manifest + // (what a pick copies) stays the manifest as written. + const ruled = applyMontageRulings(manifest, await readMontageRulings(projectDir)); + for (const line of rulingsLines(ruled)) log(`${spec.id}: ${line}`); // The render: the window's entries (timed against the project's, so every // take of a group covers the same ones), or the whole cut. - let renderDoc = manifest; + let renderDoc = ruled.manifest; /** @type {null | { ids: string[], basis: string, total: number }} */ let covered = null; if (spec.window !== "full") { const schedule = await readJson(path.join(projectDir, "out", "sourced", "schedule.json")); covered = windowEntries(base.timeline, spec.window, schedule); - const present = new Set(sourcedEntries(manifest.timeline).map((e) => e.id)); + const present = new Set(sourcedEntries(ruled.manifest.timeline).map((e) => e.id)); const ids = covered.ids.filter((id) => present.has(id)); - if (!ids.length) throw new Error(`${spec.id}: the patch removed every entry the window covers (${covered.ids.join(", ")})`); - renderDoc = windowManifest(manifest, ids); + if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`); + renderDoc = windowManifest(ruled.manifest, ids); } if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER)); diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -179,6 +179,32 @@ test("makeTake: the style's patch then the take's, rendered from beside the proj } }); +test("makeTake: the clip deck's rulings leave their clips out of the render, numbered over the whole cut; the take's own manifest is as written", async () => { + // Five montage clips; s02 ruled not-him, s04 cut. A window over s03–s05. + const m = (id, start, n) => clip(id, start, start + 4, { channel: "chan", cutStart: start + 1, cutEnd: start + 3, montage: { n, of: 5, match: "slow news" } }); + const manifest = { ...MANIFEST, timeline: [m("s01", 0, 1), m("s02", 10, 2), m("s03", 20, 3), m("s04", 30, 4), m("s05", 40, 5)] }; + const { root, dir } = await project(manifest); + const r = stubRender(); + const logs = []; + try { + await writeFile(path.join(dir, "montage-rulings.json"), JSON.stringify({ version: 1, rulings: { + "chan/v-s02@11.00": { verdict: "not-him", reason: "guest", at: "2026-10-18T00:00:00Z" }, + "chan/v-s04@31.00": { verdict: "cut", reason: "", at: "2026-10-18T00:00:00Z" }, + "chan/v-s05@41.00": { verdict: "keep", reason: "", match: "a slow news week", at: "2026-10-18T00:00:00Z" }, + } })); + await makeTake(dir, { id: "win", label: "Window", window: { at: 4.5, dur: 5 } }, opts(r, { log: (l) => logs.push(l) })); + assert.deepEqual(r.calls[0].doc.timeline.map((e) => [e.id, e.montage.n, e.montage.of]), [["s03", 2, 3], ["s05", 3, 3]]); + assert.equal(r.calls[0].doc.timeline[1].montage.match, "a slow news week"); + assert.ok(logs.some((l) => /win: montage rulings: 2 clip\(s\) left out — s02 \(not him: guest\), s04 \(cut\)/.test(l)), logs.join("\n")); + const take = JSON.parse(await readFile(path.join(dir, "takes", "win", "video.manifest.json"), "utf8")); + assert.equal(take.timeline.length, 5, "a pick copies the manifest as written; the rulings stay beside it"); + await makeTake(dir, { id: "whole", label: "Whole", window: "full" }, opts(r)); + assert.deepEqual(r.calls[1].doc.timeline.map((e) => e.id), ["s01", "s03", "s05"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + test("makeTake: no change is the reference; a transition turns crossfades on; full renders the whole cut", async () => { const { root, dir } = await project(); const r = stubRender(); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -54,6 +54,9 @@ // after its validators and before it renders anything: an // error refuses it, a warning is a note. // --no-lint Build without the lint (an old manifest it refuses) +// --no-rulings Build as if there were no montage-rulings.json beside the +// manifest (montage-rulings.mjs: the clip deck's rulings, +// which otherwise leave cut / not-him / read-aloud clips out) // --narration-unreviewed Build narrated cards the narration review has not // approved (unreviewed, or edited since); a rejected one // still refuses. Without a review file nothing is held. @@ -156,6 +159,7 @@ import { } from "./narration.mjs"; import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords } from "./narration-store.mjs"; import { readDraftsReview } from "./drafts-review.mjs"; +import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage-rulings.mjs"; import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; @@ -4683,12 +4687,21 @@ export async function prepareLocalMedia(timeline, manifestDir, render = {}) { export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } = {}) { const variant = opts.variant ?? "sourced"; const whole = JSON.parse(await readFile(manifestPath, "utf8")); - const manifest = selectVariant(whole, variant); - const { render, provenance } = manifest; // An `image` entry's `src` is relative to the MANIFEST, which is checked in // beside the pictures it cites -- not to the cwd the build was started from. // So is a clip's. const manifestDir = path.dirname(path.resolve(manifestPath)); + // The clip deck's rulings (montage-rulings.mjs), beside the manifest: a clip + // ruled cut / not-him / read-aloud is left out of this cut (and the wall), + // a ruled `match` widens its phrase, and the counter numbers the kept clips. + // On the cut only: `whole` (the validators, a bench `--fetch-only`) is the + // manifest as written. No file: the same object, today's render. + const ruled = opts.noRulings + ? { manifest: whole, left: [], matched: [], renumbered: false } + : applyMontageRulings(whole, await readMontageRulings(manifestDir), { keep: only ? [only] : [] }); + const manifest = selectVariant(ruled.manifest, variant); + for (const message of rulingsLines(ruled)) EMIT("note", { message }); + const { render, provenance } = manifest; // A `src` clip's file and cues, checked and measured before anything else. await prepareLocalMedia(manifest.timeline, manifestDir, render); // A `render.chrome` that cannot be built is refused here, before a single @@ -5500,6 +5513,7 @@ async function main() { " [--no-rail] [--rail-only] [--preview <start> <dur>]\n" + " [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" + " [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" + + " [--no-rulings] (build as if there were no montage-rulings.json beside the manifest)\n" + " [--narration-unreviewed] (build narrated cards the review has not approved; never a rejected one)\n" + " [--final] [--drafts-unreviewed] (the deliverable: drafted fields must be approved / build the unapproved anyway)\n" + " [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" + @@ -5537,6 +5551,7 @@ async function main() { thumbnailOnly: argv.includes("--thumbnail"), keepFrames: argv.includes("--keep-frames"), noLint: argv.includes("--no-lint"), + noRulings: argv.includes("--no-rulings"), narrationUnreviewed: argv.includes("--narration-unreviewed"), final: argv.includes("--final"), draftsUnreviewed: argv.includes("--drafts-unreviewed"), diff --git a/umtool/report-to-video/montage-rulings.mjs b/umtool/report-to-video/montage-rulings.mjs @@ -0,0 +1,223 @@ +// MONTAGE RULINGS — the operator's word on each instance of a montage +// (release 34 N1): keep it, cut it, not him (another speaker), read aloud (a +// post or a quote read out, not his own line). Ruled by ear on umtool's clip +// deck (`/projects/<id>/clips`), applied here at render. +// +// <project>/montage-rulings.json beside video.manifest.json +// { "version": 1, +// "rulings": { "<channel>/<video>@<cutStart, 2 decimals>": +// { "verdict": "keep" | "cut" | "not-him" | "read-aloud", +// "reason": string, "match"?: string, "at": ISO } } } +// +// KEYED BY THE SOURCE MOMENT, never the clip id: a montage's manifest is +// derived (a seed script numbers its clips s01…), and a re-seed renumbers every +// id while the moment stays where it is. `clipMomentKey` is the one key rule; +// voice-match.json (release 34 N2) uses the same one. A clip with no `channel` +// of its own takes the manifest's `provenance.channelSlug`, as every reader of +// a clip does; its moment is `cutStart`, else `start`. +// +// AT RENDER (`applyMontageRulings`, build-video and verify-build, and the take +// maker before it windows): +// - a clip ruled cut / not-him / read-aloud is left out of the cut — and so of +// the wall, which takes its tiles from the timeline; +// - a ruling's `match` replaces the clip's `montage.match` (the phrase a +// tightened cut is cut to, widened: "it's not that it's a slow news cycle"); +// - when anything was left out, every kept clip's `montage.n` / `montage.of` +// are numbered again over the kept clips, in order, so the counter never +// gaps (#1 … #N of N). Nothing left out: the numbers stay as they are, so a +// take's window of an already-ruled manifest keeps its #31 of 70. +// - NO FILE (or no ruling that changes anything): the very same manifest +// object comes back, and the render is today's, byte for byte. +// A file that does not parse refuses the build: a ruling silently ignored is a +// clip the operator cut appearing in the video. +// +// Pure but for the file's read. Its one writer is umtool's +// lib/report/montageRulings.mjs. +import { readFile } from "node:fs/promises"; +import path from "node:path"; + +export const MONTAGE_RULINGS_FILE = "montage-rulings.json"; +export const RULINGS_VERSION = 1; +export const RULING_VERDICTS = Object.freeze(["keep", "cut", "not-him", "read-aloud"]); +/** The verdicts that leave a clip out of the cut. */ +export const LEFT_OUT_VERDICTS = Object.freeze(["cut", "not-him", "read-aloud"]); +/** A verdict in plain words. */ +export const VERDICT_WORDS = Object.freeze({ keep: "kept", cut: "cut", "not-him": "not him", "read-aloud": "read aloud" }); +export const RULING_REASON_LIMIT = 500; +export const RULING_MATCH_LIMIT = 300; + +/** `<manifest's directory>/montage-rulings.json`. */ +export const montageRulingsFileOf = (dir) => path.join(dir, MONTAGE_RULINGS_FILE); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const finite = (v) => typeof v === "number" && Number.isFinite(v); + +/** A moment's key: `<channel>/<video>@<at, 2 decimals>`. */ +export const momentKey = ({ channel, video, at }) => `${channel}/${video}@${Number(at).toFixed(2)}`; + +/** `<channel>/<video>@<seconds>` — no slash in a channel, no space anywhere, two decimals. */ +const KEY_RE = /^[^/\s@]+\/[^\s]+@\d+\.\d{2}$/; +export const isMomentKey = (k) => typeof k === "string" && KEY_RE.test(k); + +/** The key's parts, or null. */ +export function parseMomentKey(k) { + if (!isMomentKey(k)) return null; + const at = k.lastIndexOf("@"); + const slash = k.indexOf("/"); + return { channel: k.slice(0, slash), video: k.slice(slash + 1, at), at: Number(k.slice(at + 1)) }; +} + +/** + * A clip's moment key, or null for an entry that is not a clip (or names no + * channel, video or time). The moment is the clip's `cutStart`, else `start`. + * + * @param {Record<string, any>} entry + * @param {{ provenance?: { channelSlug?: string } } | null} [manifest] + */ +export function clipMomentKey(entry, manifest = null) { + if (!isObj(entry) || entry.type !== "clip") return null; + const channel = entry.channel ?? manifest?.provenance?.channelSlug ?? null; + const at = finite(entry.cutStart) ? entry.cutStart : entry.start; + if (typeof channel !== "string" || !channel || typeof entry.video !== "string" || !entry.video || !finite(at)) return null; + const key = momentKey({ channel, video: entry.video, at }); + return isMomentKey(key) ? key : null; +} + +/** + * What is wrong with one ruling, as sentences. + * @param {string} key + * @param {unknown} r + */ +export function rulingProblems(key, r) { + const where = `ruling ${JSON.stringify(key)}`; + if (!isMomentKey(key)) return [`${where}: the key is not <channel>/<video>@<seconds to 2 decimals>`]; + if (!isObj(r)) return [`${where} is not an object`]; + const out = []; + if (!RULING_VERDICTS.includes(/** @type {any} */ (r).verdict)) out.push(`${where}: verdict must be one of ${RULING_VERDICTS.join(", ")}`); + if (typeof r.reason !== "string") out.push(`${where}: reason must be a string`); + else if (r.reason.length > RULING_REASON_LIMIT) out.push(`${where}: reason is over ${RULING_REASON_LIMIT} characters`); + if (r.match !== undefined && (typeof r.match !== "string" || !r.match.trim() || r.match.length > RULING_MATCH_LIMIT)) { + out.push(`${where}: match must be a phrase of 1–${RULING_MATCH_LIMIT} characters`); + } + if (typeof r.at !== "string" || Number.isNaN(Date.parse(r.at))) out.push(`${where}: at must be an ISO time`); + return out; +} + +/** + * The file's contents, checked. Throws a sentence naming what is wrong. + * @param {unknown} raw + * @returns {{ version: 1, rulings: Record<string, { verdict: string, reason: string, match?: string, at: string }> }} + */ +export function parseMontageRulings(raw) { + if (!isObj(raw)) throw new Error(`${MONTAGE_RULINGS_FILE} is not an object`); + if (raw.version !== RULINGS_VERSION) throw new Error(`${MONTAGE_RULINGS_FILE}: version must be ${RULINGS_VERSION}`); + if (!isObj(raw.rulings)) throw new Error(`${MONTAGE_RULINGS_FILE}: rulings must be an object`); + const problems = Object.entries(raw.rulings).flatMap(([k, r]) => rulingProblems(k, r)); + if (problems.length) throw new Error(`${MONTAGE_RULINGS_FILE}: ${problems.join("; ")}`); + return /** @type {any} */ (raw); +} + +/** + * The rulings beside a manifest: null when there is no file; throws when it + * does not parse or is not the shape (never read as empty). + * @param {string} dir the manifest's directory + */ +export async function readMontageRulings(dir) { + let text; + try { + text = await readFile(montageRulingsFileOf(dir), "utf8"); + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") return null; + throw err; + } + let raw; + try { + raw = JSON.parse(text); + } catch (e) { + throw new Error(`${MONTAGE_RULINGS_FILE} does not parse (${e instanceof Error ? e.message : String(e)}) — fix it or remove it`); + } + return parseMontageRulings(raw); +} + +/** + * @typedef {{ id: string, key: string, verdict: string, reason: string }} LeftOut + * @typedef {{ id: string, key: string, match: string, was: string | null }} Matched + * @typedef {{ manifest: Record<string, any>, left: LeftOut[], matched: Matched[], renumbered: boolean }} Applied + */ + +/** + * The manifest as the rulings have it. Pure. With no rulings, or none that + * change anything, `manifest` itself comes back (the same object). + * + * @param {Record<string, any>} manifest + * @param {{ rulings: Record<string, any> } | null | undefined} doc + * @param {{ keep?: string[] }} [opts] clip ids never left out (an `--only` rebuild of a ruled-out clip) + * @returns {Applied} + */ +export function applyMontageRulings(manifest, doc, { keep = [] } = {}) { + const none = { manifest, left: [], matched: [], renumbered: false }; + const rulings = doc?.rulings; + if (!isObj(rulings) || !Object.keys(rulings).length || !Array.isArray(manifest?.timeline)) return none; + /** @type {LeftOut[]} */ + const left = []; + /** @type {Matched[]} */ + const matched = []; + const timeline = []; + for (const e of manifest.timeline) { + const key = clipMomentKey(e, manifest); + const r = key ? rulings[key] : null; + if (!r) { + timeline.push(e); + continue; + } + if (LEFT_OUT_VERDICTS.includes(r.verdict) && !keep.includes(e.id)) { + left.push({ id: e.id, key: /** @type {string} */ (key), verdict: r.verdict, reason: typeof r.reason === "string" ? r.reason : "" }); + continue; + } + const was = typeof e.montage?.match === "string" ? e.montage.match : null; + if (typeof r.match === "string" && r.match.trim() && r.match !== was) { + matched.push({ id: e.id, key: /** @type {string} */ (key), match: r.match, was }); + timeline.push({ ...e, montage: { ...(isObj(e.montage) ? e.montage : {}), match: r.match } }); + } else timeline.push(e); + } + if (!left.length && !matched.length) return none; + let renumbered = false; + if (left.length) { + // The counter numbers the KEPT clips 1…N, in order. A clip that carries no + // number of its own is numbered by its place already (planMontage). + const clips = timeline.filter((e) => isObj(e) && e.type === "clip"); + const total = clips.length; + clips.forEach((e, k) => { + if (!isObj(e.montage) || (e.montage.n === undefined && e.montage.of === undefined)) return; + const next = { ...e.montage }; + if (next.n !== undefined) next.n = k + 1; + if (next.of !== undefined) next.of = total; + timeline[timeline.indexOf(e)] = { ...e, montage: next }; + renumbered = true; + }); + } + return { manifest: { ...manifest, timeline }, left, matched, renumbered }; +} + +/** One clip left out, in words: `s04 (not him: another speaker)`. */ +export const leftOutWords = (l) => `${l.id} (${VERDICT_WORDS[l.verdict] ?? l.verdict}${l.reason ? `: ${l.reason}` : ""})`; + +/** + * What the rulings did, as the build log's lines: nothing when they did nothing. + * @param {Applied} applied + */ +export function rulingsLines(applied) { + if (!applied.left.length && !applied.matched.length) return []; + const lines = []; + if (applied.left.length) { + lines.push(`montage rulings: ${applied.left.length} clip(s) left out — ${applied.left.map(leftOutWords).join(", ")}`); + } + for (const m of applied.matched) { + lines.push(`montage rulings: ${m.id} cut to "${m.match}"${m.was ? ` (was "${m.was}")` : ""}`); + } + if (applied.renumbered) { + const n = applied.manifest.timeline.filter((e) => e?.type === "clip").length; + lines.push(`montage rulings: the counter numbers the ${n} kept clip(s) 1–${n}`); + } + return lines; +} diff --git a/umtool/report-to-video/montage-rulings.test.mjs b/umtool/report-to-video/montage-rulings.test.mjs @@ -0,0 +1,243 @@ +// Montage rulings (release 34 N1): the key rule, the file's shape, and how a +// render applies the clip deck's rulings -- the ruled-out clips left out of +// the cut and the wall, a ruled phrase in place of `montage.match`, the +// counter numbered over the kept clips -- and that no file (or a file that +// changes nothing) is today's render, byte for byte. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + applyMontageRulings, clipMomentKey, isMomentKey, leftOutWords, momentKey, MONTAGE_RULINGS_FILE, parseMomentKey, + parseMontageRulings, readMontageRulings, rulingsLines, +} from "./montage-rulings.mjs"; + +// The build's cue reader takes its corpus from CHANNELS_DIR when the module +// loads, so the variable is set before the import: the render tests' clips are +// corpus moments (a channel, a video, a cut start), their windows and cues in +// a synthetic channels tree. +const corpus = await mkdtemp(path.join(os.tmpdir(), "rtv-rulings-corpus-")); +process.env.CHANNELS_DIR = corpus; +const { buildVideo } = await import("./build-video.mjs"); +const { verifyBuild } = await import("./verify-build.mjs"); +const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); +test.after(() => rm(corpus, { recursive: true, force: true })); + +const AT = "2026-10-18T12:00:00.000Z"; +const clip = (id, video, cutStart, extra = {}) => ({ + type: "clip", id, channel: "chan", video, start: cutStart - 2.5, end: cutStart + 4, cutStart, cutEnd: cutStart + 2, + montage: { n: Number(id.slice(1)), of: 5, match: "slow news day" }, ...extra, +}); +const five = () => ({ + slug: "m", provenance: { channelSlug: "chan" }, render: {}, + timeline: [clip("s1", "va", 10), clip("s2", "vb", 20.5), clip("s3", "vc", 30.25), clip("s4", "vd", 40), clip("s5", "ve", 50)], +}); +const doc = (rulings) => ({ version: 1, rulings: Object.fromEntries(Object.entries(rulings).map(([k, r]) => [k, { reason: "", at: AT, ...r }])) }); + +test("the key: <channel>/<video>@<cutStart to 2 decimals>; the manifest's channel when the clip names none; start without a cut", () => { + assert.equal(momentKey({ channel: "c", video: "v-1_x", at: 3127.5 }), "c/v-1_x@3127.50"); + assert.equal(clipMomentKey(clip("s1", "va", 10)), "chan/va@10.00"); + assert.equal(clipMomentKey({ type: "clip", id: "x", video: "vz", start: 4.256 }, { provenance: { channelSlug: "fallback" } }), "fallback/vz@4.26"); + assert.equal(clipMomentKey({ type: "clip", id: "x", video: "vz", start: 4 }), null, "no channel anywhere"); + assert.equal(clipMomentKey({ type: "card", id: "k" }), null); + assert.equal(clipMomentKey({ type: "clip", id: "x", src: "a.mp4", start: 1 }), null, "a local file is no moment"); + assert.ok(isMomentKey("the-quartering-rumble/v70yc82@3597.60")); + assert.ok(!isMomentKey("a/b@1.5"), "two decimals"); + assert.ok(!isMomentKey("a b/c@1.50")); + assert.deepEqual(parseMomentKey("ch/v@12.30"), { channel: "ch", video: "v", at: 12.3 }); +}); + +test("parseMontageRulings: the shape, each problem in words", () => { + assert.deepEqual(parseMontageRulings({ version: 1, rulings: {} }), { version: 1, rulings: {} }); + assert.throws(() => parseMontageRulings([]), /is not an object/); + assert.throws(() => parseMontageRulings({ version: 2, rulings: {} }), /version must be 1/); + assert.throws(() => parseMontageRulings({ version: 1 }), /rulings must be an object/); + assert.throws(() => parseMontageRulings(doc({ "chan/va@10.00": { verdict: "maybe" } })), /verdict must be one of keep, cut, not-him, read-aloud/); + assert.throws(() => parseMontageRulings(doc({ "s01": { verdict: "cut" } })), /the key is not <channel>\/<video>@<seconds/); + assert.throws(() => parseMontageRulings(doc({ "chan/va@10.00": { verdict: "keep", match: " " } })), /match must be a phrase/); + assert.throws(() => parseMontageRulings({ version: 1, rulings: { "chan/va@10.00": { verdict: "cut", reason: "", at: "soon" } } }), /at must be an ISO time/); +}); + +test("readMontageRulings: no file is null; a file that does not parse refuses, never reads as empty", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "rulings-")); + try { + assert.equal(await readMontageRulings(dir), null); + await writeFile(path.join(dir, MONTAGE_RULINGS_FILE), "{ nope"); + await assert.rejects(readMontageRulings(dir), /does not parse .* fix it or remove it/); + await writeFile(path.join(dir, MONTAGE_RULINGS_FILE), JSON.stringify(doc({ "chan/va@10.00": { verdict: "cut" } }))); + assert.equal((await readMontageRulings(dir)).rulings["chan/va@10.00"].verdict, "cut"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("applyMontageRulings: no rulings, or none that change anything -- the very same manifest object", () => { + const m = five(); + for (const d of [null, undefined, { version: 1, rulings: {} }, doc({ "chan/va@10.00": { verdict: "keep" } }), doc({ "chan/gone@1.00": { verdict: "cut" } }), + doc({ "chan/va@10.00": { verdict: "keep", match: "slow news day" } })]) { + const r = applyMontageRulings(m, d); + assert.equal(r.manifest, m); + assert.deepEqual([r.left, r.matched, r.renumbered], [[], [], false]); + assert.deepEqual(rulingsLines(r), []); + } +}); + +test("applyMontageRulings: cut, not-him and read-aloud leave; the counter numbers the kept 1…N of N; match widens the phrase", () => { + const m = five(); + const before = JSON.stringify(m); + const r = applyMontageRulings(m, doc({ + "chan/vb@20.50": { verdict: "not-him", reason: "another speaker" }, + "chan/vc@30.25": { verdict: "keep", match: "it's not that it's a slow news day" }, + "chan/vd@40.00": { verdict: "read-aloud", reason: "a post read out" }, + "chan/ve@50.00": { verdict: "cut" }, + })); + assert.equal(JSON.stringify(m), before, "the input is never changed"); + assert.deepEqual(r.manifest.timeline.map((e) => e.id), ["s1", "s3"]); + assert.deepEqual(r.manifest.timeline.map((e) => [e.montage.n, e.montage.of]), [[1, 2], [2, 2]]); + assert.equal(r.manifest.timeline[1].montage.match, "it's not that it's a slow news day"); + assert.deepEqual(r.left.map((l) => [l.id, l.verdict]), [["s2", "not-him"], ["s4", "read-aloud"], ["s5", "cut"]]); + assert.deepEqual(r.matched, [{ id: "s3", key: "chan/vc@30.25", match: "it's not that it's a slow news day", was: "slow news day" }]); + assert.equal(r.renumbered, true); + assert.equal(leftOutWords(r.left[0]), "s2 (not him: another speaker)"); + assert.deepEqual(rulingsLines(r), [ + "montage rulings: 3 clip(s) left out — s2 (not him: another speaker), s4 (read aloud: a post read out), s5 (cut)", + 'montage rulings: s3 cut to "it\'s not that it\'s a slow news day" (was "slow news day")', + "montage rulings: the counter numbers the 2 kept clip(s) 1–2", + ]); +}); + +test("applyMontageRulings: a card stays; `keep` holds an --only rebuild's clip; applying twice changes nothing more", () => { + const m = five(); + m.timeline.splice(2, 0, { type: "card", id: "k1", seconds: 2 }); + const d = doc({ "chan/va@10.00": { verdict: "cut" }, "chan/vc@30.25": { verdict: "keep", match: "a wider phrase" } }); + const r = applyMontageRulings(m, d); + assert.deepEqual(r.manifest.timeline.map((e) => e.id), ["s2", "k1", "s3", "s4", "s5"]); + assert.deepEqual(r.manifest.timeline.filter((e) => e.montage).map((e) => e.montage.n), [1, 2, 3, 4]); + assert.deepEqual(applyMontageRulings(m, d, { keep: ["s1"] }).manifest.timeline.map((e) => e.id), ["s1", "s2", "k1", "s3", "s4", "s5"]); + // A take's window of an already-ruled manifest: its numbers are the whole cut's, and stay. + const window = { ...r.manifest, timeline: r.manifest.timeline.slice(3) }; + const again = applyMontageRulings(window, d); + assert.equal(again.manifest, window); + assert.deepEqual(again.manifest.timeline.map((e) => e.montage.n), [3, 4]); +}); + +// ---- real renders ----------------------------------------------------------------- + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const FPS = 30; +const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" }; +const RENDER = { + width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0, + headerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + snapWindow: 0.4, silenceMinDur: 0.1, +}; + +/** + * Four corpus moments (channel "demo", videos vid1–vid4, each cut at 1.5 s), + * numbered 1–4 of 4: a four-second window in each video's clips/ and its + * cues. A fresh channel per fixture, so two fixtures never share a window. + */ +let fixtures = 0; +async function fixture({ montage = { tighten: "phrase", counter: { style: "chip", of: true } }, rulings = null } = {}) { + const root = await mkdtemp(path.join(os.tmpdir(), "rtv-rulings-")); + fixtures += 1; + const slug = `demo${fixtures}`; + const timeline = []; + for (let i = 1; i <= 4; i += 1) { + const dir = path.join(corpus, slug, "data", `vid${i}`); + await mkdir(path.join(dir, "clips"), { recursive: true }); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=${FPS}:d=4`, + "-f", "lavfi", "-i", `aevalsrc='0.5*sin(2*PI*${300 + 40 * i}*t)*between(mod(t,1.5),0,1.0)':s=48000:d=4`, + "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(dir, "clips", "0.00-4.00.mp4"), + ]); + assert.equal(r.status, 0, String(r.stderr)); + await writeFile(path.join(dir, "transcript.cues.json"), JSON.stringify({ + id: `vid${i}`, title: `Clip ${i}`, channel: "Demo", uploadDate: `20${18 + i}0${i}0${i}`, duration: 4, platform: "youtube", + cues: [ + { start: 0.2, end: 1.5, text: "well it is a" }, + { start: 1.5, end: 3.0, text: "slow news day again" }, + { start: 3.0, end: 3.8, text: "here we go" }, + ], + })); + timeline.push({ + id: `c${i}`, type: "clip", channel: slug, video: `vid${i}`, start: 0.2, end: 3.8, cutStart: 1.5, cutEnd: 3.0, + montage: { n: i, of: 4, date: `20${18 + i}0${i}0${i}`, platform: "youtube", match: "slow news day" }, + }); + } + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "demo", title: "Demo", provenance: { channelSlug: slug }, render: { ...RENDER, fetchPad: 0, montage }, timeline, + })); + const key = (i) => `${slug}/vid${i}@1.50`; + if (rulings) await writeFile(path.join(root, MONTAGE_RULINGS_FILE), JSON.stringify(doc(rulings(key)))); + return { root, manifestPath, key }; +} + +const OPTS = { noNetwork: true, cueSource: "local" }; +const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0]; + +test("render: no rulings file, or one that changes nothing, is byte for byte the same cut", { skip: !have && "needs ffmpeg" }, async () => { + const a = await fixture(); + const b = await fixture({ rulings: (k) => ({ [k(2)]: { verdict: "keep" }, "demo/gone@9.00": { verdict: "cut" } }) }); + try { + await buildVideo({ manifestPath: a.manifestPath, opts: OPTS }); + await buildVideo({ manifestPath: b.manifestPath, opts: OPTS }); + for (const f of ["demo.mp4", "sourced/segments/c2.mp4", "sourced/segments/c4.mp4"]) { + assert.equal(md5(path.join(a.root, "out", f)), md5(path.join(b.root, "out", f)), f); + } + } finally { + await rm(a.root, { recursive: true, force: true }); + await rm(b.root, { recursive: true, force: true }); + } +}); + +test("render: the ruled-out clips are left out, the counter is the kept clips', verify-build counts what was built; --no-rulings builds them all", { skip: !have && "needs ffmpeg" }, async () => { + const ruled = await fixture({ rulings: (k) => ({ [k(2)]: { verdict: "not-him", reason: "guest" }, [k(3)]: { verdict: "read-aloud" } }) }); + const kept = await fixture({ rulings: null }); + try { + const r = await buildVideo({ manifestPath: ruled.manifestPath, opts: OPTS }); + const segs = (await readdir(path.join(ruled.root, "out", "sourced", "segments"))).filter((f) => /^c\d\.mp4$/.test(f)).sort(); + assert.deepEqual(segs, ["c1.mp4", "c4.mp4"]); + const v = await verifyBuild(ruled.manifestPath); + assert.equal(v.ok, true, v.problems?.join("; ")); + assert.equal(v.entries, 2); + // The kept fourth clip is #2 of 2: built as the second clip of a two-clip + // cut, it is the very file a manifest of those two clips numbered 1, 2 of 2 makes. + const twoOf = JSON.parse(spawnSync("cat", [kept.manifestPath]).stdout.toString()); + twoOf.timeline = [twoOf.timeline[0], { ...twoOf.timeline[3], montage: { ...twoOf.timeline[3].montage, n: 2, of: 2 } }]; + twoOf.timeline[0].montage.of = 2; + await writeFile(kept.manifestPath, JSON.stringify(twoOf)); + await buildVideo({ manifestPath: kept.manifestPath, opts: OPTS }); + assert.equal(md5(path.join(ruled.root, "out", "sourced", "segments", "c4.mp4")), md5(path.join(kept.root, "out", "sourced", "segments", "c4.mp4"))); + assert.equal(md5(r.out), md5(path.join(kept.root, "out", "demo.mp4"))); + // --no-rulings: every clip again, and verify-build told the same. + await buildVideo({ manifestPath: ruled.manifestPath, opts: { ...OPTS, noRulings: true } }); + const all = await verifyBuild(ruled.manifestPath, { noRulings: true }); + assert.equal(all.ok, true, all.problems?.join("; ")); + assert.equal(all.entries, 4); + } finally { + await rm(ruled.root, { recursive: true, force: true }); + await rm(kept.root, { recursive: true, force: true }); + } +}); + +test("render: a ruled-out clip is not a tile of the wall either", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture({ + montage: { tighten: "phrase", wall: { tiles: 9, build: 2 } }, + rulings: (k) => ({ [k(1)]: { verdict: "cut" } }), + }); + try { + await buildVideo({ manifestPath, opts: OPTS }); + const tiles = (await readdir(path.join(root, "out", "sourced", "segments", "montage-wall"))).filter((f) => f.endsWith(".mp4")).sort(); + assert.ok(tiles.length > 0); + assert.ok(!tiles.includes("c1.mp4"), tiles.join(", ")); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -29,6 +29,7 @@ "./frames-cut": "./frames-cut.mjs", "./ledger-totals": "./ledger-totals.mjs", "./montage-styles": "./montage-styles.mjs", + "./montage-rulings": "./montage-rulings.mjs", "./lint": "./lint.mjs", "./local-media": "./local-media.mjs", "./mute": "./mute.mjs", diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs @@ -23,17 +23,21 @@ import { deckGeometry, deckOn, frameCount, postsGeometry, resolveDeck, teaserSec import { statsClips } from "./stats.mjs"; import { frameKeyOf, framesOf } from "./prune-frames.mjs"; import { montageSplit, resolveMontage } from "./montage.mjs"; +import { applyMontageRulings, readMontageRulings } from "./montage-rulings.mjs"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; -export async function verifyBuild(manifestPath, { outDir, variant = "sourced", noXfade = false } = {}) { +export async function verifyBuild(manifestPath, { outDir, variant = "sourced", noXfade = false, noRulings = false } = {}) { // The SAME filter the build ran. Verifying the whole manifest against one // variant's file would report a missing chapter for every entry the other cut // carries -- i.e. it would be red exactly when the build was right. + // And the same rulings (montage-rulings.mjs): a clip the clip deck left out + // has no chapter. `noRulings` matches a `--no-rulings` build. + const parsed = JSON.parse(await readFile(manifestPath, "utf8")); const manifest = selectVariant( - JSON.parse(await readFile(manifestPath, "utf8")), + noRulings ? parsed : applyMontageRulings(parsed, await readMontageRulings(path.dirname(path.resolve(manifestPath)))).manifest, variant, ); const root = outDir ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); @@ -329,7 +333,7 @@ async function main() { const argv = process.argv.slice(2); const manifestPath = argv.find((a) => !a.startsWith("--")); if (!manifestPath) { - console.error("usage: verify-build.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--no-xfade] [--json]"); + console.error("usage: verify-build.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--no-xfade] [--no-rulings] [--json]"); process.exit(2); } const flag = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; }; @@ -338,6 +342,7 @@ async function main() { variant: flag("--variant") ?? "sourced", // The build's own flag: a cut joined without crossfades. noXfade: argv.includes("--no-xfade"), + noRulings: argv.includes("--no-rulings"), }); if (argv.includes("--json")) {