Archilyzer · Source

archilyzer

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

commit 6e94189e853a02a59804e88c77320dd485cb6d4c
parent 8540c28f29cf61e8556f450b9fcc4714fae985fe
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 00:40:22 -0400

umtool: the clip finder -- `umtool new --seed reactions`, `umtool clips analyze|propose|show`, the assist key validated (release 35 C1, slice 3)

lib/report/reactions.mjs reads a recording (diarization.json required --
the refusal names the `archilyzer diarize backfill` to run; words from
<project>/words.json, else the corpus transcript, else the cues), runs or
reuses the laugh scan and the voice centroids on its sound (cached in
<project>/scans/), and proposes: the manifest through its writer (token,
undo point), reactions.json whole. A clip the operator edited, ruled, locked
or added is never moved; ids stay put across passes; params and the
operator's roles are kept in reactions.json. The seed writes the first pass
(laughs from the transcript); `umtool new` then runs `clips analyze` unless
--no-analyze. validateAssist joins the build's validators, the lint and the
manifest writer's structure checks.

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

Diffstat:
Mcommon/lib/clips/reactions.mjs | 8+++++---
Mumtool/bin/umtool.mjs | 30+++++++++++++++++++++++++++---
Mumtool/lib/projects/scaffold.mjs | 60+++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/lib/report/manifest.mjs | 2++
Aumtool/lib/report/reactions.mjs | 560+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reactions.test.mjs | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 3++-
Mumtool/report-to-video/lint.mjs | 3+++
8 files changed, 904 insertions(+), 16 deletions(-)

diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs @@ -53,8 +53,9 @@ const labelOf = (role, index) => (role === "host" ? "Host" : role === "subject" * marked `how: "operator"` (a re-analysis keeps it); `null` hands the speaker * back to the analysis (`how: "auto"`, the role as it is until the next * proposal pass). Marking a host or a subject takes that role off every - * speaker the ANALYSIS gave it (they become "other" until the next pass); - * the operator's own marks stay. Records `rolesChangedAt`, so a page can say + * other speaker that held it (they become "other", handed back to the + * analysis, until the next pass) — one host, one subject; a cluster merged + * into this one (`sameAs`) keeps it. Records `rolesChangedAt`, so a page can say * the proposals were made before the roles changed (and offer Re-propose). * * @param {string} dir the project @@ -74,9 +75,10 @@ export async function setSpeakerRole(dir, index, role, { now = () => new Date() } else { if (role !== "other") { for (const o of doc.speakers) { - if (o !== s && isObj(o) && o.role === role && o.how !== "operator" && o.sameAs !== index) { + if (o !== s && isObj(o) && o.role === role && o.sameAs !== index) { o.role = "other"; o.label = labelOf("other", o.index); + o.how = "auto"; delete o.sameAs; } } diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -58,6 +58,8 @@ // [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass) // umtool voice-match <project> [--reference auto|rulings|recordings] [--instances F] [--dry] [--json] // a speaker-similarity score per montage clip -> <project>/voice-match.json +// umtool clips analyze|propose|show <project> [--from <channel>/<id>] [--target S] [--host N] … +// the clip finder (release 35): proposed clips from a long recording -> reactions.json import process from "node:process"; import { PROJECT_KINDS, @@ -711,6 +713,9 @@ function usage() { " channel's copy where it has one (a twin by date and duration); a context matching --exclude", " is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances", " spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")", + " --seed reactions --from <channel>/<id> [--target S] [--no-analyze]: the clip finder on a long", + " recording (needs its diarization.json): highlights proposed from the host's laughs and comments,", + " then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze", " [--brand archilyzer-media] render.brand: the report-to-video brand preset", " umtool doctor [--json] exit 1 if the report pipeline is missing a tool", " or the media root is set and not there; the roots, and a leftover old cache", @@ -736,6 +741,11 @@ function usage() { " how often each phrase was said, by year, in one pass (the phrase finder's search)", " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]", " a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json", + " umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params]", + " umtool clips propose <project> [--host N] [params] [--dry] | show <project>", + " the clip finder: the laugh scan + voices on the recording's sound, then clips proposed", + " (setup → reaction → tail) into the manifest (assist: by the assistant) and reactions.json;", + " params --target S --laugh-min X --merge-gap S --setup-max S --clip-max S; a clip you edited is never moved", " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", " re-fetch an article's scope, see what changed, update: the plan (the editor's);", " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", @@ -780,6 +790,8 @@ const COMMANDS = { phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))), // Who is speaking, per montage clip (release 34): lib/report/voiceMatch.mjs. "voice-match": async () => process.exit(await (await import("../lib/report/voiceMatch.mjs")).voiceMatchCommand(argv.slice(argv.indexOf("voice-match") + 1))), + // The clip finder (release 35 C1): lib/report/reactions.mjs. + clips: async () => process.exit(await (await import("../lib/report/reactions.mjs")).clipsCommand(argv.slice(argv.indexOf("clips") + 1))), inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), @@ -1130,7 +1142,8 @@ async function cmdNew() { "usage: umtool new <slug> [--kind report-video] [--title T]\n" + " [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" + " [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" + - " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]", + " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]\n" + + " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--no-analyze]]", ); } const kind = val("--kind") ?? "report-video"; @@ -1161,11 +1174,22 @@ async function cmdNew() { die(e?.message ?? String(e)); } - if (json) return out({ ok: true, ...r }); + // The clip finder's seed (release 35): the scans and a second proposal pass + // right away, unless --no-analyze (the app's form runs them as a job). + let analyzed = null; + if (val("--seed") === "reactions" && !has("--no-analyze")) { + const { clipsCommand } = await import("../lib/report/reactions.mjs"); + const log = json ? (s) => console.error(s) : (s) => console.log(s); + if (!json) console.log(`${r.dir}\n running umtool clips analyze ${slug} …`); + analyzed = await clipsCommand(["analyze", slug], { log, err: (s) => console.error(s) }); + } + + if (json) return out({ ok: true, ...r, ...(analyzed !== null ? { analyzed: analyzed === 0 } : {}) }); console.log(`${r.dir}`); if (r.seeded) { - console.log(` video.manifest.json ${r.seeded} clip(s) SEEDED from ${val("--seed") === "frames" ? "the frame scan's events" : val("--seed") === "phrase" ? "a phrase scan (phrase-scan.json)" : "digest chapters"} — review each`); + const seedWhat = { frames: "the frame scan's events", phrase: "a phrase scan (phrase-scan.json)", reactions: "the recording's laughs and comments (reactions.json)" }[val("--seed") ?? ""] ?? "digest chapters"; + console.log(` video.manifest.json ${r.seeded} clip(s) SEEDED from ${seedWhat} — review each`); } else { console.log(` video.manifest.json an EMPTY timeline — see README.md`); } diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs @@ -8,12 +8,14 @@ import path from "node:path"; import { BRAND_IDS } from "umtool-report-to-video/brand-ids"; import { FRAMES_CUT_DEFAULTS, framesCut } from "umtool-report-to-video/frames-cut"; import { capInstances, instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; +import { PARAM_BOUNDS } from "yt-dlp-transcript-common/lib/clips/clips.mjs"; +import { writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs"; export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/; // A channel's directory name: mixed case is a channel too (HasanAbiVODs3); no separators, no dot first. export const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; -export const SEEDS = ["chapters", "frames", "phrase"]; +export const SEEDS = ["chapters", "frames", "phrase", "reactions"]; /** * A manifest skeleton, and deliberately an EMPTY timeline. @@ -182,16 +184,20 @@ export async function chaptersAsClips({ channelsDir, channel, video }) { * `from` is not a video ref. * * @param {{ channelsDir?: string, from: string | null }} args - * @returns {Promise<{ video: boolean, chapters: boolean, frames: boolean }>} + * Release 35: `reactions` — its speakers (diarization.json), what the clip + * finder needs (`--seed reactions`). + * + * @returns {Promise<{ video: boolean, chapters: boolean, frames: boolean, reactions: boolean }>} */ export async function seedsFor({ channelsDir = GLOBAL_CHANNELS_DIR(), from }) { + const none = { video: false, chapters: false, frames: false, reactions: false }; const src = detectFrom(from); - if (src?.kind !== "video") return { video: false, chapters: false, frames: false }; + if (src?.kind !== "video") return none; const dir = path.join(channelsDir, src.channel, "data", src.video); - if (path.relative(channelsDir, dir).startsWith("..")) return { video: false, chapters: false, frames: false }; + if (path.relative(channelsDir, dir).startsWith("..")) return none; const has = (name) => stat(path.join(dir, name)).then((x) => x.isFile(), () => false); - const [chapters, frames] = await Promise.all([has("ai-digest.json"), has("frame-scan.poker.json")]); - return { video: true, chapters, frames }; + const [chapters, frames, reactions] = await Promise.all([has("ai-digest.json"), has("frame-scan.poker.json"), has("diarization.json")]); + return { video: true, chapters, frames, reactions }; } /** @@ -282,9 +288,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site } const capped = max !== null && max !== undefined; if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed"); - if (target !== undefined && seed !== "frames") throw new Error("--target is the frames seed's length budget: give it with --seed frames"); - if (target !== undefined && !(Number.isFinite(target) && target >= 10 && target <= 3600)) { - throw new Error("--target must be a number of seconds from 10 to 3600"); + if (target !== undefined && seed !== "frames" && seed !== "reactions") throw new Error("--target is a seed's length budget: give it with --seed frames or --seed reactions"); + const [tLo, tHi] = seed === "reactions" ? PARAM_BOUNDS.target : [10, 3600]; + if (target !== undefined && !(Number.isFinite(target) && target >= tLo && target <= tHi)) { + throw new Error(`--target must be a number of seconds from ${tLo} to ${tHi}`); } if (timeline && (!Array.isArray(timeline) || !timeline.every(isBoardClip))) { throw new Error("a timeline is a list of clips, each { type: \"clip\", id, channel, video, start, end }"); @@ -368,6 +375,28 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site if (!scan.instances.length) notes.push("the phrase was not found, so the timeline is empty"); } + // Release 35: the clip finder's first pass over a long recording — its + // speakers' turns (diarization.json), its words, laughs from the transcript + // (the scans come with `umtool clips analyze`), proposals ranked into the + // target, each used one a clip marked `assist` (by the assistant). + let reactionsSeeded = null; + if (seed === "reactions") { + const { seedReactions } = await import("../report/reactions.mjs"); + const pass = await seedReactions({ channelsDir, channel: src.channel, video: src.video, ...(target !== undefined ? { target } : {}) }); + doc.timeline = pass.timeline; + // Hard cuts: a highlights reel. + doc.render.transition = 0; + seeded = doc.timeline.length; + reactionsSeeded = pass; + const used = pass.doc.proposals.filter((p) => p.used); + const host = pass.doc.speakers.find((s) => s.role === "host"); + notes.push(`${pass.doc.proposals.length} proposal(s), ${used.length} in the cut: ${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of a ${pass.doc.params.target} s target (--target)`); + notes.push(`the host: speaker ${host ? host.index : "?"} of ${pass.doc.speakers.length} (by turn statistics — flip it in the clip editor or with umtool clips propose ${slug} --host N)`); + notes.push(`laughs from the transcript only (${pass.doc.laughs.length}); umtool clips analyze ${slug} runs the laugh scan and the voices on the sound, then proposes again`); + if (pass.rec.wordsFrom === "cues") notes.push("no word timings: edges sit on the cues; pnpm ops transcribe {path, words:true, out: <project>/words.json} gives words, then umtool clips propose"); + if (!pass.doc.proposals.length) notes.push("nothing to propose: no host comments or laughs were found"); + } + if (timeline) { doc.timeline = timeline.map((c) => ({ ...c })); seeded = doc.timeline.length; @@ -377,6 +406,7 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n", "utf8"); + if (reactionsSeeded) await writeReactions(dir, reactionsSeeded.doc); if (reportText !== null) await writeFile(path.join(dir, "sweep-report.md"), reportText, "utf8"); if (phraseSeeded) { const { instances, dropped, hits, scanned, skippedByCap } = phraseSeeded; @@ -415,6 +445,18 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site "", ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.onscreen?.subtitle ?? ""} ${c.channel}/${c.video} ${c.cutStart}–${c.cutEnd} "${c.onscreen?.title ?? ""}"${c.note ? ` (${c.note})` : ""}`), ); + } else if (seeded && reactionsSeeded) { + lines.push( + "## Clips proposed from the recording — review each", + "", + "Every clip below is a proposal: a narrated line, the host's reaction (a laugh,", + "a comment) and a tail to the next pause, found from the speakers' turns, the", + "words and the laughs (reactions.json). None is a decision: keep, cut, trim or", + "comment on each in the clip editor. A clip you edit is yours, and a new", + "proposal pass (umtool clips propose) never moves it.", + "", + ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.cutStart}–${c.cutEnd} ${c.assist?.score ?? ""} ${c.assist?.why ?? ""}`), + ); } else if (seeded && framesSeeded) { lines.push( "## Clips seeded from the frame scan — review each", diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -32,6 +32,7 @@ import { import { isCalendarDate } from "umtool-report-to-video/attribution"; import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck"; import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs"; +import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; import { validateNarration } from "umtool-report-to-video/narration"; @@ -909,6 +910,7 @@ function structureErrors(manifest) { ...validateNarration(manifest), ...validateDrafted(manifest), ...validatePublish(manifest), + ...validateAssist(manifest), ]; } diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs @@ -0,0 +1,560 @@ +// The clip finder in umtool (release 35 C1): `umtool new --seed reactions`, +// `umtool clips analyze|propose|show`, and the app's job for them. +// +// The arithmetic is common's (yt-dlp-transcript-common/lib/clips/clips.mjs), +// the scans are common's (lib/clips/scan.mjs), the manifest's `assist` key +// and the one proposal-to-clip writer are common's (lib/clips/assist.mjs). +// This module is umtool's half: WHICH recording (a project's reactions.json +// `source`, or `--from <channel>/<id>`), what is on disk for it (the +// diarization, the words, the sound), the scans' cache in the project +// (`scans/`), and the writes: the manifest through the manifest writer (its +// lock, a token, an undo point) and reactions.json whole. +// +// What a run needs on disk, in order of what it does without: +// diarization.json REQUIRED — no speakers, no roles; the message names the +// `archilyzer diarize backfill …` to run +// words <project>/words.json (`pnpm ops transcribe {path, +// words:true, out}`), else whisper.cpp's word offsets in +// the corpus transcript.json, else the cues (each cue's +// words spread over it) +// the sound the recording's audio.* in the corpus, else any local +// source that covers it (a saved video): the laugh scan +// and the voice centroids; without it, laughs come from +// the transcript's markers only +// the laugh model CED-mini under .diarize/models/ (AUDIO_TAG_MODEL): the +// laugh scores; without it, the transcript's markers plus +// the host's wordless energy bursts +// +// Nothing here calls a model but the local ones; nothing touches the network. +import { readFile, rename, stat, writeFile, mkdir } from "node:fs/promises"; +import path from "node:path"; +import { + DEFAULT_PARAMS, + PARAM_BOUNDS, + analyze, + cleanWords, + wordsFromCues, +} from "yt-dlp-transcript-common/lib/clips/clips.mjs"; +import { applyProposals, fixedClips } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; +import { REACTIONS_FILE, operatorRoles, readReactions, writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs"; +import { clockOffset, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources"; +import { whisperWords } from "umtool-report-to-video/montage"; +import { clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { replaceManifest, manifestToken, StaleToken } from "./manifest.mjs"; +import { REPO_ROOT } from "../paths.mjs"; +import { UMTOOL_DIR } from "./driver.mjs"; + +export { REACTIONS_FILE }; +export const WORDS_FILE = "words.json"; +export const SCANS_DIR = "scans"; +/** The sound files a recording's directory may hold, in the order they are used. */ +export const AUDIO_NAMES = Object.freeze(["audio.m4a", "audio.mp3", "audio.opus", "audio.wav", "audio.flac"]); + +export class ClipsError extends Error {} + +const readJson = (file) => readFile(file, "utf8").then(JSON.parse, () => null); +const num = (x) => typeof x === "number" && Number.isFinite(x); +const isFile = (p) => stat(p).then((s) => s.isFile(), () => false); + +/** The command that makes the diarization a run needs. */ +export const diarizeCommand = (channel, video) => `archilyzer diarize backfill --scope video:${channel}/${video}`; + +// ---- the recording ---------------------------------------------------------------- + +/** + * Everything on disk about one recording the analysis reads: its turns + * (diarization.json — required), its words, its duration. + * @param {{ channelsDir: string, channel: string, video: string, projectDir?: string | null, wordsFile?: string | null }} o + */ +export async function loadRecording({ channelsDir, channel, video, projectDir = null, wordsFile = null }) { + const videoDir = await resolveVideoDir(channelsDir, channel, video).catch(() => path.join(channelsDir, channel, "data", video)); + if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) throw new ClipsError(`no video directory for ${channel}/${video} under ${channelsDir}`); + const diar = await readJson(path.join(videoDir, "diarization.json")); + if (!diar || !Array.isArray(diar.turns) || !diar.turns.length) { + throw new ClipsError(`${channel}/${video} has no diarization.json (the speakers) — run ${diarizeCommand(channel, video)} (or the editor's diarize job), then this again`); + } + const meta = await readJson(path.join(videoDir, "metadata.info.json")); + const cuesDoc = await readJson(path.join(videoDir, "transcript.cues.json")); + let words = null; + let wordsFrom = "cues"; + const own = wordsFile ? path.resolve(wordsFile) : projectDir ? path.join(projectDir, WORDS_FILE) : null; + if (own) { + const doc = await readJson(own); + const list = Array.isArray(doc) ? doc : Array.isArray(doc?.words) ? doc.words : null; + if (list && list.length) { + words = cleanWords(list); + wordsFrom = wordsFile ? path.basename(own) : WORDS_FILE; + } else if (wordsFile) throw new ClipsError(`${wordsFile} holds no words ({ words: [{ w, start, end }] })`); + } + if (!words) { + const tj = await readJson(path.join(videoDir, "transcript.json")); + const ww = tj ? whisperWords(tj) : null; + if (ww && ww.length) { + words = cleanWords(ww.map((w) => ({ w: w.text, start: w.start, end: w.end }))); + wordsFrom = "transcript.json"; + } + } + if (!words) words = wordsFromCues(Array.isArray(cuesDoc?.cues) ? cuesDoc.cues : []); + const turnsEnd = Math.max(...diar.turns.map((t) => (num(t?.end) ? t.end : 0))); + const duration = [diar.audioSeconds, meta?.duration, cuesDoc?.duration].find((d) => num(d) && d > 0) ?? turnsEnd; + return { + channel, + video, + videoDir, + duration: Math.max(Number(duration), turnsEnd), + turns: diar.turns, + diarization: { generatedAt: typeof diar.generatedAt === "string" ? diar.generatedAt : null, engine: typeof diar.engine?.engine === "string" ? diar.engine.engine : null }, + words, + wordsFrom, + }; +} + +/** + * The recording's sound, whole: its audio.* in the corpus, else a local source + * that covers it (a saved video, a corpus window). `clock` is where the file's + * zero sits on the recording's clock. Null when nothing on disk holds it. + * @param {{ channelsDir: string, channel: string, video: string, videoDir: string, duration: number }} o + */ +export async function recordingAudio({ channelsDir, channel, video, videoDir, duration }) { + for (const name of AUDIO_NAMES) { + const p = path.join(videoDir, name); + if (await isFile(p)) return { path: p, kind: "audio", clock: 0 }; + } + const hit = await resolveLocalSource({ video, slug: channel, from: 0, to: Math.max(1, duration - 1) }, { channelsDir, audio: true, probe: ffprobeSource }).catch(() => null); + if (!hit) return null; + return { path: hit.path, kind: hit.kind, clock: (hit.windowStart ?? 0) + (await clockOffset(hit.path)) }; +} + +// ---- the scans -------------------------------------------------------------------- + +const scanFile = (projectDir, channel, video, what) => path.join(/* turbopackIgnore: true */ projectDir, SCANS_DIR, `${channel}--${video}.${what}.json`); + +async function writeWhole(file, doc) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(doc)}\n`); + await rename(tmp, file); +} + +async function fileKey(p) { + const s = await stat(p); + return { path: p, size: s.size, mtimeMs: Math.round(s.mtimeMs) }; +} + +const sameKey = (a, b) => a && b && a.path === b.path && a.size === b.size && a.mtimeMs === b.mtimeMs; + +/** The cached scans of a recording in a project (either may be null). */ +export async function readScans(projectDir, channel, video) { + const [audio, voices] = await Promise.all([readJson(scanFile(projectDir, channel, video, "audio")), readJson(scanFile(projectDir, channel, video, "voices"))]); + return { audio: audio?.version === 1 ? audio : null, voices: voices?.version === 1 ? voices : null }; +} + +const SETTINGS_FILE = () => process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); + +async function readSettings() { + try { + return JSON.parse(await readFile(SETTINGS_FILE(), "utf8")); + } catch { + return null; + } +} + +/** + * Run (or reuse) the laugh scan and the voice centroids for a recording. + * A cached scan is reused while the sound file, the window, the model (and + * for the voices, the diarization) are unchanged; `rescan` makes both again. + * @param {{ projectDir: string, rec: Awaited<ReturnType<typeof loadRecording>>, audio: { path: string, kind: string, clock: number }, + * laughs?: boolean, voices?: boolean, rescan?: boolean, tagger?: any, engine?: any, + * onProgress?: (e: Record<string, unknown>) => void, say?: (s: string) => void }} o + */ +export async function scanRecording({ projectDir, rec, audio, laughs = true, voices = true, rescan = false, tagger = null, engine = null, onProgress = () => {}, say = () => {} }) { + const settings = tagger && engine ? null : await readSettings(); + const tag = tagger ?? resolveTagger({ repoRoot: REPO_ROOT, settings }); + const emb = engine ?? resolveEngine({ repoRoot: REPO_ROOT, settings }); + const key = await fileKey(audio.path); + const cached = await readScans(projectDir, rec.channel, rec.video); + const out = { audio: cached.audio, voices: cached.voices, ran: [] }; + if (laughs) { + const want = tag.available ? path.basename(tag.model) : null; + const c = cached.audio; + if (!rescan && c && sameKey(c.source, key) && (c.model?.file ?? null) === want && c.clock === audio.clock) { + say(`laugh scan: cached (${c.model ? c.model.file : "energy only"})`); + } else { + if (!tag.available) say(`laugh scan: no laugh model at ${tag.model} — energy only (set AUDIO_TAG_MODEL)`); + say(`laugh scan: ${path.basename(audio.path)}, ${Math.round(rec.duration)} s`); + const scan = await runAudioScan({ + file: audio.path, + duration: Math.max(0, rec.duration - audio.clock), + clock: audio.clock, + tagger: tag.available ? tag : null, + scratch: path.join(/* turbopackIgnore: true */ projectDir, ".clips-work"), + onProgress: (e) => onProgress({ phase: "laughs", ...e }), + }); + out.audio = { ...scan, source: key, clock: audio.clock, kind: audio.kind, madeAt: new Date().toISOString() }; + await writeWhole(scanFile(projectDir, rec.channel, rec.video, "audio"), out.audio); + out.ran.push("laughs"); + } + } + if (voices) { + const c = cached.voices; + if (!rescan && c && sameKey(c.source, key) && c.diarization === rec.diarization.generatedAt && c.engineModel === path.basename(emb.model)) { + say("voices: cached"); + } else if (!engine && !(await isFile(emb.model))) { + say(`voices: no speaker model at ${emb.model} — no centroid merge (set VOICE_MATCH_MODEL)`); + } else { + say("voices: a centroid per speaker"); + const turns = rec.turns.filter((t) => t && num(t.start) && num(t.end) && t.end > t.start && Number.isInteger(t.speaker)); + const v = await speakerCentroids({ + file: audio.path, + clock: audio.clock, + turns, + engine: emb, + scratch: path.join(/* turbopackIgnore: true */ projectDir, ".clips-work"), + onProgress: (e) => onProgress({ phase: "voices", ...e }), + }); + out.voices = { ...v, engineModel: path.basename(emb.model), source: key, diarization: rec.diarization.generatedAt, madeAt: new Date().toISOString() }; + await writeWhole(scanFile(projectDir, rec.channel, rec.video, "voices"), out.voices); + out.ran.push("voices"); + } + } + return out; +} + +// ---- the proposal pass ------------------------------------------------------------ + +/** The scans as the analysis takes them. */ +function scanInputs(scans) { + const a = scans?.audio ?? null; + const laughScan = a ? { t0: a.t0 ?? 0, hop: a.hop, window: a.window, scores: Array.isArray(a.laugh) ? a.laugh : null, energy: Array.isArray(a.energy) ? a.energy : null } : null; + const v = scans?.voices?.speakers ?? null; + const centroids = v ? Object.fromEntries(Object.entries(v).map(([k, s]) => [k, s?.centroid ?? null])) : null; + return { laughScan, centroids }; +} + +/** + * One proposal pass, pure apart from what it is given: the analysis, then the + * timeline (applyProposals), then the reactions.json document. + * @param {{ rec: any, scans?: any, params?: Record<string, unknown>, operator?: Record<string, string>, previous?: any, + * timeline?: any[], isProtected?: (e: any) => boolean, audio?: { path: string, kind: string } | null, now?: Date }} o + */ +export function proposalPass({ rec, scans = null, params = {}, operator = {}, previous = null, timeline = [], isProtected = () => false, audio = null, now = new Date() }) { + const { laughScan, centroids } = scanInputs(scans); + const fixed = fixedClips(timeline, { channel: rec.channel, video: rec.video, isProtected }); + const a = analyze({ + turns: rec.turns, + duration: rec.duration, + words: rec.words, + params, + operator, + centroids, + laughScan, + previous: previous?.proposals ?? [], + fixed, + }); + const applied = applyProposals(timeline, { proposals: a.proposals, channel: rec.channel, video: rec.video, duration: a.duration, words: cleanWords(rec.words), isProtected }); + const madeAt = now.toISOString(); + const doc = { + version: 1, + source: { + channel: rec.channel, + video: rec.video, + duration: a.duration, + words: rec.wordsFrom === WORDS_FILE ? WORDS_FILE : null, + wordsFrom: rec.wordsFrom, + diarization: rec.diarization, + ...(audio ? { audio: path.basename(audio.path), audioKind: audio.kind } : {}), + }, + params: a.params, + speakers: a.speakers, + turns: a.turns, + laughs: a.laughs, + moments: a.moments, + proposals: applied.proposals.map((p) => ({ id: p.id, start: p.start, end: p.end, score: p.score, moments: p.moments ?? [], used: p.used, clipId: p.clipId, why: p.why })), + laughSource: a.laughSource, + scans: { + laughs: scans?.audio ? { model: scans.audio.model?.file ?? null, windows: scans.audio.windows, madeAt: scans.audio.madeAt ?? null } : null, + voices: scans?.voices ? { model: scans.voices.model ?? null, madeAt: scans.voices.madeAt ?? null } : null, + }, + madeAt: previous?.madeAt ?? madeAt, + proposedAt: madeAt, + }; + return { doc, timeline: applied.timeline, changes: applied.changes, analysis: a }; +} + +/** What a pass did, in one line. */ +export function passSummary(doc, changes) { + const used = doc.proposals.filter((p) => p.used); + const seconds = used.reduce((n, p) => n + (p.end - p.start), 0); + const host = doc.speakers.filter((s) => s.role === "host").map((s) => `${s.index}${s.how === "operator" ? " (yours)" : ""}`).join("+") || "none"; + return ( + `${doc.proposals.length} proposal(s), ${used.length} in the cut (${Math.round(seconds)} s of a ${doc.params.target} s target); ` + + `laughs: ${doc.laughs.length} (${doc.laughSource}); host: speaker ${host}` + + (changes ? `; clips +${changes.added.length} ~${changes.updated.length} -${changes.removed.length}` : "") + ); +} + +/** Which clips the operator has ruled (montage-rulings.json): a re-proposal never moves them. */ +async function rulingsGuard(dir, manifest) { + let doc = null; + try { + doc = await readMontageRulings(dir); + } catch { + doc = null; + } + const keys = new Set(Object.keys(doc?.rulings ?? {})); + return (e) => { + const k = clipMomentKey(e, manifest); + return k ? keys.has(k) : false; + }; +} + +/** + * The seed (`umtool new --seed reactions`): the first pass over a recording, + * with no scans yet (laughs from the transcript only). The scaffold writes + * what it returns; `umtool clips analyze` then runs the scans and re-proposes. + * @param {{ channelsDir: string, channel: string, video: string, target?: number }} o + */ +export async function seedReactions({ channelsDir, channel, video, target }) { + const rec = await loadRecording({ channelsDir, channel, video }); + const pass = proposalPass({ rec, params: target !== undefined ? { target } : {} }); + return { ...pass, rec }; +} + +/** + * Re-propose a project: its reactions.json source (or `from`), what is on + * disk now, the cached scans, the params (the file's, with `params` over + * them), the operator's roles (the file's, `host` over them). Writes the + * manifest (through its writer, with an undo point) and reactions.json. + * @param {{ project: { id: string, dir: string }, from?: { channel: string, video: string } | null, params?: Record<string, unknown>, + * host?: number | null, wordsFile?: string | null, scans?: any, audio?: any, dry?: boolean, now?: Date }} o + */ +export async function proposeProject({ project, from = null, params = {}, host = null, wordsFile = null, scans = undefined, audio = null, dry = false, now = new Date() }) { + for (let attempt = 0; ; attempt += 1) { + const token = await manifestToken(project.dir); + const manifest = await readManifest(project.dir); + if (!manifest) throw new ClipsError(`${project.id} has no manifest`); + const previous = await readReactions(project.dir); + const src = from ?? (previous ? { channel: previous.source.channel, video: previous.source.video } : null); + if (!src) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} yet — say which recording: --from <channel>/<id>`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + if (!channelsDir) throw new ClipsError("no channels directory (CHANNELS_DIR)"); + const rec = await loadRecording({ channelsDir, channel: src.channel, video: src.video, projectDir: project.dir, wordsFile }); + const operator = operatorRoles(previous); + if (host !== null && host !== undefined) { + if (!rec.turns.some((t) => t?.speaker === host)) throw new ClipsError(`--host ${host}: no such speaker in the diarization`); + for (const [k, v] of Object.entries(operator)) if (v === "host") delete operator[k]; + operator[host] = "host"; + } + const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video; + const merged = { ...(sameSource ? previous.params : {}), ...Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== null)) }; + const s = scans === undefined ? await readScans(project.dir, rec.channel, rec.video) : scans; + const isProtected = await rulingsGuard(project.dir, manifest); + const pass = proposalPass({ rec, scans: s, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now }); + if (!sameSource || !previous) pass.doc.madeAt = now.toISOString(); + if (dry) return { ...pass, rec, written: false }; + try { + await replaceManifest(project.dir, { ...manifest, timeline: pass.timeline }, { token, op: "clips-propose" }); + } catch (e) { + if (e instanceof StaleToken && attempt < 2) continue; + throw e; + } + await writeReactions(project.dir, pass.doc); + return { ...pass, rec, written: true }; + } +} + +// ---- the CLI ---------------------------------------------------------------------- + +export const CLIPS_USAGE = [ + "usage: umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--progress ndjson] [--json]", + " umtool clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]", + " umtool clips show <project> [--json]", + "", + "The clip finder: a long recording (a stream, a podcast) to proposed clips, written to the", + `manifest (each marked "assist": by the assistant) and to <project>/${REACTIONS_FILE}.`, + " analyze runs the laugh scan (CED-mini, local) and a voice centroid per speaker on the", + ` recording's sound (cached in <project>/${SCANS_DIR}/), then proposes`, + " propose proposes again from what is there (after a role flip, a param change, new words)", + " show the speakers, the laughs, what is in the cut", + "params: --target S (the cut's length, default 600) --laugh-min X (0..1, default 0.25)", + " --merge-gap S (6) --setup-max S (20) --clip-max S (75); kept in reactions.json for the next run", + "--host N speaker N is the host (your word: kept until you change it)", + "A clip you have edited (assist.by \"operator\"), ruled, locked or added is never moved or removed.", + "Needs diarization.json beside the recording (archilyzer diarize backfill --scope video:<channel>/<id>).", + `Words: <project>/${WORDS_FILE} (pnpm ops transcribe {path, words:true, out}), else the corpus transcript.`, + "The laugh model: AUDIO_TAG_MODEL, else .diarize/models/<ced>/model.int8.onnx; the voices: VOICE_MATCH_MODEL.", +].join("\n"); + +const PARAM_FLAGS = { "--target": "target", "--laugh-min": "laughMin", "--merge-gap": "mergeGap", "--setup-max": "setupMax", "--clip-max": "clipMax" }; + +function parse(args) { + const valued = new Set(["--from", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]); + /** @type {Record<string, string[]>} */ + const flags = {}; + const positional = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a.startsWith("--")) { + if (valued.has(a)) { + if (i + 1 >= args.length) throw new ClipsError(`${a} needs a value`); + (flags[a] ??= []).push(args[++i]); + } else (flags[a] ??= []).push(""); + } else positional.push(a); + } + return { flags, positional, one: (n) => flags[n]?.[flags[n].length - 1], has: (n) => n in flags }; +} + +/** The params given on the command line, each checked against its bounds. */ +export function paramsFromFlags(p) { + const out = {}; + for (const [flag, key] of Object.entries(PARAM_FLAGS)) { + if (!p.has(flag)) continue; + const v = Number(p.one(flag)); + const [lo, hi] = PARAM_BOUNDS[key]; + if (!Number.isFinite(v) || v < lo || v > hi) throw new ClipsError(`${flag} takes ${lo}..${hi}, not ${p.one(flag)}`); + out[key] = v; + } + return out; +} + +function parseFrom(v) { + if (v === undefined) return null; + const m = /^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(String(v)); + if (!m) throw new ClipsError(`--from ${v}: <channel>/<videoId>`); + return { channel: m[1], video: m[2] }; +} + +async function pickProject(arg, root) { + if (!arg) throw new ClipsError("which project? pass an id, a name, or a directory"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new ClipsError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new ClipsError(`no project matches "${arg}"`); + if (!kindMakesTakes(r.project.kind)) throw new ClipsError(`${r.project.id} is a ${r.project.kind}, not a report video`); + return r.project; +} + +function showLines(doc) { + const lines = []; + const src = doc.source; + lines.push(`${src.channel}/${src.video} ${Math.round(src.duration)} s words: ${src.wordsFrom ?? (src.words ? src.words : "cues")} diarization: ${src.diarization?.generatedAt ?? "?"}`); + for (const s of doc.speakers) lines.push(` speaker ${s.index} ${s.label.padEnd(10)} ${s.role.padEnd(8)} ${String(Math.round(s.seconds)).padStart(6)} s ${String(s.turns).padStart(5)} turns ${s.how}${s.sameAs !== undefined ? ` (same voice as ${s.sameAs})` : ""}`); + lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}), moments: ${doc.moments.length}`); + const used = doc.proposals.filter((p) => p.used); + lines.push(` proposals: ${doc.proposals.length}, in the cut: ${used.length} (${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of ${doc.params.target} s)`); + for (const p of used) lines.push(` ${p.id} ${(p.clipId ?? "-").padEnd(5)} ${p.start.toFixed(1).padStart(8)}–${p.end.toFixed(1).padEnd(8)} ${p.score.toFixed(2)} ${p.why}`); + if (doc.rolesChangedAt && doc.proposedAt && doc.rolesChangedAt > doc.proposedAt) lines.push(" the roles changed since this was proposed: umtool clips propose <project>"); + return lines; +} + +/** + * `umtool clips …` + * @param {string[]} args everything after `clips` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, tagger?: any, engine?: any, now?: Date }} [opts] + */ +export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, tagger = null, engine = null, now = undefined } = {}) { + try { + const sub = args[0]; + const p = parse(args.slice(1)); + if (!sub || sub === "--help" || sub === "help" || p.has("--help") || !["analyze", "propose", "show"].includes(sub)) { + log(CLIPS_USAGE); + return sub && sub !== "--help" && sub !== "help" && !p.has("--help") ? 2 : 0; + } + const project = await pickProject(p.positional[0], reportsRoot); + if (sub === "show") { + const doc = await readReactions(project.dir); + if (!doc) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} — umtool clips analyze ${project.id} --from <channel>/<id>`); + log(p.has("--json") ? JSON.stringify(doc, null, 1) : showLines(doc).join("\n")); + return 0; + } + const ndjson = p.one("--progress") === "ndjson"; + if (p.has("--progress") && !ndjson) throw new ClipsError("--progress takes ndjson"); + const say = (line) => (ndjson ? err(line) : log(line)); + const emit = (ev) => { + if (ndjson) log(JSON.stringify({ ev: "clips", ...ev })); + }; + const from = parseFrom(p.one("--from")); + const params = paramsFromFlags(p); + let host = null; + if (p.has("--host")) { + host = Number(p.one("--host")); + if (!Number.isInteger(host) || host < 0) throw new ClipsError(`--host ${p.one("--host")}: a speaker number (0, 1, …)`); + } + let scans; + let audio = null; + if (sub === "analyze") { + const manifest = await readManifest(project.dir); + if (!manifest) throw new ClipsError(`${project.id} has no manifest`); + const previous = await readReactions(project.dir); + const src = from ?? (previous ? { channel: previous.source.channel, video: previous.source.video } : null); + if (!src) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} yet — say which recording: --from <channel>/<id>`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + emit({ phase: "load" }); + const rec = await loadRecording({ channelsDir, channel: src.channel, video: src.video, projectDir: project.dir, wordsFile: p.one("--words") ?? null }); + say(`${rec.channel}/${rec.video}: ${Math.round(rec.duration)} s, ${new Set(rec.turns.map((t) => t.speaker)).size} speaker(s), ${rec.words.length} word(s) from ${rec.wordsFrom}`); + audio = await recordingAudio({ channelsDir, channel: rec.channel, video: rec.video, videoDir: rec.videoDir, duration: rec.duration }); + if (!audio) { + say(`no sound on disk for ${rec.channel}/${rec.video} (no audio.*, no saved video): laughs from the transcript only — persist the source video in the editor, then analyze again`); + scans = await readScans(project.dir, rec.channel, rec.video); + } else if (p.has("--no-laughs") && p.has("--no-voices")) { + scans = await readScans(project.dir, rec.channel, rec.video); + } else { + const t0 = Date.now(); + scans = await scanRecording({ + projectDir: project.dir, rec, audio, laughs: !p.has("--no-laughs"), voices: !p.has("--no-voices"), rescan: p.has("--rescan"), + tagger, engine, onProgress: emit, say, + }); + if (scans.ran.length) say(`scanned (${scans.ran.join(", ")}) in ${Math.round((Date.now() - t0) / 1000)} s`); + } + } + emit({ phase: "propose" }); + const r = await proposeProject({ project, from, params, host, wordsFile: p.one("--words") ?? null, scans, audio, dry: p.has("--dry"), now }); + emit({ phase: "done", proposals: r.doc.proposals.length, used: r.doc.proposals.filter((x) => x.used).length, changes: r.changes }); + if (p.has("--json")) log(JSON.stringify({ written: r.written, changes: r.changes, reactions: r.doc }, null, 1)); + else { + if (!ndjson) log(showLines(r.doc).join("\n")); + say(`${r.written ? "" : "(dry run, nothing written) "}${passSummary(r.doc, r.changes)}`); + } + return 0; + } catch (e) { + err(e instanceof ClipsError ? `umtool clips: ${e.message}` : `umtool clips: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); + return e instanceof ClipsError ? 2 : 1; + } +} + +/** The CLI path the app's job runs. */ +const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); + +/** + * The app's "Find the clips" / "Re-propose": ONE job step on lib/jobs.ts + * running this command, nice'd (the laugh scan is CPU for a few minutes on a + * long stream, one thread; the proposal pass is arithmetic). + * @param {{ id: string }} project + * @param {{ mode?: "analyze" | "propose", from?: string, target?: number, host?: number }} [req] + */ +export function clipsSteps(project, req = {}) { + const mode = req.mode === "propose" ? "propose" : "analyze"; + const argv = ["nice", "-n", "10", "node", umtoolCli(), "clips", mode, project.id]; + if (typeof req.from === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(req.from)) argv.push("--from", req.from); + if (num(req.target) && req.target >= PARAM_BOUNDS.target[0] && req.target <= PARAM_BOUNDS.target[1]) argv.push("--target", String(req.target)); + if (Number.isInteger(req.host) && /** @type {number} */ (req.host) >= 0) argv.push("--host", String(req.host)); + argv.push("--progress", "ndjson"); + return { + kind: `clips-${mode} ${project.id}`, + steps: [{ + label: mode === "analyze" ? "scan the recording and propose clips" : "propose clips", + argv, + cwd: UMTOOL_DIR, + env: {}, + ndjson: /** @type {const} */ (true), + timeoutMs: (mode === "analyze" ? 90 : 5) * 60 * 1000, + }], + }; +} + +export { DEFAULT_PARAMS }; diff --git a/umtool/lib/report/reactions.test.mjs b/umtool/lib/report/reactions.test.mjs @@ -0,0 +1,254 @@ +// The clip finder in umtool (release 35 C1): `umtool new --seed reactions`, +// `umtool clips analyze|propose|show` over a synthetic reaction stream, with +// the test kit's fake tagger and fake embedder (no python, no model), the +// no-model fallback, and the app's job step. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, readFile, rm, writeFile, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { reactionAudio, writeReactionCorpus } from "yt-dlp-transcript-common/testing/clips/reactionStream.mjs"; +import { readReactions, setSpeakerRole } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { lintManifest } from "umtool-report-to-video/lint"; +import { scaffoldReportVideo, seedsFor } from "../projects/scaffold.mjs"; +import { clipsCommand, clipsSteps, loadRecording } from "./reactions.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const KIT = path.resolve(HERE, "..", "..", "..", "common", "testing", "audio"); +const TAGGER = { python: process.execPath, script: path.join(KIT, "fakeAudioTag.mjs"), model: path.join(KIT, "fakeAudioTag.mjs"), labels: "none.csv", threads: 1, available: true }; +const NO_TAGGER = { ...TAGGER, model: "/nonexistent/model.onnx", available: false }; +const ENGINE = { python: process.execPath, script: path.join(KIT, "fakeSpeakerEmbed.mjs"), model: "fake.onnx", threads: 1 }; + +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +const quiet = () => { + const lines = []; + return { lines, log: (s) => lines.push(s), err: (s) => lines.push(s) }; +}; + +/** A corpus with the synthetic stream, and a reports root. */ +async function fixture({ audio = false, diarization = true } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "clips-")); + const channelsDir = path.join(root, "channels"); + const reportsRoot = path.join(root, "reports"); + writeReactionCorpus(channelsDir, { diarization, audio: audio ? encodeWav16(reactionAudio()) : null }); + return { root, channelsDir, reportsRoot }; +} + +/** Point a scaffolded project at the fixture's corpus (as a shadow tree would). */ +async function pointAt(dir, channelsDir) { + const file = path.join(dir, "video.manifest.json"); + const m = JSON.parse(await readFile(file, "utf8")); + m.provenance.channelsDir = path.relative(dir, channelsDir); + await writeFile(file, JSON.stringify(m, null, 2)); + return m; +} + +const manifestOf = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + +test("--seed reactions: clips marked by the assistant, reactions.json beside the manifest, hard cuts, the README's checklist", async () => { + const f = await fixture(); + try { + assert.deepEqual(await seedsFor({ channelsDir: f.channelsDir, from: "synth-reacts/react001" }), { video: true, chapters: false, frames: false, reactions: true }); + const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 60 }); + assert.ok(r.seeded >= 3, `seeded ${r.seeded}`); + const m = await manifestOf(r.dir); + assert.equal(m.render.transition, 0); + assert.equal(m.provenance.channelSlug, "synth-reacts"); + const clips = m.timeline; + assert.ok(clips.every((c) => c.type === "clip" && /^r\d{3}$/.test(c.id) && c.channel === "synth-reacts" && c.video === "react001")); + assert.ok(clips.every((c) => c.assist.by === "assistant" && /^p\d{3}$/.test(c.assist.proposal) && c.cutStart >= c.start && c.cutEnd <= c.end)); + // Chronological. + assert.deepEqual(clips.map((c) => c.cutStart), [...clips.map((c) => c.cutStart)].sort((a, b) => a - b)); + const total = clips.reduce((n, c) => n + c.cutEnd - c.cutStart, 0); + assert.ok(total <= 60 * 1.03, `total ${total}`); + const doc = await readReactions(r.dir); + assert.ok(doc); + assert.equal(doc.source.channel, "synth-reacts"); + assert.equal(doc.source.words, null); + assert.equal(doc.source.wordsFrom, "cues"); + assert.equal(doc.laughSource, "text"); + assert.deepEqual(doc.speakers.map((s) => [s.index, s.role]), [[0, "host"], [1, "subject"]]); + assert.equal(doc.params.target, 60); + for (const c of clips) assert.equal(doc.proposals.find((p) => p.id === c.assist.proposal)?.clipId, c.id); + assert.ok(doc.proposals.some((p) => !p.used && p.clipId === null), "the rest stay listed"); + const readme = await readFile(path.join(r.dir, "README.md"), "utf8"); + assert.match(readme, /Clips proposed from the recording/); + assert.ok(r.notes.some((n) => /umtool clips analyze reacts/.test(n))); + // The build's validators and lint accept it. + const lint = lintManifest(m, { validators: true }); + assert.deepEqual(lint.errors.filter((e) => /assist/.test(e)), []); + m.timeline[0].assist.by = "robot"; + assert.ok(lintManifest(m, { validators: true }).errors.some((e) => /assist\.by must be/.test(e))); + // A recording with no speakers: refused, naming the command that makes them. + await assert.rejects( + scaffoldReportVideo({ root: f.reportsRoot, slug: "nope", from: "synth-reacts/missing", seed: "reactions", channelsDir: f.channelsDir }), + /no video directory/, + ); + await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "nope2", seed: "reactions", channelsDir: f.channelsDir }), /--seed reactions needs --from/); + await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "nope3", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 5 }), /from 10 to 7200/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("no diarization: the seed and the CLI say which archilyzer diarize backfill to run", async () => { + const f = await fixture({ diarization: false }); + try { + await assert.rejects( + scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir }), + /archilyzer diarize backfill --scope video:synth-reacts\/react001/, + ); + assert.deepEqual(await seedsFor({ channelsDir: f.channelsDir, from: "synth-reacts/react001" }), { video: true, chapters: false, frames: false, reactions: false }); + await assert.rejects(loadRecording({ channelsDir: f.channelsDir, channel: "synth-reacts", video: "react001" }), /diarize backfill/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("clips propose: params kept, a host flip is the operator's, ids stable, an edited clip never moved", async () => { + const f = await fixture(); + try { + const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 60 }); + await pointAt(r.dir, f.channelsDir); + const before = await manifestOf(r.dir); + // The same inputs again: nothing changes, every id stays. + const q = quiet(); + assert.equal(await clipsCommand(["propose", "reacts"], { reportsRoot: f.reportsRoot, ...q }), 0, q.lines.join("\n")); + const same = await manifestOf(r.dir); + assert.deepEqual(same.timeline.map((c) => [c.id, c.cutStart, c.cutEnd]), before.timeline.map((c) => [c.id, c.cutStart, c.cutEnd])); + assert.match(q.lines.join("\n"), /clips \+0 ~0 -0/); + // The operator trims the first clip: it is theirs now. + const first = same.timeline[0]; + first.cutStart = Math.round((first.cutStart + 0.5) * 100) / 100; + first.assist.by = "operator"; + first.assist.edits.push({ at: "2026-10-18T22:00:00.000Z", by: "operator", what: "trim", from: { cutStart: first.cutStart - 0.5 }, to: { cutStart: first.cutStart } }); + await writeFile(path.join(r.dir, "video.manifest.json"), JSON.stringify(same, null, 2)); + // A bigger target and a dry run first: nothing written. + const d = quiet(); + assert.equal(await clipsCommand(["propose", "reacts", "--target", "300", "--dry"], { reportsRoot: f.reportsRoot, ...d }), 0); + assert.match(d.lines.join("\n"), /dry run, nothing written/); + assert.equal((await readReactions(r.dir)).params.target, 60); + assert.equal(await clipsCommand(["propose", "reacts", "--target", "300"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + const wider = await manifestOf(r.dir); + assert.ok(wider.timeline.length > same.timeline.length); + const kept = wider.timeline.find((c) => c.id === first.id); + assert.equal(kept.cutStart, first.cutStart); + assert.equal(kept.assist.by, "operator"); + for (const c of same.timeline.slice(1)) assert.equal(wider.timeline.find((x) => x.id === c.id)?.cutStart, c.cutStart, `${c.id} kept its id and cut`); + const doc = await readReactions(r.dir); + assert.equal(doc.params.target, 300); + // The flip: speaker 1 is the host (the operator's word), kept by the next pass. + assert.equal(await clipsCommand(["propose", "reacts", "--host", "1"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + const flipped = await readReactions(r.dir); + assert.deepEqual(flipped.speakers.map((s) => [s.index, s.role, s.how]), [[0, "subject", "auto"], [1, "host", "operator"]]); + assert.equal(flipped.params.target, 300); + assert.equal(await clipsCommand(["propose", "reacts"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + assert.equal((await readReactions(r.dir)).speakers.find((s) => s.index === 1).how, "operator"); + // The editor's writer: back to speaker 0, then a proposal pass. + await setSpeakerRole(r.dir, 0, "host"); + assert.equal(await clipsCommand(["propose", "reacts"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + assert.deepEqual((await readReactions(r.dir)).speakers.map((s) => [s.index, s.role]), [[0, "host"], [1, "subject"]]); + // show, and the refusals. + const s = quiet(); + assert.equal(await clipsCommand(["show", "reacts"], { reportsRoot: f.reportsRoot, ...s }), 0); + assert.match(s.lines.join("\n"), /speaker 0 {2}Host/); + const bad = quiet(); + assert.equal(await clipsCommand(["propose", "reacts", "--host", "9"], { reportsRoot: f.reportsRoot, ...bad }), 2); + assert.match(bad.lines.join("\n"), /no such speaker/); + assert.equal(await clipsCommand(["propose", "reacts", "--laugh-min", "3"], { reportsRoot: f.reportsRoot, ...quiet() }), 2); + assert.equal(await clipsCommand(["frobnicate", "reacts"], { reportsRoot: f.reportsRoot, ...quiet() }), 2); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("clips propose reads <project>/words.json when there is one", async () => { + const f = await fixture(); + try { + const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir }); + await pointAt(r.dir, f.channelsDir); + const { reactionStream } = await import("yt-dlp-transcript-common/testing/clips/reactionStream.mjs"); + await writeFile(path.join(r.dir, "words.json"), JSON.stringify({ path: "/x", words: reactionStream().words })); + assert.equal(await clipsCommand(["propose", "reacts"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + const doc = await readReactions(r.dir); + assert.equal(doc.source.words, "words.json"); + assert.equal(doc.source.wordsFrom, "words.json"); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("clips analyze (fake tagger + fake embedder): the scans, cached in the project; the model's laughs", { skip: !hasFfmpeg && "no ffmpeg" }, async () => { + const f = await fixture({ audio: true }); + try { + const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 60 }); + await pointAt(r.dir, f.channelsDir); + const q = quiet(); + assert.equal(await clipsCommand(["analyze", "reacts", "--progress", "ndjson"], { reportsRoot: f.reportsRoot, ...q, tagger: TAGGER, engine: ENGINE }), 0, q.lines.join("\n")); + const events = q.lines.filter((l) => l.startsWith("{")).map((l) => JSON.parse(l)); + assert.ok(events.some((e) => e.phase === "laughs" && e.event === "decode")); + assert.ok(events.some((e) => e.phase === "voices")); + assert.equal(events.at(-1).phase, "done"); + const doc = await readReactions(r.dir); + assert.equal(doc.laughSource, "model"); + assert.equal(doc.laughs.length, 3); + assert.ok(doc.laughs.every((l) => l.speaker === 0)); + assert.equal(doc.scans.laughs.model, "fakeAudioTag.mjs"); + assert.equal(doc.scans.voices.model, "fake-spectrum"); + assert.equal(doc.source.audio, "audio.wav"); + await stat(path.join(r.dir, "scans", "synth-reacts--react001.audio.json")); + await stat(path.join(r.dir, "scans", "synth-reacts--react001.voices.json")); + // Again: both cached. + const again = quiet(); + assert.equal(await clipsCommand(["analyze", "reacts"], { reportsRoot: f.reportsRoot, ...again, tagger: TAGGER, engine: ENGINE }), 0); + assert.match(again.lines.join("\n"), /laugh scan: cached/); + assert.match(again.lines.join("\n"), /voices: cached/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("the no-model fallback: no laugh model — the sound's energy and the transcript's markers", { skip: !hasFfmpeg && "no ffmpeg" }, async () => { + const f = await fixture({ audio: true }); + try { + const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir }); + await pointAt(r.dir, f.channelsDir); + const q = quiet(); + assert.equal(await clipsCommand(["analyze", "reacts", "--no-voices"], { reportsRoot: f.reportsRoot, ...q, tagger: NO_TAGGER, engine: ENGINE }), 0, q.lines.join("\n")); + assert.match(q.lines.join("\n"), /no laugh model at \/nonexistent\/model\.onnx — energy only/); + const doc = await readReactions(r.dir); + assert.equal(doc.laughSource, "text+energy"); + assert.equal(doc.scans.laughs.model, null); + assert.ok(doc.laughs.length >= 3); + assert.ok(doc.laughs.some((l) => l.src === "text")); + assert.ok(doc.proposals.some((p) => p.used)); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("clipsSteps: one nice'd step running the CLI, its flags checked", () => { + const plan = clipsSteps({ id: "reacts" }, { mode: "analyze", from: "synth-reacts/react001", target: 300, host: 1 }); + assert.equal(plan.kind, "clips-analyze reacts"); + assert.equal(plan.steps.length, 1); + const argv = plan.steps[0].argv; + assert.deepEqual(argv.slice(0, 3), ["nice", "-n", "10"]); + assert.deepEqual(argv.slice(-10), ["clips", "analyze", "reacts", "--from", "synth-reacts/react001", "--target", "300", "--host", "1", "--progress", "ndjson"].slice(-10)); + const bad = clipsSteps({ id: "reacts" }, { mode: "propose", from: "../etc", target: 2 }); + assert.equal(bad.kind, "clips-propose reacts"); + assert.ok(!bad.steps[0].argv.includes("--from") && !bad.steps[0].argv.includes("--target")); +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -161,6 +161,7 @@ import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords 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"; +import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; @@ -4715,7 +4716,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), - ...validateStatsEntries(whole), ...validateMontage(whole), + ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -85,6 +85,7 @@ import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; import { validateMontage } from "./montage.mjs"; +import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; @@ -231,6 +232,8 @@ export function validatorErrors(whole) { ...validateStatsEntries(whole), // Release 33: render.montage, its keys and what it does not combine with. ...validateMontage(whole), + // Release 35: a clip's `assist` (the clip finder's provenance; the render ignores it). + ...validateAssist(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`));