Archilyzer · Source

archilyzer

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

commit c8e8e83b773adf0d5965cdbcb73dcaddbcfdc097
parent 579fe5421a1a061e9df3e4bff12d53e7b6a3df95
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 21:20:10 -0500

umtool: quote-check -- is each clip's quote in the seconds it plays; window --align; check and takes refuse a moved or missing quote

`umtool quote-check <project> [--clips a,b] [--pad S] | --status`: for every
clip with a quote, the source the render would cut it from (the build's own
lookup: raw cache, corpus window, the saved video through its clock), its cut
±15 s transcribed by the editor (pnpm ops transcribe, words on: the GPU lane,
queued there), the quote found in those words and in the recording's cues.
ok | moved (heard more than 0.5 s from where the cues have it; with no cues,
heard outside the cut) | not-found | no-window | no-quote, one row per clip in
<project>/quote-check.json with the cut, quote and source it judged -- a
changed cut or quote makes the row stale.

`umtool window <p> <clip> --align` snaps the cut to the quote as heard (0.15 s
before its first word, 0.3 s after its last; the extent widened to hold it;
lockCut set), and `--quote-ruled` / `--no-quote-ruled` is a person's ruling.
`umtool check` calls a current moved or missing quote blocking
(clip-quote-moved / clip-quote-missing, with the fix), and a take refuses
them like an incorrect clip, unless ruled.

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

Diffstat:
Mumtool/bin/umtool.mjs | 35+++++++++++++++++++++++++++++++++++
Mumtool/lib/projects/report.mjs | 22++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 4+++-
Aumtool/lib/report/quoteCheck.mjs | 368+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/quoteCheck.test.mjs | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 13+++++++++++++
Mumtool/report-to-video/package.json | 1+
7 files changed, 610 insertions(+), 1 deletion(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -16,6 +16,7 @@ // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) // umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json) +// umtool quote-check <project> [--clips a,b] [--status] is each clip's quote in the seconds it plays (quote-check.json) // umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump // umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct // umtool decisions [--json] @@ -28,6 +29,7 @@ // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--reject not-matching|wrong-speaker|irrelevant|repeats|weak|privacy|other [--note TEXT]] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent +// [--align] the cut snapped to the quote as heard (quote-check.json); [--quote-ruled] // [--gap FROM-TO]… [--gap-remove S] [--gaps 'A-B,C-D' | ''] seconds cut out of its middle // [--take <id>] a take's clip: the edit goes into the take's patch (walk a take) // umtool walk <project> [--take <id>] [--all] [--json] the walk: clips in walk order, verdicts, fetched @@ -866,6 +868,10 @@ function usage() { " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each", " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list", + " umtool quote-check <project> [--clips a,b] [--pad S] [--json] | --status is each clip's quote in the seconds it plays?", + " the cut ±15 s of the source the render would use, transcribed by the editor (words on), the quote", + " found in it and in the cues: ok | moved (heard N s away: window --align) | not-found -> quote-check.json;", + " check calls moved and not-found blocking, and a take refuses them unless the clip is --quote-ruled", " umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the", " next post item draws a post the one before showed: its join, the SSIM across it, the largest jump", " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy", @@ -894,6 +900,9 @@ function usage() { " takes it out, on record): not-matching|wrong-speaker (fact errors: incorrect, the note its", " correction) or irrelevant|repeats|weak|privacy|other (rejected; other needs --note)", " --cut-start S --cut-end E --lock-cut the cut the video renders", + " --align the cut snapped to the quote as HEARD (quote-check.json: a breath before its first word,", + " its last let ring; the extent widened to hold it; lockCut kept) -- the per-clip fix for a moved quote", + " --quote-ruled / --no-quote-ruled a person heard it and rules the quote check's verdict: a take renders it", " --move-stamp first|nearest|<s> | --clear-stamp with --start/--end: a stamp's second (claim.at,", " a mark's at) the new window would leave outside moves to the first second that plays, the nearest,", " or <s>, or loses its at -- in the same write; --move-mute nearest | --clear-mute the mute mark's", @@ -1177,6 +1186,8 @@ const COMMANDS = { links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs. "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))), + // Is each clip's quote in the seconds it plays (lane one-clock): the editor transcribes, quote-check.json keeps the rows. + "quote-check": async () => process.exit(await (await import("../lib/report/quoteCheck.mjs")).quoteCheckCommand(argv.slice(argv.indexOf("quote-check") + 1))), // Do a rendered take's post joins carry on (operator, 4 Nov, mid-7): lib/report/checkJoinsCli.mjs. "check-joins": async () => process.exit(await (await import("../lib/report/checkJoinsCli.mjs")).checkJoinsCommand(argv.slice(argv.indexOf("check-joins") + 1))), // The project's link policy (UI notes #10): lib/report/linksCli.mjs. @@ -1283,6 +1294,8 @@ async function cmdWindow() { ["--lock-cut", "lockCut"], // The walk's favourite: a trailer candidate (lib/report/trailerCandidates.mjs). ["--star", "star"], + // A person heard it: the quote check's verdict is ruled (lib/report/quoteCheck.mjs quoteGate). + ["--quote-ruled", "quoteRuled"], ]) { if (has(flag)) patch[key] = true; if (has(`--no-${flag.slice(2)}`)) patch[key] = false; @@ -1362,6 +1375,28 @@ async function cmdWindow() { die(e?.message ?? String(e)); } } + // --align: the cut snapped to the quote as HEARD by the quote check + // (lib/report/quoteCheck.mjs alignPatch), from the clip as the project's + // manifest (or the take's) holds it now. + if (has("--align")) { + if (patch.cutStart !== undefined || patch.cutEnd !== undefined) die("--align sets the cut; give it or --cut-start/--cut-end, not both"); + const { alignPatch, readQuoteCheck } = await import("../lib/report/quoteCheck.mjs"); + const doc = await readQuoteCheck(p.dir); + let entry = null; + if (val("--take") !== undefined) { + const { resolveTakeManifest } = await import("../lib/report/takeManifest.mjs"); + entry = ((await resolveTakeManifest(p.dir, val("--take"))).manifest.timeline ?? []).find((e) => e.id === clipId) ?? null; + } else { + const { readManifest } = await import("../lib/projects/report.mjs"); + entry = ((await readManifest(p.dir))?.timeline ?? []).find((e) => e.id === clipId) ?? null; + } + if (!entry) die(`no clip ${clipId}`); + try { + Object.assign(patch, alignPatch(entry, doc.clips[clipId])); + } catch (e) { + die(e?.message ?? String(e)); + } + } if (!Object.keys(patch).length) die("nothing to change"); // --take <id>: the clip is the TAKE's (walk a take), and the edit goes into diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -1068,6 +1068,13 @@ export const REPORT_DECISION_KINDS = [ // would count its marks, and the video would cite a clip somebody already // said is wrong. Remove it, fix it and re-confirm, or clear the verdict. "clip-incorrect", + // The QUOTE CHECK (lib/report/quoteCheck.mjs, lane one-clock): a clip whose + // quote is not heard in the seconds it plays, or heard seconds away from its + // cut. BLOCKING: the video would put the quote's words on screen over other + // words (6 Nov: c43 played 13 s early). Fixed by `umtool window --align`, a + // refetch, or ruled by a person (`--quote-ruled`). + "clip-quote-missing", + "clip-quote-moved", // A clip REJECTED for a cut reason (irrelevant, repeats, weak, privacy, // other -- not a fact error) that is still in the timeline. `open`, not // blocking: the report is right, and Play the cut already skips it; the @@ -1423,6 +1430,21 @@ export async function reportDecisions(ctx, summary) { for (const e of incorrectClips(clips)) { add("clip-incorrect", e.id, incorrectWhy(e), "blocking", { href: clipHref(e.id) }); } + // A CLIP WHOSE QUOTE IS NOT WHERE IT PLAYS (the quote check's rows, when + // there are any; a stale row -- the cut or the quote changed since -- says + // nothing). + { + const { quoteGate, readQuoteCheck } = await import("../report/quoteCheck.mjs"); + for (const g of quoteGate(clips, await readQuoteCheck(dir))) { + const moved = g.status === "moved"; + add(moved ? "clip-quote-moved" : "clip-quote-missing", g.id, g.why.replace("<p>", id), "blocking", { + href: clipHref(g.id), + fix: moved + ? `umtool window ${id} ${g.id} --align # or --quote-ruled, having heard it` + : `umtool fetch ${id} --refetch ${g.id} && umtool quote-check ${id} --clips ${g.id} # or --quote-ruled, having heard it`, + }); + } + } // A clip rejected (irrelevant, weak, …) but kept in place: open, never blocking. for (const e of rejectedClips(clips)) { add("clip-rejected", e.id, rejectedWhy(e, id), "open", { href: clipHref(e.id) }); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -244,7 +244,9 @@ function keptSecondNear(entry, at) { } const WINDOW_FIELDS = ["start", "end"]; -const FLAG_FIELDS = ["lock", "lockStart", "lockEnd", "lockCut"]; +// `quoteRuled` (lane one-clock): a person heard the clip and rules the quote +// check's verdict (lib/report/quoteCheck.mjs quoteGate) -- a flag like the locks. +const FLAG_FIELDS = ["lock", "lockStart", "lockEnd", "lockCut", "quoteRuled"]; /** Same tolerance the resolver and the build use for a stored 2 dp edge. */ const WIN_EPS = 0.02; diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs @@ -0,0 +1,368 @@ +// `umtool quote-check <project>` (lane one-clock): IS EACH CLIP'S QUOTE IN THE +// SECONDS IT PLAYS? +// +// For every clip with a quote: the source the render would cut it from (the +// raw cache, a corpus window, the saved video through its clock — sources.mjs +// resolveLocalSource, exactly the build's lookup), its cut ± SEARCH_PAD_S of +// it transcribed by the editor (`pnpm ops transcribe` with words: the GPU lane, +// paced and queued there; nothing is decoded here), the quote found in those +// words (quote-in-audio.mjs) and in the recording's cues, and the offset +// between the two. `<project>/quote-check.json` keeps one row per clip: +// +// ok heard within ON_TIME_S of where the cues have it +// moved heard, but seconds away: the render plays other words at the cut +// -- `umtool window <p> <clip> --align` snaps the cut to them +// not-found not in the seconds checked +// no-window nothing on disk holds the cut (fetch first) +// +// A row remembers the cut and the source it judged: a clip whose cut or +// source changed since reads as STALE, and is checked again on the next run. +// `umtool check` reads the rows (projects/report.mjs: clip-quote-moved, +// clip-quote-missing, blocking), and a take refuses a clip whose quote was not +// found or moved unless the clip says `quoteRuled` (`umtool window <p> <clip> +// --quote-ruled`: heard and ruled by a person). +// +// Plain ESM: the CLI runs under bare node; the app reads the file. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { createCueSource, siteOriginFromManifest } from "umtool-report-to-video/cues"; +import { cueWords, findQuote, ON_TIME_S, quoteOffset } from "umtool-report-to-video/quote-in-audio"; +import { resolveLocalSource } from "umtool-report-to-video/sources"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; + +export const QUOTE_CHECK_FILE = "quote-check.json"; +/** Seconds either side of the cut that are transcribed: the 6 Nov offsets reached 13.6 s. */ +export const SEARCH_PAD_S = 15; +/** Cues read either side of the searched span, to find the quote in. */ +const CUE_PAD_S = 30; +/** The cut's edges after --align: a breath before the first word, the last word let ring. */ +export const ALIGN_LEAD_S = 0.15; +export const ALIGN_TAIL_S = 0.3; + +const r2 = (x) => Math.round(Number(x) * 100) / 100; +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** The span a clip plays: its cut, else its extent. */ +export const playedSpan = (e) => ({ from: r2(e.cutStart ?? e.start), to: r2(e.cutEnd ?? e.end) }); + +/** The source's identity a row was judged on: a change makes the row stale. */ +export const sourceKey = (s) => + s ? `${s.kind}:${s.path}@${r2(s.windowStart)}${s.clock ? `#${s.clock.id}` : ""}` : null; + +/** + * Is this row about the clip as it is now? Same cut, same source. + * @param {Record<string, any> | null | undefined} row + * @param {Record<string, any>} entry + * @param {string | null} [srcKey] the source as it resolves now, when known + */ +export function rowIsCurrent(row, entry, srcKey = undefined) { + if (!row) return false; + const p = playedSpan(entry); + if (Math.abs(row.cut?.from - p.from) > 0.011 || Math.abs(row.cut?.to - p.to) > 0.011) return false; + if (String(row.quote ?? "") !== String(entry.quote ?? "")) return false; + if (srcKey !== undefined && row.source?.key !== srcKey) return false; + return true; +} + +/** The file, or an empty one. */ +export async function readQuoteCheck(dir) { + try { + const doc = JSON.parse(await readFile(path.join(dir, QUOTE_CHECK_FILE), "utf8")); + return doc && typeof doc === "object" && doc.clips && typeof doc.clips === "object" ? doc : { version: 1, clips: {} }; + } catch { + return { version: 1, clips: {} }; + } +} + +async function writeQuoteCheck(dir, doc) { + const file = path.join(dir, QUOTE_CHECK_FILE); + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); + await rename(tmp, file); + return file; +} + +/** + * The clips to check and where each one's seconds are. Pure but for the disk + * lookups the build makes. + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {{ channelsDirs: string[], rawDir?: string, clipIds?: string[], pad?: number, probe?: any }} opts + */ +export async function planQuoteCheck(dir, manifest, { channelsDirs, rawDir = path.join(dir, "out", "clips-raw"), clipIds = [], pad = SEARCH_PAD_S, probe } = /** @type {any} */ ({})) { + const prov = manifest?.provenance ?? {}; + const rows = []; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip" || e.src) continue; + if (clipIds.length && !clipIds.includes(e.id)) continue; + const slug = e.channel ?? prov.channelSlug ?? null; + const cut = playedSpan(e); + const base = { id: e.id, slug, video: e.video ?? null, quote: e.quote ?? null, cut }; + if (!String(e.quote ?? "").trim()) { + rows.push({ ...base, skip: "no-quote" }); + continue; + } + if (!slug || !e.video || !fin(cut.from) || !fin(cut.to)) { + rows.push({ ...base, skip: "no-window" }); + continue; + } + const src = await resolveLocalSource( + { video: e.video, slug, from: cut.from, to: cut.to }, + { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, ...(probe ? { probe } : {}) }, + ); + if (!src) { + rows.push({ ...base, skip: "no-window" }); + continue; + } + // The searched span, on the cue clock, inside what the source holds. + const from = Math.max(src.windowStart, cut.from - pad); + const to = Math.min(src.windowEnd, cut.to + pad); + rows.push({ + ...base, + source: { kind: src.kind, path: src.path, name: src.name, windowStart: src.windowStart, windowEnd: src.windowEnd, ...(src.clock ? { clock: src.clock } : {}), key: sourceKey(src) }, + span: { from: r2(from), to: r2(to) }, + // The same span in the source FILE's seconds: what the editor transcribes. + file: { start: r2(Math.max(0, from - src.windowStart)), end: r2(Math.max(0, to - src.windowStart)) }, + }); + } + return rows; +} + +/** + * One clip's verdict from the words heard (CUE clock) and the recording's cues. + * @param {{ quote: string, cut: { from: number, to: number }, span: { from: number, to: number } }} row + * @param {{ w?: string, text?: string, start: number, end: number }[]} heardWords + * @param {{ start: number, end: number, text: string }[] | null} cues + */ +export function judgeClip(row, heardWords, cues) { + const heard = findQuote(row.quote, heardWords); + const cued = cues ? findQuote(row.quote, cueWords(cues, { from: row.span.from - CUE_PAD_S, to: row.span.to + CUE_PAD_S })) : null; + let offset = heard.found && cued?.found ? quoteOffset(heard, cued) : null; + // No cues to compare with: where the clip's cut starts is the best guess of + // where the quote should be. + const against = offset !== null ? "cues" : heard.found ? "cut" : null; + if (offset === null && heard.found && heard.from !== null) offset = r2(heard.from - row.cut.from); + // Moved: heard away from where the cues have it -- or, with no cues to ask, + // heard outside the cut (the cut does not play it). + const outsideCut = heard.found && (heard.from < row.cut.from - ON_TIME_S || heard.to > row.cut.to + ON_TIME_S); + const status = !heard.found + ? "not-found" + : against === "cues" + ? Math.abs(/** @type {number} */ (offset)) > ON_TIME_S ? "moved" : "ok" + : outsideCut ? "moved" : "ok"; + return { + status, + offset, + against, + match: heard.match, + heard: heard.found ? { from: heard.from, to: heard.to } : null, + cued: cued?.found ? { from: cued.from, to: cued.to } : null, + words: heard.heard.slice(0, 400), + }; +} + +/** "c43 moved +13.06 s (heard 2132.90–2140.10, cues 2119.84–…)" */ +export function rowLine(id, row) { + const off = fin(row.offset) ? ` ${row.offset >= 0 ? "+" : ""}${row.offset.toFixed(2)} s` : ""; + const where = row.heard ? ` heard ${row.heard.from.toFixed(2)}–${row.heard.to.toFixed(2)}` : ""; + const src = row.source ? ` [${row.source.kind}${row.source.clock ? `, clock ${row.source.clock.certain ? "" : "NOT "}certain` : ""}]` : ""; + return `${String(id).padEnd(5)} ${String(row.status).padEnd(9)}${off}${where}${row.match !== undefined ? ` match ${row.match}` : ""}${src}`; +} + +/** + * The clips a render must refuse: a CURRENT row that says the quote was not + * heard, or heard elsewhere, on a clip nobody ruled (`quoteRuled`). + * @param {Record<string, any>[]} timeline + * @param {{ clips: Record<string, any> }} doc + * @returns {{ id: string, status: string, why: string }[]} + */ +export function quoteGate(timeline, doc) { + const out = []; + for (const e of timeline ?? []) { + if (e?.type !== "clip" || e.quoteRuled) continue; + const row = doc?.clips?.[e.id]; + if (!rowIsCurrent(row, e)) continue; + if (row.status === "not-found") { + out.push({ id: e.id, status: row.status, why: `${e.id}: its quote is not in the seconds it plays (umtool quote-check, match ${row.match})` }); + } else if (row.status === "moved") { + out.push({ + id: e.id, + status: row.status, + why: `${e.id}: its quote is heard ${row.offset >= 0 ? "+" : ""}${Number(row.offset).toFixed(2)} s from its cut — umtool window <p> ${e.id} --align`, + }); + } + } + return out; +} + +/** + * The window patch that snaps a clip's cut to its quote as HEARD (the row's + * heard span), widening the extent to hold it; lockCut set so no resolver + * re-derives the cut from cues the audio disagrees with. + * @param {Record<string, any>} entry + * @param {Record<string, any> | null | undefined} row + */ +export function alignPatch(entry, row) { + if (!row) throw new Error(`${entry.id} has no quote check: umtool quote-check <p> --clips ${entry.id}`); + if (!rowIsCurrent(row, entry)) throw new Error(`${entry.id}: its quote check is stale (the cut or the quote changed): run umtool quote-check again`); + if (!row.heard) throw new Error(`${entry.id}: its quote was not heard (${row.status}) — nothing to align to; fetch it again (umtool fetch <p> --refetch ${entry.id}) or rule it`); + const cutStart = r2(Math.max(0, row.heard.from - ALIGN_LEAD_S)); + const cutEnd = r2(row.heard.to + ALIGN_TAIL_S); + const patch = { cutStart, cutEnd, lockCut: true }; + if (entry.start > cutStart) patch.start = cutStart; + if (entry.end < cutEnd) patch.end = cutEnd; + return patch; +} + +// --------------------------------------------------------------------------- +// The run. +// --------------------------------------------------------------------------- + +/** + * Transcribe through the editor: `POST /api/ops/transcribe {path, start, end, + * words: true, out}`, waited for; the words on the FILE's clock. + * @param {{ path: string, start: number, end: number, out: string }} req + */ +async function editorWords(req, { emit }) { + const { askEditorOp } = await import("umtool-report-to-video/narrate-via-editor"); + await askEditorOp("/api/ops/transcribe", { path: req.path, start: req.start, end: req.end, words: true, out: req.out }, { emit }); + const doc = JSON.parse(await readFile(req.out, "utf8")); + return Array.isArray(doc.words) ? doc.words : []; +} + +/** + * Check the planned clips; merge the rows into quote-check.json. + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {Awaited<ReturnType<typeof planQuoteCheck>>} plan + * @param {{ transcribe?: typeof editorWords, cuesOf?: (slug: string, video: string) => Promise<any[] | null>, log?: (l: string) => void, now?: () => Date }} [opts] + */ +export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date() } = {}) { + const doc = await readQuoteCheck(dir); + const work = path.join(dir, "out", "quote-check"); + await mkdir(work, { recursive: true }); + const cueSource = cuesOf + ? null + : createCueSource({ channelsDirs: channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }), siteOrigin: siteOriginFromManifest(manifest) }); + const cueMemo = new Map(); + const cues = async (slug, video) => { + const k = `${slug}/${video}`; + if (!cueMemo.has(k)) { + cueMemo.set( + k, + cuesOf + ? await cuesOf(slug, video) + : await cueSource + .load(slug, video, {}) + .then((r) => r?.cues ?? null) + .catch(() => null), + ); + } + return cueMemo.get(k); + }; + const results = {}; + for (const p of plan) { + const checkedAt = now().toISOString(); + if (p.skip) { + results[p.id] = { status: p.skip, cut: p.cut, quote: p.quote, checkedAt }; + log(rowLine(p.id, results[p.id])); + continue; + } + const out = path.join(work, `${p.id}.words.json`); + let words; + try { + words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} }); + } catch (e) { + log(`${p.id}: the transcription failed: ${e instanceof Error ? e.message : String(e)}`); + continue; + } + // The words on the CUE clock: the file's seconds + where the file starts on it. + const heardWords = words.map((w) => ({ w: w.w ?? w.text, start: w.start + p.source.windowStart, end: w.end + p.source.windowStart })); + const verdict = judgeClip(p, heardWords, await cues(p.slug, p.video)); + results[p.id] = { ...verdict, cut: p.cut, quote: p.quote, span: p.span, source: p.source, checkedAt }; + log(rowLine(p.id, results[p.id])); + } + const merged = { version: 1, checkedAt: now().toISOString(), clips: { ...doc.clips, ...results } }; + const file = await writeQuoteCheck(dir, merged); + return { file, doc: merged, results }; +} + +// --------------------------------------------------------------------------- +// The CLI. +// --------------------------------------------------------------------------- + +export const QUOTE_CHECK_USAGE = [ + "usage: umtool quote-check <project> [--clips a,b] [--pad S] [--json] transcribe what each clip plays; find its quote", + " umtool quote-check <project> --status [--json] the rows as they stand (stale ones said)", + "", + `Each clip's cut ±${SEARCH_PAD_S} s (--pad) of the source the render would cut it from is transcribed by the`, + "editor (its transcription lane, words on), and the quote is found in those words and in the recording's", + `cues: ok (within ${ON_TIME_S} s), moved (heard elsewhere: umtool window <p> <clip> --align), not-found.`, + `Rows go to <project>/${QUOTE_CHECK_FILE}; umtool check reads them, and a take refuses a moved or`, + "missing quote unless the clip is ruled (umtool window <p> <clip> --quote-ruled).", +].join("\n"); + +class CliError extends Error {} + +export async function quoteCheckCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, transcribe, cuesOf } = {}) { + try { + const words = []; + /** @type {Record<string, string[]>} */ + const flags = {}; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--json" || a === "--status" || a === "--help") flags[a] = ["1"]; + else if (a.startsWith("--")) (flags[a] ??= []).push(args[++i] ?? ""); + else words.push(a); + } + if (flags["--help"] || !words.length) { + log(QUOTE_CHECK_USAGE); + return flags["--help"] ? 0 : 2; + } + const r = await resolveProject(words[0], reportsRoot); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const json = !!flags["--json"]; + + if (flags["--status"]) { + const doc = await readQuoteCheck(project.dir); + const rows = []; + for (const e of manifest.timeline ?? []) { + if (e?.type !== "clip") continue; + const row = doc.clips[e.id]; + rows.push({ id: e.id, ...(row ?? { status: "unchecked" }), current: rowIsCurrent(row, e) }); + } + if (json) log(JSON.stringify({ project: project.id, clips: rows }, null, 1)); + else for (const row of rows) log(`${rowLine(row.id, row)}${row.current || row.status === "unchecked" ? "" : " (stale: the cut or the quote changed)"}`); + return 0; + } + + const clipIds = (flags["--clips"] ?? []).flatMap((s) => s.split(",")).map((s) => s.trim()).filter(Boolean); + const pad = flags["--pad"] ? Number(flags["--pad"].at(-1)) : SEARCH_PAD_S; + if (!(pad >= 0 && pad <= 60)) throw new CliError("--pad is seconds, 0 to 60"); + const channelsDirs = channelsLayersFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + if (!channelsDirs.length) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from"); + const plan = await planQuoteCheck(project.dir, manifest, { channelsDirs, clipIds, pad }); + if (clipIds.length && !plan.length) throw new CliError(`none of ${clipIds.join(", ")} is a clip of ${project.id}`); + const { file, results } = await runQuoteCheck(project.dir, manifest, plan, { + ...(transcribe ? { transcribe } : {}), + ...(cuesOf ? { cuesOf } : {}), + log: json ? () => {} : log, + }); + if (json) log(JSON.stringify({ project: project.id, file, clips: results }, null, 1)); + else { + const count = (s) => Object.values(results).filter((x) => x.status === s).length; + log(`→ ${file}: ${count("ok")} ok, ${count("moved")} moved, ${count("not-found")} not found, ${count("no-window")} with no window`); + } + return 0; + } catch (e) { + err(e instanceof CliError ? `umtool quote-check: ${e.message}` : `umtool quote-check: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} diff --git a/umtool/lib/report/quoteCheck.test.mjs b/umtool/lib/report/quoteCheck.test.mjs @@ -0,0 +1,168 @@ +// quoteCheck.mjs (lane one-clock): the plan finds what the render would play, +// the run judges each clip from the words the editor heard and the cues, the +// gate refuses a moved or missing quote unless ruled, and --align snaps the cut +// to the words. The words and cues are the 6 Nov c43 window's +// (report-to-video/fixtures/rev9-a3-rumble-words.json): heard 13 s late. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { alignPatch, judgeClip, planQuoteCheck, quoteCheckCommand, quoteGate, readQuoteCheck, rowIsCurrent, runQuoteCheck } from "./quoteCheck.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIX = JSON.parse(await readFile(path.join(HERE, "..", "..", "report-to-video", "fixtures", "rev9-a3-rumble-words.json"), "utf8")); +const C43 = FIX.clips.find((c) => c.id === "c43"); +const C44 = FIX.clips.find((c) => c.id === "c44"); + +async function project() { + const root = await mkdtemp(path.join(os.tmpdir(), "quote-check-")); + const dir = path.join(root, "diet"); + const raw = path.join(dir, "out", "clips-raw"); + await mkdir(raw, { recursive: true }); + const channels = path.join(root, "channels"); + await mkdir(channels, { recursive: true }); + // The windows the render would play: the project's raw cache, named for the cue clock. + for (const c of [C43, C44]) await writeFile(path.join(raw, `${c.video}_${c.window[0].toFixed(2)}-${c.window[1].toFixed(2)}.mp4`), "mp4"); + const manifest = { + provenance: { channelSlug: "the-quartering-rumble", channelsDir: channels, channelsFallback: false }, + timeline: [ + { type: "clip", id: "c43", channel: C43.channel, video: C43.video, start: 2119.34, end: 2127.44, quote: C43.quote }, + { type: "clip", id: "c44", channel: C44.channel, video: C44.video, start: 633.42, end: 644.16, quote: C44.quote }, + { type: "clip", id: "c99", channel: C44.channel, video: C44.video, start: 10, end: 20 }, + ], + }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest)); + return { root, dir, channels, manifest }; +} + +// The editor, stood in for: the fixture's words between start and end, on the file's clock. +const fakeTranscribe = async (req) => { + const clip = [C43, C44].find((c) => req.path.includes(c.video)); + return clip.words.filter((w) => w.start >= req.start - 0.01 && w.end <= req.end + 0.01); +}; +const fakeCues = async (_slug, video) => [C43, C44].find((c) => c.video === video)?.cues ?? null; + +test("plan, run, gate, align: c43 is heard 13 s late; c44 where its cues say", async () => { + const p = await project(); + try { + const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] }); + const c43 = plan.find((r) => r.id === "c43"); + assert.equal(c43.source.kind, "raw-cache"); + assert.equal(c43.source.windowStart, C43.window[0]); + // The cut ±15 s, inside the window the render would cut from. + assert.deepEqual(c43.span, { from: 2104.34, to: 2142.44 }); + assert.deepEqual(c43.file, { start: 0, end: 38.1 }); + assert.equal(plan.find((r) => r.id === "c99").skip, "no-quote"); + + const lines = []; + const { doc } = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: fakeTranscribe, cuesOf: fakeCues, log: (l) => lines.push(l) }); + assert.equal(doc.clips.c43.status, "moved"); + assert.ok(Math.abs(doc.clips.c43.offset - 13.1) < 0.15, String(doc.clips.c43.offset)); + assert.equal(doc.clips.c43.against, "cues"); + assert.equal(doc.clips.c44.status, "ok"); + assert.equal(doc.clips.c99.status, "no-quote"); + assert.match(lines.join("\n"), /c43 +moved +\+13\.\d\d s heard 2132\.\d\d/); + assert.deepEqual(await readQuoteCheck(p.dir), doc); + + // The gate: c43 refused, c44 not; ruled, c43 renders; a changed cut is stale and says nothing. + assert.deepEqual(quoteGate(p.manifest.timeline, doc).map((g) => [g.id, g.status]), [["c43", "moved"]]); + const ruled = p.manifest.timeline.map((e) => (e.id === "c43" ? { ...e, quoteRuled: true } : e)); + assert.deepEqual(quoteGate(ruled, doc), []); + const moved = p.manifest.timeline.map((e) => (e.id === "c43" ? { ...e, cutStart: 2120, cutEnd: 2127 } : e)); + assert.equal(rowIsCurrent(doc.clips.c43, moved[0]), false); + assert.deepEqual(quoteGate(moved, doc), []); + + // --align: the cut on the words as heard, the extent widened to hold it. + const patch = alignPatch(p.manifest.timeline[0], doc.clips.c43); + assert.equal(patch.lockCut, true); + assert.ok(Math.abs(patch.cutStart - (doc.clips.c43.heard.from - 0.15)) < 0.011); + assert.ok(patch.cutStart > 2132 && patch.cutEnd > 2140, JSON.stringify(patch)); + assert.equal(patch.start, undefined); + assert.equal(patch.end, patch.cutEnd); + assert.throws(() => alignPatch(moved[0], doc.clips.c43), /stale/); + assert.throws(() => alignPatch(p.manifest.timeline[0], null), /no quote check/); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("judge: not heard is not-found; with no cues the cut is what the offset is measured from", () => { + const row = { quote: C43.quote, cut: { from: 2119.34, to: 2127.44 }, span: { from: 2104.34, to: 2142.44 } }; + const words = C43.words.map((w) => ({ ...w, start: w.start + C43.window[0], end: w.end + C43.window[0] })); + const noCues = judgeClip(row, words, null); + assert.equal(noCues.against, "cut"); + // Against the cut only: moved when the words are heard outside the cut (the cut does not play them). + assert.equal(noCues.status, "moved"); + const inside = judgeClip({ ...row, cut: { from: 2130, to: 2142 } }, words, null); + assert.equal(inside.status, "ok"); + const elsewhere = judgeClip({ ...row, quote: "I promise you by this time next year I will be down 100 pounds" }, words, C43.cues); + assert.equal(elsewhere.status, "not-found"); +}); + +test("the CLI: a project's clips checked through the injected editor, --status after", async () => { + const p = await project(); + try { + const out = []; + const code = await quoteCheckCommand(["diet", "--clips", "c43"], { + reportsRoot: p.root, + log: (l) => out.push(l), + err: (l) => out.push(`ERR ${l}`), + transcribe: fakeTranscribe, + cuesOf: fakeCues, + }); + assert.equal(code, 0, out.join("\n")); + assert.match(out.join("\n"), /0 ok, 1 moved, 0 not found/); + const st = []; + assert.equal(await quoteCheckCommand(["diet", "--status"], { reportsRoot: p.root, log: (l) => st.push(l), err: (l) => st.push(l) }), 0); + assert.match(st.join("\n"), /c43 +moved/); + assert.match(st.join("\n"), /c44 +unchecked/); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("umtool check: a moved quote and a missing one are blocking, with the fix; ruled or stale, nothing", async () => { + const { decisionsFor } = await import("../projects/core.mjs"); + const { walkProjects } = await import("../projects/walk.mjs"); + const root = await mkdtemp(path.join(os.tmpdir(), "quote-decisions-")); + try { + const channelsDir = path.join(root, "channels"); + const vdir = path.join(channelsDir, "chan", "data", "vid"); + await mkdir(vdir, { recursive: true }); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ cues: Array.from({ length: 200 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })) })); + const dir = path.join(root, "reports", "cut"); + await mkdir(dir, { recursive: true }); + const clip = (id, start, extra = {}) => ({ type: "clip", id, video: "vid", start, end: start + 5, cite: start, lock: true, quote: `Line ${start}`, ...extra }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: "cut", title: "Cut", + provenance: { channelSlug: "chan", channelsDir: path.relative(dir, channelsDir), siteOrigin: "https://example.test" }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline: [clip("a", 10), clip("b", 20), clip("c", 30, { quoteRuled: true }), clip("d", 40)], + })); + const row = (start, status, extra = {}) => ({ status, cut: { from: start, to: start + 5 }, quote: `Line ${start}`, match: 0.3, ...extra }); + await writeFile(path.join(dir, "quote-check.json"), JSON.stringify({ + version: 1, + clips: { + a: row(10, "moved", { offset: 13.06, match: 1, heard: { from: 23.06, to: 25 } }), + b: row(20, "not-found"), + c: row(30, "not-found"), + d: { ...row(40, "not-found"), cut: { from: 41, to: 45 } }, + }, + })); + const [ref] = (await walkProjects(path.join(root, "reports"))).filter((p) => p.id === "cut"); + const ds = (await decisionsFor(ref, path.join(root, "reports"))).filter((d) => d.kind.startsWith("clip-quote")); + assert.deepEqual(ds.map((d) => [d.kind, d.target, d.severity]), [ + ["clip-quote-moved", "a", "blocking"], + ["clip-quote-missing", "b", "blocking"], + ]); + assert.match(ds[0].why, /a: its quote is heard \+13\.06 s from its cut — umtool window cut a --align/); + assert.equal(ds[0].fix, "umtool window cut a --align # or --quote-ruled, having heard it"); + assert.match(ds[1].fix, /umtool fetch cut --refetch b/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -690,6 +690,19 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { // blocking (clip-incorrect), and a take is a render like any other. const wrong = incorrectClips(renderDoc.timeline); if (wrong.length) throw new Error(`${spec.id}: ${wrong.map(incorrectWhy).join("; ")}`); + // A clip whose quote the quote check did not hear where it plays (lane + // one-clock, lib/report/quoteCheck.mjs): refused the same way, unless a + // person ruled it (`quoteRuled`). No check on record refuses nothing. + { + const { quoteGate, readQuoteCheck } = await import("./quoteCheck.mjs"); + const unheard = quoteGate(renderDoc.timeline, await readQuoteCheck(projectDir)); + if (unheard.length) { + throw new Error( + `${spec.id}: ${unheard.map((u) => u.why.replace("<p>", path.basename(projectDir))).join("; ")} ` + + "(heard and right after all: umtool window <p> <clip> --quote-ruled)", + ); + } + } await mkdir(takeDir, { recursive: true }); await opts.onTakeDir?.(takeDir, spec.id); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -29,6 +29,7 @@ "./side-card": "./side-card.mjs", "./check-availability": "./check-availability.mjs", "./recording-ids": "./recording-ids.mjs", + "./quote-in-audio": "./quote-in-audio.mjs", "./check-joins": "./check-joins.mjs", "./chunked-encode": "./chunked-encode.mjs", "./claims": "./claims.mjs",