// `umtool quote-check ` (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. `/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

--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

// --quote-ruled`: heard and ruled by a person). // // A TAKE'S OWN VERDICTS (`--take `): the take's clips -- its patch over the // draft, as it renders -- judged into takes//quote-check.json. A take's // refusal, `umtool check

--take ` and `window --take --align` read the // take's rows AND the project's (takeQuoteGate): a take may only ever ADD a // refusal to what the project's rows refuse for the same cut, never take one // away (review, 12 Nov: a stale take row once hid a current project `moved`). // Each row counts only while it is current for the take's clip (rowIsCurrent); // the project's, only for the same clip too -- its video and channel the // draft's entry of that id (a row does not record them). // // Plain ESM: the CLI runs under bare node; the app reads the file. import { mkdir, readFile, realpath, rename, rmdir, writeFile } from "node:fs/promises"; import os from "node:os"; 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 { isTakeId } from "./takes.mjs"; import { channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const QUOTE_CHECK_FILE = "quote-check.json"; /** Where a take's own rows live: beside its take.json. */ export const takeQuoteCheckDir = (projectDir, take) => { if (!isTakeId(take)) throw new Error(`"${take}" is not a take id (lower-case letters, digits, dashes)`); return path.join(projectDir, "takes", take); }; /** 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 | null | undefined} row * @param {Record} 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: {} }; } } /** * The two files a take is judged by: its own rows (takes//quote-check.json) and the project's. The take id is * checked before anything is read. * @param {string} projectDir * @param {string} take * @returns {Promise<{ own: { clips: Record }, project: { clips: Record } }>} */ export async function readTakeQuoteCheck(projectDir, take) { const dir = takeQuoteCheckDir(projectDir, take); const [project, own] = await Promise.all([readQuoteCheck(projectDir), readQuoteCheck(dir)]); return { own, project }; } /** The draft's entry of that id is the same clip as the take's: the same video and channel (a row records neither). */ const sameClip = (draftEntry, e) => !draftEntry || (String(draftEntry.video ?? "") === String(e.video ?? "") && String(draftEntry.channel ?? "") === String(e.channel ?? "")); /** * Per clip of the take, the row that speaks for it: its own when current for the take's entry, else the project's * when current and about the same clip (sameClip), else null. `from` says whose. For --status and --align. * @param {Record[]} timeline the take's * @param {Awaited>} docs * @param {Record[]} draftTimeline the project's manifest's * @returns {Map, from: "take" | "project" }>} */ export function takeQuoteRows(timeline, docs, draftTimeline = []) { const draft = new Map((draftTimeline ?? []).filter((e) => e?.id).map((e) => [e.id, e])); const out = new Map(); for (const e of timeline ?? []) { if (e?.type !== "clip") continue; const own = docs.own?.clips?.[e.id]; const proj = docs.project?.clips?.[e.id]; if (rowIsCurrent(own, e)) out.set(e.id, { row: own, from: "take" }); else if (rowIsCurrent(proj, e) && sameClip(draft.get(e.id), e)) out.set(e.id, { row: proj, from: "project" }); } return out; } /** * What a take's render refuses: the clips its own current rows refuse AND those the project's current rows refuse * (same clip, same cut) -- never fewer than the project's rows refuse for the same cut. `from` on each. * @param {Record[]} timeline the take's * @param {Awaited>} docs * @param {Record[]} draftTimeline */ export function takeQuoteGate(timeline, docs, draftTimeline = []) { const draft = new Map((draftTimeline ?? []).filter((e) => e?.id).map((e) => [e.id, e])); const own = quoteGate(timeline, docs.own ?? { clips: {} }).map((g) => ({ ...g, from: "take" })); const mine = new Set(own.map((g) => g.id)); const proj = quoteGate( (timeline ?? []).filter((e) => sameClip(draft.get(e?.id), e)), docs.project ?? { clips: {} }, ).filter((g) => !mine.has(g.id)).map((g) => ({ ...g, from: "project" })); const order = new Map((timeline ?? []).map((e, i) => [e?.id, i])); return [...own, ...proj].sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)); } /** takeQuoteGate over the files on disk: the take's rows, the project's, and the draft's timeline. */ export async function takeQuoteRefusals(projectDir, take, timeline) { const docs = await readTakeQuoteCheck(projectDir, take); const draft = await readFile(path.join(projectDir, "video.manifest.json"), "utf8").then((t) => JSON.parse(t)?.timeline ?? [], () => []); return takeQuoteGate(timeline, docs, draft); } async function writeQuoteCheck(dir, doc) { const file = path.join(dir, QUOTE_CHECK_FILE); const tmp = tmpPathFor(file); 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} 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 }, // The manifest's render: the build's own cap (sources.mjs tallWindowCap), so this vouches for the file it cuts. { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, render: manifest?.render ?? 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[]} timeline * @param {{ clips: Record }} doc * @returns {{ id: string, status: string, why: string }[]} */ export function quoteGate(timeline, doc) { // A take's two files (readTakeQuoteCheck) are not one doc: their gate is takeQuoteGate, never an empty [] here. if (doc && !doc.clips && (doc.own || doc.project)) throw new Error("quoteGate takes one quote-check doc; a take's rows go through takeQuoteGate"); 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

${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} entry * @param {Record | null | undefined} row */ export function alignPatch(entry, row) { if (!row) throw new Error(`${entry.id} has no quote check: umtool quote-check

--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

--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; } /** * `umtool check

--take `'s quote rows: the take's clips (as it renders: its rulings applied) gated by the * take's verdicts over the project's. The rows `umtool check` makes of the project's quote check, for the take. * @param {{ id: string, dir: string }} p * @param {string} take */ export async function takeQuoteDecisions(p, take) { if (!isTakeId(take)) throw new Error(`"${take}" is not a take id (lower-case letters, digits, dashes)`); const [{ resolveTakeManifest }, { applyMontageRulings, readMontageRulings }] = await Promise.all([ import("./takeManifest.mjs"), import("umtool-report-to-video/montage-rulings"), ]); const { manifest } = await resolveTakeManifest(p.dir, take); const timeline = applyMontageRulings(manifest, await readMontageRulings(p.dir)).manifest.timeline ?? []; return (await takeQuoteRefusals(p.dir, take, timeline)).map((g) => ({ kind: g.status === "moved" ? "clip-quote-moved" : "clip-quote-missing", project: p.id, take, target: g.id, why: `take ${take}: ${g.why.replace("

", `${p.id} --take ${take}`)}${g.from === "take" ? "" : " (the project's row)"}`, severity: "blocking", href: `/projects/${p.id}/takes/${take}`, fix: g.status === "moved" ? `umtool window ${p.id} ${g.id} --take ${take} --align # or --quote-ruled, having heard it` : `umtool fetch ${p.id} --refetch ${g.id} && umtool quote-check ${p.id} --take ${take} --clips ${g.id} # or --quote-ruled, having heard it`, })); } // --------------------------------------------------------------------------- // 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 : []; } /** * WHERE THE EDITOR WRITES THE WORDS (12 Nov): the work files were `/out/quote-check/.words.json`, and * a project's `out/` may be a symlink onto the media drive -- inside a corpus location, where the editor rightly * refuses to write (transcribeFile.ts: `"out" … is inside the corpus`). So the work dir is never under `out/`: * these, in order, each by its REAL path (a link in the way is followed here, not found out by the editor), the * next one taken when the editor refuses the one before as inside the corpus -- * * /.quote-check/ beside the manifest * /.umtool/quote-check// umtool's own state, when the project dir itself is in a location * $XDG_CACHE_HOME|~/.cache/umtool/quote-check// * * The rows are the project's whichever it is: quote-check.json, beside the manifest. * @param {string} dir the project's dir * @param {{ reportsRoot?: string | null, env?: Record, home?: string }} [opts] * @returns {Promise} */ export async function quoteCheckWorkDirs(dir, { reportsRoot = null, env = process.env, home = os.homedir() } = {}) { const real = async (p) => { // The deepest ancestor that exists, resolved; the rest as named (the dir may not be made yet). const rest = []; let cur = path.resolve(p); for (;;) { const r = await realpath(cur).catch(() => null); if (r) return path.join(r, ...rest); const up = path.dirname(cur); if (up === cur) return path.resolve(p); rest.unshift(path.basename(cur)); cur = up; } }; const name = path.basename(path.resolve(dir)); const cache = env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : path.join(home, ".cache"); const all = [ path.join(dir, ".quote-check"), path.join(reportsRoot ?? path.dirname(path.resolve(dir)), ".umtool", "quote-check", name), path.join(cache, "umtool", "quote-check", name), ]; const out = []; for (const p of all) { const r = await real(p); if (!out.includes(r)) out.push(r); } return out; } /** * Is this the editor's refusal of an `out` inside the corpus? The controller's sentence is * `"out" is inside the corpus () — this command never writes there; pick a path outside it` * (common/controller/transcribeFile.ts checkTranscribeFileRequest), answered at once as HTTP 400 `{ error }` by * POST /api/ops/transcribe (the route's jobResponse), which askEditorOp throws as `the editor refused it (, * HTTP 400): `. Matched on the part that says what it is -- `"out" … is inside the corpus` -- not on the path, * the root or the advice after the dash (quoteCheck.test.mjs holds the controller's source to these words). */ export const OUT_INSIDE_CORPUS = /"out" .* is inside the corpus\b/; const insideCorpus = (e) => OUT_INSIDE_CORPUS.test(e instanceof Error ? e.message : String(e)); /** * Take back the directories a refused work dir cost: `dir` and every parent made for it, up to `first` (what * mkdir's `recursive` says it made first) -- each only when empty (rmdir), so nothing that was there is touched * and no empty `.quote-check/` is left inside a corpus location. */ async function unmake(dir, first) { if (!first) return; const stop = path.resolve(first); let cur = path.resolve(dir); for (;;) { if (cur !== stop && !cur.startsWith(stop + path.sep)) return; if (!(await rmdir(cur).then(() => true, () => false))) return; if (cur === stop) return; cur = path.dirname(cur); } } /** * Check the planned clips; merge the rows into quote-check.json. * @param {string} dir * @param {Record} manifest * @param {Awaited>} plan * @param {{ transcribe?: typeof editorWords, cuesOf?: (slug: string, video: string) => Promise, log?: (l: string) => void, now?: () => Date }} [opts] */ export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date(), workDirs = null, reportsRoot = null, store = dir } = {}) { // `store`: where the rows go -- the project's dir, or a take's (takeQuoteCheckDir). const doc = await readQuoteCheck(store); // Never under out/ (quoteCheckWorkDirs): the first the editor does not refuse as inside the corpus. const works = workDirs ?? (await quoteCheckWorkDirs(dir, { reportsRoot })); let wi = 0; 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; } let words; try { for (;;) { // The editor needs the directory to be there (it refuses an `out` whose directory is not), so it is made // -- and taken back, with any parent made for it, the moment the editor says it is inside the corpus. const made = await mkdir(works[wi], { recursive: true }); const out = path.join(works[wi], `${p.id}.words.json`); try { words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} }); break; } catch (e) { if (!insideCorpus(e)) throw e; await unmake(works[wi], made); if (wi + 1 >= works.length) throw e; log(`quote-check: the editor will not write in ${works[wi]} (inside the corpus) -- its work files go to ${works[wi + 1]}`); wi += 1; } } } 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(store, merged); return { file, doc: merged, results, work: works[wi] }; } // --------------------------------------------------------------------------- // The CLI. // --------------------------------------------------------------------------- export const QUOTE_CHECK_USAGE = [ "usage: umtool quote-check [--take T] [--clips a,b] [--pad S] [--json] transcribe what each clip plays; find its quote", " umtool quote-check [--take T] --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

--align), not-found.`, "The editor's work files (.words.json) go to /.quote-check/ -- never under out/, which may be a link", "onto a media drive the editor will not write in; were the project itself inside the corpus, to umtool's own", "/.umtool/quote-check//, then ~/.cache/umtool/quote-check//.", `Rows go to /${QUOTE_CHECK_FILE}; umtool check reads them, and a take refuses a moved or`, "missing quote unless the clip is ruled (umtool window

--quote-ruled).", "--take T judges the TAKE's clips (its patch over the draft, as it renders) into takes/T/quote-check.json; the", "take's render, `umtool check

--take T` and `umtool window

--take T --align` read the take's rows", "and the project's: a take refuses what either current row refuses (the project's only for the same clip: video,", "channel), so --take only ever adds a refusal, never takes one away.", ].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} */ 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 take = flags["--take"]?.at(-1) ?? null; if (take !== null && !take) throw new CliError("--take names a take of the project"); let manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); if (take) { // The take as it renders: its patch over the draft (resolveTakeManifest), its clip rulings applied. const [{ resolveTakeManifest }, { applyMontageRulings, readMontageRulings }] = await Promise.all([ import("./takeManifest.mjs"), import("umtool-report-to-video/montage-rulings"), ]); const r = await resolveTakeManifest(project.dir, take).catch((e) => { throw new CliError(`--take ${take}: ${e instanceof Error ? e.message : String(e)}`); }); manifest = applyMontageRulings(r.manifest, await readMontageRulings(project.dir)).manifest; } const json = !!flags["--json"]; if (flags["--status"]) { const doc = take ? null : await readQuoteCheck(project.dir); // A take's: the row that speaks for each clip (takeQuoteRows), else its own stale one. const docs = take ? await readTakeQuoteCheck(project.dir, take) : null; const picked = docs ? takeQuoteRows(manifest.timeline, docs, (await readManifest(project.dir))?.timeline ?? []) : null; const own = docs?.own ?? null; const rows = []; for (const e of manifest.timeline ?? []) { if (e?.type !== "clip") continue; const got = picked?.get(e.id) ?? null; const row = take ? got?.row ?? own?.clips[e.id] : doc?.clips[e.id]; rows.push({ id: e.id, ...(row ?? { status: "unchecked" }), current: rowIsCurrent(row, e), ...(take && row ? { from: got?.from ?? "take" } : {}) }); } if (json) log(JSON.stringify({ project: project.id, ...(take ? { take } : {}), 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)"}${row.from === "project" ? " (the project's row)" : ""}`); 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 ${take ? `take ${take}` : project.id}`); const { file, results, work } = await runQuoteCheck(project.dir, manifest, plan, { ...(transcribe ? { transcribe } : {}), ...(cuesOf ? { cuesOf } : {}), reportsRoot, log: json ? () => {} : log, ...(take ? { store: takeQuoteCheckDir(project.dir, take) } : {}), }); if (json) log(JSON.stringify({ project: project.id, ...(take ? { take } : {}), file, work, 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; } }