// 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 /`), 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 /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 // the chat live_chat.cues.json beside the recording (release 36): // the room's laugh bursts as `chat` moments; without it, // nothing changes // // Nothing here calls a model but the local ones; nothing touches the network. import { readdir, readFile, rename, stat, writeFile, mkdir } from "node:fs/promises"; import path from "node:path"; import { DEFAULT_PARAMS, PARAM_BOUNDS, analyze, cleanWords, laughKey, laughVoiceSpan, normalizeParams, wordsFromCues, } from "yt-dlp-transcript-common/lib/clips/clips.mjs"; import { applyProposals, fixedClips, watchUrlAt } 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 { embedSpans, resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs"; import { SEGMENT_MIN_S, findSegments, pickSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs"; import { readChatCues } from "yt-dlp-transcript-common/lib/clips/chat.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 { SITES_DIR } from "../paths.mjs"; import { replaceManifest, manifestToken, StaleToken } from "./manifest.mjs"; import { REPO_ROOT } from "../paths.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.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 chat = await readChatCues(videoDir); 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, chat, meta: meta ? { webpageUrl: typeof meta.webpage_url === "string" ? meta.webpage_url : null, channel: typeof meta.channel === "string" ? meta.channel : typeof meta.uploader === "string" ? meta.uploader : null, extractor: typeof meta.extractor_key === "string" ? meta.extractor_key : typeof meta.extractor === "string" ? meta.extractor : null } : null, }; } /** * 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, render: null }).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 = tmpPathFor(file); 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>, audio: { path: string, kind: string, clock: number }, * laughs?: boolean, voices?: boolean, rescan?: boolean, tagger?: any, engine?: any, * onProgress?: (e: Record) => void, say?: (s: string) => void }} o */ export async function scanRecording({ projectDir, rec, audio, laughs = true, voices = true, rescan = false, tagger = null, engine = null, scope = 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; const scopeKey = scope ? `${scope[0]}-${scope[1] ?? "end"}` : "all"; if (!rescan && c && sameKey(c.source, key) && c.diarization === rec.diarization.generatedAt && c.engineModel === path.basename(emb.model) && (c.scope ?? "all") === scopeKey) { 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 [a, b] = scope ? [scope[0], scope[1] ?? Infinity] : [-Infinity, Infinity]; // The scope's turns, cut to it: the voices of THIS part of the recording. const turns = rec.turns .filter((t) => t && num(t.start) && num(t.end) && t.end > t.start && Number.isInteger(t.speaker) && t.end > a && t.start < b) .map((t) => ({ start: Math.max(t.start, a), end: Math.min(t.end, b), speaker: 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 }), }); // Laugh voices are embeddings of the sound, whatever the centroids: kept across a re-scan of the same file. const keptLaughs = c && sameKey(c.source, key) && c.engineModel === path.basename(emb.model) ? c.laughs ?? {} : {}; out.voices = { ...v, engineModel: path.basename(emb.model), scope: scopeKey, laughs: keptLaughs, 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; const laughVoices = scans?.voices?.laughs && typeof scans.voices.laughs === "object" ? scans.voices.laughs : null; return { laughScan, centroids, laughVoices }; } /** * 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, operator?: Record, 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(), citeUrlAt = null, keepCut = false }) { const { laughScan, centroids, laughVoices } = scanInputs(scans); const segments = recordingSegments(rec, operator); // `keepCut` (release 36: the editor's Find clips on a project already cut): // every clip stays as it is and nothing is added — the pass only lists. const guard = keepCut ? () => true : isProtected; const fixed = fixedClips(timeline, { channel: rec.channel, video: rec.video, isProtected: guard }); const a = analyze({ turns: rec.turns, duration: rec.duration, words: rec.words, params, operator, centroids, laughScan, laughVoices, previous: previous?.proposals ?? [], fixed, chat: rec.chat ?? null, }); const proposals = keepCut ? a.proposals.map((p) => (p.fixedClip ? p : { ...p, used: false })) : a.proposals; const applied = applyProposals(timeline, { proposals, channel: rec.channel, video: rec.video, duration: a.duration, words: cleanWords(rec.words), isProtected: guard, citeUrlAt }); 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, segments, segment: segmentOfScope(segments, a.params.scope), chat: a.chat, 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, }; // Kept means kept: not even re-sorted. return { doc, timeline: keepCut ? timeline : applied.timeline, changes: applied.changes, analysis: a }; } // ---- site-less links (release 36 B3) --------------------------------------------------- /** * Whether a channel is on a public site: in a `site.json`'s `channels` (or * `citedChannels`) with a `siteUrl` to link to. A private site (no siteUrl) * does not count: nobody else can open its links. * @param {string} channel * @param {string} [sitesDir] */ export async function channelOnPublicSite(channel, sitesDir = SITES_DIR) { let ids; try { ids = await readdir(sitesDir); } catch { return false; } for (const id of ids) { const site = await readJson(path.join(/* turbopackIgnore: true */ sitesDir, id, "site.json")); if (!site || typeof site.siteUrl !== "string" || !site.siteUrl.trim()) continue; const pool = [...(Array.isArray(site.channels) ? site.channels.map((c) => c?.slug) : []), ...(Array.isArray(site.citedChannels) ? site.citedChannels : [])]; if (pool.includes(channel)) return true; } return false; } /** * The link rule for a pass: with no siteOrigin and the channel on no public * site, each clip the pass writes links its platform page at its cite * (watchUrlAt over the recording's `webpage_url`); else null (the QR's link * is the site's, as before). * @returns {Promise<((s: number) => string | null) | null>} */ export async function siteLessLinks(rec, manifest, { sitesDir = SITES_DIR } = {}) { const origin = manifest?.provenance?.siteOrigin; if (typeof origin === "string" && origin.trim()) return null; const url = rec.meta?.webpageUrl ?? null; if (!watchUrlAt(url, 0)) return null; if (await channelOnPublicSite(rec.channel, sitesDir)) return null; return (s) => watchUrlAt(url, s); } // ---- auto-scope (release 36 B1) ----------------------------------------------------- /** The host the operator named, if any (`{index: role}`). */ function operatorHost(operator) { const k = Object.entries(operator ?? {}).find(([, v]) => v === "host")?.[0]; return k === undefined ? null : Number(k); } /** The recording's narrated-video segments (lib/clips/segments.mjs), the operator's host left out of the counting. */ export function recordingSegments(rec, operator = {}) { return findSegments({ turns: rec.turns, duration: rec.duration, host: operatorHost(operator) }); } /** The segment a scope is (its edges within 0.01 s), or null. */ export function segmentOfScope(segments, scope) { if (!Array.isArray(scope)) return null; const hit = segments.find((g) => Math.abs(g.from - scope[0]) < 0.01 && scope[1] !== null && Math.abs(g.to - scope[1]) < 0.01); return hit ? hit.id : null; } /** * `--scope auto`: the segment named (`segment`), else the longest. When the * recording has none (no cluster holds the long turns for SEGMENT_MIN_S), the * whole recording is read and `note` says so. * @returns {{ scope: [number, number] | null, segment: any, segments: any[], note: string }} */ export function autoScope(rec, { segment = null, operator = {} } = {}) { const segments = recordingSegments(rec, operator); let seg; try { seg = pickSegment(segments, segment); } catch (e) { throw new ClipsError(e instanceof Error ? e.message : String(e)); } if (!seg) { return { scope: null, segment: null, segments, note: `auto-scope: no narrated video found (no speaker holds the long turns for ${SEGMENT_MIN_S} s) — the whole recording is read` }; } const list = segments.map((g) => `${g.id} ${Math.round(g.from)}–${Math.round(g.to)} s`).join(", "); return { scope: [seg.from, seg.to], segment: seg, segments, note: `auto-scope: ${seg.id}, ${Math.round(seg.from)}–${Math.round(seg.to)} s (${seg.why}); segments: ${list}` }; } /** Params with `scope: "auto"` (and `segment`) resolved against the recording; anything else as given. */ export function resolveParams(rec, params, operator = {}, say = () => {}) { if (params?.scope !== "auto" && !(params?.segment && params?.scope === undefined)) return params; const r = autoScope(rec, { segment: params.segment ?? null, operator }); say(r.note); const { segment: _s, ...rest } = params; return { ...rest, scope: r.scope ?? "all" }; } /** The chat in one line: its messages, the lag found and how. */ export function chatLine(chat) { const how = chat.lag?.how === "xcorr" ? chat.lag.why : `the default (${chat.lag?.why ?? "no lag found"})`; return `chat: ${chat.messages} message(s), ${chat.bursts} laugh burst(s); lag ${chat.lagS} s — ${how}`; } /** 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}` + (doc.chat ? `; chat: ${doc.chat.bursts} burst(s), lag ${doc.chat.lagS} s` : "") + (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, laughMin, scope, segment = null, siteOrigin = null, sitesDir = SITES_DIR }) { const rec = await loadRecording({ channelsDir, channel, video }); const citeUrlAt = await siteLessLinks(rec, { provenance: { siteOrigin: siteOrigin ?? "" } }, { sitesDir }); const notes = []; const given = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}), ...(segment ? { segment } : {}) }; const params = resolveParams(rec, given, {}, (n) => notes.push(n)); const pass = proposalPass({ rec, params: { ...params, ...(params.scope === "all" ? { scope: null } : {}) }, citeUrlAt }); return { ...pass, rec, notes, siteLess: !!citeUrlAt }; } /** * 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, * 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, engine = null, dry = false, now = new Date(), say = () => {}, sitesDir = SITES_DIR, keepCut = false }) { 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 /`); 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 = mergeParams(sameSource ? previous.params : null, resolveParams(rec, params, operator, attempt === 0 ? say : () => {})); const s = scans === undefined ? await readScans(project.dir, rec.channel, rec.video) : scans; const isProtected = await rulingsGuard(project.dir, manifest); const citeUrlAt = await siteLessLinks(rec, manifest, { sitesDir }); const passOf = (sc) => proposalPass({ rec, scans: sc, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now, citeUrlAt, keepCut }); let pass = passOf(s); // Each laugh's voice (release 35, the live case): embedded once and kept in // the voices scan, so a pass with a new laughMin or scope embeds only the new ones. if (s?.voices?.speakers) { const have = s.voices.laughs ?? {}; const missing = pass.doc.laughs.filter((l) => !have[laughKey(l)]); if (missing.length) { const sound = audio ?? (await recordingAudio({ channelsDir, channel: rec.channel, video: rec.video, videoDir: rec.videoDir, duration: rec.duration })); const emb = engine ?? resolveEngine({ repoRoot: REPO_ROOT, settings: await readSettings() }); if (sound && (engine || (await isFile(emb.model)))) { say(`laugh voices: ${missing.length} laugh(s) to check against the host's and the subject's voices`); const got = await embedSpans({ file: sound.path, clock: sound.clock, spans: missing.map((l) => ({ key: laughKey(l), ...laughVoiceSpan(l) })), engine: emb, scratch: path.join(/* turbopackIgnore: true */ project.dir, ".clips-work"), }); const voices = { ...s.voices, laughs: { ...have, ...Object.fromEntries(got) } }; if (!dry) await writeWhole(scanFile(project.dir, rec.channel, rec.video, "voices"), voices); pass = passOf({ ...s, voices }); } else say(`laugh voices: ${missing.length} laugh(s) not checked (no sound or no speaker model)`); } } 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 params of a pass: the file's (when it is the same recording), the * given over them. `scopeFrom` / `scopeTo` change one end of the file's scope; * `scope: "all"` clears it. */ export function mergeParams(prev, given = {}) { const out = { ...(prev ?? {}) }; for (const [k, v] of Object.entries(given ?? {})) { if (v === undefined || v === null || k === "scopeFrom" || k === "scopeTo") continue; out[k] = v; } if (given?.scopeFrom !== undefined || given?.scopeTo !== undefined) { const was = Array.isArray(out.scope) ? out.scope : [0, null]; out.scope = [given.scopeFrom ?? was[0], given.scopeTo ?? was[1]]; } try { return normalizeParams(out); } catch (e) { throw new ClipsError(e instanceof Error ? e.message : String(e)); } } // ---- the CLI ---------------------------------------------------------------------- export const CLIPS_USAGE = [ "usage: umtool clips analyze [--from /] [--rescan] [--no-laughs] [--no-voices] [params] [--keep-cut] [--progress ndjson] [--json]", " umtool clips propose [--from /] [--host N] [params] [--words FILE] [--keep-cut] [--dry] [--json]", " umtool clips show [--json]", " umtool clips segments [--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 /${REACTIONS_FILE}.`, " analyze runs the laugh scan (CED-mini, local) and a voice centroid per speaker on the", ` recording's sound (cached in /${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", "scope: --scope FROM:TO (seconds; TO may be empty: to the end; `all` clears it), or --from S / --to S with numbers:", " only that part of the recording is read (a stream that reacts to two videos, one at a time);", " --scope auto: the narrated video found in the speakers' turns (--segment s2 names one, else the longest)", " segments the narrated-video spans auto-scope finds in the recording (where one long-turn speaker holds the floor)", "--host N speaker N is the host (your word: kept until you change it)", "--keep-cut propose without touching the cut: every clip stays, nothing is added (the proposals are listed)", "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:/).", `Words: /${WORDS_FILE} (pnpm ops transcribe {path, words:true, out}), else the corpus transcript.`, "The laugh model: AUDIO_TAG_MODEL, else .diarize/models//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", "--to", "--scope", "--segment", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]); /** @type {Record} */ 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) { /** @type {Record} */ const out = {}; const secs = (flag, v) => { const n = Number(v); if (!Number.isFinite(n) || n < 0) throw new ClipsError(`${flag} takes seconds ≥ 0, not ${v}`); return n; }; if (p.has("--scope")) { const v = String(p.one("--scope")); if (v === "all" || v === "auto") out.scope = v; else { const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(v); if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), auto, or all`); out.scope = [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null]; } } if (p.has("--segment")) { const id = String(p.one("--segment")); if (!/^s\d+$/.test(id)) throw new ClipsError(`--segment ${id}: a segment id (s1, s2, …; umtool clips segments lists them)`); if (out.scope !== undefined && out.scope !== "auto") throw new ClipsError("--segment goes with --scope auto (or alone)"); out.scope = "auto"; out.segment = id; } if (p.has("--from") && isSeconds(p.one("--from"))) out.scopeFrom = secs("--from", p.one("--from")); if (p.has("--to")) out.scopeTo = secs("--to", p.one("--to")); 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; } const isSeconds = (v) => /^\d+(?:\.\d+)?$/.test(String(v ?? "")); /** `--from /` (a number is the scope's start instead). */ function parseFrom(v) { if (v === undefined || isSeconds(v)) 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}: /`); 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})` : ""}`); if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}–${doc.params.scope[1] ?? "end"} s${doc.segment ? ` (segment ${doc.segment})` : ""}`); if (Array.isArray(doc.segments) && doc.segments.length) lines.push(` segments: ${doc.segments.map((g) => `${g.id} ${Math.round(g.from)}–${Math.round(g.to)} s (subject ${g.subject})`).join(", ")}`); const byVoice = doc.laughs.filter((l) => l.by === "voice").length; const voiced = doc.laughs.filter((l) => l.voice).length; lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}${voiced ? `; ${voiced} voice-checked, ${byVoice} re-attributed by voice` : ""}), moments: ${doc.moments.length}`); if (doc.chat) lines.push(` ${chatLine(doc.chat)}`); 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 "); return lines; } /** * The recording's segments for `umtool clips segments`: found afresh from the * diarization on disk (the operator's host from reactions.json left out), with * which one the project's scope is. */ export async function projectSegments(project, { from = null } = {}) { 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 /`); 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 }); const segments = recordingSegments(rec, operatorRoles(previous)); const scope = previous && previous.source.channel === rec.channel && previous.source.video === rec.video ? previous.params?.scope ?? null : null; return { channel: rec.channel, video: rec.video, duration: Math.round(rec.duration * 100) / 100, scope, segment: segmentOfScope(segments, scope), segments }; } function segmentLines(r) { const lines = [`${r.channel}/${r.video} ${Math.round(r.duration)} s ${r.segments.length} segment(s)${r.scope ? `; this project reads ${r.scope[0]}–${r.scope[1] ?? "end"} s` : ""}`]; for (const g of r.segments) { lines.push(` ${g.id} ${g.from.toFixed(1).padStart(8)}–${g.to.toFixed(1).padEnd(8)} ${String(Math.round(g.to - g.from)).padStart(5)} s subject ${g.subject}, host ${g.host ?? "?"} ${g.why}${g.id === r.segment ? " (this project's scope)" : ""}`); } if (!r.segments.length) lines.push(" none: no speaker holds the long turns for long enough (a scope by hand: --scope FROM:TO)"); 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", "segments"].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 === "segments") { const r = await projectSegments(project, { from: parseFrom(p.one("--from")) }); log(p.has("--json") ? JSON.stringify(r, null, 1) : segmentLines(r).join("\n")); return 0; } 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 /`); 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 /`); 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(); const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video; const { scope } = mergeParams(sameSource ? previous.params : null, resolveParams(rec, params, operatorRoles(previous))); scans = await scanRecording({ projectDir: project.dir, rec, audio, laughs: !p.has("--no-laughs"), voices: !p.has("--no-voices"), rescan: p.has("--rescan"), tagger, engine, scope, 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, engine, dry: p.has("--dry"), now, say, keepCut: p.has("--keep-cut") }); 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")); else if (r.doc.chat) say(chatLine(r.doc.chat)); 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, laughMin?: number, scope?: [number, number | null] | "auto" | "all", segment?: string, keepCut?: boolean }} [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)); if (num(req.laughMin) && req.laughMin >= PARAM_BOUNDS.laughMin[0] && req.laughMin <= PARAM_BOUNDS.laughMin[1]) argv.push("--laugh-min", String(req.laughMin)); if (Array.isArray(req.scope) && num(req.scope[0]) && (req.scope[1] === null || num(req.scope[1]))) argv.push("--scope", `${req.scope[0]}:${req.scope[1] ?? ""}`); else if (req.scope === "auto" || req.scope === "all") argv.push("--scope", req.scope); if (typeof req.segment === "string" && /^s\d+$/.test(req.segment) && req.scope !== "all" && !Array.isArray(req.scope)) argv.push("--segment", req.segment); if (req.keepCut === true) argv.push("--keep-cut"); 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 };