Archilyzer · Source

archilyzer

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

commit e4742019a52da5783b409a74e966a3865a5d6fe0
parent 6258f7feebc4a9180b677bd8c5e29f6b5734dc85
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 02:10:43 -0400

Merge main (release 35 C1, the clip finder) into r35/clip-editor

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

Diffstat:
MENVIRONMENT.md | 4++++
Acommon/lib/clips/assist.d.mts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/assist.mjs | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/clips.d.mts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/clips.mjs | 867+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/clips.test.ts | 420+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/reactions.d.mts | 44++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/reactions.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/scan.d.mts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/scan.mjs | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/scan.test.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 4++++
Mcommon/package.json | 4++++
Acommon/testing/audio/fakeAudioTag.d.mts | 2++
Acommon/testing/audio/fakeAudioTag.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/clips/reactionStream.d.mts | 18++++++++++++++++++
Acommon/testing/clips/reactionStream.mjs | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-35/clip-analysis.md | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/audio-tag.py | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/clips/route.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 39++++++++++++++++++++++++++++++++++++---
Mumtool/components/NewProjectMenu.tsx | 65++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/create/CreateView.tsx | 16++++++++++++++++
Mumtool/docs/cli.md | 29++++++++++++++++++++++++++++-
Mumtool/docs/report-video.md | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/create.spec.ts | 46+++++++++++++++++++++++++++++++++++++++++++---
Mumtool/e2e/visual-audit.spec.ts | 2+-
Mumtool/lib/hrefs.ts | 3++-
Mumtool/lib/projects/scaffold.mjs | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/lib/projects/scaffold.ts | 12++++++++++--
Mumtool/lib/report/manifest.mjs | 2++
Aumtool/lib/report/reactions.mjs | 648+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reactions.test.mjs | 286+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/scaffold-frames.test.mjs | 10+++++-----
Mumtool/playwright.config.ts | 4++++
Mumtool/report-to-video/build-video.mjs | 3++-
Mumtool/report-to-video/lint.mjs | 3+++
39 files changed, 4273 insertions(+), 31 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -109,6 +109,10 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `VOICE_MATCH_PYTHON` | `settings.diarization.python`, else `<repo>/.diarize/env/bin/python` | The program that runs the speaker-embedding script for a montage's voice match: the diarization venv's python. Any program that takes the script's arguments will do; the e2e suite runs the test kit's fake embedder with `node`. | common/lib/montage/voiceMatch.mjs (`umtool voice-match`) | | `VOICE_MATCH_SCRIPT` | `<repo>/scripts/speaker-embed.py` | The speaker-embedding script (WAV segments in, L2-normalised embeddings out, JSON). The e2e suite points it at `common/testing/audio/fakeSpeakerEmbed.mjs`. | common/lib/montage/voiceMatch.mjs (`umtool voice-match`) | | `VOICE_MATCH_MODEL` | `settings.diarization.embModel`, else `<repo>/.diarize/models/titanet.onnx` | The speaker-embedding ONNX model for the voice match: TitaNet-small, the same file the diarization lane loads. | common/lib/montage/voiceMatch.mjs (`umtool voice-match`) | +| `AUDIO_TAG_PYTHON` | `settings.diarization.python`, else `<repo>/.diarize/env/bin/python` | The program that runs the audio-tagging script for the clip finder's laugh scan: the diarization venv's python (sherpa-onnx). Any program that takes the script's arguments will do; the tests run the test kit's fake tagger with `node`. | common/lib/clips/scan.mjs (`umtool clips analyze`) | +| `AUDIO_TAG_SCRIPT` | `<repo>/scripts/audio-tag.py` | The audio-tagging script (WAV files in, per-window class probabilities out, JSON). The tests point it at `common/testing/audio/fakeAudioTag.mjs`. | common/lib/clips/scan.mjs (`umtool clips analyze`) | +| `AUDIO_TAG_MODEL` | `<repo>/.diarize/models/sherpa-onnx-ced-mini-audio-tagging-2024-04-19/model.int8.onnx` | The audio-tagging ONNX model for the laugh scan: CED-mini (AudioSet's 527 classes). Absent, the scan keeps each window's level only and the laughs come from the transcript and the host's wordless bursts. | common/lib/clips/scan.mjs (`umtool clips analyze`) | +| `AUDIO_TAG_LABELS` | `class_labels_indices.csv` beside the model | The model's class labels file. | common/lib/clips/scan.mjs (`umtool clips analyze`) | | `DIARIZE_SEG_MODEL` | — (required) | Segmentation model. The editor passes the settings' value as a flag. | scripts/diarize.mjs | | `DIARIZE_EMB_MODEL` | — (required) | Speaker-embedding model. The editor passes the settings' value as a flag. | scripts/diarize.mjs | | `DIARIZE_THRESHOLD` | `0.5` | Clustering threshold. | scripts/diarize.mjs | diff --git a/common/lib/clips/assist.d.mts b/common/lib/clips/assist.d.mts @@ -0,0 +1,60 @@ +import type { Word } from "./clips.mjs"; + +export const ASSIST_BY: readonly ("assistant" | "operator")[]; +export const ASSIST_EDITS: readonly ("trim" | "split" | "merge" | "add" | "restore")[]; +export const WINDOW_PAD_S: number; +export const QUOTE_MAX: number; + +export type AssistSpan = { start: number; end: number; cutStart: number; cutEnd: number }; +export type AssistEdit = { + at: string; + by: "assistant" | "operator"; + what: "trim" | "split" | "merge" | "add" | "restore"; + from?: Record<string, unknown>; + to?: Record<string, unknown>; +}; +export type Assist = { + by: "assistant" | "operator"; + proposal?: string; + score?: number; + why?: string; + original?: AssistSpan; + edits?: AssistEdit[]; +}; +export type AssistClip = { + type: "clip"; + id: string; + channel: string; + video: string; + start: number; + end: number; + cutStart: number; + cutEnd: number; + cite: number; + quote: string; + assist: Assist; +}; + +export function validateAssist(manifest: unknown): string[]; +export function isAssistantClip(e: unknown): boolean; +export function cutOf(e: { start: number; end: number; cutStart?: number; cutEnd?: number }): { start: number; end: number }; +export function clipFromProposal( + p: { id: string; start: number; end: number; score: number; why: string }, + o: { id: string; channel: string; video: string; duration?: number; words?: Word[] }, +): AssistClip; +export function fixedClips(timeline: unknown[], o: { channel: string; video: string; isProtected?: (e: any) => boolean }): { id: string; start: number; end: number }[]; +export function applyProposals( + timeline: unknown[], + o: { + proposals: { id: string; start: number; end: number; score: number; why: string; used: boolean; fixedClip?: string; moments?: string[] }[]; + channel: string; + video: string; + duration?: number; + words?: Word[]; + isProtected?: (e: any) => boolean; + }, +): { + timeline: any[]; + proposals: { id: string; start: number; end: number; score: number; why: string; used: boolean; clipId: string | null; moments?: string[] }[]; + changes: { added: string[]; updated: string[]; removed: string[]; kept: number }; +}; diff --git a/common/lib/clips/assist.mjs b/common/lib/clips/assist.mjs @@ -0,0 +1,222 @@ +// A manifest clip's `assist` key (release 35 C1): which clips the clip finder +// proposed, what it proposed, and what the operator did to them since. +// +// "assist": { "by": "assistant"|"operator", "proposal": "p001", "score": 0.83, "why": "…", +// "original": { "start", "end", "cutStart", "cutEnd" }, +// "edits": [ { "at": ISO, "by": "operator", "what": "trim"|"split"|"merge"|"add"|"restore", +// "from": {…}, "to": {…} } ] } +// +// `by` flips to "operator" on the first human edit, and from then on a +// re-proposal never touches the clip. A clip the operator adds has +// `by: "operator"` and no `proposal`. The renderer ignores the key; the +// validator here (run by the build and by `umtool check`) refuses a malformed +// one so a hand edit that breaks it is caught before a render. +// +// Also here: applyProposals, the one place a proposal becomes a timeline +// entry — the seed and `umtool clips propose` both call it. +// +// Plain ESM with a .d.mts beside it. +import { textIn } from "./clips.mjs"; + +export const ASSIST_BY = Object.freeze(["assistant", "operator"]); +export const ASSIST_EDITS = Object.freeze(["trim", "split", "merge", "add", "restore"]); +/** The seconds either side of a proposed cut the clip's window (start/end) leaves for trimming. */ +export const WINDOW_PAD_S = 1.5; +/** A clip's quote: the cut's words, at most this many characters. */ +export const QUOTE_MAX = 160; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const num = (v) => typeof v === "number" && Number.isFinite(v); +const round2 = (n) => Math.round(n * 100) / 100; + +/** + * What is wrong with every clip's `assist`, as sentences. Unknown keys are + * left alone (the editor may add its own); the known ones must have their + * types. + * @param {any} manifest + * @returns {string[]} + */ +export function validateAssist(manifest) { + const errors = []; + for (const e of manifest?.timeline ?? []) { + if (!isObj(e) || e.assist === undefined) continue; + const W = `timeline entry ${e.id ?? "?"}: assist`; + const a = e.assist; + if (e.type !== "clip") { + errors.push(`${W} is only for clips`); + continue; + } + if (!isObj(a)) { + errors.push(`${W} must be an object ({ by, proposal, score, why, original, edits })`); + continue; + } + if (!ASSIST_BY.includes(a.by)) errors.push(`${W}.by must be "assistant" or "operator", not ${JSON.stringify(a.by)}`); + if (a.by === "assistant" && (typeof a.proposal !== "string" || !a.proposal)) errors.push(`${W}.proposal must name the proposal an assistant clip came from`); + if (a.proposal !== undefined && a.proposal !== null && (typeof a.proposal !== "string" || !a.proposal)) errors.push(`${W}.proposal must be a proposal id`); + if (a.score !== undefined && a.score !== null && !(num(a.score) && a.score >= 0 && a.score <= 1)) errors.push(`${W}.score must be a number from 0 to 1`); + if (a.why !== undefined && a.why !== null && typeof a.why !== "string") errors.push(`${W}.why must be text`); + if (a.original !== undefined && a.original !== null) { + if (!isObj(a.original)) errors.push(`${W}.original must be { start, end, cutStart, cutEnd }`); + else { + for (const k of ["start", "end", "cutStart", "cutEnd"]) { + if (!(num(a.original[k]) && a.original[k] >= 0)) errors.push(`${W}.original.${k} must be a number of seconds ≥ 0`); + } + if (num(a.original.cutStart) && num(a.original.cutEnd) && a.original.cutEnd <= a.original.cutStart) errors.push(`${W}.original: cutEnd must be after cutStart`); + } + } + if (a.edits !== undefined && a.edits !== null) { + if (!Array.isArray(a.edits)) errors.push(`${W}.edits must be a list`); + else { + a.edits.forEach((ed, i) => { + const EW = `${W}.edits[${i}]`; + if (!isObj(ed)) { + errors.push(`${EW} must be { at, by, what, from, to }`); + return; + } + if (typeof ed.at !== "string" || Number.isNaN(Date.parse(ed.at))) errors.push(`${EW}.at must be an ISO time`); + if (!ASSIST_BY.includes(ed.by)) errors.push(`${EW}.by must be "assistant" or "operator"`); + if (!ASSIST_EDITS.includes(ed.what)) errors.push(`${EW}.what must be one of ${ASSIST_EDITS.join(", ")}, not ${JSON.stringify(ed.what)}`); + for (const k of ["from", "to"]) if (ed[k] !== undefined && ed[k] !== null && !isObj(ed[k])) errors.push(`${EW}.${k} must be an object`); + }); + } + } + } + return errors; +} + +/** An assistant's clip that no person has touched: the only kind a re-proposal may move or remove. */ +export const isAssistantClip = (e) => isObj(e) && e.type === "clip" && isObj(e.assist) && e.assist.by === "assistant"; + +/** The span a clip's cut covers (cutStart–cutEnd, else start–end). */ +export const cutOf = (e) => (num(e?.cutStart) && num(e?.cutEnd) ? { start: e.cutStart, end: e.cutEnd } : { start: e.start, end: e.end }); + +/** + * A proposal as a clip entry (or the fields that change on one already in + * the cut): the cut is the proposal; the window leaves WINDOW_PAD_S either + * side for trimming, inside the recording. + * @param {{ id: string, start: number, end: number, score: number, why: string }} p + * @param {{ id: string, channel: string, video: string, duration?: number, words?: { w: string, start: number, end: number }[] }} o + */ +export function clipFromProposal(p, { id, channel, video, duration = Infinity, words = [] }) { + const cutStart = round2(p.start); + const cutEnd = round2(p.end); + const start = round2(Math.max(0, cutStart - WINDOW_PAD_S)); + const end = round2(Math.min(Number.isFinite(duration) && duration > 0 ? duration : Infinity, cutEnd + WINDOW_PAD_S)); + return { + type: "clip", + id, + channel, + video, + start, + end: Math.max(end, cutEnd), + cutStart, + cutEnd, + cite: Math.floor(cutStart), + quote: textIn(words, cutStart, cutEnd, QUOTE_MAX), + assist: { + by: "assistant", + proposal: p.id, + score: p.score, + why: p.why, + original: { start, end: Math.max(end, cutEnd), cutStart, cutEnd }, + edits: [], + }, + }; +} + +/** The next free `r<NNN>` id in a timeline. */ +function nextClipId(used) { + let n = 0; + for (const id of used) { + const m = /^r(\d+)$/.exec(id); + if (m) n = Math.max(n, Number(m[1])); + } + let id; + do { + n += 1; + id = `r${String(n).padStart(3, "0")}`; + } while (used.has(id)); + used.add(id); + return id; +} + +/** + * The clips of the source recording a re-proposal may not move: every clip of + * it that is not an untouched assistant clip — the operator's, a hand-made + * one — and an assistant clip the operator has ruled on or locked. + * @param {any[]} timeline + * @param {{ channel: string, video: string, isProtected?: (e: any) => boolean }} o + */ +export function fixedClips(timeline, { channel, video, isProtected = () => false }) { + return (timeline ?? []) + .filter((e) => isObj(e) && e.type === "clip" && e.video === video && (e.channel ?? channel) === channel) + .filter((e) => !isAssistantClip(e) || isProtected(e) || e.lock || e.lockStart || e.lockEnd || e.lockCut) + .map((e) => ({ id: String(e.id), ...cutOf(e) })); +} + +/** + * The timeline after a proposal pass. Untouched assistant clips (isAssistantClip, + * not protected) are the assistant's to move: one whose proposal is still used + * is updated in place (same id); one whose proposal is not used is removed. + * Every used proposal with no clip yet becomes one (`r<NNN>`). Everything + * else in the timeline stays as it is. The recording's clips are kept in + * time order in the slots they occupy; other entries do not move. + * + * Returns the timeline, the proposals with their `clipId` (null when unused), + * and what changed. + * @param {any[]} timeline + * @param {{ proposals: { id: string, start: number, end: number, score: number, why: string, used: boolean, fixedClip?: string }[], + * channel: string, video: string, duration?: number, words?: { w: string, start: number, end: number }[], isProtected?: (e: any) => boolean }} o + */ +export function applyProposals(timeline, { proposals, channel, video, duration = Infinity, words = [], isProtected = () => false }) { + const entries = (timeline ?? []).map((e) => (isObj(e) ? { ...e } : e)); + const movable = (e) => isAssistantClip(e) && e.video === video && (e.channel ?? channel) === channel && !isProtected(e) && !(e.lock || e.lockStart || e.lockEnd || e.lockCut); + const byProposal = new Map(); + for (const e of entries) if (movable(e)) byProposal.set(e.assist.proposal, e); + const used = new Set(entries.filter(isObj).map((e) => String(e.id))); + const usedIds = new Set(proposals.filter((p) => p.used && !p.fixedClip).map((p) => p.id)); + const changes = { added: [], updated: [], removed: [], kept: 0 }; + const out = []; + for (const e of entries) { + if (movable(e) && !usedIds.has(e.assist.proposal)) { + changes.removed.push(e.id); + continue; + } + out.push(e); + } + const withClips = proposals.map((p) => { + if (!p.used) return { ...p, clipId: null }; + if (p.fixedClip) return { ...p, clipId: p.fixedClip }; + const have = byProposal.get(p.id); + if (have) { + const fresh = clipFromProposal(p, { id: have.id, channel: have.channel ?? channel, video, duration, words }); + const same = have.cutStart === fresh.cutStart && have.cutEnd === fresh.cutEnd && have.assist.score === fresh.assist.score && have.assist.why === fresh.assist.why; + if (same) changes.kept += 1; + else { + Object.assign(have, { start: fresh.start, end: fresh.end, cutStart: fresh.cutStart, cutEnd: fresh.cutEnd, cite: fresh.cite, quote: fresh.quote }); + have.assist = { ...have.assist, score: fresh.assist.score, why: fresh.assist.why, original: fresh.assist.original }; + changes.updated.push(have.id); + } + return { ...p, clipId: have.id }; + } + const clip = clipFromProposal(p, { id: nextClipId(used), channel, video, duration, words }); + out.push(clip); + changes.added.push(clip.id); + return { ...p, clipId: clip.id }; + }); + // The recording's clips in time order, in the slots they hold. + const isOurs = (e) => isObj(e) && e.type === "clip" && e.video === video && (e.channel ?? channel) === channel; + const slots = []; + const ours = []; + out.forEach((e, i) => { + if (isOurs(e)) { + slots.push(i); + ours.push(e); + } + }); + ours.sort((a, b) => cutOf(a).start - cutOf(b).start || String(a.id).localeCompare(String(b.id))); + slots.forEach((slot, k) => { + out[slot] = ours[k]; + }); + return { timeline: out, proposals: withClips, changes }; +} diff --git a/common/lib/clips/clips.d.mts b/common/lib/clips/clips.d.mts @@ -0,0 +1,106 @@ +export const REACTIONS_VERSION: 1; +export type Scope = [number, number | null]; +export type Params = { target: number; laughMin: number; mergeGap: number; setupMax: number; clipMax: number; scope: Scope | null }; +export const DEFAULT_PARAMS: Readonly<Params>; +export const PARAM_BOUNDS: Readonly<Record<Exclude<keyof Params, "scope">, [number, number]>>; +export const SHORT_TURN_S: number; +export const SPREAD_BINS: number; +export const MIN_SPEAKER_SHARE: number; +export const SAME_VOICE_COSINE: number; +export type Role = "host" | "subject" | "other"; +export const ROLES: readonly Role[]; +export const LAUGH_CLASSES: readonly number[]; +export const SCAN_WINDOW_S: number; +export const SCAN_HOP_S: number; +export const LAUGH_BRIDGE_S: number; +export const LAUGH_WEIGHT: Readonly<{ host: number; none: number; other: number; subject: number; subjectVoice: number }>; +export const TEXT_LAUGH: Readonly<{ score: number; before: number; after: number }>; +export const TEXT_LAUGH_RE: RegExp; +export const ENERGY_BURST_DB: number; +export const ENERGY_LAUGH_SCORE: number; +export const COMMENT_MIN_WORDS_S: number; +export const SETUP_MIN_S: number; +export const REACTION_AFTER_LAUGH_S: number; +export const COMMENT_MAX_S: number; +export const TAIL_MAX_S: number; +export const SILENCE_GAP_S: number; +export const SENTENCE_GAP_S: number; +export const TARGET_SLACK: number; +export const SAME_CLIP_OVERLAP: number; +export const CLIP_MIN_S: number; +export const USE_MIN_SCORE: number; +export const VOICE_MIN: number; +export const VOICE_MARGIN: number; + +export type Turn = { start: number; end: number; speaker: number }; +export type Word = { w: string; start: number; end: number; cueStart?: true; conf?: number }; +export type Speaker = { index: number; role: Role; label: string; seconds: number; turns: number; how: "auto" | "operator"; sameAs?: number }; +export type Laugh = { start: number; end: number; score: number; speaker: number | null; src?: "text" | "energy"; voice?: { host: number; subject: number }; by?: "voice" }; +export type Moment = { id: string; t: number; end: number; kind: "laugh" | "comment"; score: number; speaker: number | null; text: string }; +export type Proposal = { id: string; start: number; end: number; score: number; moments: string[]; why: string; used: boolean; clipId?: string | null; fixedClip?: string }; +export type LaughScan = { t0?: number; hop?: number; window?: number; scores?: number[] | null; energy?: number[] | null }; + +export function normalizeParams(given?: Record<string, unknown>): Params; +export function normalizeScope(v: unknown): Scope | null; +export function laughKey(l: { start: number; end: number }): string; +export function laughVoiceSpan(l: { start: number; end: number }): { start: number; dur: number }; +export function voiceLaughs<L extends { start: number; end: number; speaker: number | null }>( + laughs: L[], + speakers: { index: number; role: string; seconds: number }[], + centroids: Record<string, number[] | null> | null, + laughVoices: Map<string, number[]> | Record<string, number[]> | null, +): (L & { voice?: { host: number; subject: number }; by?: "voice" })[]; +export function widenTo(words: Word[], start: number, end: number, min: number, duration?: number): { start: number; end: number }; +export function cleanTurns(turns: unknown): Turn[]; +export function turnStats(turns: Turn[], duration: number, from?: number): { index: number; seconds: number; turns: number; short: number; spread: number; meanTurn: number }[]; +export function assignRoles(o: { turns: Turn[]; duration: number; operator?: Record<string, string>; centroids?: Record<string, number[] | null> | null; from?: number }): Speaker[]; +export function roleMap(speakers: { index: number; role: string }[]): Map<number, string>; +export function wordsFromCues(cues: { start: number; end: number; text?: string }[]): Word[]; +export function cleanWords(words: unknown): Word[]; +export function wordsIn(words: Word[], a: number, b: number): Word[]; +export function wordSeconds(words: Word[], a: number, b: number): number; +export function textIn(words: Word[], a: number, b: number, max?: number): string; +export function sentenceStarts(words: Word[]): number[]; +export function snapEdge(words: Word[], t: number, side: "start" | "end"): number; +export function tailEnd(words: Word[], end: number): number; +export function laughScore(probs: number[] | Record<string, number>): number; +export function laughEvents(w: { t0?: number; hop?: number; window?: number; scores: number[] }, o?: { laughMin?: number }): { start: number; end: number; score: number }[]; +export function textLaughs(words: Word[]): { start: number; end: number; score: number; src: "text" }[]; +export function energyLaughs( + scan: { t0?: number; hop?: number; window?: number; energy: number[] }, + o: { words: Word[]; turns: Turn[]; speakers: { index: number; role: string }[] }, +): { start: number; end: number; score: number; src: "energy" }[]; +export function attributeLaughs<L extends { start: number; end: number }>(laughs: L[], turns: Turn[], speakers: { index: number; role: string }[]): (L & { speaker: number | null })[]; +export function findMoments(o: { turns: Turn[]; speakers: { index: number; role: string }[]; laughs: { start: number; end: number; score: number; speaker: number | null; by?: string }[]; words: Word[] }): Moment[]; +export function momentSpan( + m: { t: number; end: number; kind: "laugh" | "comment" }, + o: { turns: Turn[]; speakers: { index: number; role: string }[]; words: Word[]; sentences: number[]; setupMax: number; duration: number }, +): { start: number; end: number; setupBy: "subject" | null; setupSeconds: number }; +export function momentWhy(m: { t: number; end: number; kind: "laugh" | "comment"; speakerRole?: string }, span: { setupBy: string | null; setupSeconds: number }): string; +export function buildProposals(o: { moments: Moment[]; turns: Turn[]; speakers: { index: number; role: string }[]; words: Word[]; duration: number; params?: Partial<Params> }): { start: number; end: number; score: number; moments: string[]; why: string }[]; +export function stableIds<P extends { start: number; end: number }>(proposals: P[], previous?: { id: string; start: number; end: number }[]): (P & { id: string })[]; +export function rankIntoTarget<P extends { id: string; start: number; end: number; score: number }>( + proposals: P[], + o: { target: number; fixed?: { id: string; start: number; end: number }[] }, +): (P & { used: boolean; fixedClip?: string })[]; +export function analyze(o: { + turns: unknown; + duration: number; + words: unknown; + params?: Record<string, unknown>; + operator?: Record<string, string>; + centroids?: Record<string, number[] | null> | null; + laughScan?: LaughScan | null; + laughVoices?: Map<string, number[]> | Record<string, number[]> | null; + previous?: { id: string; start: number; end: number }[]; + fixed?: { id: string; start: number; end: number }[]; +}): { + params: Params; + duration: number; + laughSource: "model" | "text" | "text+energy"; + speakers: Speaker[]; + turns: Turn[]; + laughs: Laugh[]; + moments: Moment[]; + proposals: (Proposal & { used: boolean })[]; +}; diff --git a/common/lib/clips/clips.mjs b/common/lib/clips/clips.mjs @@ -0,0 +1,867 @@ +// The clip finder's arithmetic (release 35 C1): from a long recording's +// speaker turns, words and laugh scores to a ranked list of clip proposals. +// +// Pure functions over plain numbers — no disk, no audio, no model — so every +// step is unit-tested on synthetic turns and a person can re-run any of it by +// hand. The pipeline (plans/release-35/clip-finder.md): +// +// turns (diarization.json) ─► roles: which cluster is the HOST, which the +// SUBJECT (turn statistics; voice centroids merge a +// split voice; the operator's word beats both) +// laugh windows (CED) ─► laugh events, attributed to who is talking then +// (no model) ─► laughs from transcript markers and from the +// host's voiced bursts with no words +// turns + words + laughs ─► moments: a host laugh, a host comment, scored +// moments ─► proposals: the subject's setup line → the +// reaction → a tail to the next silence; edges on +// word gaps; near ones merged; capped; ranked into +// a target length (the rest kept, `used: false`) +// +// Deterministic: the same input gives the same output, and every number +// written is rounded. No network; no LLM. +// +// Plain ESM with a .d.mts beside it, so umtool's CLI runs it with bare node. + +export const REACTIONS_VERSION = 1; + +/** The defaults `reactions.json` records under `params`. */ +export const DEFAULT_PARAMS = Object.freeze({ target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75, scope: null }); + +/** The bounds a param is accepted within (the CLI and the form say so). */ +export const PARAM_BOUNDS = Object.freeze({ + target: [10, 7200], + laughMin: [0.01, 1], + mergeGap: [0, 60], + setupMax: [0, 120], + clipMax: [5, 600], +}); + +// ---- roles ------------------------------------------------------------------------ + +/** A host interjection is a turn shorter than this. */ +export const SHORT_TURN_S = 8; +/** The stream is cut into this many bins to measure how widely a voice is spread. */ +export const SPREAD_BINS = 20; +/** A cluster with less than this share of the speech is never the host or the subject by itself. */ +export const MIN_SPEAKER_SHARE = 0.01; +/** Two clusters whose voice centroids are at least this similar are one voice. */ +export const SAME_VOICE_COSINE = 0.6; +export const ROLES = Object.freeze(["host", "subject", "other"]); + +// ---- laughs ----------------------------------------------------------------------- + +/** + * The AudioSet laughter family in CED's 527 classes (class_labels_indices.csv): + * Laughter, Giggle, Snicker, Belly laugh, Chuckle/chortle. 17 (Baby laughter) + * is left out. + */ +export const LAUGH_CLASSES = Object.freeze([16, 18, 19, 20, 21]); +export const SCAN_WINDOW_S = 1; +export const SCAN_HOP_S = 0.5; +/** Two laugh runs closer than this are one laugh. */ +export const LAUGH_BRIDGE_S = 0.5; +/** What a laugh's score is weighted by, by who was talking when it was heard. */ +export const LAUGH_WEIGHT = Object.freeze({ host: 1, none: 0.8, other: 0.6, subject: 0.5, subjectVoice: 0.3 }); +/** A transcript marker's laugh: its score, and the seconds around the word. */ +export const TEXT_LAUGH = Object.freeze({ score: 0.5, before: 0.3, after: 0.7 }); +export const TEXT_LAUGH_RE = /^[[(]?(?:laugh(?:s|ter|ing)?|chuckles?|giggles?)[\])]?$|^(?:ha){2,}h?$|^(?:he){2,}h?$|^l+o+l+$|^lmf?ao+$|^rofl$/i; +/** An energy burst (no model): this far over the stream's median level, with no words in it. */ +export const ENERGY_BURST_DB = 10; +export const ENERGY_LAUGH_SCORE = 0.3; + +// ---- moments and proposals -------------------------------------------------------- + +/** A host comment is a host turn with at least this many seconds of words. */ +export const COMMENT_MIN_WORDS_S = 1.5; +/** A setup is at least this long when the subject was talking longer than that. */ +export const SETUP_MIN_S = 3; +/** The reaction after a laugh runs at most this far past the laugh. */ +export const REACTION_AFTER_LAUGH_S = 12; +/** A comment's reaction is at most this long. */ +export const COMMENT_MAX_S = 45; +/** The tail after the reaction, to the next silence: at most this long. */ +export const TAIL_MAX_S = 1.5; +/** A gap between words this long is a silence an edge can sit in. */ +export const SILENCE_GAP_S = 0.25; +/** A gap this long, or a word ending in . ? ! …, ends a sentence. */ +export const SENTENCE_GAP_S = 0.6; +/** Ranking into the target may run over it by this share. */ +export const TARGET_SLACK = 0.03; +/** A proposal overlapping a clip already in the cut by this share is that clip. */ +export const SAME_CLIP_OVERLAP = 0.5; +/** A proposal shorter than this is widened to it around its moment (snapped); shorter ones are never used. */ +export const CLIP_MIN_S = 5; +/** A proposal scoring under this is never used by the ranking (it stays listed). */ +export const USE_MIN_SCORE = 0.2; +/** A laugh's voice is the host's when its similarity to the host is at least this… */ +export const VOICE_MIN = 0.2; +/** …and at least this much more than to the subject (and the mirror for the subject). */ +export const VOICE_MARGIN = 0.1; + +const round = (x, d = 2) => (Number.isFinite(x) ? Math.round(x * 10 ** d) / 10 ** d : null); +const clamp01 = (x) => Math.max(0, Math.min(1, x)); +const num = (x) => typeof x === "number" && Number.isFinite(x); +const overlap = (a0, a1, b0, b1) => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0)); + +/** + * The params, defaults filled in and every value checked against PARAM_BOUNDS. + * @param {Record<string, unknown>} [given] + * @returns {{ target: number, laughMin: number, mergeGap: number, setupMax: number, clipMax: number }} + */ +export function normalizeParams(given = {}) { + const out = { ...DEFAULT_PARAMS }; + for (const [k, [lo, hi]] of Object.entries(PARAM_BOUNDS)) { + const v = given?.[k]; + if (v === undefined || v === null) continue; + const n = Number(v); + if (!Number.isFinite(n) || n < lo || n > hi) throw new Error(`${k} must be a number from ${lo} to ${hi}, not ${JSON.stringify(v)}`); + out[k] = n; + } + out.scope = normalizeScope(given?.scope); + return out; +} + +/** + * The part of the recording the analysis reads: `[from, to]` seconds, or null + * for the whole of it (release 35: a stream that reacts to two videos is cut + * from one at a time). `to` may be null (to the end). + * @param {unknown} v + * @returns {[number, number | null] | null} + */ +export function normalizeScope(v) { + if (v === undefined || v === null || v === "all") return null; + if (!Array.isArray(v) || v.length !== 2) throw new Error(`scope must be [from, to] in seconds (or null), not ${JSON.stringify(v)}`); + const from = v[0] === null ? 0 : Number(v[0]); + const to = v[1] === null ? null : Number(v[1]); + if (!Number.isFinite(from) || from < 0 || (to !== null && (!Number.isFinite(to) || to <= from))) { + throw new Error(`scope must be [from, to] with 0 ≤ from < to, not ${JSON.stringify(v)}`); + } + if (from === 0 && to === null) return null; + return [from, to]; +} + +// ---- turns ------------------------------------------------------------------------ + +/** + * diarization.json's turns, cleaned: finite, end > start, sorted, 2 dp. + * @param {unknown} turns + * @returns {{ start: number, end: number, speaker: number }[]} + */ +export function cleanTurns(turns) { + if (!Array.isArray(turns)) return []; + return turns + .filter((t) => t && num(t.start) && num(t.end) && t.end > t.start && Number.isInteger(t.speaker) && t.speaker >= 0) + .map((t) => ({ start: round(t.start), end: round(t.end), speaker: t.speaker })) + .sort((a, b) => a.start - b.start || a.end - b.end || a.speaker - b.speaker); +} + +/** + * Per cluster: seconds spoken, turns, turns under SHORT_TURN_S, the share of + * SPREAD_BINS bins of the stream it speaks in, and its mean turn. + * @param {{ start: number, end: number, speaker: number }[]} turns + * @param {number} duration + */ +export function turnStats(turns, duration, from = 0) { + const dur = Math.max((duration || 0) - from, ...turns.map((t) => t.end - from), 1); + /** @type {Map<number, { index: number, seconds: number, turns: number, short: number, bins: Set<number> }>} */ + const by = new Map(); + for (const t of turns) { + let s = by.get(t.speaker); + if (!s) by.set(t.speaker, (s = { index: t.speaker, seconds: 0, turns: 0, short: 0, bins: new Set() })); + const len = t.end - t.start; + s.seconds += len; + s.turns += 1; + if (len < SHORT_TURN_S) s.short += 1; + s.bins.add(Math.max(0, Math.min(SPREAD_BINS - 1, Math.floor(((t.start - from) / dur) * SPREAD_BINS)))); + } + return [...by.values()] + .sort((a, b) => a.index - b.index) + .map((s) => ({ index: s.index, seconds: round(s.seconds, 1), turns: s.turns, short: s.short, spread: round(s.bins.size / SPREAD_BINS, 2), meanTurn: round(s.seconds / s.turns, 2) })); +} + +/** + * Who is who. In order: + * 1. the operator's roles (`operator`: {index: role}) stand; + * 2. the host, if the operator named none: the cluster with the most short + * turns times the widest spread (a reaction stream's host interjects all + * the way through; the narrated video talks in long runs); + * 3. the subject, if the operator named none: the cluster with the most + * seconds among the rest; + * 4. every other cluster is `other`, unless its voice centroid is at least + * SAME_VOICE_COSINE like the host's or the subject's — then it is that + * role too (`sameAs` names the cluster it was merged into). + * Clusters under MIN_SPEAKER_SHARE of the speech never win step 2 or 3. + * + * @param {{ turns: { start: number, end: number, speaker: number }[], duration: number, + * operator?: Record<string, string>, centroids?: Record<string, number[] | null> | null }} o + * @returns {{ index: number, role: "host"|"subject"|"other", label: string, seconds: number, turns: number, how: "auto"|"operator", sameAs?: number }[]} + */ +export function assignRoles({ turns, duration, operator = {}, centroids = null, from = 0 }) { + const stats = turnStats(turns, duration, from); + const total = stats.reduce((n, s) => n + s.seconds, 0) || 1; + const op = new Map(); + for (const [k, v] of Object.entries(operator ?? {})) { + const i = Number(k); + if (Number.isInteger(i) && ROLES.includes(v)) op.set(i, v); + } + const role = new Map(op); + const eligible = (s) => !role.has(s.index) && s.seconds / total >= MIN_SPEAKER_SHARE; + const hasRole = (r) => [...role.values()].includes(r); + if (!hasRole("host")) { + const best = stats.filter(eligible).sort((a, b) => b.short * b.spread - a.short * a.spread || b.turns - a.turns || a.index - b.index)[0]; + if (best) role.set(best.index, "host"); + } + if (!hasRole("subject")) { + const best = stats.filter(eligible).sort((a, b) => b.seconds - a.seconds || a.index - b.index)[0]; + if (best) role.set(best.index, "subject"); + } + /** @type {Map<number, number>} */ + const sameAs = new Map(); + if (centroids) { + const vec = (i) => (Array.isArray(centroids[i]) ? centroids[i] : null); + const anchor = (r) => stats.find((s) => role.get(s.index) === r); + const host = anchor("host"); + const subject = anchor("subject"); + for (const s of stats) { + if (role.has(s.index)) continue; + const v = vec(s.index); + if (!v) continue; + let best = null; + for (const a of [host, subject]) { + const av = a ? vec(a.index) : null; + if (!av) continue; + const c = cosineOf(v, av); + if (c >= SAME_VOICE_COSINE && (!best || c > best.c)) best = { a, c }; + } + if (best) { + role.set(s.index, /** @type {string} */ (role.get(best.a.index))); + sameAs.set(s.index, best.a.index); + } + } + } + return stats.map((s) => { + const r = /** @type {"host"|"subject"|"other"} */ (role.get(s.index) ?? "other"); + return { + index: s.index, + role: r, + label: r === "host" ? "Host" : r === "subject" ? "Subject" : `Speaker ${s.index + 1}`, + seconds: s.seconds, + turns: s.turns, + how: op.has(s.index) ? "operator" : "auto", + ...(sameAs.has(s.index) ? { sameAs: sameAs.get(s.index) } : {}), + }; + }); +} + +function cosineOf(a, b) { + let ab = 0; + let aa = 0; + let bb = 0; + for (let i = 0; i < Math.min(a.length, b.length); i += 1) { + ab += a[i] * b[i]; + aa += a[i] * a[i]; + bb += b[i] * b[i]; + } + return aa > 0 && bb > 0 ? ab / Math.sqrt(aa * bb) : 0; +} + +/** index → role, for the speakers list. */ +export const roleMap = (speakers) => new Map((speakers ?? []).map((s) => [s.index, s.role])); + +// ---- words ------------------------------------------------------------------------ + +/** + * Words from a transcript's cues when there are no word timings: each cue's + * words spread evenly over its span (by length), the first flagged as a + * sentence start (a cue boundary is the nearest thing to one a cue has). + * @param {{ start: number, end: number, text?: string }[]} cues + * @returns {{ w: string, start: number, end: number, cueStart?: true }[]} + */ +export function wordsFromCues(cues) { + const out = []; + for (const c of [...(cues ?? [])].filter((c) => c && num(c.start) && num(c.end) && c.end > c.start).sort((a, b) => a.start - b.start)) { + const ws = String(c.text ?? "").replace(/\s+/g, " ").trim().split(" ").filter(Boolean); + if (!ws.length) continue; + const weights = ws.map((w) => w.length + 1); + const sum = weights.reduce((a, b) => a + b, 0); + let at = c.start; + ws.forEach((w, i) => { + const d = ((c.end - c.start) * weights[i]) / sum; + out.push({ w, start: round(at, 3), end: round(at + d, 3), ...(i === 0 ? { cueStart: /** @type {true} */ (true) } : {}) }); + at += d; + }); + } + return out; +} + +/** + * Word timings, cleaned: `{w, start, end}` with text, finite, sorted. + * @param {unknown} words + */ +export function cleanWords(words) { + if (!Array.isArray(words)) return []; + return words + .filter((w) => w && typeof w.w === "string" && w.w.trim() && num(w.start) && num(w.end) && w.end >= w.start) + .map((w) => ({ w: w.w.trim(), start: w.start, end: w.end, ...(w.cueStart ? { cueStart: true } : {}) })) + .sort((a, b) => a.start - b.start); +} + +/** The index of the first word ending after `t` (binary search). */ +function firstEndingAfter(words, t) { + let lo = 0; + let hi = words.length; + while (lo < hi) { + const m = (lo + hi) >> 1; + if (words[m].end <= t) lo = m + 1; + else hi = m; + } + return lo; +} + +/** The words that overlap [a, b]. */ +export function wordsIn(words, a, b) { + const out = []; + for (let i = firstEndingAfter(words, a); i < words.length && words[i].start < b; i += 1) out.push(words[i]); + return out; +} + +/** Seconds of words inside [a, b] (each word clipped to it). */ +export function wordSeconds(words, a, b) { + return wordsIn(words, a, b).reduce((n, w) => n + overlap(w.start, w.end, a, b), 0); +} + +/** The words of [a, b] as text, at most `max` characters (an ellipsis when cut). */ +export function textIn(words, a, b, max = 200) { + const t = wordsIn(words, a, b).map((w) => w.w).join(" "); + return t.length > max ? `${t.slice(0, max - 1).replace(/\s+\S*$/, "")}…` : t; +} + +/** Where sentences start: a cue's first word, a word after . ? ! …, a word after a SENTENCE_GAP_S pause. */ +export function sentenceStarts(words) { + const out = []; + words.forEach((w, i) => { + const prev = words[i - 1]; + if (!prev || w.cueStart || /[.?!…]["')\]]*$/.test(prev.w) || w.start - prev.end >= SENTENCE_GAP_S) out.push(w.start); + }); + return out; +} + +/** + * An edge snapped to the words: a start inside a word moves to that word's + * start, then back into the gap before it (half the gap, at most 0.15 s); an + * end inside a word moves to that word's end, then into the gap after it. + * An edge already in a gap stays. + */ +export function snapEdge(words, t, side) { + const i = firstEndingAfter(words, t); + const w = words[i]; + if (side === "start") { + if (!w || w.start >= t) return t; + const prev = words[i - 1]; + const gap = prev ? w.start - prev.end : 0.3; + return round(Math.max(0, w.start - Math.min(0.15, Math.max(0, gap) / 2)), 3); + } + // An end: the word that contains t (it starts before t and ends after it). + if (!w || w.start >= t) return t; + const next = words[i + 1]; + const gap = next ? next.start - w.end : 0.3; + return round(w.end + Math.min(0.15, Math.max(0, gap) / 2), 3); +} + +/** + * The tail after a reaction: to the first silence (a SILENCE_GAP_S gap + * between words) within TAIL_MAX_S, sitting a little into it; no words at + * the end at all: a short pad. Else the end + TAIL_MAX_S, snapped. + */ +export function tailEnd(words, end) { + const i = firstEndingAfter(words, end - 0.05); + const w = words[i]; + if (!w || w.start > end + TAIL_MAX_S) return round(end + Math.min(0.3, TAIL_MAX_S), 3); + for (let k = Math.max(0, i); k < words.length && words[k].end <= end + TAIL_MAX_S; k += 1) { + const next = words[k + 1]; + const gap = next ? next.start - words[k].end : Infinity; + if (gap >= SILENCE_GAP_S && words[k].end >= end - 0.05) return round(words[k].end + Math.min(0.2, gap / 2), 3); + } + return snapEdge(words, end + TAIL_MAX_S, "end"); +} + +// ---- laughs ----------------------------------------------------------------------- + +/** + * The laugh score of one window: the family's probabilities summed, at most 1 + * (CED's outputs are independent per class, so a sum can pass 1). + * @param {number[] | Record<string, number>} probs by class index, or the family's in LAUGH_CLASSES order + */ +export function laughScore(probs) { + if (Array.isArray(probs)) return clamp01(probs.reduce((a, b) => a + (num(b) ? b : 0), 0)); + return clamp01(LAUGH_CLASSES.reduce((a, c) => a + (num(probs?.[c]) ? probs[c] : 0), 0)); +} + +/** + * Laugh events from per-window scores: runs of windows at or over `laughMin`, + * runs closer than LAUGH_BRIDGE_S joined; an event's score is its windows' + * mean, its span from its first window's start to its last window's end. + * @param {{ t0?: number, hop?: number, window?: number, scores: number[] }} w + * @param {{ laughMin?: number }} [o] + * @returns {{ start: number, end: number, score: number }[]} + */ +export function laughEvents(w, { laughMin = DEFAULT_PARAMS.laughMin } = {}) { + const t0 = w.t0 ?? 0; + const hop = w.hop ?? SCAN_HOP_S; + const win = w.window ?? SCAN_WINDOW_S; + const runs = []; + let open = null; + (w.scores ?? []).forEach((s, i) => { + if (num(s) && s >= laughMin) { + if (!open) open = { a: i, b: i, sum: 0, n: 0 }; + open.b = i; + open.sum += s; + open.n += 1; + } else if (open) { + runs.push(open); + open = null; + } + }); + if (open) runs.push(open); + const events = runs.map((r) => ({ start: t0 + r.a * hop, end: t0 + r.b * hop + win, sum: r.sum, n: r.n })); + const merged = []; + for (const e of events) { + const last = merged[merged.length - 1]; + if (last && e.start - last.end <= LAUGH_BRIDGE_S) { + last.end = e.end; + last.sum += e.sum; + last.n += e.n; + } else merged.push({ ...e }); + } + return merged.map((e) => ({ start: round(e.start), end: round(e.end), score: round(e.sum / e.n, 3) })); +} + +/** + * Laughs from the transcript (no model): a word that is a laugh marker + * (`[laughter]`, `haha`, `lol`, `lmao`…), as an event around the word. + * @param {{ w: string, start: number, end: number }[]} words + */ +export function textLaughs(words) { + const out = []; + for (const w of words) { + const bare = w.w.replace(/[.,!?;:"'…]+$/g, "").replace(/^["']+/, ""); + if (!TEXT_LAUGH_RE.test(bare)) continue; + const e = { start: round(Math.max(0, w.start - TEXT_LAUGH.before)), end: round(w.end + TEXT_LAUGH.after), score: TEXT_LAUGH.score, src: "text" }; + const last = out[out.length - 1]; + if (last && e.start - last.end <= LAUGH_BRIDGE_S) last.end = e.end; + else out.push(e); + } + return out; +} + +/** + * Laughs from the sound alone (no model): runs of windows ENERGY_BURST_DB + * over the stream's median level that hold no words and fall in a host turn + * or in no turn at all — the host laughing between lines. + * @param {{ t0?: number, hop?: number, window?: number, energy: number[] }} scan + * @param {{ words: { start: number, end: number }[], turns: { start: number, end: number, speaker: number }[], speakers: { index: number, role: string }[] }} o + */ +export function energyLaughs(scan, { words, turns, speakers }) { + const levels = (scan.energy ?? []).filter(num); + if (!levels.length) return []; + const sorted = [...levels].sort((a, b) => a - b); + const median = sorted[Math.floor(sorted.length / 2)]; + const bar = median + ENERGY_BURST_DB; + const roles = roleMap(speakers); + const hop = scan.hop ?? SCAN_HOP_S; + const win = scan.window ?? SCAN_WINDOW_S; + const t0 = scan.t0 ?? 0; + const scores = (scan.energy ?? []).map((db, i) => { + if (!num(db) || db < bar) return 0; + const a = t0 + i * hop; + const b = a + win; + if (wordsIn(words, a, b).length) return 0; + const who = turns.filter((t) => overlap(t.start, t.end, a, b) > 0).map((t) => roles.get(t.speaker)); + return who.length === 0 || who.includes("host") ? 1 : 0; + }); + return laughEvents({ t0, hop, window: win, scores }, { laughMin: 0.5 }).map((e) => ({ ...e, score: ENERGY_LAUGH_SCORE, src: "energy" })); +} + +/** + * Who laughed: a host turn that overlaps the laugh makes it the host's (the + * host laughs over the video he reacts to); else the cluster that overlaps it + * most; else nobody (null). + * @template {{ start: number, end: number }} L + * @param {L[]} laughs + * @param {{ start: number, end: number, speaker: number }[]} turns + * @param {{ index: number, role: string }[]} speakers + * @returns {(L & { speaker: number | null })[]} + */ +export function attributeLaughs(laughs, turns, speakers) { + const roles = roleMap(speakers); + return laughs.map((l) => { + const by = new Map(); + for (const t of turns) { + if (t.start >= l.end) break; + const o = overlap(t.start, t.end, l.start, l.end); + if (o > 0) by.set(t.speaker, (by.get(t.speaker) ?? 0) + o); + } + const host = [...by.keys()].filter((i) => roles.get(i) === "host").sort((a, b) => by.get(b) - by.get(a) || a - b)[0]; + const most = [...by.keys()].sort((a, b) => by.get(b) - by.get(a) || a - b)[0]; + return { ...l, speaker: host ?? most ?? null }; + }); +} + +// ---- moments ---------------------------------------------------------------------- + +const roleOf = (roles, speaker) => (speaker === null || speaker === undefined ? "none" : roles.get(speaker) ?? "other"); + +/** + * The moments: every laugh (score = its strength × its length, squashed to + * 0..1, weighted by who laughed — LAUGH_WEIGHT), and every host turn with at + * least COMMENT_MIN_WORDS_S of words (score: half its length, half the + * strongest laugh around it). Chronological, ids m001…. + * @param {{ turns: { start: number, end: number, speaker: number }[], speakers: { index: number, role: string }[], + * laughs: { start: number, end: number, score: number, speaker: number | null }[], words: { w: string, start: number, end: number }[] }} o + * @returns {{ id: string, t: number, end: number, kind: "laugh"|"comment", score: number, speaker: number | null, text: string }[]} + */ +export function findMoments({ turns, speakers, laughs, words }) { + const roles = roleMap(speakers); + const laughMoments = laughs.map((l) => { + const raw = l.score * (l.end - l.start); + const who = roleOf(roles, l.speaker); + const weight = who === "subject" && l.by === "voice" ? LAUGH_WEIGHT.subjectVoice : LAUGH_WEIGHT[who]; + const score = (1 - Math.exp(-raw / 1.5)) * weight; + return { t: l.start, end: l.end, kind: /** @type {const} */ ("laugh"), score: round(score, 3), speaker: l.speaker }; + }); + const comments = []; + for (const t of turns) { + if (roles.get(t.speaker) !== "host") continue; + const ws = wordSeconds(words, t.start, t.end); + if (ws < COMMENT_MIN_WORDS_S) continue; + const near = laughMoments.filter((m) => m.end >= t.start - 2 && m.t <= t.end + 3).reduce((a, m) => Math.max(a, m.score), 0); + const score = 0.5 * Math.min(1, ws / 10) + 0.5 * near; + comments.push({ t: t.start, end: Math.min(t.end, t.start + COMMENT_MAX_S), kind: /** @type {const} */ ("comment"), score: round(score, 3), speaker: t.speaker }); + } + const all = [...laughMoments, ...comments].sort((a, b) => a.t - b.t || (a.kind === "laugh" ? -1 : 1)); + const pad = Math.max(3, String(all.length).length); + return all.map((m, i) => ({ + id: `m${String(i + 1).padStart(pad, "0")}`, + t: round(m.t), + end: round(m.end), + kind: m.kind, + score: m.score, + speaker: m.speaker, + text: m.kind === "laugh" ? textIn(words, m.t - 6, m.end + 1) : textIn(words, m.t, m.end), + })); +} + +// ---- proposals -------------------------------------------------------------------- + +const fmtS = (s) => `${round(s, 1)} s`; + +/** + * One moment's clip, before merging: the setup, the reaction, the tail. + * setup: the last subject turn that started before the moment and was still + * going within `setupMax` of it — from the latest sentence start that + * leaves at least SETUP_MIN_S of it, never earlier than `setupMax` before + * the moment; no subject turn: the host's own turn start (a comment) or 2 s + * before (a laugh); + * reaction: to the end of the host turn the laugh is in (at most + * REACTION_AFTER_LAUGH_S past the laugh) — or the comment's end; + * tail: to the next silence (tailEnd). + */ +export function momentSpan(m, { turns, speakers, words, sentences, setupMax, duration }) { + const roles = roleMap(speakers); + const t = m.t; + let setupStart = null; + let setupBy = null; + let subj = null; + for (const turn of turns) { + if (turn.start >= t) break; + if (roles.get(turn.speaker) === "subject" && turn.end > t - setupMax) subj = turn; + } + if (subj) { + const lo = Math.max(subj.start, t - setupMax); + if (subj.start > t - SETUP_MIN_S) setupStart = subj.start; + else { + const starts = sentences.filter((s) => s >= lo && s <= t - SETUP_MIN_S); + setupStart = starts.length ? starts[starts.length - 1] : lo; + } + setupBy = "subject"; + } else if (m.kind === "comment") setupStart = t; + else { + const own = turns.find((x) => x.start <= t && x.end > t && roles.get(x.speaker) === "host"); + setupStart = own && own.start > t - setupMax ? Math.min(own.start, t - 0.5) : t - 2; + } + let reactionEnd = m.end; + if (m.kind === "laugh") { + const host = turns.filter((x) => roles.get(x.speaker) === "host" && overlap(x.start, x.end, m.t, m.end) > 0); + const turnEnd = host.reduce((a, x) => Math.max(a, x.end), m.end); + reactionEnd = Math.min(turnEnd, m.end + REACTION_AFTER_LAUGH_S); + } + const start = Math.max(0, snapEdge(words, Math.max(0, setupStart), "start")); + const end = Math.min(duration || Infinity, tailEnd(words, reactionEnd)); + return { start: round(start), end: round(Math.max(end, start + 0.5)), setupBy, setupSeconds: round(t - start, 1) }; +} + +/** Plain words for why a moment is a clip. */ +export function momentWhy(m, span) { + const who = m.kind === "laugh" ? (m.speakerRole === "host" ? "host laughs" : m.speakerRole === "subject" ? "laughter under the narration" : "laughter") : "host comments"; + if (m.kind === "laugh") { + const len = fmtS(m.end - m.t); + return span.setupBy === "subject" ? `${who} (${len}) ${fmtS(span.setupSeconds)} after the narrated line` : `${who} for ${len}`; + } + return span.setupBy === "subject" ? `${who} for ${fmtS(m.end - m.t)} on the narrated line` : `${who} for ${fmtS(m.end - m.t)}`; +} + +/** + * The proposals: one span per moment (momentSpan), then merged — overlapping + * spans always, spans closer than `mergeGap` while the whole stays within + * `clipMax` — then each capped at `clipMax` (kept: the end, and the start of + * the latest sentence that fits). Score: the best moment's, plus a tenth of + * each other's, at most 1. Chronological, ids not yet given. + * @returns {{ start: number, end: number, score: number, moments: string[], why: string }[]} + */ +export function buildProposals({ moments, turns, speakers, words, duration, params }) { + const p = normalizeParams(params); + const roles = roleMap(speakers); + const sentences = sentenceStarts(words); + const spans = moments + .map((m) => { + const span = momentSpan(m, { turns, speakers, words, sentences, setupMax: p.setupMax, duration }); + return { start: span.start, end: span.end, best: m.score, scores: [m.score], moments: [m.id], whys: [momentWhy({ ...m, speakerRole: roleOf(roles, m.speaker) }, span)] }; + }) + .sort((a, b) => a.start - b.start || a.end - b.end); + const merged = []; + for (const s of spans) { + const last = merged[merged.length - 1]; + const joined = last ? Math.max(last.end, s.end) - last.start : Infinity; + if (last && (s.start < last.end || (s.start - last.end < p.mergeGap && joined <= p.clipMax))) { + last.end = Math.max(last.end, s.end); + last.scores.push(...s.scores); + last.moments.push(...s.moments); + if (s.best > last.best) { + last.best = s.best; + last.whys.unshift(...s.whys); + } else last.whys.push(...s.whys); + } else merged.push({ ...s, scores: [...s.scores], moments: [...s.moments], whys: [...s.whys] }); + } + return merged.map((m) => { + let { start, end } = m; + if (end - start > p.clipMax) { + const from = end - p.clipMax; + const fit = sentences.find((t) => t >= from && t < end - 1); + start = fit !== undefined ? fit : from; + start = snapEdge(words, start, "start"); + if (end - start > p.clipMax) start = end - p.clipMax; + } + if (end - start < CLIP_MIN_S) ({ start, end } = widenTo(words, start, end, CLIP_MIN_S, duration)); + const sorted = [...m.scores].sort((a, b) => b - a); + const score = clamp01(sorted[0] + 0.1 * sorted.slice(1).reduce((a, b) => a + b, 0)); + const whys = [...new Set(m.whys)]; + return { + start: round(start), + end: round(end), + score: round(score, 3), + moments: m.moments, + why: whys.slice(0, 2).join("; ") + (whys.length > 2 ? ` (+${whys.length - 2} more)` : ""), + }; + }); +} + +/** + * A span shorter than `min` widened to it about its middle, inside [0, + * duration], each edge snapped into the gap between words (outward). + */ +export function widenTo(words, start, end, min, duration = Infinity) { + const lim = Number.isFinite(duration) && duration > 0 ? duration : Infinity; + const mid = (start + end) / 2; + let a = Math.max(0, mid - min / 2); + let b = Math.min(lim, a + min); + a = Math.max(0, b - min); + a = Math.min(start, snapEdge(words, a, "start")); + b = Math.max(end, Math.min(lim, snapEdge(words, b, "end"))); + return { start: round(a), end: round(b) }; +} + +/** + * Ids that stay put across a re-proposal: a proposal overlapping a previous + * one by at least half (of the longer of the two) takes its id; the rest get + * the next free numbers, chronologically. + * @template {{ start: number, end: number }} P + * @param {P[]} proposals chronological + * @param {{ id: string, start: number, end: number }[]} [previous] + * @returns {(P & { id: string })[]} + */ +export function stableIds(proposals, previous = []) { + const taken = new Set(); + const prev = (previous ?? []).filter((q) => q && typeof q.id === "string" && num(q.start) && num(q.end)); + let next = prev.reduce((n, q) => Math.max(n, Number(/^p(\d+)$/.exec(q.id)?.[1] ?? 0)), 0); + const out = proposals.map((p) => { + let best = null; + for (const q of prev) { + if (taken.has(q.id)) continue; + const o = overlap(p.start, p.end, q.start, q.end) / Math.max(p.end - p.start, q.end - q.start, 1e-9); + if (o >= 0.5 && (!best || o > best.o)) best = { q, o }; + } + if (best) { + taken.add(best.q.id); + return { ...p, id: best.q.id }; + } + return { ...p, id: "" }; + }); + const width = Math.max(3, String(next + out.filter((p) => !p.id).length).length); + for (const p of out) { + if (!p.id) { + next += 1; + p.id = `p${String(next).padStart(width, "0")}`; + } + } + return out; +} + +/** + * Which proposals the cut uses: the seconds of the clips already in it that + * the analysis may not move (`fixed`, the operator's) count first; a proposal + * overlapping one of them by SAME_CLIP_OVERLAP is that clip (used, its + * `clipId`); then the rest by score (then time), each taken while the total + * stays within `target` (+ TARGET_SLACK). Everything comes back, chronological, + * with `used`. + * @template {{ id: string, start: number, end: number, score: number }} P + * @param {P[]} proposals + * @param {{ target: number, fixed?: { id: string, start: number, end: number }[] }} o + * @returns {(P & { used: boolean, fixedClip?: string })[]} + */ +export function rankIntoTarget(proposals, { target, fixed = [] }) { + let total = fixed.reduce((n, c) => n + Math.max(0, c.end - c.start), 0); + const limit = target * (1 + TARGET_SLACK); + /** @type {Map<string, { used: boolean, fixedClip?: string }>} */ + const state = new Map(); + for (const p of proposals) { + const hit = fixed.find((c) => { + const o = overlap(p.start, p.end, c.start, c.end); + return o >= SAME_CLIP_OVERLAP * (p.end - p.start) || o >= SAME_CLIP_OVERLAP * (c.end - c.start); + }); + if (hit) state.set(p.id, { used: true, fixedClip: hit.id }); + } + const order = proposals.filter((p) => !state.has(p.id)).sort((a, b) => b.score - a.score || a.start - b.start); + for (const p of order) { + const d = p.end - p.start; + if (d < CLIP_MIN_S - 0.01 || p.score < USE_MIN_SCORE) state.set(p.id, { used: false }); + else if (total + d <= limit) { + total += d; + state.set(p.id, { used: true }); + } else state.set(p.id, { used: false }); + } + return proposals.map((p) => ({ ...p, ...state.get(p.id) })); +} + +// ---- the whole analysis ----------------------------------------------------------- + +/** + * Everything from the inputs to `reactions.json`'s body (no clip ids yet: + * those are the manifest's, given by the caller). Laughs: the model's windows + * when there are any (`laughScan.scores`); else transcript markers plus the + * host's energy bursts (`laughScan.energy`), when there is a scan. + * + * @param {{ turns: unknown, duration: number, words: unknown, params?: Record<string, unknown>, + * operator?: Record<string, string>, centroids?: Record<string, number[] | null> | null, + * laughScan?: { t0?: number, hop?: number, window?: number, scores?: number[] | null, energy?: number[] | null } | null, + * previous?: { id: string, start: number, end: number }[], fixed?: { id: string, start: number, end: number }[] }} o + */ +export function analyze(o) { + const params = normalizeParams(o.params); + const whole = Math.max(Number(o.duration) || 0, cleanTurns(o.turns).at(-1)?.end ?? 0); + const from = params.scope ? params.scope[0] : 0; + const to = params.scope ? Math.min(params.scope[1] ?? whole, whole) : whole; + const inScope = (a, b) => a >= from - 1e-9 && b <= to + 1e-9; + // Turns cut to the scope; words and laugh windows wholly inside it. + const turns = cleanTurns(o.turns) + .filter((t) => t.end > from && t.start < to) + .map((t) => ({ ...t, start: Math.max(t.start, from), end: Math.min(t.end, to) })) + .filter((t) => t.end - t.start > 0.01); + const words = cleanWords(o.words).filter((w) => inScope(w.start, w.end)); + const duration = to; + const speakers = assignRoles({ turns, duration, operator: o.operator ?? {}, centroids: o.centroids ?? null, from }); + const scan = scopeScan(o.laughScan ?? null, from, to); + let laughsRaw; + let laughSource; + if (scan && Array.isArray(scan.scores) && scan.scores.length) { + laughsRaw = laughEvents({ t0: scan.t0, hop: scan.hop, window: scan.window, scores: scan.scores }, { laughMin: params.laughMin }).map((e) => ({ ...e, src: "model" })); + laughSource = "model"; + } else { + const fromText = textLaughs(words); + const fromEnergy = scan && Array.isArray(scan.energy) ? energyLaughs(/** @type {any} */ (scan), { words, turns, speakers }) : []; + laughsRaw = [...fromText, ...fromEnergy].sort((a, b) => a.start - b.start); + laughSource = fromEnergy.length || (scan && Array.isArray(scan.energy)) ? "text+energy" : "text"; + } + const laughs = voiceLaughs(attributeLaughs(laughsRaw, turns, speakers), speakers, o.centroids ?? null, o.laughVoices ?? null); + const moments = findMoments({ turns, speakers, laughs, words }); + const built = buildProposals({ moments, turns, speakers, words, duration, params }); + const withIds = stableIds(built, o.previous ?? []); + const ranked = rankIntoTarget(withIds, { target: params.target, fixed: o.fixed ?? [] }); + return { + params, + duration: round(duration), + laughSource, + speakers, + turns, + laughs: laughs.map((l) => ({ + start: l.start, end: l.end, score: l.score, speaker: l.speaker, + ...(l.src && l.src !== "model" ? { src: l.src } : {}), + ...(l.voice ? { voice: l.voice } : {}), + ...(l.by === "voice" ? { by: "voice" } : {}), + })), + moments, + proposals: ranked, + }; +} + +/** A laugh's key in a cache of laugh voices: its span, 2 dp. */ +export const laughKey = (l) => `${Number(l.start).toFixed(2)}-${Number(l.end).toFixed(2)}`; + +/** The seconds embedded for a laugh's voice: at least 1.5 s (at most 8), centred on it. */ +export function laughVoiceSpan(l) { + const d = Math.min(8, Math.max(1.5, l.end - l.start)); + return { start: Math.max(0, (l.start + l.end) / 2 - d / 2), dur: d }; +} + +/** The laugh scan's windows wholly inside [from, to]. */ +function scopeScan(scan, from, to) { + if (!scan) return null; + const t0 = scan.t0 ?? 0; + const hop = scan.hop ?? SCAN_HOP_S; + const win = scan.window ?? SCAN_WINDOW_S; + const len = Math.max(scan.scores?.length ?? 0, scan.energy?.length ?? 0); + const a = Math.max(0, Math.ceil((from - t0) / hop - 1e-9)); + const b = Math.min(len, Math.floor((to - win - t0) / hop + 1e-9) + 1); + if (a === 0 && b >= len) return scan; + const cut = (arr) => (Array.isArray(arr) ? arr.slice(a, Math.max(a, b)) : arr); + return { ...scan, t0: t0 + a * hop, scores: cut(scan.scores), energy: cut(scan.energy) }; +} + +/** + * Who laughed, by the voice (release 35, the live case: a narrated video's + * voice-acted laughs read as the host's by turn overlap, and the host laughing + * over a narrated line read as the subject's). With an embedding of the laugh + * (`laughVoices`, by laughKey) and the host's and subject's voice centroids, + * each laugh gets `voice: {host, subject}` (cosines, 3 dp) and is the host's + * when host ≥ VOICE_MIN and host − subject ≥ VOICE_MARGIN, the subject's on the + * mirror (`by: "voice"`); else the overlap rule's answer stands. + */ +export function voiceLaughs(laughs, speakers, centroids, laughVoices) { + if (!centroids || !laughVoices) return laughs; + const pick = (role) => speakers.filter((s) => s.role === role && Array.isArray(centroids[s.index])).sort((a, b) => b.seconds - a.seconds)[0]; + const host = pick("host"); + const subject = pick("subject"); + if (!host || !subject) return laughs; + const H = centroids[host.index]; + const S = centroids[subject.index]; + const get = (k) => (laughVoices instanceof Map ? laughVoices.get(k) : laughVoices[k]); + return laughs.map((l) => { + const v = get(laughKey(l)); + if (!Array.isArray(v)) return l; + const vh = round(cosineOf(v, H), 3); + const vs = round(cosineOf(v, S), 3); + const out = { ...l, voice: { host: vh, subject: vs } }; + if (vh >= VOICE_MIN && vh - vs >= VOICE_MARGIN) return { ...out, speaker: host.index, by: "voice" }; + if (vs >= VOICE_MIN && vs - vh >= VOICE_MARGIN) return { ...out, speaker: subject.index, by: "voice" }; + return out; + }); +} diff --git a/common/lib/clips/clips.test.ts b/common/lib/clips/clips.test.ts @@ -0,0 +1,420 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + CLIP_MIN_S, + DEFAULT_PARAMS, + USE_MIN_SCORE, + analyze, + laughKey, + laughVoiceSpan, + normalizeScope, + voiceLaughs, + widenTo, + assignRoles, + attributeLaughs, + buildProposals, + cleanTurns, + cleanWords, + energyLaughs, + findMoments, + laughEvents, + laughScore, + normalizeParams, + rankIntoTarget, + sentenceStarts, + snapEdge, + stableIds, + tailEnd, + textIn, + textLaughs, + turnStats, + wordsFromCues, +} from "./clips.mjs"; +import { applyProposals, clipFromProposal, fixedClips, isAssistantClip, validateAssist } from "./assist.mjs"; +import { REACTIONS_FILE, operatorRoles, readReactions, setSpeakerRole, writeReactions } from "./reactions.mjs"; +import { HOST, LAUGHS, SUBJECT, reactionStream } from "../../testing/clips/reactionStream.mjs"; + +const tmp = () => mkdtempSync(path.join(os.tmpdir(), "clips-")); + +test("normalizeParams: the defaults, a value inside its bounds, a refusal outside them", () => { + assert.deepEqual(normalizeParams(), { ...DEFAULT_PARAMS }); + assert.equal(normalizeParams({ target: 300, laughMin: null }).target, 300); + assert.throws(() => normalizeParams({ target: 2 }), /target must be a number from 10/); + assert.throws(() => normalizeParams({ laughMin: "x" }), /laughMin/); +}); + +test("turnStats + assignRoles: the host is the cluster of short turns spread across the stream, not the one with the most seconds", () => { + const s = reactionStream(); + const stats = turnStats(s.turns, s.duration); + const host = stats.find((x) => x.index === HOST); + const subject = stats.find((x) => x.index === SUBJECT); + assert.ok(host && subject); + assert.equal(host.short, 7); + assert.equal(subject.short, 0); + assert.ok(subject.seconds > host.seconds); + const roles = assignRoles({ turns: s.turns, duration: s.duration }); + assert.deepEqual(roles.map((r) => [r.index, r.role, r.label, r.how]), [ + [0, "host", "Host", "auto"], + [1, "subject", "Subject", "auto"], + ]); +}); + +test("assignRoles: the operator's word stands; a tiny cluster never wins; a split voice merges by its centroid", () => { + const s = reactionStream(); + // The operator says cluster 1 is the host: cluster 0 becomes the subject. + const flipped = assignRoles({ turns: s.turns, duration: s.duration, operator: { 1: "host" } }); + assert.deepEqual(flipped.map((r) => [r.index, r.role, r.how]), [ + [0, "subject", "auto"], + [1, "host", "operator"], + ]); + // A third cluster: two short turns (a sliver of the speech) — never the host by itself. + const turns = [...s.turns, { start: 41, end: 42, speaker: 2 }, { start: 300, end: 301, speaker: 2 }]; + const three = assignRoles({ turns, duration: s.duration }); + assert.equal(three.find((r) => r.index === 2)?.role, "other"); + assert.equal(three.find((r) => r.index === 2)?.label, "Speaker 3"); + // …unless its voice is the host's: then it is the host too, sameAs 0. + const merged = assignRoles({ turns, duration: s.duration, centroids: { 0: [1, 0, 0], 1: [0, 1, 0], 2: [0.9, 0.1, 0.05] } }); + assert.deepEqual(merged.find((r) => r.index === 2), { index: 2, role: "host", label: "Host", seconds: 2, turns: 2, how: "auto", sameAs: 0 }); + const apart = assignRoles({ turns, duration: s.duration, centroids: { 0: [1, 0, 0], 1: [0, 1, 0], 2: [0.3, 0.3, 0.9] } }); + assert.equal(apart.find((r) => r.index === 2)?.role, "other"); +}); + +test("cleanTurns drops broken turns and sorts; wordsFromCues spreads a cue's words over it, the first a sentence start", () => { + assert.deepEqual(cleanTurns([{ start: 5, end: 4, speaker: 0 }, { start: 2, end: 3.456, speaker: 1 }, { start: 1, end: 2, speaker: 0 }, { start: 1, end: 2 }]), [ + { start: 1, end: 2, speaker: 0 }, + { start: 2, end: 3.46, speaker: 1 }, + ]); + const w = wordsFromCues([{ start: 10, end: 12, text: "aa bb" }, { start: 12, end: 13, text: " " }]); + assert.deepEqual(w, [ + { w: "aa", start: 10, end: 11, cueStart: true }, + { w: "bb", start: 11, end: 12 }, + ]); + assert.deepEqual(sentenceStarts(cleanWords(w)), [10]); +}); + +test("sentenceStarts, snapEdge, tailEnd: edges sit in the gaps between words, a tail ends in the next silence", () => { + const words = cleanWords([ + { w: "one", start: 0, end: 0.4 }, + { w: "two.", start: 0.5, end: 0.9 }, + { w: "three", start: 1.0, end: 1.4 }, + { w: "four", start: 2.2, end: 2.6 }, + { w: "five", start: 2.7, end: 3.1 }, + ]); + assert.deepEqual(sentenceStarts(words), [0, 1.0, 2.2]); + assert.equal(snapEdge(words, 1.2, "start"), 0.95); // inside "three": its start, half the 0.1 gap back + assert.equal(snapEdge(words, 1.7, "start"), 1.7); // in a gap: stays + assert.equal(snapEdge(words, 1.2, "end"), 1.55); // the end of "three", 0.15 into the long gap + assert.equal(tailEnd(words, 0.6), 1.6); // the silence after "three" + assert.equal(tailEnd(words, 5), 5.3); // no words after: a short pad + assert.equal(textIn(words, 0.45, 1.5), "two. three"); + assert.equal(textIn(words, 0, 4, 12), "one two.…"); +}); + +test("laughScore sums the family (at most 1); laughEvents joins runs over the bar", () => { + assert.equal(laughScore([0.5, 0.4, 0.3]), 1); + assert.equal(laughScore({ 16: 0.2, 21: 0.1, 17: 0.9 }), 0.30000000000000004); + const ev = laughEvents({ t0: 10, hop: 0.5, window: 1, scores: [0, 0.3, 0.5, 0.1, 0.4, 0, 0, 0, 0.9] }, { laughMin: 0.25 }); + // windows 1-2 (10.5–12), 4 (12–13: within the bridge, joined), 8 (14–15) + assert.deepEqual(ev, [ + { start: 10.5, end: 13, score: 0.4 }, + { start: 14, end: 15, score: 0.9 }, + ]); +}); + +test("textLaughs finds the markers; energyLaughs finds wordless loud bursts in the host's turns only", () => { + const words = cleanWords([ + { w: "[laughter]", start: 5, end: 6 }, + { w: "hahaha!", start: 6.2, end: 6.8 }, + { w: "lol", start: 20, end: 20.3 }, + { w: "hello", start: 30, end: 30.4 }, + { w: "phaha", start: 40, end: 40.4 }, + ]); + assert.deepEqual(textLaughs(words), [ + { start: 4.7, end: 7.5, score: 0.5, src: "text" }, + { start: 19.7, end: 21, score: 0.5, src: "text" }, + ]); + const energy = new Array(40).fill(-40); + energy[4] = -20; // 2–3 s: wordless, in the host's turn + energy[10] = -20; // 5–6 s: in the subject's turn + energy[20] = -20; // 10–11 s: but a word is there + const turns = [{ start: 0, end: 4, speaker: 0 }, { start: 4, end: 20, speaker: 1 }]; + const speakers = [{ index: 0, role: "host" }, { index: 1, role: "subject" }]; + const got = energyLaughs({ t0: 0, hop: 0.5, window: 1, energy }, { words: cleanWords([{ w: "x", start: 10.2, end: 10.5 }]), turns, speakers }); + assert.deepEqual(got, [{ start: 2, end: 3, score: 0.3, src: "energy" }]); +}); + +test("attributeLaughs: a host turn that overlaps makes it the host's; else the most overlap; else nobody", () => { + const turns = [{ start: 0, end: 10, speaker: 1 }, { start: 9, end: 11, speaker: 0 }, { start: 20, end: 30, speaker: 2 }]; + const speakers = [{ index: 0, role: "host" }, { index: 1, role: "subject" }, { index: 2, role: "other" }]; + const got = attributeLaughs([{ start: 5, end: 9.5 }, { start: 2, end: 3 }, { start: 15, end: 16 }, { start: 25, end: 26 }], turns, speakers); + assert.deepEqual(got.map((l) => l.speaker), [0, 1, null, 2]); +}); + +test("findMoments: host laughs and host comments, scored; a comment needs 1.5 s of words", () => { + const s = reactionStream(); + const speakers = assignRoles({ turns: s.turns, duration: s.duration }); + const laughs = attributeLaughs(laughEvents(s.laughScan, { laughMin: 0.25 }), s.turns, speakers); + const moments = findMoments({ turns: s.turns, speakers, laughs, words: cleanWords(s.words) }); + assert.equal(moments.filter((m) => m.kind === "laugh").length, LAUGHS.length); + assert.equal(moments.filter((m) => m.kind === "comment").length, 7); + assert.deepEqual(moments.map((m) => m.id).slice(0, 3), ["m001", "m002", "m003"]); + const strong = moments.find((m) => m.kind === "laugh" && m.t === 94.5); + const weak = moments.find((m) => m.kind === "laugh" && m.t === 519.5); + assert.ok(strong && weak && strong.score > weak.score); + // A comment beside a laugh outranks one with none. + const near = moments.find((m) => m.kind === "comment" && m.t === 95); + const plain = moments.find((m) => m.kind === "comment" && m.t === 170); + assert.ok(near && plain && near.score > plain.score); + // No words in a host turn: no comment. + const quiet = findMoments({ turns: [{ start: 0, end: 5, speaker: 0 }], speakers: [{ index: 0, role: "host" }], laughs: [], words: [] }); + assert.deepEqual(quiet, []); +}); + +test("buildProposals: the setup starts on a sentence of the subject's line, the reaction and tail follow, near spans merge", () => { + const s = reactionStream(); + const words = cleanWords(s.words); + const speakers = assignRoles({ turns: s.turns, duration: s.duration }); + const laughs = attributeLaughs(laughEvents(s.laughScan, { laughMin: 0.25 }), s.turns, speakers); + const moments = findMoments({ turns: s.turns, speakers, laughs, words }); + const props = buildProposals({ moments, turns: s.turns, speakers, words, duration: s.duration, params: {} }); + const p = props.find((x) => x.moments.includes("m002")); + assert.ok(p); + // The laugh at 94.5 merged with the comment at 95 (they overlap). + assert.deepEqual(p.moments, ["m002", "m003"]); + // The setup: the latest sentence start at least 3 s before the laugh, in the gap before a word. + assert.ok(p.start >= 94.5 - DEFAULT_PARAMS.setupMax && p.start <= 94.5 - 3, `start ${p.start}`); + assert.ok(sentenceStarts(words).some((t) => Math.abs(t - 0.05 - p.start) < 0.11), `start ${p.start} on a sentence`); + assert.ok(p.end > 100 && p.end <= 100 + 1.5 + 0.2, `end ${p.end}`); + assert.match(p.why, /^host laughs \(3\.5 s\) .* after the narrated line/); + // A tight clipMax splits nothing into overlong clips. + const capped = buildProposals({ moments, turns: s.turns, speakers, words, duration: s.duration, params: { clipMax: 8, mergeGap: 60 } }); + assert.ok(capped.every((x) => x.end - x.start <= 8 + 1e-9), JSON.stringify(capped.map((x) => x.end - x.start))); + // A wide merge gap joins close spans while they fit clipMax. + const wide = buildProposals({ moments, turns: s.turns, speakers, words, duration: s.duration, params: { mergeGap: 60, clipMax: 600 } }); + assert.ok(wide.length < props.length); +}); + +test("stableIds: a proposal that overlaps a previous one keeps its id; new ones take the next numbers", () => { + const first = stableIds([{ start: 0, end: 10 }, { start: 20, end: 30 }]); + assert.deepEqual(first.map((p) => p.id), ["p001", "p002"]); + const again = stableIds([{ start: 1, end: 10 }, { start: 12, end: 15 }, { start: 21, end: 31 }], first); + assert.deepEqual(again.map((p) => p.id), ["p001", "p003", "p002"]); +}); + +test("rankIntoTarget: the best first while they fit; a proposal on a fixed clip is that clip; too short or too weak is never used", () => { + const props = [ + { id: "p001", start: 0, end: 30, score: 0.2 }, + { id: "p002", start: 40, end: 60, score: 0.9 }, + { id: "p003", start: 70, end: 100, score: 0.5 }, + { id: "p004", start: 110, end: 115, score: 0.3 }, + ]; + const r = rankIntoTarget(props, { target: 60 }); + assert.deepEqual(r.map((p) => [p.id, p.used]), [["p001", false], ["p002", true], ["p003", true], ["p004", true]]); + const f = rankIntoTarget(props, { target: 60, fixed: [{ id: "r009", start: 0, end: 25 }] }); + assert.deepEqual(f.map((p) => [p.id, p.used, p.fixedClip ?? null]), [["p001", true, "r009"], ["p002", true, null], ["p003", false, null], ["p004", true, null]]); + // The floor: under CLIP_MIN_S, or scoring under USE_MIN_SCORE, stays listed and unused however much room is left. + const junk = rankIntoTarget( + [ + { id: "p001", start: 0, end: 2, score: 0.9 }, + { id: "p002", start: 10, end: 16, score: 0.106 }, + { id: "p003", start: 20, end: 25, score: USE_MIN_SCORE }, + ], + { target: 600 }, + ); + assert.deepEqual(junk.map((p) => [p.id, p.used]), [["p001", false], ["p002", false], ["p003", true]]); + assert.equal(CLIP_MIN_S, 5); +}); + +test("widenTo + buildProposals: a span under CLIP_MIN_S is widened about its middle, edges in the word gaps", () => { + const words = cleanWords(Array.from({ length: 40 }, (_, i) => ({ w: `w${i}`, start: i * 0.5, end: i * 0.5 + 0.4 }))); + const w = widenTo(words, 9, 10, 5, 100); + assert.ok(w.end - w.start >= 5, JSON.stringify(w)); + assert.ok(w.start <= 9 && w.end >= 10); + assert.ok(Math.abs((w.start + w.end) / 2 - 9.5) < 0.3); + // Inside the recording. + const edge = widenTo(words, 0, 1, 5, 100); + assert.equal(edge.start, 0); + assert.ok(edge.end >= 5); + // A lone short laugh with nothing around it still makes a 5 s proposal. + const speakers = [{ index: 0, role: "host", seconds: 10 }]; + const moments = [{ id: "m001", t: 50, end: 51, kind: "laugh" as const, score: 0.5, speaker: 0, text: "" }]; + const props = buildProposals({ moments, turns: [{ start: 49, end: 52, speaker: 0 }], speakers, words: [], duration: 100, params: {} }); + assert.equal(props.length, 1); + assert.ok(props[0].end - props[0].start >= 5); +}); + +test("scope: only that part of the recording is read; normalizeParams keeps it", () => { + assert.equal(normalizeParams({}).scope, null); + assert.deepEqual(normalizeParams({ scope: [100, 300] }).scope, [100, 300]); + assert.deepEqual(normalizeParams({ scope: [100, null] }).scope, [100, null]); + assert.equal(normalizeParams({ scope: [0, null] }).scope, null); + assert.equal(normalizeParams({ scope: "all" }).scope, null); + assert.throws(() => normalizeScope([300, 100]), /0 ≤ from < to/); + assert.throws(() => normalizeScope("x"), /scope must be/); + const s = reactionStream(); + const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { scope: [300, 450], target: 600 } }); + assert.equal(a.duration, 450); + assert.deepEqual(a.params.scope, [300, 450]); + assert.ok(a.turns.every((t) => t.start >= 300 && t.end <= 450)); + // The laugh at 340 is in; 95 and 520 are not. + assert.deepEqual(a.laughs.map((l) => Math.round(l.start)), [340]); + assert.ok(a.proposals.every((p) => p.end > 300 && p.start < 450)); + assert.deepEqual(a.speakers.map((x) => [x.index, x.role]), [[0, "host"], [1, "subject"]]); +}); + +test("voiceLaughs: a laugh in the subject's voice is the subject's, the host's over a narrated line the host's; else the overlap rule", () => { + const speakers = [{ index: 1, role: "host", seconds: 100 }, { index: 4, role: "subject", seconds: 900 }, { index: 7, role: "other", seconds: 5 }]; + const centroids = { 1: [1, 0, 0], 4: [0, 1, 0], 7: [0, 0, 1] }; + const laughs = [ + { start: 10, end: 12, score: 0.5, speaker: 1 }, // overlap said host, the voice is the narrator's + { start: 20, end: 21, score: 0.5, speaker: 4 }, // overlap said subject, the voice is the host's + { start: 30, end: 31, score: 0.5, speaker: 1 }, // neither voice clearly: the overlap stands + { start: 40, end: 41, score: 0.5, speaker: 4 }, // no embedding + ]; + const voices = { + [laughKey(laughs[0])]: [0.05, 0.4, 0.1], + [laughKey(laughs[1])]: [0.3, 0.02, 0.1], + [laughKey(laughs[2])]: [0.15, 0.1, 0.9], + }; + const got = voiceLaughs(laughs, speakers, centroids, voices); + assert.deepEqual(got.map((l) => [l.speaker, l.by ?? null]), [[4, "voice"], [1, "voice"], [1, null], [4, null]]); + assert.ok(got[0].voice && got[0].voice.subject > got[0].voice.host); + assert.equal(got[3].voice, undefined); + assert.deepEqual(laughVoiceSpan({ start: 10, end: 10.5 }), { start: 9.5, dur: 1.5 }); + // Through analyze: the voice decides, and a narrator's laugh weighs less than a host's. + const s = reactionStream(); + const a0 = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan }); + const lv = Object.fromEntries(a0.laughs.map((l, i) => [laughKey(l), i === 0 ? [0, 1, 0] : [1, 0, 0]])); + const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, centroids: { 0: [1, 0, 0], 1: [0, 1, 0] }, laughVoices: lv }); + assert.equal(a.laughs[0].speaker, SUBJECT); + assert.equal(a.laughs[0].by, "voice"); + assert.deepEqual(a.laughs[0].voice, { host: 0, subject: 1 }); + assert.equal(a.laughs[1].speaker, HOST); + const m0 = a.moments.find((m) => m.kind === "laugh" && m.t === a.laughs[0].start); + const was = a0.moments.find((m) => m.kind === "laugh" && m.t === a0.laughs[0].start); + assert.ok(m0 && was && m0.score < was.score * 0.5, `${m0?.score} vs ${was?.score}`); +}); + +test("analyze: deterministic; the model's laughs when there is a scan, the transcript's markers when there is none", () => { + const s = reactionStream(); + const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { target: 120 } }); + const b = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { target: 120 } }); + assert.deepEqual(a, b); + assert.equal(a.laughSource, "model"); + assert.equal(a.laughs.length, 3); + assert.ok(a.laughs.every((l) => l.speaker === HOST && !("src" in l))); + assert.ok(a.proposals.length >= 5); + const used = a.proposals.filter((p) => p.used).reduce((n, p) => n + p.end - p.start, 0); + assert.ok(used <= 120 * 1.03, `used ${used}`); + // The two strong laughs are the two best proposals. + const best = [...a.proposals].sort((x, y) => y.score - x.score).slice(0, 2); + assert.deepEqual(best.map((p) => p.moments.some((id) => a.moments.find((m) => m.id === id)?.kind === "laugh")), [true, true]); + // No model: the "haha" words are the laughs, and the same moments come out. + const c = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: null, params: { target: 120 } }); + assert.equal(c.laughSource, "text"); + assert.equal(c.laughs.length, 3); + assert.ok(c.laughs.every((l) => l.src === "text")); + // With an energy-only scan: "text+energy". + const d = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: { t0: 0, hop: 0.5, window: 1, scores: null, energy: s.laughScan.scores.map(() => -30) } }); + assert.equal(d.laughSource, "text+energy"); +}); + +test("validateAssist: the plan's shape passes; broken keys are named", () => { + const s = reactionStream(); + const clip = clipFromProposal({ id: "p001", start: 48.2, end: 66, score: 0.83, why: "host laughs" }, { id: "r001", channel: "c", video: "v", duration: 600, words: cleanWords(s.words) }); + assert.deepEqual(clip.assist, { by: "assistant", proposal: "p001", score: 0.83, why: "host laughs", original: { start: 46.7, end: 67.5, cutStart: 48.2, cutEnd: 66 }, edits: [] }); + assert.equal(clip.start, 46.7); + assert.ok(clip.quote.length > 0 && clip.quote.length <= 160); + const edited = { ...clip, assist: { ...clip.assist, by: "operator", edits: [{ at: "2026-10-18T22:00:00Z", by: "operator", what: "trim", from: { cutStart: 48.2 }, to: { cutStart: 49 } }] } }; + const added = { type: "clip", id: "r002", channel: "c", video: "v", start: 1, end: 5, assist: { by: "operator" } }; + assert.deepEqual(validateAssist({ timeline: [clip, edited, added, { type: "clip", id: "x", start: 0, end: 1 }] }), []); + const bad = validateAssist({ + timeline: [ + { type: "clip", id: "a", start: 0, end: 1, assist: { by: "robot" } }, + { type: "clip", id: "b", start: 0, end: 1, assist: { by: "assistant" } }, + { type: "clip", id: "c", start: 0, end: 1, assist: { by: "operator", score: 2, original: { start: 0 }, edits: [{ at: "nope", by: "operator", what: "nudge" }] } }, + { type: "card", id: "d", assist: { by: "operator" } }, + ], + }); + assert.equal(bad.length, 9, bad.join("\n")); + assert.match(bad.join("\n"), /entry a: assist\.by must be/); + assert.match(bad.join("\n"), /entry b: assist\.proposal must name/); + assert.match(bad.join("\n"), /edits\[0\]\.what must be one of trim, split, merge, add, restore/); + assert.match(bad.join("\n"), /entry d: assist is only for clips/); +}); + +test("applyProposals: adds, updates in place, removes the assistant's; never moves the operator's, a ruled one or a locked one", () => { + const s = reactionStream(); + const words = cleanWords(s.words); + const base = { channel: "c", video: "v", duration: 600, words }; + const first = applyProposals([], { + ...base, + proposals: [ + { id: "p001", start: 10, end: 20, score: 0.5, why: "a", used: true }, + { id: "p002", start: 30, end: 40, score: 0.4, why: "b", used: true }, + { id: "p003", start: 50, end: 60, score: 0.1, why: "c", used: false }, + ], + }); + assert.deepEqual(first.timeline.map((e) => e.id), ["r001", "r002"]); + assert.deepEqual(first.proposals.map((p) => p.clipId), ["r001", "r002", null]); + assert.deepEqual(first.changes, { added: ["r001", "r002"], updated: [], removed: [], kept: 0 }); + // The operator trims r002; adds a clip of their own at 70; a card sits first. + const tl = [{ type: "card", id: "intro" }, ...first.timeline]; + const r2 = tl.find((e) => e.id === "r002"); + Object.assign(r2, { cutStart: 31, assist: { ...r2.assist, by: "operator" } }); + tl.push({ type: "clip", id: "mine", channel: "c", video: "v", start: 69, end: 76, cutStart: 70, cutEnd: 75, assist: { by: "operator" } }); + assert.deepEqual(fixedClips(tl, base).map((c) => c.id), ["r002", "mine"]); + // A re-proposal: p001 moved, p002 is gone, p003 is now used, p004 is new and the cut is short. + const second = applyProposals(tl, { + ...base, + proposals: [ + { id: "p001", start: 11, end: 20, score: 0.5, why: "a", used: true }, + { id: "p003", start: 50, end: 60, score: 0.6, why: "c", used: true }, + { id: "p005", start: 70, end: 74, score: 0.7, why: "e", used: true, fixedClip: "mine" }, + { id: "p004", start: 5, end: 8, score: 0.6, why: "d", used: true }, + ], + }); + assert.deepEqual(second.timeline.map((e) => e.id), ["intro", "r004", "r001", "r002", "r003", "mine"]); + assert.equal(second.timeline.find((e) => e.id === "r002").cutStart, 31); // the operator's, untouched + assert.equal(second.timeline.find((e) => e.id === "r001").cutStart, 11); + assert.deepEqual(second.changes, { added: ["r003", "r004"], updated: ["r001"], removed: [], kept: 0 }); + assert.deepEqual(second.proposals.map((p) => p.clipId), ["r001", "r003", "mine", "r004"]); + // A ruled or locked assistant clip is never removed. + const third = applyProposals(second.timeline, { ...base, proposals: [], isProtected: (e) => e.id === "r001" }); + assert.deepEqual(third.timeline.map((e) => e.id), ["intro", "r001", "r002", "mine"]); + assert.deepEqual(third.changes.removed.sort(), ["r003", "r004"]); + assert.ok(isAssistantClip(third.timeline[1]) && !isAssistantClip(third.timeline[2])); +}); + +test("reactions.json: written whole, read back; setSpeakerRole marks the operator's role and records when", async () => { + const dir = tmp(); + try { + assert.equal(await readReactions(dir), null); + const s = reactionStream(); + const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan }); + const doc = { version: 1 as const, source: { channel: "c", video: "v", duration: 600, words: null, diarization: { generatedAt: null, engine: null } }, ...a, proposals: a.proposals.map((p) => ({ ...p, clipId: null })) }; + await writeReactions(dir, doc); + const back = await readReactions(dir); + assert.ok(back); + assert.equal(back.speakers.length, 2); + assert.deepEqual(operatorRoles(back), {}); + const after = await setSpeakerRole(dir, 1, "host", { now: () => new Date("2026-10-18T23:00:00Z") }); + assert.deepEqual(after.speakers.map((x) => [x.index, x.role, x.how]), [[0, "other", "auto"], [1, "host", "operator"]]); + assert.equal(after.rolesChangedAt, "2026-10-18T23:00:00.000Z"); + assert.deepEqual(operatorRoles(await readReactions(dir)), { 1: "host" }); + await setSpeakerRole(dir, 1, null); + assert.deepEqual(operatorRoles(await readReactions(dir)), {}); + await assert.rejects(setSpeakerRole(dir, 7, "host"), /no speaker 7/); + await assert.rejects(setSpeakerRole(dir, 0, "boss" as never), /a role is one of/); + // Not a reactions file: null, and the writer refuses. + writeFileSync(path.join(dir, REACTIONS_FILE), JSON.stringify({ version: 2 })); + assert.equal(await readReactions(dir), null); + await assert.rejects(setSpeakerRole(dir, 0, "host"), /no reactions\.json/); + assert.ok(readFileSync(path.join(dir, REACTIONS_FILE), "utf8").includes("2")); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/clips/reactions.d.mts b/common/lib/clips/reactions.d.mts @@ -0,0 +1,44 @@ +import type { Laugh, Moment, Params, Role, Speaker, Turn } from "./clips.mjs"; + +export const REACTIONS_FILE: string; +export const REACTIONS_VERSION: 1; + +export type ReactionsProposal = { + id: string; + start: number; + end: number; + score: number; + moments: string[]; + used: boolean; + clipId: string | null; + why: string; +}; + +export type ReactionsDoc = { + version: 1; + source: { + channel: string; + video: string; + duration: number; + words: string | null; + diarization: { generatedAt: string | null; engine: string | null }; + audio?: string | null; + }; + params: Params; + speakers: Speaker[]; + turns: Turn[]; + laughs: Laugh[]; + moments: Moment[]; + proposals: ReactionsProposal[]; + madeAt?: string; + proposedAt?: string; + rolesChangedAt?: string; + laughSource?: "model" | "text" | "text+energy"; + scans?: Record<string, unknown>; +}; + +export function reactionsFileOf(dir: string): string; +export function readReactions(dir: string): Promise<ReactionsDoc | null>; +export function writeReactions(dir: string, doc: ReactionsDoc): Promise<string>; +export function operatorRoles(doc: ReactionsDoc | null): Record<string, Role>; +export function setSpeakerRole(dir: string, index: number, role: Role | null, opts?: { now?: () => Date }): Promise<ReactionsDoc>; diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs @@ -0,0 +1,94 @@ +// `<project>/reactions.json` (release 35 C1): the clip finder's analysis of +// one recording — speakers and their roles, turns, laughs, moments, and the +// proposals with the clip each became. Written whole by the analysis +// (`umtool new --seed reactions`, `umtool clips analyze|propose`); the clip +// editor reads it, and changes one thing only: a speaker's role, through +// setSpeakerRole below (the operator's "This is the host"). +// +// The shape is plans/release-35/clip-finder.md's, plus a few optional keys +// (FACTS.md, "reactions.json"). +// +// Plain ESM with a .d.mts beside it. +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { REACTIONS_VERSION, ROLES } from "./clips.mjs"; + +export const REACTIONS_FILE = "reactions.json"; +export { REACTIONS_VERSION }; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export const reactionsFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, REACTIONS_FILE); + +/** `<project>/reactions.json`, or null when there is none (or it is not one). */ +export async function readReactions(dir) { + try { + const doc = JSON.parse(await readFile(reactionsFileOf(dir), "utf8")); + return isObj(doc) && doc.version === REACTIONS_VERSION && Array.isArray(doc.speakers) && Array.isArray(doc.proposals) ? doc : null; + } catch { + return null; + } +} + +/** Written whole: tmp + rename, so a reader never sees half a file. */ +export async function writeReactions(dir, doc) { + const file = reactionsFileOf(dir); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`; + await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); + await rename(tmp, file); + return file; +} + +/** The roles the operator has set, as `{index: role}` — what a re-analysis keeps. */ +export function operatorRoles(doc) { + const out = {}; + for (const s of doc?.speakers ?? []) if (isObj(s) && s.how === "operator" && ROLES.includes(s.role)) out[s.index] = s.role; + return out; +} + +const labelOf = (role, index) => (role === "host" ? "Host" : role === "subject" ? "Subject" : `Speaker ${index + 1}`); + +/** + * The operator's word on one speaker: `role` "host" | "subject" | "other", + * 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 + * 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 + * @param {number} index the speaker (diarization cluster) + * @param {"host"|"subject"|"other"|null} role + * @param {{ now?: () => Date }} [opts] + * @returns {Promise<any>} the document as written + */ +export async function setSpeakerRole(dir, index, role, { now = () => new Date() } = {}) { + const doc = await readReactions(dir); + if (!doc) throw new Error(`no ${REACTIONS_FILE} in ${dir}`); + if (role !== null && !ROLES.includes(role)) throw new Error(`a role is one of ${ROLES.join(", ")} (or null), not ${JSON.stringify(role)}`); + const s = doc.speakers.find((x) => isObj(x) && x.index === index); + if (!s) throw new Error(`no speaker ${index} in ${REACTIONS_FILE}`); + if (role === null) { + s.how = "auto"; + } else { + if (role !== "other") { + for (const o of doc.speakers) { + 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; + } + } + } + s.role = role; + s.label = labelOf(role, index); + s.how = "operator"; + delete s.sameAs; + } + doc.rolesChangedAt = now().toISOString(); + await writeReactions(dir, doc); + return doc; +} diff --git a/common/lib/clips/scan.d.mts b/common/lib/clips/scan.d.mts @@ -0,0 +1,70 @@ +export const AUDIO_SCAN_VERSION: 1; +export const VOICES_VERSION: 1; +export const CHUNK_S: number; +export const CHUNKS_PER_GROUP: number; +export const CED_DIR: string; +export const PIECES_MAIN: number; +export const PIECES_PER_SPEAKER: number; +export const PIECE_MIN_S: number; +export const PIECE_MAX_S: number; + +export type Tagger = { python: string; script: string; model: string; labels: string; threads: number; available: boolean }; +export function resolveTagger(o: { + repoRoot: string; + env?: Record<string, string | undefined>; + settings?: unknown; + python?: string; + script?: string; + model?: string; + labels?: string; + threads?: number; +}): Tagger; +export function tagWavs( + items: { id: string; wav: string; window?: number; hop?: number }[], + engine: { python: string; script: string; model: string; labels: string; threads?: number }, + scratch: string, + opts?: { classes?: readonly number[] }, +): Promise<{ model: string; version: string | null; classes: number[]; items: Map<string, { scores: number[][] | null; seconds: number; error?: string }> }>; +export function windowLevels(samples: Float32Array, o: { rate?: number; window?: number; hop?: number; count: number }): number[]; +export type AudioScan = { + version: 1; + window: number; + hop: number; + t0: number; + windows: number; + energy: number[]; + laugh: number[] | null; + model: { file: string; sherpaOnnx: string | null; classes: number[] } | null; + classes: number[]; +}; +export function runAudioScan(o: { + file: string; + duration: number; + clock?: number; + tagger?: Tagger | null; + scratch: string; + window?: number; + hop?: number; + chunkS?: number; + perGroup?: number; + ffmpeg?: string; + onProgress?: (e: Record<string, unknown>) => void; +}): Promise<AudioScan>; +export function centroidPieces(turns: { start: number; end: number; speaker: number }[], speaker: number, n?: number): { start: number; dur: number }[]; +export function speakerCentroids(o: { + file: string; + clock?: number; + turns: { start: number; end: number; speaker: number }[]; + engine: { python: string; script: string; model: string; threads?: number }; + scratch: string; + ffmpeg?: string; + onProgress?: (e: Record<string, unknown>) => void; +}): Promise<{ version: number; model: string; speakers: Record<string, { centroid: number[] | null; pieces: number; kept: number }> }>; +export function embedSpans(o: { + file: string; + clock?: number; + spans: { key: string; start: number; dur: number }[]; + engine: { python: string; script: string; model: string; threads?: number }; + scratch: string; + ffmpeg?: string; +}): Promise<Map<string, number[]>>; diff --git a/common/lib/clips/scan.mjs b/common/lib/clips/scan.mjs @@ -0,0 +1,284 @@ +// The clip finder's two scans of a recording's sound (release 35 C1): laughs +// and voices. The I/O half of common/lib/clips — the arithmetic is clips.mjs. +// +// runAudioScan the sound in SCAN_WINDOW_S windows every SCAN_HOP_S: +// each window's level (dBFS, always — the no-model +// fallback's energy) and, when the tagger is there, its +// laugh score (CED-mini through scripts/audio-tag.py, the +// AudioSet laughter family summed). Decoded in chunks with +// ffmpeg (voiceMatch's decodeSpan), so a 3-hour stream +// never sits in memory; one tagger process per group of +// chunks (the model loads once per group). +// speakerCentroids a voice centroid per diarization cluster: its longest +// turns that overlap nobody (24 for the two clusters with +// the most seconds, 6 for each other), voiced frames only, +// embedded with TitaNet-small (voiceMatch's embedWavs) and +// averaged robustly — what merges one voice split in two. +// embedSpans spans embedded as they are: each laugh's voice, scored +// against the host's and the subject's centroids. +// +// Deterministic for a given model and input; no network; no LLM. +// +// Plain ESM with a .d.mts beside it. +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { decodeSpan, embedWavs, encodeWav16, frameLevels, robustCentroid, voicedSamples, SAMPLE_RATE, MIN_SPEECH_S } from "../montage/voiceMatch.mjs"; +import { LAUGH_CLASSES, SCAN_HOP_S, SCAN_WINDOW_S, laughScore } from "./clips.mjs"; + +export const AUDIO_SCAN_VERSION = 1; +export const VOICES_VERSION = 1; +/** The seconds decoded at a time. */ +export const CHUNK_S = 300; +/** Chunks per tagger process. */ +export const CHUNKS_PER_GROUP = 4; +/** The default model directory under `<repo>/.diarize/models/`. */ +export const CED_DIR = "sherpa-onnx-ced-mini-audio-tagging-2024-04-19"; +/** Pieces for the two clusters with the most seconds (the voices that matter), and for each of the rest. */ +export const PIECES_MAIN = 24; +export const PIECES_PER_SPEAKER = 6; +/** A turn shorter than this is not used for a voice centroid. */ +export const PIECE_MIN_S = 2; +/** A piece is at most this long. */ +export const PIECE_MAX_S = 8; + +const round = (x, d = 3) => (Number.isFinite(x) ? Math.round(x * 10 ** d) / 10 ** d : null); + +function run(cmd, args) { + return new Promise((resolve, reject) => { + const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); + const out = []; + let err = ""; + child.stdout.on("data", (b) => out.push(b)); + child.stderr.on("data", (b) => { + err += b; + if (err.length > 20000) err = err.slice(-20000); + }); + child.on("error", reject); + child.on("close", (code) => { + if (code === 0) resolve({ stdout: Buffer.concat(out), stderr: err }); + else reject(new Error(`${path.basename(cmd)} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`)); + }); + }); +} + +/** + * Which python, script and model tag. In order: the explicit `opts`, then + * AUDIO_TAG_PYTHON / AUDIO_TAG_SCRIPT / AUDIO_TAG_MODEL / AUDIO_TAG_LABELS, + * then the diarization venv (`settings.diarization.python`, else + * `<repo>/.diarize/env/bin/python`), `<repo>/scripts/audio-tag.py`, + * `<repo>/.diarize/models/<CED_DIR>/model.int8.onnx` and the + * class_labels_indices.csv beside the model. `available` is whether the + * model file is there (the scan runs without it: energy only). + * @param {{ repoRoot: string, env?: Record<string, string | undefined>, settings?: any, + * python?: string, script?: string, model?: string, labels?: string, threads?: number }} o + */ +export function resolveTagger(o) { + const env = o.env ?? process.env; + const d = o.settings?.diarization ?? {}; + const python = o.python || env.AUDIO_TAG_PYTHON || (typeof d.python === "string" && d.python) || path.join(o.repoRoot, ".diarize", "env", "bin", "python"); + const script = o.script || env.AUDIO_TAG_SCRIPT || path.join(o.repoRoot, "scripts", "audio-tag.py"); + const model = o.model || env.AUDIO_TAG_MODEL || path.join(o.repoRoot, ".diarize", "models", CED_DIR, "model.int8.onnx"); + const labels = o.labels || env.AUDIO_TAG_LABELS || path.join(path.dirname(model), "class_labels_indices.csv"); + return { python, script, model, labels, threads: o.threads ?? 1, available: existsSync(model) }; +} + +/** + * Tag WAV files: one process for the batch. + * @param {{ id: string, wav: string, window?: number, hop?: number }[]} items + * @param {{ python: string, script: string, model: string, labels: string, threads?: number }} engine + * @param {string} scratch + * @returns {Promise<{ model: string, version: string | null, classes: number[], items: Map<string, { scores: number[][] | null, seconds: number, error?: string }> }>} + */ +export async function tagWavs(items, engine, scratch, { classes = LAUGH_CLASSES } = {}) { + await mkdir(scratch, { recursive: true }); + const req = path.join(scratch, "tag-request.json"); + await writeFile(req, JSON.stringify({ items })); + const { stdout } = await run(engine.python, [engine.script, "--model", engine.model, "--labels", engine.labels, "--threads", String(engine.threads ?? 1), "--classes", classes.join(","), req]); + const doc = JSON.parse(String(stdout)); + const byId = new Map(); + for (const it of doc.items ?? []) byId.set(String(it.id), { scores: Array.isArray(it.scores) ? it.scores : null, seconds: Number(it.seconds) || 0, ...(it.error ? { error: String(it.error) } : {}) }); + return { model: String(doc.model ?? path.basename(engine.model)), version: doc.version ?? null, classes: Array.isArray(doc.classes) ? doc.classes : [...classes], items: byId }; +} + +/** Each window's RMS level in dBFS (1 dp): the mean power of its 20 ms frames. */ +export function windowLevels(samples, { rate = SAMPLE_RATE, window = SCAN_WINDOW_S, hop = SCAN_HOP_S, count }) { + const frames = frameLevels(samples, rate, 0.02); + const per = Math.round(window / 0.02); + const step = Math.round(hop / 0.02); + const out = []; + for (let i = 0; i < count; i += 1) { + const a = i * step; + let p = 0; + let n = 0; + for (let f = a; f < Math.min(frames.length, a + per); f += 1) { + p += 10 ** (frames[f] / 10); + n += 1; + } + out.push(n ? round(10 * Math.log10(p / n + 1e-12), 1) : -120); + } + return out; +} + +/** + * The sound of [0, duration) of `file` (FILE seconds; `clock` is added to + * every time, the file's offset on the source's clock), in windows. Returns + * `{ version, window, hop, t0, windows, energy, laugh, model, classes }`: + * `laugh` null when no tagger ran (`tagger` null or not available). + * @param {{ file: string, duration: number, clock?: number, tagger?: (ReturnType<typeof resolveTagger>) | null, + * scratch: string, window?: number, hop?: number, chunkS?: number, perGroup?: number, ffmpeg?: string, + * onProgress?: (e: Record<string, unknown>) => void }} o + */ +export async function runAudioScan(o) { + const window = o.window ?? SCAN_WINDOW_S; + const hop = o.hop ?? SCAN_HOP_S; + const chunkS = o.chunkS ?? CHUNK_S; + const perGroup = Math.max(1, o.perGroup ?? CHUNKS_PER_GROUP); + const emit = o.onProgress ?? (() => {}); + const tagger = o.tagger && o.tagger.available ? o.tagger : null; + const total = Math.max(0, Math.floor((o.duration - window) / hop + 1e-9) + 1); + const perChunk = Math.max(1, Math.round(chunkS / hop)); + const chunks = Math.ceil(total / perChunk); + await rm(o.scratch, { recursive: true, force: true }); + await mkdir(o.scratch, { recursive: true }); + const energy = new Array(total).fill(-120); + const laugh = tagger ? new Array(total).fill(0) : null; + let model = null; + let pending = []; + const flush = async () => { + if (!pending.length || !tagger) return; + const got = await tagWavs(pending.map((p) => ({ id: p.id, wav: p.wav, window, hop })), tagger, o.scratch); + model = { file: got.model, sherpaOnnx: got.version, classes: got.classes }; + for (const p of pending) { + const it = got.items.get(p.id); + if (it?.error) throw new Error(`audio-tag: chunk ${p.id}: ${it.error}`); + const rows = it?.scores ?? []; + for (let k = 0; k < Math.min(rows.length, p.count); k += 1) /** @type {number[]} */ (laugh)[p.i0 + k] = round(laughScore(rows[k]), 3); + await rm(p.wav, { force: true }); + } + emit({ event: "tag", chunks: pending.length }); + pending = []; + }; + for (let c = 0; c < chunks; c += 1) { + const i0 = c * perChunk; + const i1 = Math.min(total, i0 + perChunk); + const start = i0 * hop; + const dur = (i1 - i0 - 1) * hop + window; + const samples = await decodeSpan(o.file, start, dur, { ffmpeg: o.ffmpeg }); + const count = i1 - i0; + const lv = windowLevels(samples, { window, hop, count }); + for (let k = 0; k < count; k += 1) energy[i0 + k] = lv[k]; + if (tagger) { + const wav = path.join(o.scratch, `chunk-${String(c).padStart(5, "0")}.wav`); + await writeFile(wav, encodeWav16(samples)); + pending.push({ id: `c${c}`, wav, i0, count }); + if (pending.length >= perGroup) await flush(); + } + emit({ event: "decode", n: c + 1, of: chunks }); + } + await flush(); + await rm(o.scratch, { recursive: true, force: true }); + return { + version: AUDIO_SCAN_VERSION, + window, + hop, + t0: round(o.clock ?? 0, 3), + windows: total, + energy, + laugh, + model, + classes: [...LAUGH_CLASSES], + }; +} + +/** + * Up to `n` of a cluster's turns for its voice: the LONGEST of those at least + * PIECE_MIN_S long that overlap no other cluster's turn (when none is clean, + * the longest at all), each the middle PIECE_MAX_S of the turn (0.2 s in from + * either end), in time order. + * @param {{ start: number, end: number, speaker: number }[]} turns sorted + */ +export function centroidPieces(turns, speaker, n = PIECES_PER_SPEAKER) { + const own = turns.filter((t) => t.speaker === speaker && t.end - t.start >= PIECE_MIN_S); + const others = turns.filter((t) => t.speaker !== speaker); + const clean = own.filter((t) => !others.some((o) => o.start < t.end && o.end > t.start)); + const pool = clean.length ? clean : own; + const picked = [...pool].sort((a, b) => b.end - b.start - (a.end - a.start) || a.start - b.start).slice(0, n).sort((a, b) => a.start - b.start); + return picked.map((t) => { + const d = Math.min(PIECE_MAX_S, t.end - t.start - 0.4); + return { start: round((t.start + t.end) / 2 - d / 2, 3), dur: round(d, 3) }; + }); +} + +/** + * Embed spans of the sound as they are (no gate): a laugh's voice. + * @param {{ file: string, clock?: number, spans: { key: string, start: number, dur: number }[], + * engine: { python: string, script: string, model: string, threads?: number }, scratch: string, ffmpeg?: string }} o + * @returns {Promise<Map<string, number[]>>} key → embedding (5 dp); a span that would not embed is left out + */ +export async function embedSpans(o) { + const out = new Map(); + if (!o.spans.length) return out; + await rm(o.scratch, { recursive: true, force: true }); + await mkdir(o.scratch, { recursive: true }); + const items = []; + for (const [k, sp] of o.spans.entries()) { + const x = await decodeSpan(o.file, Math.max(0, sp.start - (o.clock ?? 0)), sp.dur, { ffmpeg: o.ffmpeg }); + if (x.length < SAMPLE_RATE * 0.5) continue; + const wav = path.join(o.scratch, `span-${k}.wav`); + await writeFile(wav, encodeWav16(x)); + items.push({ id: sp.key, wav }); + } + const emb = items.length ? await embedWavs(items, o.engine, o.scratch) : { items: new Map() }; + for (const it of items) { + const v = emb.items.get(it.id)?.embedding; + if (Array.isArray(v)) out.set(it.id, v.map((x) => round(x, 5))); + } + await rm(o.scratch, { recursive: true, force: true }); + return out; +} + +/** + * A voice centroid per cluster (null when none of its pieces had speech). + * @param {{ file: string, clock?: number, turns: { start: number, end: number, speaker: number }[], + * engine: { python: string, script: string, model: string, threads?: number }, scratch: string, ffmpeg?: string, + * onProgress?: (e: Record<string, unknown>) => void }} o + * @returns {Promise<{ version: number, model: string, speakers: Record<string, { centroid: number[] | null, pieces: number, kept: number }> }>} + */ +export async function speakerCentroids(o) { + const emit = o.onProgress ?? (() => {}); + const clock = o.clock ?? 0; + await rm(o.scratch, { recursive: true, force: true }); + await mkdir(o.scratch, { recursive: true }); + const speakers = [...new Set(o.turns.map((t) => t.speaker))].sort((a, b) => a - b); + const seconds = new Map(); + for (const t of o.turns) seconds.set(t.speaker, (seconds.get(t.speaker) ?? 0) + t.end - t.start); + const main = new Set([...speakers].sort((a, b) => (seconds.get(b) ?? 0) - (seconds.get(a) ?? 0) || a - b).slice(0, 2)); + const items = []; + const bySpeaker = new Map(); + for (const s of speakers) { + const pieces = centroidPieces(o.turns, s, main.has(s) ? PIECES_MAIN : PIECES_PER_SPEAKER); + bySpeaker.set(s, []); + for (const [k, p] of pieces.entries()) { + const v = voicedSamples(await decodeSpan(o.file, Math.max(0, p.start - clock), p.dur, { ffmpeg: o.ffmpeg })); + if (v.seconds < MIN_SPEECH_S) continue; + const id = `s${s}-${k}`; + const wav = path.join(o.scratch, `${id}.wav`); + await writeFile(wav, encodeWav16(v.samples)); + items.push({ id, wav }); + bySpeaker.get(s).push(id); + } + emit({ event: "voice", speaker: s, pieces: bySpeaker.get(s).length }); + } + const emb = items.length ? await embedWavs(items, o.engine, o.scratch) : { model: path.basename(o.engine.model), items: new Map() }; + /** @type {Record<string, { centroid: number[] | null, pieces: number, kept: number }>} */ + const out = {}; + for (const s of speakers) { + const vecs = bySpeaker.get(s).map((id) => emb.items.get(id)?.embedding).filter(Array.isArray); + const r = robustCentroid(vecs); + out[s] = { centroid: r.centroid ? r.centroid.map((x) => round(x, 5)) : null, pieces: bySpeaker.get(s).length, kept: r.kept.length }; + } + await rm(o.scratch, { recursive: true, force: true }); + return { version: VOICES_VERSION, model: emb.model, speakers: out }; +} diff --git a/common/lib/clips/scan.test.ts b/common/lib/clips/scan.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { cosine, encodeWav16 } from "../montage/voiceMatch.mjs"; +import { analyze } from "./clips.mjs"; +import { CED_DIR, centroidPieces, resolveTagger, runAudioScan, speakerCentroids, tagWavs, windowLevels } from "./scan.mjs"; +import { HOST, SUBJECT, reactionAudio, reactionStream } from "../../testing/clips/reactionStream.mjs"; +import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FAKE_TAG = path.join(HERE, "..", "..", "testing", "audio", "fakeAudioTag.mjs"); +const FAKE_EMBED = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const tmp = () => mkdtempSync(path.join(os.tmpdir(), "clip-scan-")); +const ffmpeg = hasFfmpeg(); + +test("resolveTagger: env over settings over the repo's .diarize; available is whether the model is there", () => { + const d = resolveTagger({ repoRoot: "/repo", env: {} }); + assert.deepEqual(d, { + python: "/repo/.diarize/env/bin/python", + script: "/repo/scripts/audio-tag.py", + model: `/repo/.diarize/models/${CED_DIR}/model.int8.onnx`, + labels: `/repo/.diarize/models/${CED_DIR}/class_labels_indices.csv`, + threads: 1, + available: false, + }); + const s = resolveTagger({ repoRoot: "/repo", env: {}, settings: { diarization: { python: "/venv/python" } } }); + assert.equal(s.python, "/venv/python"); + const e = resolveTagger({ repoRoot: "/repo", env: { AUDIO_TAG_PYTHON: "node", AUDIO_TAG_SCRIPT: FAKE_TAG, AUDIO_TAG_MODEL: FAKE_TAG } }); + assert.deepEqual([e.python, e.script, e.available], ["node", FAKE_TAG, true]); + assert.equal(e.labels, path.join(path.dirname(FAKE_TAG), "class_labels_indices.csv")); +}); + +test("windowLevels: one level per window, loud where the sound is", () => { + const x = new Float32Array(16000 * 4); + for (let i = 16000 * 2; i < 16000 * 3; i += 1) x[i] = 0.5 * Math.sin(i / 3); + const lv = windowLevels(x, { count: 7 }); + assert.equal(lv.length, 7); + assert.ok(lv[4] > -10 && lv[0] < -100, JSON.stringify(lv)); +}); + +test("centroidPieces: the longest turns that overlap nobody (else the longest at all), the middle of each", () => { + const turns = [ + { start: 0, end: 10, speaker: 1 }, + { start: 9, end: 12, speaker: 0 }, + { start: 12, end: 13, speaker: 0 }, + { start: 20, end: 40, speaker: 0 }, + ]; + assert.deepEqual(centroidPieces(turns, 0), [{ start: 26, dur: 8 }]); + // Speaker 1's only turn overlaps speaker 0: with nothing clean, the longest at all. + assert.deepEqual(centroidPieces(turns, 1), [{ start: 1, dur: 8 }]); + const many = Array.from({ length: 30 }, (_, i) => ({ start: i * 10, end: i * 10 + 3 + (i % 3), speaker: 0 })); + const picked = centroidPieces(many, 0, 4); + // The four longest (5 s: i = 2, 5, 8, 11), in time order, each 0.2 s in from its ends. + assert.deepEqual(picked.map((p) => p.start), [20.2, 50.2, 80.2, 110.2]); + assert.ok(picked.every((p) => p.dur === 4.6)); +}); + +test("tagWavs + runAudioScan (fake tagger): the laugh is heard where it is, energy everywhere, chunked", { skip: !ffmpeg && "no ffmpeg" }, async () => { + const dir = tmp(); + try { + const wav = path.join(dir, "audio.wav"); + writeFileSync(wav, encodeWav16(reactionAudio({ seconds: 120 }))); + const tagger = resolveTagger({ repoRoot: dir, env: { AUDIO_TAG_PYTHON: process.execPath, AUDIO_TAG_SCRIPT: FAKE_TAG, AUDIO_TAG_MODEL: FAKE_TAG } }); + const one = await tagWavs([{ id: "a", wav, window: 1, hop: 0.5 }], tagger, path.join(dir, "s")); + assert.equal(one.items.get("a")?.scores?.length, 239); + const events: Record<string, unknown>[] = []; + const scan = await runAudioScan({ file: wav, duration: 120, tagger, scratch: path.join(dir, "work"), chunkS: 30, perGroup: 2, onProgress: (e) => events.push(e) }); + assert.equal(scan.windows, 239); + assert.equal(scan.energy.length, 239); + assert.ok(scan.laugh); + const at = (t: number) => scan.laugh![Math.round(t / 0.5)]; + assert.ok(at(95.5) >= 0.8, `laugh at 95.5: ${at(95.5)}`); + assert.ok(at(60) < 0.1 && at(110) < 0.1); + assert.equal(scan.model?.file, "fakeAudioTag.mjs"); + assert.equal(events.filter((e) => e.event === "decode").length, 4); + assert.equal(events.filter((e) => e.event === "tag").length, 2); + assert.ok(!existsSync(path.join(dir, "work"))); + // The same scan's laughs through the analysis: the host's laugh at 95. + const s = reactionStream(); + const turns = s.turns.filter((t) => t.start < 120); + const a = analyze({ turns, duration: 120, words: s.words.filter((w) => w.end < 120), laughScan: { t0: 0, hop: 0.5, window: 1, scores: scan.laugh } }); + assert.equal(a.laughSource, "model"); + assert.equal(a.laughs.length, 1); + assert.equal(a.laughs[0].speaker, HOST); + assert.ok(Math.abs(a.laughs[0].start - 95) <= 1); + // No tagger: energy only. + const quiet = await runAudioScan({ file: wav, duration: 120, tagger: null, scratch: path.join(dir, "work2"), chunkS: 60 }); + assert.equal(quiet.laugh, null); + assert.equal(quiet.model, null); + assert.deepEqual(quiet.energy, scan.energy); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("speakerCentroids (fake embedder): one centroid per cluster, the two voices apart", { skip: !ffmpeg && "no ffmpeg" }, async () => { + const dir = tmp(); + try { + const wav = path.join(dir, "audio.wav"); + writeFileSync(wav, encodeWav16(reactionAudio({ seconds: 200 }))); + const s = reactionStream(); + const turns = s.turns.filter((t) => t.end <= 200); + const engine = { python: process.execPath, script: FAKE_EMBED, model: "fake.onnx", threads: 1 }; + const v = await speakerCentroids({ file: wav, turns, engine, scratch: path.join(dir, "v") }); + const h = v.speakers[HOST].centroid; + const sub = v.speakers[SUBJECT].centroid; + assert.ok(h && sub); + assert.ok(v.speakers[HOST].pieces >= 2 && v.speakers[SUBJECT].pieces >= 2); + assert.ok(cosine(h, sub) < 0.6, `cosine ${cosine(h, sub)}`); + assert.ok(!existsSync(path.join(dir, "v"))); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -145,6 +145,10 @@ const DECLARED: EnvVarDecl[] = [ { name: "VOICE_MATCH_PYTHON", audience: "runtime", default: "`settings.diarization.python`, else `<repo>/.diarize/env/bin/python`", readBy: "common/lib/montage/voiceMatch.mjs (`umtool voice-match`)", doc: "The program that runs the speaker-embedding script for a montage's voice match: the diarization venv's python. Any program that takes the script's arguments will do; the e2e suite runs the test kit's fake embedder with `node`." }, { name: "VOICE_MATCH_SCRIPT", audience: "runtime", default: "`<repo>/scripts/speaker-embed.py`", readBy: "common/lib/montage/voiceMatch.mjs (`umtool voice-match`)", doc: "The speaker-embedding script (WAV segments in, L2-normalised embeddings out, JSON). The e2e suite points it at `common/testing/audio/fakeSpeakerEmbed.mjs`." }, { name: "VOICE_MATCH_MODEL", audience: "runtime", default: "`settings.diarization.embModel`, else `<repo>/.diarize/models/titanet.onnx`", readBy: "common/lib/montage/voiceMatch.mjs (`umtool voice-match`)", doc: "The speaker-embedding ONNX model for the voice match: TitaNet-small, the same file the diarization lane loads." }, + { name: "AUDIO_TAG_PYTHON", audience: "runtime", default: "`settings.diarization.python`, else `<repo>/.diarize/env/bin/python`", readBy: "common/lib/clips/scan.mjs (`umtool clips analyze`)", doc: "The program that runs the audio-tagging script for the clip finder's laugh scan: the diarization venv's python (sherpa-onnx). Any program that takes the script's arguments will do; the tests run the test kit's fake tagger with `node`." }, + { name: "AUDIO_TAG_SCRIPT", audience: "runtime", default: "`<repo>/scripts/audio-tag.py`", readBy: "common/lib/clips/scan.mjs (`umtool clips analyze`)", doc: "The audio-tagging script (WAV files in, per-window class probabilities out, JSON). The tests point it at `common/testing/audio/fakeAudioTag.mjs`." }, + { name: "AUDIO_TAG_MODEL", audience: "runtime", default: "`<repo>/.diarize/models/sherpa-onnx-ced-mini-audio-tagging-2024-04-19/model.int8.onnx`", readBy: "common/lib/clips/scan.mjs (`umtool clips analyze`)", doc: "The audio-tagging ONNX model for the laugh scan: CED-mini (AudioSet's 527 classes). Absent, the scan keeps each window's level only and the laughs come from the transcript and the host's wordless bursts." }, + { name: "AUDIO_TAG_LABELS", audience: "runtime", default: "`class_labels_indices.csv` beside the model", readBy: "common/lib/clips/scan.mjs (`umtool clips analyze`)", doc: "The model's class labels file." }, { name: "DIARIZE_SEG_MODEL", audience: "runtime", default: "— (required)", readBy: "scripts/diarize.mjs", doc: "Segmentation model. The editor passes the settings' value as a flag." }, { name: "DIARIZE_EMB_MODEL", audience: "runtime", default: "— (required)", readBy: "scripts/diarize.mjs", doc: "Speaker-embedding model. The editor passes the settings' value as a flag." }, { name: "DIARIZE_THRESHOLD", audience: "runtime", default: "`0.5`", readBy: "scripts/diarize.mjs", doc: "Clustering threshold." }, diff --git a/common/package.json b/common/package.json @@ -32,6 +32,10 @@ "./components/virtualizer": "./components/virtualizer.ts", "./components/*": "./components/*.tsx", "./lib/citations/respell.mjs": "./lib/citations/respell.mjs", + "./lib/clips/assist.mjs": "./lib/clips/assist.mjs", + "./lib/clips/clips.mjs": "./lib/clips/clips.mjs", + "./lib/clips/reactions.mjs": "./lib/clips/reactions.mjs", + "./lib/clips/scan.mjs": "./lib/clips/scan.mjs", "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", diff --git a/common/testing/audio/fakeAudioTag.d.mts b/common/testing/audio/fakeAudioTag.d.mts @@ -0,0 +1,2 @@ +export function toneShare(x: Float32Array, rate: number, hz?: number): number; +export function fakeProbs(x: Float32Array, rate: number, classes: number[]): number[]; diff --git a/common/testing/audio/fakeAudioTag.mjs b/common/testing/audio/fakeAudioTag.mjs @@ -0,0 +1,94 @@ +#!/usr/bin/env node +// A stand-in for scripts/audio-tag.py (release 35 C1), with its exact command +// line and JSON — so the laugh scan, its CLI and the app's job run in a test +// with no python, no sherpa-onnx and no model file. +// +// node fakeAudioTag.mjs --model <x> --labels <x> [--threads N] [--classes 16,18,19,20,21] <request.json> +// +// It "hears laughter" where a window's sound is mostly the test kit's laugh +// tone (testing/clips/reactionStream.mjs LAUGH_TONE_HZ, by a Goertzel filter +// against the window's total energy): 0.8 for the first class (Laughter), +// 0.05 for the second, 0.01 for the rest; elsewhere 0.01. Deterministic. It +// is not a sound model. Point AUDIO_TAG_PYTHON at `node` and AUDIO_TAG_SCRIPT +// at this file (AUDIO_TAG_MODEL at any existing file). +import { readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; +import { LAUGH_TONE_HZ } from "../clips/reactionStream.mjs"; + +function readWav(file) { + const buf = readFileSync(file); + let at = 12; + let rate = 16000; + while (at + 8 <= buf.length) { + const id = buf.toString("ascii", at, at + 4); + const size = buf.readUInt32LE(at + 4); + if (id === "fmt ") rate = buf.readUInt32LE(at + 12); + if (id === "data") { + const n = Math.floor(Math.min(size, buf.length - at - 8) / 2); + const x = new Float32Array(n); + for (let i = 0; i < n; i += 1) x[i] = buf.readInt16LE(at + 8 + i * 2) / 32768; + return { x, rate }; + } + at += 8 + size + (size % 2); + } + return { x: new Float32Array(0), rate }; +} + +/** The share of a stretch's energy at `hz` (0..1). */ +export function toneShare(x, rate, hz = LAUGH_TONE_HZ) { + if (!x.length) return 0; + const w = (2 * Math.PI * hz) / rate; + const c = 2 * Math.cos(w); + let s1 = 0; + let s2 = 0; + let total = 0; + for (let i = 0; i < x.length; i += 1) { + const s0 = x[i] + c * s1 - s2; + s2 = s1; + s1 = s0; + total += x[i] * x[i]; + } + const power = (s1 * s1 + s2 * s2 - c * s1 * s2) / (x.length / 2); + return total > 1e-9 ? Math.min(1, power / total) : 0; +} + +export function fakeProbs(x, rate, classes) { + const laugh = toneShare(x, rate) > 0.35; + return classes.map((_, i) => (laugh ? (i === 0 ? 0.8 : i === 1 ? 0.05 : 0.01) : 0.01)); +} + +function main(argv) { + let classes = [16, 18, 19, 20, 21]; + let model = "fake.onnx"; + const positional = []; + for (let i = 0; i < argv.length; i += 1) { + const a = argv[i]; + if (a === "--classes") classes = argv[++i].split(",").filter(Boolean).map(Number); + else if (a === "--model") model = argv[++i]; + else if (a === "--labels" || a === "--threads") i += 1; + else positional.push(a); + } + const req = JSON.parse(readFileSync(positional[0], "utf8")); + const items = (req.items ?? []).map((item) => { + const rec = { id: item.id, seconds: 0, window: null, hop: null, scores: null }; + try { + const { x, rate } = readWav(item.wav); + rec.seconds = Math.round((x.length / rate) * 1000) / 1000; + if (item.window == null) rec.scores = [fakeProbs(x, rate, classes)]; + else { + const win = Math.round(item.window * rate); + const hop = Math.max(1, Math.round((item.hop ?? item.window) * rate)); + rec.window = item.window; + rec.hop = item.hop ?? item.window; + rec.scores = []; + for (let a = 0; a + win <= x.length; a += hop) rec.scores.push(fakeProbs(x.subarray(a, a + win), rate, classes)); + } + } catch (e) { + rec.error = e instanceof Error ? e.message : String(e); + } + return rec; + }); + process.stdout.write(JSON.stringify({ model: model.split("/").pop(), version: "fake", classes, names: classes.map(String), items })); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) main(process.argv.slice(2)); diff --git a/common/testing/clips/reactionStream.d.mts b/common/testing/clips/reactionStream.d.mts @@ -0,0 +1,18 @@ +export const STREAM_SECONDS: number; +export const SUBJECT: number; +export const HOST: number; +export const SUBJECT_RUNS: readonly [number, number][]; +export const LAUGHS: readonly [number, number, number][]; +export const LAUGH_TONE_HZ: number; +export function reactionStream(o?: { hop?: number; window?: number; laughWords?: boolean }): { + duration: number; + turns: { start: number; end: number; speaker: number }[]; + words: { w: string; start: number; end: number }[]; + cues: { start: number; end: number; text: string }[]; + laughScan: { t0: number; hop: number; window: number; scores: number[] }; +}; +export function reactionAudio(o?: { seconds?: number; rate?: number }): Float32Array; +export function writeReactionCorpus( + channelsDir: string, + o?: { channel?: string; video?: string; diarization?: boolean; audio?: Buffer | null }, +): string; diff --git a/common/testing/clips/reactionStream.mjs b/common/testing/clips/reactionStream.mjs @@ -0,0 +1,151 @@ +// A synthetic reaction stream for the clip finder's tests (release 35 C1): +// a host reacting to a narrated video, as the inputs the analysis reads — +// speaker turns (diarization.json), words, cues, per-window laugh scores — +// and, for the scan tests, its sound. Nothing in it is a recording, a person +// or a transcript: the "narration" is numbered filler words, the host says +// the same few words, and the laughs are placed by hand. +// +// speaker 1 (the SUBJECT, the narrated video) talks in long runs; +// speaker 0 (the HOST) interjects in the gaps, all the way through; +// the host laughs at LAUGHS (strong ones in the gaps, one weak one). +// +// reactionStream() the inputs, as plain data +// writeReactionCorpus(dir, o) a channel on disk: diarization.json, +// transcript.cues.json, metadata.info.json, +// and (o.audio) the sound as audio.wav +// reactionAudio(o) the sound: VOICE_B narrates, VOICE_A interjects, +// a laugh is LAUGH_TONE_HZ bursts — what the fake +// tagger (fakeAudioTag.mjs) hears as laughter +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { VOICE_A, VOICE_B, syntheticVoice } from "../audio/syntheticVoice.mjs"; + +export const STREAM_SECONDS = 600; +export const SUBJECT = 1; +export const HOST = 0; +/** The subject's runs; the host talks in the gaps between them. */ +export const SUBJECT_RUNS = Object.freeze([ + [0, 40], [44, 95], [100, 170], [176, 260], [266, 340], [345, 430], [436, 520], [526, 600], +]); +/** The host's laughs: [start, end, strength]. 520 is a weak one. */ +export const LAUGHS = Object.freeze([ + [95, 97.5, 0.8], + [340, 342, 0.7], + [520, 521, 0.3], +]); +/** The tone the synthetic laugh is made of, and the fake tagger listens for. */ +export const LAUGH_TONE_HZ = 1500; + +const HOST_WORDS = ["wow", "that's", "crazy.", "no", "way.", "look", "at", "this."]; + +/** + * @param {{ hop?: number, window?: number, laughWords?: boolean }} [o] + * `laughWords`: the host's laughs are also in the words ("haha"), for the + * no-model fallback. + */ +export function reactionStream({ hop = 0.5, window = 1, laughWords = true } = {}) { + const turns = []; + const gaps = []; + SUBJECT_RUNS.forEach(([a, b], i) => { + turns.push({ start: a, end: b, speaker: SUBJECT }); + const next = SUBJECT_RUNS[i + 1]; + if (next) gaps.push([b, next[0]]); + }); + for (const [a, b] of gaps) turns.push({ start: a, end: b, speaker: HOST }); + turns.sort((x, y) => x.start - y.start); + + const words = []; + let k = 0; + for (const [a, b] of SUBJECT_RUNS) { + // A word every 0.5 s, 0.4 s long; a sentence every 7 words. + for (let t = a + 0.2; t + 0.4 <= b - 0.2; t += 0.5) { + k += 1; + words.push({ w: k % 7 === 0 ? `n${k}.` : `n${k}`, start: round3(t), end: round3(t + 0.4) }); + } + } + for (const [a, b] of gaps) { + const laugh = LAUGHS.find(([s]) => s >= a - 0.01 && s < b); + let t = a + 0.1; + if (laugh && laughWords) { + words.push({ w: "haha", start: round3(laugh[0] + 0.2), end: round3(laugh[1] - 0.2) }); + t = laugh[1] + 0.1; + } + let j = 0; + for (; t + 0.35 <= b - 0.1; t += 0.45) { + words.push({ w: HOST_WORDS[j % HOST_WORDS.length], start: round3(t), end: round3(t + 0.35) }); + j += 1; + } + } + words.sort((x, y) => x.start - y.start); + + // Cues: the words in runs of up to 8, as captions would carry them. + const cues = []; + for (let i = 0; i < words.length; i += 8) { + const run = words.slice(i, i + 8); + cues.push({ start: run[0].start, end: run[run.length - 1].end, text: run.map((w) => w.w).join(" ") }); + } + + const n = Math.floor((STREAM_SECONDS - window) / hop) + 1; + const scores = Array.from({ length: n }, (_, i) => { + const a = i * hop; + const b = a + window; + const l = LAUGHS.find(([s, e]) => Math.min(b, e) - Math.max(a, s) >= window / 2); + return l ? l[2] : 0.02; + }); + return { duration: STREAM_SECONDS, turns, words, cues, laughScan: { t0: 0, hop, window, scores } }; +} + +const round3 = (x) => Math.round(x * 1000) / 1000; + +/** + * The stream's sound at 16 kHz: VOICE_B over the subject's runs, VOICE_A over + * the host's turns, LAUGH_TONE_HZ bursts (5 per second) over each laugh. + * @param {{ seconds?: number, rate?: number }} [o] `seconds` cuts it short (a quick test) + */ +export function reactionAudio({ seconds = STREAM_SECONDS, rate = 16000 } = {}) { + const out = new Float32Array(Math.round(seconds * rate)); + const { turns } = reactionStream(); + for (const t of turns) { + if (t.start >= seconds) continue; + const end = Math.min(t.end, seconds); + const voice = syntheticVoice({ ...(t.speaker === HOST ? VOICE_A : VOICE_B), seconds: end - t.start, rate, phase: t.start, level: 0.25 }); + out.set(voice.subarray(0, Math.max(0, out.length - Math.round(t.start * rate))), Math.round(t.start * rate)); + } + for (const [a, b] of LAUGHS) { + if (a >= seconds) continue; + for (let i = Math.round(a * rate); i < Math.min(out.length, Math.round(b * rate)); i += 1) { + const t = i / rate; + const burst = 0.5 - 0.5 * Math.cos(2 * Math.PI * 5 * t); + out[i] = 0.5 * burst * Math.sin(2 * Math.PI * LAUGH_TONE_HZ * t); + } + } + return out; +} + +/** + * The stream as a channel on disk. Returns the video dir. + * @param {string} channelsDir + * @param {{ channel?: string, video?: string, diarization?: boolean, audio?: Buffer | null, words?: boolean }} [o] + * `audio`: WAV bytes to write as audio.wav (encodeWav16(reactionAudio())); + * `diarization` false leaves diarization.json out. + */ +export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", video = "react001", diarization = true, audio = null } = {}) { + const s = reactionStream(); + const dir = path.join(channelsDir, channel, "data", video); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(channelsDir, channel, "config.json"), JSON.stringify({ name: "Synth Reacts" })); + writeFileSync( + path.join(dir, "transcript.cues.json"), + JSON.stringify({ id: video, title: "Synthetic reaction stream", source: "whisper", duration: s.duration, uploadDate: "20240102", cues: s.cues }), + ); + writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: video, title: "Synthetic reaction stream", duration: s.duration })); + if (diarization) { + const speakers = new Set(s.turns.map((t) => t.speaker)).size; + writeFileSync( + path.join(dir, "diarization.json"), + JSON.stringify({ videoId: video, generatedAt: "2026-10-18T00:00:00.000Z", audioSeconds: s.duration, speakers, turns: s.turns, engine: { engine: "sherpa-onnx", threshold: 0.9 } }), + ); + } + if (audio) writeFileSync(path.join(dir, "audio.wav"), audio); + return dir; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -4,6 +4,7 @@ - **Hop in on an assistant's clips in umtool: trim, split, merge, keep or cut them, and comment.** A report video whose cut is not a montage has a **Clip editor** on its Cut tab (`/projects/<id>/clips`). It loops the selected clip from what is on disk, and under it shows the clip's neighbourhood (± 60 s, or closer): the speaker turns coloured host and subject, the laughs, the words, the other clips, and the cut with a handle at each edge. Move the edges by dragging, typing, nudging (±0.1, ±0.5, ±2 s) or **Snap to words**; **Keep** / **Cut**; **Split here** at the playhead; **Merge with next**; **Add a clip** from a span dragged on the strip; **Restore the assistant's version**; **Bring in** a proposal the assistant left out. Each clip says whether it is "by the assistant" (with its score and why) or "edited by you", with its edit history. A comment on a clip is a note anchored to it, so an agent reading `umtool notes` can act on it and its reply shows in the clip's thread. **This is the host** on a speaker's turn corrects which voice is the host. Keys: space, J/L, I/O, S, M, K, X, ←/→. A keep or cut follows its clip when an edit moves the clip's start. It works on any report video; a cut without the clip finder's speakers simply has no colours. - **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first — how many per platform, how many already on disk — then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** — the same moment in the stream's YouTube upload (or Odysee) — and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`. - **Cap a phrase montage at N clips, spread across the years.** `umtool new … --seed phrase --max N`, the New project form's **Max** and the phrase finder's **Max clips** keep N instances, each year's share in proportion to how often it was said there (at least one per year), preferring clips with no speaker change in the captions and spread through each year. The rest are listed in `phrase-scan.json`. +- **umtool proposes highlights from a long recording.** Create → **Highlights from a recording** (or the new-project form's seed "highlights", or `umtool new <slug> --seed reactions --from <channel>/<id> --target 600`) takes a stream or podcast whose speakers the editor has found (its diarization) and proposes clips: each runs from the line that set it up, through the host's laugh or comment, to the next pause. The host is the speaker who interjects all the way through (you can say otherwise: `--host N`, or the clip editor's "This is the host"). Laughs are heard by a small local sound model (CED-mini, installed under `.diarize/models/`), and without it read from the transcript ("[laughter]", "haha") and the host's loud wordless moments. The clips are ranked into the target length, put in the video manifest in time order with hard cuts, and each is marked as proposed by the assistant, with its score and why; the rest stay listed in `reactions.json` beside the manifest to bring in by hand. `umtool clips analyze <project>` runs the scans on the recording's sound (a few minutes for a 2.5-hour stream, kept for the next run) and proposes again; `umtool clips propose` proposes again after a change of host or length, and never moves or removes a clip you edited, ruled, locked or added. Each laugh is also checked against the host's and the narrator's voices, so a laugh voice-acted in the video he is watching is not taken for his. `--scope FROM:TO` (or the form's From/To) reads only part of a recording — a stream that reacts to two videos, one at a time — and the laugh bar is `--laugh-min` (the form's **Laugh min**). Proposals under five seconds or with a low score are listed but never put in the cut. A recording with no diarization is refused with the command that makes it. Nothing calls an AI model, and nothing leaves the machine. Needs a restart of umtool. - **The report-video test suite passes in the Docker image.** Run inside `archilyzer:r33-umtool` (Debian's ffmpeg 7.1), six report-to-video tests failed that pass on a newer ffmpeg. Four came from how the tests drove ffmpeg, not from the videos it renders: they now run the graphs the way a build does. One compared against an older ffmpeg's timing drift, which 7.1 does not show; it is now only checked where the drift happens. The sixth needs a git checkout, which an image does not include, and now says so and skips. Nothing a build renders changed. - **umtool scores who is speaking in each montage clip.** A montage's clip deck and its Cut tab have **Score the voices**: each clip's phrase (and a second either side, its speech only) is compared with the host's voice, and every Cut-tab row then reads `voice 0.43 · unsure` — likely, unsure or unlikely him — and the deck puts the doubtful clips first with their scores. The host's voice is the clips you ruled keep in the audition deck once there are three, or before that solo uploads of the channel found on disk (captioned, no speaker change in the captions, not a stream, no guest in the title, spread over the years); the picker beside the button chooses. It runs on this machine with the speaker model the diarization lane already uses — no network, no AI model — and takes about half a minute for 73 clips. It sorts and flags; whether it is him is still decided by ear. The scores are kept in `voice-match.json` beside the manifest, by the source moment, so a re-seeded montage keeps them. The same from a terminal: `umtool voice-match <project>`. Needs a restart of umtool. - **A montage's closing wall is the right length on older ffmpeg.** With ffmpeg 7.1 (the umtool Docker image), a tile did not hold its last frame after saying its phrase and did not wait for its turn, so the wall came out short of the length its plan gives (23 frames on the test cut) and, with groups, tiles vanished instead of freezing. The tiles now hold and wait on ffmpeg 7.1 as they do on newer versions; renders on the newer ffmpeg are unchanged. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10649,6 +10649,70 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri fallback`; components `FetchWindowsPanel` (Cut tab, clip deck) and `MontageFetchTools` (clip deck: fetch + stand-ins). The e2e stub's door is `umtool/e2e/fixtures/editor-stub-fetch-windows.mjs` (a `vrefuse*` id = a 403). +## Release 35 lane C1: the clip finder — reactions.json, the assist key (verified 2026-10-19, branch `r35/clip-analysis`) + +- **`<project>/reactions.json`** `{version: 1, source {channel, video, duration, words: "words.json" | null, wordsFrom + "words.json"|"transcript.json"|"cues"|<--words basename>, diarization {generatedAt, engine}, audio?, audioKind?}, + params {target 600, laughMin 0.25, mergeGap 6, setupMax 20, clipMax 75, scope [from, to|null] | null}, speakers [{index, role "host"|"subject"| + "other", label "Host"|"Subject"|"Speaker N+1", seconds, turns, how "auto"|"operator", sameAs?}], turns [{start, end, + speaker}], laughs [{start, end, score, speaker: n|null, src? "text"|"energy", voice? {host, subject}, by? "voice"}], moments [{id m001…, t, end, kind + "laugh"|"comment", score, speaker: n|null, text}], proposals [{id p001…, start, end, score, moments[], used, clipId + "r001"|null, why}], laughSource "model"|"text"|"text+energy", scans {laughs {model, windows, madeAt} | null, voices + {model, madeAt} | null}, madeAt, proposedAt, rolesChangedAt?}`. The plan's shape (plans/release-35/clip-finder.md) + plus the optional keys `wordsFrom`, `audio*`, `sameAs`, `src`, `voice`, `by`, `params.scope`, `laughSource`, `scans`, + `madeAt`, `proposedAt`, `rolesChangedAt`, and `speaker: null` on a laugh/moment heard in no turn. Writers: `writeReactions` (tmp + rename, + whole) from the analysis, and `setSpeakerRole(dir, index, role|null)` (the clip editor's only write): role + + `how: "operator"`, every OTHER speaker that held that host/subject role → "other"/auto (one host, one subject; a + `sameAs` of this one keeps it); null hands it back (`how: "auto"`); stamps `rolesChangedAt`. Module + `yt-dlp-transcript-common/lib/clips/reactions.mjs` (also `readReactions`, `operatorRoles`, `REACTIONS_FILE`). +- **The manifest clip's `assist`** `{by "assistant"|"operator", proposal?, score? 0..1, why?, original? {start, end, + cutStart, cutEnd}, edits? [{at ISO, by, what "trim"|"split"|"merge"|"add"|"restore", from?, to?}]}`; + `validateAssist(manifest)` (`lib/clips/assist.mjs`) runs in report-to-video's build validators and lint + (`validatorErrors`) and in umtool's manifest writer's structure checks; unknown keys inside `assist` are allowed, the + known ones typed; `by: "assistant"` needs `proposal`. The renderer ignores it. A seeded clip: `{type, id r<NNN>, + channel, video, start = cutStart − 1.5, end = cutEnd + 1.5 (clamped), cutStart, cutEnd (= the proposal), cite = + floor(cutStart), quote (the cut's words ≤ 160 chars), assist {by: "assistant", proposal, score, why, original, + edits: []}}`. +- **A proposal pass** (`applyProposals`): movable = an assistant clip of the recording with no ruling (clipMomentKey in + montage-rulings.json) and no `lock*`. Movable clips are updated in place (same id) when their proposal is still used, + removed when not; new used proposals become `r<next>`; everything else is untouched. A proposal overlapping a fixed + clip by ≥ 50 % (of either) is that clip (`used`, `clipId` = it), and fixed clips' seconds count toward the target + first. The recording's clips are sorted by cut in the slots they hold; other entries do not move. Proposal ids: + overlap ≥ 50 % of the longer with a previous proposal → its id; else the next number. +- **The scans** (`lib/clips/scan.mjs`): `runAudioScan` decodes 300 s chunks (`decodeSpan`), windows 1 s / hop 0.5 s, + each window's dBFS (mean power of 20 ms frames, 1 dp) and, with the tagger, its laugh score = Σ CED probs of classes + 16, 18, 19, 20, 21 clamped to 1 (3 dp); one `scripts/audio-tag.py` process per 4 chunks (wav per chunk, deleted after). + `speakerCentroids`: ≤ 12 turns ≥ 2 s per cluster overlapping no other cluster, spread by start, first 8 s each, voiced + frames (`voicedSamples`), `embedWavs`, `robustCentroid` (5 dp). Cache `<project>/scans/<channel>--<video>.audio.json` + `{…scan, source {path, size, mtimeMs}, clock, kind, madeAt}` (reused while source key, `model.file`, clock match) and + `.voices.json` `{version, model, speakers {i: {centroid, pieces, kept}}, engineModel, source, diarization, madeAt}` + (reused while source key, diarization `generatedAt`, engine model basename match). Scratch `<project>/.clips-work`. + Tagger: `AUDIO_TAG_PYTHON|SCRIPT|MODEL|LABELS`, else `settings.diarization.python`, `scripts/audio-tag.py`, + `.diarize/models/sherpa-onnx-ced-mini-audio-tagging-2024-04-19/model.int8.onnx` + its `class_labels_indices.csv` + (gitignored; the orchestrator installed it). Measured: ~11 ms per 1 s window on one thread (CED-mini int8), so a + 2.5 h stream ≈ 18,500 windows ≈ 3–4 min. +- **The sound** (`umtool/lib/report/reactions.mjs` `recordingAudio`): the video dir's `audio.m4a|mp3|opus|wav|flac` + first, else `resolveLocalSource(0..duration, audio: true)`; `clock` = windowStart + `clockOffset`. **Words**: + `<project>/words.json` (`{words: [...]}` as `pnpm ops transcribe {words: true, out}` writes, or a bare array) > + corpus `transcript.json` (whisper tokens via montage.mjs `whisperWords`) > `transcript.cues.json` spread by length. + **Duration**: diarization `audioSeconds` > metadata `duration` > cues doc `duration` > the last turn's end. +- **Job**: `/api/report/clips` POST `{project, mode? "analyze"|"propose", from?, target?, host?}` → `clipsSteps` → one + lib/jobs.ts step `nice -n 10 node umtool/bin/umtool.mjs clips <mode> <id> … --progress ndjson` (events `{ev: "clips", + phase: load|laughs|voices|propose|done, …}`), timeout 90 min (analyze) / 5 min (propose). GET `?project=` summarizes + reactions.json. The new-project form posts `mode: "analyze"` right after creating a reactions project. +- **The scope** (`params.scope`, the live case's addendum): turns cut to [from, to], words and laugh windows wholly + inside it, `duration` = to, the role spread measured over the scope; voice centroids from the scope's turns (the + voices cache key carries it, `scope: "<from>-<to|end>"|"all"`). CLI `--scope FROM:TO|all`, or numeric `--from S` / + `--to S` (one end; a non-numeric `--from` is the recording); the form's From s / To s; the seed's `scope`. +- **Laugh voices**: every laugh's span (≥ 1.5 s, ≤ 8 s, centred; `laughVoiceSpan`) embedded raw (`embedSpans`, no gate) + and kept in `.voices.json` `laughs {"<start>-<end>" (2 dp): embedding}` across re-scans of the same file; a propose + embeds only missing ones (it opens the sound). `voiceLaughs`: cosine to the centroid of the host (resp. subject) + speaker with the most seconds; ≥ 0.2 and ≥ 0.1 over the other → that speaker, `by: "voice"`; else the overlap rule. + A laugh the voice gives the subject weighs 0.3 (LAUGH_WEIGHT.subjectVoice). Centroid pieces: the longest clean turns + ≥ 2 s (else the longest at all), 24 for the two clusters with the most seconds, 6 for the rest, each the middle ≤ 8 s. +- **The floor**: a proposal under CLIP_MIN_S (5 s) is widened to 5 s about its middle (`widenTo`, snapped outward) + before ranking; `rankIntoTarget` never uses one under 5 s or scoring under USE_MIN_SCORE (0.2) — it stays listed. + ## Release 35 lane C2: the clip editor (verified 2026-10-19, branch `r35/clip-editor`) - **Where**: `/projects/<id>/clips` on a report video whose manifest has NO montage clip (`hasMontageClips` false) → diff --git a/plans/release-35/clip-analysis.md b/plans/release-35/clip-analysis.md @@ -0,0 +1,113 @@ +# Release 35 lane C1 — `r35/clip-analysis`: finding the clips (as shipped) + +The plan of record is [clip-finder.md](clip-finder.md); this lane is its analysis half: from a long recording's +speaker turns, words and sound to clip proposals in a report-video manifest, each marked as the assistant's, and +`reactions.json` beside it. Lane C2 (`r35/clip-editor`) is the review UI over the same two shapes. + +## What + +- **`common/lib/clips/`** (plain ESM + `.d.mts`, exported as `yt-dlp-transcript-common/lib/clips/*.mjs`): + - `clips.mjs` — pure: `assignRoles` (host = most turns < 8 s × widest spread over 20 bins; subject = most seconds + of the rest; < 1 % of the speech never wins; a third cluster whose TitaNet centroid is ≥ 0.6 like the host's or + subject's takes that role with `sameAs`; the operator's roles stand), `laughEvents` (runs ≥ `laughMin`, joined + across 0.5 s, mean score), `textLaughs` / `energyLaughs` (the no-model fallback), `attributeLaughs` (a host turn + overlapping makes it the host's), `findMoments`, `momentSpan` / `buildProposals` (setup → reaction → tail, + snapped to word gaps, merged, capped), `stableIds`, `rankIntoTarget`, and `analyze` (all of it). + - `assist.mjs` — `validateAssist`, `clipFromProposal`, `fixedClips`, `applyProposals` (the one proposal-to-clip + writer: an untouched assistant clip is moved in place or removed; everything else stays). + - `reactions.mjs` — `readReactions`, `writeReactions` (tmp + rename), `operatorRoles`, **`setSpeakerRole`** (C2's + write: the operator's "This is the host"). + - `scan.mjs` — `resolveTagger`, `tagWavs`, `runAudioScan` (1 s windows / 0.5 s hop: level always, laugh score with + the tagger; 300 s chunks, one tagger process per 4), `centroidPieces`, `speakerCentroids` (voiceMatch's + `embedWavs` + `robustCentroid`). +- **`scripts/audio-tag.py`** — sherpa-onnx `AudioTagging` (CED-mini), modelled on `speaker-embed.py`: wavs in, + per-window probabilities of the requested classes out (JSON, 4 dp, one thread). Proved on the model's bundled + `test_wavs/4.wav` (laughter): whole-file family sum 0.99; per-window 0.84 peak; the JS driver over the same file + in 4 s chunks gives the same 19 values as the script alone. +- **umtool** (`umtool/lib/report/reactions.mjs`): `loadRecording` (diarization required — the refusal names + `archilyzer diarize backfill --scope video:<channel>/<id>`; words from `<project>/words.json` > corpus + `transcript.json` > cues), `recordingAudio`, `scanRecording` (cached in `<project>/scans/`), `proposalPass`, + `proposeProject` (manifest via `replaceManifest` with a token and an undo point, retried on a stale token; + ruled and locked clips protected), `clipsCommand` (`umtool clips analyze|propose|show`), `clipsSteps` (the job). + `scaffold.mjs` gains `--seed reactions` (and `seedsFor().reactions`); `umtool new --seed reactions` then runs + `clips analyze` unless `--no-analyze`. `/api/report/clips` (GET summary / job, POST start, cancel). The + new-project form's seed "highlights" (+ target) and Create's line **Highlights from a recording**, which starts + the analyze job after creating the project. +- **The validator:** `validateAssist` in report-to-video's build validators and `lint.mjs validatorErrors`, and in + umtool's manifest writer's `structureErrors`. The renderer ignores the key. +- **Test kit:** `testing/clips/reactionStream.mjs` (a synthetic reaction stream: turns, words, cues, laugh windows, + its sound, and `writeReactionCorpus`), `testing/audio/fakeAudioTag.mjs` (the shim's stand-in: it hears the + stream's 1.5 kHz laugh tone). The umtool e2e app runs the fake tagger (`AUDIO_TAG_*` in playwright.config.ts). + +### The live case's findings, folded in (the orchestrator's run on the first case) + +- **Scope**: `params.scope: [from, to|null] | null` — turns cut to it, words and laugh windows wholly inside it, + duration = its end; CLI `--scope FROM:TO|all` or numeric `--from S --to S` (the plan's `--from <channel>/<id>` + keeps its meaning: a number is the scope); the seed and the form (From s / To s) take it. +- **Centroids computed in `clips analyze`**: the longest clean turns, 24 for the two clusters with the most seconds, + 6 for each other (30 clusters at threshold 0.9 on the live case; host and subject at cosine 0.02). +- **Laugh voice check**: each laugh's span (≥ 1.5 s, centred) embedded; host if host ≥ 0.2 and host − subject ≥ 0.1, + subject on the mirror (`by: "voice"`), else the overlap rule; `voice: {host, subject}` on every checked laugh; a + laugh the voice gives the subject weighs 0.3. Embeddings kept in the voices scan. +- **laughMin** settable from the CLI (`--laugh-min`, already), the seed (`umtool new … --laugh-min`) and the form + (**Laugh min**); default stays 0.25. +- **The floor**: proposals under 5 s are widened to 5 s (snapped) before ranking; `rankIntoTarget` never uses one + under 5 s or under score 0.2. + +## The shapes (owned here; C2 codes against them) + +Exactly the plan's, plus optional keys (FACTS.md, "Release 35 lane C1"): `source.wordsFrom`, `source.audio`, +`source.audioKind`, `speakers[].sameAs`, `laughs[].src` ("text" | "energy"; absent = the model), `laughSource`, +`scans`, `madeAt`, `proposedAt`, `rolesChangedAt`; `speaker: null` on a laugh or moment heard in no turn; an unused +proposal has `clipId: null`; laughs may carry `voice: {host, subject}` and `by: "voice"`; `params.scope`. A proposal's `start`/`end` IS the clip's cut (`cutStart`/`cutEnd`); the clip's +window is 1.5 s wider each side (`assist.original` carries all four). + +## Rulings followed + +- The UI works without AI: every step is signal processing plus two small local models (CED-mini, TitaNet), and the + no-model fallback (transcript markers + energy) runs the whole loop. Nothing calls an LLM; no network. +- Fetches and transcription are not done here: words come from `pnpm ops transcribe {words: true, out}`; the sound + is whatever the corpus already holds. +- Records state rulings, not reasons; no corpus content in fixtures (the stream is numbered filler words). + +## Commits + +| sha | what | +|---|---| +| `9da7c408` | common: lib/clips — roles, laughs, moments, proposals, reactions.json, the assist key; test kit stream | +| `318eb9d2` | common: the laugh scan + voice centroids, scripts/audio-tag.py, the fake tagger | +| `ada3e840` | umtool: `--seed reactions`, `umtool clips analyze\|propose\|show`, validateAssist wired | +| `98a208e9` | umtool: seedsFor's reactions key; the frames test's words kept | +| `71d70f47` | umtool: the form's "highlights" seed, Create's line, the clips job route; create.spec | +| `9911841f` | docs: cli.md, report-video.md "Highlights", FACTS, ENVIRONMENT.md (AUDIO_TAG_*), CHANGELOG | +| `455318e8` | plans: this record | +| `a62cdc98` | clips: the live case's findings — scope, centroids, laugh voice check, laughMin in seed/form, the floor | +| (this) | plans: the record's gates | + +## Gates (all through the shared lock, from the worktree root) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` — clean at `ada3e840` (8.7 min, the lock shared) + and at `71d70f47`'s tree (umtool tsc after the e2e edits: clean). +- common `pnpm --filter yt-dlp-transcript-common test` — 4648 tests, 4646 pass, 2 skipped (the one failure in that + run was `ENVIRONMENT.md is stale`, an artefact of editing envVars.ts mid-run; regenerated and re-run green). Before + this lane: 4627 (21 new: clips.test.ts 16, scan.test.ts 5). +- `pnpm run test:scripts` — 1182 tests, 1178 pass, 0 fail, 4 skipped (before: 1175; 7 new in + `umtool/lib/report/reactions.test.mjs`; `scaffold-frames.test.mjs` updated for seedsFor's new key). +- `pnpm archilyzer docs env --check` — clean (ENVIRONMENT.md regenerated: four `AUDIO_TAG_*` rows). +- After `a62cdc98`: full tsc clean; `common/lib/clips/*.test.ts` 24/24, `umtool/lib/report/reactions.test.mjs` 8/8, + scaffold-frames + scaffold-phrase green. The full common suite and test:scripts were queued behind the shared lock + at hand-off (logs `$T/r35c1-commontest2.log`, `$T/r35c1-testscripts2.log`). +- e2e `create.spec.ts` (umtool, `E2E_MODE=dev`, with the new "Highlights from a recording" test): NOT RUN — it sat + 14 min behind the machine's heavy slot (the live case's diarization, a `next build`) while holding the session's + shared lock, and was stopped so the other lanes' tsc could run. The orchestrator's full umtool suite covers it. +- No build: the slice changes umtool, and its one e2e spec ran under `next dev`. + +## Found and left + +- The plan's example shows a proposal's span wider than its clip's cut; here the proposal IS the cut and the window + is the pad. Same keys, recorded above. +- CED's per-class outputs are independent sigmoids, so the family's sum can pass 1; it is clamped. On 1 s windows the + scores run lower than on a whole laugh (0.84 peak vs 0.99 on the bundled laugh file): `laughMin` 0.25 is the plan's + default, to be calibrated on the first case (`--laugh-min`). +- Multi-host streams (more than one host role) are later (the plan's "Later"): `setSpeakerRole` keeps one host and + one subject. diff --git a/scripts/audio-tag.py b/scripts/audio-tag.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Audio tagging for common/lib/clips/scan.mjs (release 35 C1): the laugh scan. + +WAV files in, per-window class probabilities out, as JSON. Nothing else: +which audio, the windows' clock, the laugh family's sum, the events and the +cache all live in the .mjs caller, so this file stays a thin shell over +sherpa-onnx's AudioTagging (CED-mini, AudioSet's 527 classes) — modelled on +scripts/speaker-embed.py. + +stdout is JSON ONLY; progress goes to stderr. + +Usage: + audio-tag.py --model <model.onnx> --labels <class_labels_indices.csv> + [--threads N] [--classes 16,18,19,20,21] <request.json> + +request.json: {"items": [{"id": "...", "wav": "/abs/path.wav", + "window": 1.0, "hop": 0.5}, ...]} + Each wav is 16-bit PCM, mono, 16 kHz (the caller decodes to it). With a + `window` (seconds) the wav is scored window by window, every `hop` seconds + (default: the window), as many whole windows as fit; without one, the + whole wav is one window. + +Output: {"model": "<file name>", "version": "<sherpa-onnx>", "classes": [...], + "names": [...], "items": [{"id", "seconds", "window", "hop", + "scores": [[p, ...], ...] | null, "error"?: "..."}]} + `scores` has one row per window, one probability per requested class, in + `classes` order, rounded to 4 decimals (the same input prints the same + bytes). One thread by default, as speaker-embed.py: a CPU reduction split + across threads is where an ONNX run can differ in its last bits. +""" +import argparse, csv, json, os, sys, wave + + +def read_wav(np, path): + with wave.open(path, "rb") as w: + rate = w.getframerate() + width = w.getsampwidth() + chans = w.getnchannels() + raw = w.readframes(w.getnframes()) + if width != 2: + raise ValueError(f"{os.path.basename(path)}: {width * 8}-bit wav, want 16-bit PCM") + x = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0 + if chans > 1: + x = x.reshape(-1, chans).mean(axis=1) + return x, rate + + +def read_labels(path): + names = {} + with open(path, "r", encoding="utf8") as f: + for row in csv.DictReader(f): + names[int(row["index"])] = row["display_name"] + return names + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("request") + ap.add_argument("--model", required=True) + ap.add_argument("--labels", required=True) + ap.add_argument("--threads", type=int, default=1) + ap.add_argument("--classes", default="16,18,19,20,21") + args = ap.parse_args() + + try: + import numpy as np + import sherpa_onnx + except ImportError as e: + print(f"audio-tag: missing dependency: {e}", file=sys.stderr) + return 3 + + classes = [int(c) for c in args.classes.split(",") if c.strip() != ""] + names = read_labels(args.labels) + with open(args.request, "r", encoding="utf8") as f: + req = json.load(f) + items = req.get("items") or [] + + cfg = sherpa_onnx.AudioTaggingConfig( + model=sherpa_onnx.AudioTaggingModelConfig(ced=args.model, num_threads=args.threads), + labels=args.labels, + top_k=max(len(names), 1), + ) + if not cfg.validate(): + print("audio-tag: invalid model config", file=sys.stderr) + return 2 + tagger = sherpa_onnx.AudioTagging(cfg) + + def probs(rate, x): + stream = tagger.create_stream() + stream.accept_waveform(rate, x) + by = {e.index: e.prob for e in tagger.compute(stream)} + return [round(float(by.get(c, 0.0)), 4) for c in classes] + + out = [] + done = 0 + for item in items: + rec = {"id": item.get("id"), "seconds": 0.0, "window": None, "hop": None, "scores": None} + try: + x, rate = read_wav(np, item["wav"]) + rec["seconds"] = round(x.size / rate, 3) + win = item.get("window") + if win is None: + rec["scores"] = [probs(rate, x)] if x.size else [] + else: + win = float(win) + hop = float(item.get("hop") or win) + rec["window"] = win + rec["hop"] = hop + n_win = int(round(win * rate)) + n_hop = max(1, int(round(hop * rate))) + rows = [] + a = 0 + while a + n_win <= x.size: + rows.append(probs(rate, x[a:a + n_win])) + a += n_hop + rec["scores"] = rows + except Exception as e: # one bad file is that item's error, not the run's + rec["error"] = str(e) + out.append(rec) + done += 1 + print(f"audio-tag: {done}/{len(items)}", file=sys.stderr, flush=True) + + json.dump( + { + "model": os.path.basename(args.model), + "version": getattr(sherpa_onnx, "__version__", None), + "classes": classes, + "names": [names.get(c, str(c)) for c in classes], + "items": out, + }, + sys.stdout, + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/umtool/app/api/report/clips/route.ts b/umtool/app/api/report/clips/route.ts @@ -0,0 +1,85 @@ +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { clipsSteps } from "@/lib/report/reactions.mjs"; + +export const dynamic = "force-dynamic"; + +// THE CLIP FINDER (release 35 C1) -- "Find the clips" (the laugh scan and the +// voices on the recording's sound, then a proposal pass) and "Re-propose" +// (the pass alone, after a role flip or a param change), as ONE job on the +// app's runner (lib/jobs.ts: one at a time, a log, the NDJSON events, +// Cancel). The job runs the CLI (`umtool clips analyze|propose`), so the +// button and a terminal do the same thing. Local (CED-mini and TitaNet on the +// CPU, nice'd), no network, no LLM. +// +// GET ?job=<id>[&since=&sinceEvent=] that job +// GET ?project=<id> the project's reactions.json summary, and the job running, if any +// POST { project, mode?: "analyze" | "propose", from?: "<channel>/<id>", target?: seconds, host?: speaker } +// ?cancel=<job> stop it +export async function GET(request: Request) { + const url = new URL(request.url); + const headers = { "cache-control": "no-store" }; + const id = url.searchParams.get("job"); + if (id) { + const job = getJob(id); + if (!job) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const project = await projectRef(String(url.searchParams.get("project") ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const doc = await readReactions(project.dir); + const running = runningJob(); + const used = doc ? doc.proposals.filter((p) => p.used) : []; + return Response.json( + { + reactions: doc + ? { + source: doc.source, + params: doc.params, + speakers: doc.speakers, + laughs: doc.laughs.length, + laughSource: doc.laughSource ?? null, + proposals: doc.proposals.length, + used: used.length, + usedSeconds: Math.round(used.reduce((n, p) => n + (p.end - p.start), 0)), + proposedAt: doc.proposedAt ?? null, + rolesChangedAt: doc.rolesChangedAt ?? null, + } + : null, + running: running && running.project === project.id && running.kind.startsWith("clips-") ? jobView(running) : null, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const { cancelJob } = await import("@/lib/jobs"); + return Response.json({ cancelled: cancelJob(cancel) }); + } + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "clips are found for a report video" }, { status: 400 }); + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + const plan = clipsSteps(project, { + mode: body.mode === "propose" ? "propose" : "analyze", + ...(typeof body.from === "string" ? { from: body.from } : {}), + ...(typeof body.target === "number" ? { target: body.target } : {}), + ...(typeof body.host === "number" ? { host: body.host } : {}), + }); + try { + const job = startJob(plan.kind, plan.steps, { project: project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -59,6 +59,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, @@ -712,6 +714,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] [--laugh-min X] [--scope FROM:TO] [--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", @@ -739,6 +744,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)", @@ -784,6 +794,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"), @@ -1127,6 +1139,13 @@ async function cmdIndex() { // Scaffolding. The writer is lib/projects/scaffold.mjs, shared with the route. // --------------------------------------------------------------------------- +/** `--scope FROM:TO` (seconds; either side may be empty). */ +function parseScopeFlag(v) { + const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(String(v)); + if (!m) die(`--scope ${v}: FROM:TO in seconds (either may be empty)`); + return [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null]; +} + async function cmdNew() { const slug = positional[0]; if (!slug) { @@ -1134,7 +1153,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>] [--laugh-min X] [--scope FROM:TO] [--no-analyze]]", ); } const kind = val("--kind") ?? "report-video"; @@ -1160,16 +1180,29 @@ async function cmdNew() { } : {}), ...(val("--max") != null ? { max: Number(val("--max")) } : {}), + ...(val("--laugh-min") != null ? { laughMin: Number(val("--laugh-min")) } : {}), + ...(val("--scope") != null ? { scope: parseScopeFlag(val("--scope")) } : {}), }); } catch (e) { 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/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx @@ -33,6 +33,11 @@ import { useHydrated } from "@/components/ui/use-hydrated"; // Release 33: with no source, [data-new-seed] offers "a phrase across channels" // ([data-new-phrase], [data-new-channels], [data-new-prefer], [data-new-exclude]). // Release 35: [data-new-max] caps the reel at N instances spread across the years. +// Release 35 C1: [data-new-seed] offers "highlights" (the clip finder, when the +// recording has its speakers: diarization.json), its target in [data-new-target] +// (seconds, default 600), [data-new-laugh-min] and the scope [data-new-scope-from]/ +// [data-new-scope-to]; creating one starts "Find the clips" (the laugh scan +// and the voices, then proposals) as a job, and opens the project. type Brand = { id: string; label: string }; type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null }; @@ -43,6 +48,9 @@ const FIELD_HINT: Record<string, string> = { siteOrigin: "the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)", seed: "seed the timeline from the video's digest chapters, or from its frame scan's events (review each)", target: "the frame-scan cut's length budget: the events ranked into this many seconds (10 to 3600)", + highlights: "the highlights' length: the proposed clips ranked into this many seconds (10 to 7200)", + laughMin: "how sure the sound model must be that a second is laughter, 0.01 to 1 (default 0.25; lower finds more)", + scope: "read only this part of the recording, in seconds (empty: from the start / to the end)", phrase: "a regular expression, any case — e.g. slow[ ,]+news (day|week)", channels: "the channel slugs to scan, separated by commas", prefer: "the channel to cut from where it holds a copy of the same stream (optional)", @@ -63,6 +71,7 @@ export default function NewProjectMenu({ reports, submitLabel = "Create", onCancel, + seed: initialSeed = "", }: { kinds: Kind[]; /** One kind, fixed: no kind select (Create's lines). */ @@ -78,6 +87,8 @@ export default function NewProjectMenu({ reports?: Report[]; submitLabel?: string; onCancel?: () => void; + /** The seed chosen to start with (Create's "Highlights from a recording": reactions). */ + seed?: "" | "chapters" | "frames" | "reactions"; }) { const router = useRouter(); const hydrated = useHydrated(); @@ -89,15 +100,19 @@ export default function NewProjectMenu({ const [src, setSrc] = useState(from ?? reports?.[0]?.path ?? ""); const [byHand, setByHand] = useState(!reports?.length); const [origin, setOrigin] = useState(""); - const [seed, setSeed] = useState<"" | "chapters" | "frames" | "phrase">(""); + const [seed, setSeed] = useState<"" | "chapters" | "frames" | "phrase" | "reactions">(initialSeed); const [phrase, setPhrase] = useState(""); const [channels, setChannels] = useState(""); const [prefer, setPrefer] = useState(""); const [exclude, setExclude] = useState(""); const [max, setMax] = useState(""); const [target, setTarget] = useState("240"); + const [hlTarget, setHlTarget] = useState("600"); + const [laughMin, setLaughMin] = useState("0.25"); + const [scopeFrom, setScopeFrom] = useState(""); + const [scopeTo, setScopeTo] = useState(""); // What the video can be seeded from (null: not asked yet, or not a video). - const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean } | null>(null); + const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean; reactions: boolean } | null>(null); const [brand, setBrand] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); @@ -118,7 +133,7 @@ export default function NewProjectMenu({ .then((r) => (r.ok ? r.json() : null)) .then((j) => { if (gone || !j?.video) return; - setSeeds({ chapters: !!j.chapters, frames: !!j.frames }); + setSeeds({ chapters: !!j.chapters, frames: !!j.frames, reactions: !!j.reactions }); setSeed((v) => (v && !j[v] ? "" : v)); }) .catch(() => {}); @@ -143,6 +158,11 @@ export default function NewProjectMenu({ } else if (fields.includes("seed") && seed && seed !== "phrase" && looksLikeVideo) { body.seed = seed; if (seed === "frames") body.target = Number(target); + if (seed === "reactions") { + body.target = Number(hlTarget); + if (laughMin.trim()) body.laughMin = Number(laughMin.trim()); + if (scopeFrom.trim() || scopeTo.trim()) body.scope = [scopeFrom.trim() || null, scopeTo.trim() || null]; + } } if (fields.includes("brand") && brand) body.brand = brand; const res = await fetch("/api/projects/new", { @@ -153,6 +173,16 @@ export default function NewProjectMenu({ }); const j = await res.json(); if (!res.ok) throw new Error(j.error || `HTTP ${res.status}`); + // The clip finder's scans run as a job (minutes on a long stream); the + // project opens on its first proposals, from the transcript alone. + if (body.seed === "reactions" && j.id) { + await fetch("/api/report/clips", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project: j.id, mode: "analyze" }), + cache: "no-store", + }).catch(() => null); + } router.push(j.href); router.refresh(); } catch (e) { @@ -291,6 +321,9 @@ export default function NewProjectMenu({ <option value="frames" disabled={seeds !== null && !seeds.frames}> the frame scan&apos;s events{seeds !== null && !seeds.frames ? " (no scan)" : ""} </option> + <option value="reactions" disabled={seeds !== null && !seeds.reactions}> + highlights: the host&apos;s laughs and comments{seeds !== null && !seeds.reactions ? " (no speakers yet)" : ""} + </option> </Select> </Field> )} @@ -334,6 +367,32 @@ export default function NewProjectMenu({ /> </Field> )} + {asksSeed && seed === "reactions" && ( + <Field label="Target s"> + <Input + value={hlTarget} + onChange={(e) => setHlTarget(e.target.value)} + inputMode="numeric" + aria-label={`target seconds — ${FIELD_HINT.highlights}`} + title={FIELD_HINT.highlights} + data-new-target + className="num w-20" + /> + </Field> + )} + {asksSeed && seed === "reactions" && ( + <> + <Field label="Laugh min"> + <Input value={laughMin} onChange={(e) => setLaughMin(e.target.value)} inputMode="decimal" aria-label={`laugh min — ${FIELD_HINT.laughMin}`} title={FIELD_HINT.laughMin} data-new-laugh-min className="num w-20" /> + </Field> + <Field label="From s"> + <Input value={scopeFrom} onChange={(e) => setScopeFrom(e.target.value)} inputMode="numeric" placeholder="start" aria-label={`from seconds — ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-from className="num w-20" /> + </Field> + <Field label="To s"> + <Input value={scopeTo} onChange={(e) => setScopeTo(e.target.value)} inputMode="numeric" placeholder="end" aria-label={`to seconds — ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-to className="num w-20" /> + </Field> + </> + )} <div className="flex items-center gap-2 pb-px"> <Button type="submit" variant="go" disabled={!hydrated || busy || !slug.trim()} data-new-create> {busy ? "Creating…" : submitLabel} diff --git a/umtool/components/create/CreateView.tsx b/umtool/components/create/CreateView.tsx @@ -55,6 +55,7 @@ function lines(d: CreateData): { group: string; lines: Line[] }[][] { { make: "video-article", title: "From an article", sub: "Chains a cut from the current report", action: "Choose article" }, { make: "video-board", title: "From a board", sub: "A timeline scaffolded from the pinned cites", action: "Choose board" }, { make: "video-recording", title: "From a recording", sub: "A video URL, or <channel>/<id> from the archive", action: "Choose recording" }, + { make: "video-highlights", title: "Highlights from a recording", sub: "A long stream cut to its laughs and comments · needs its speakers", action: "Choose recording" }, { make: "video-report", title: "From a sweep report", @@ -160,6 +161,21 @@ export default function CreateView({ onCancel={cancel} /> ) : null; + case "video-highlights": + return data.kinds.recording ? ( + <NewProjectMenu + kinds={[data.kinds.recording]} + kind={data.kinds.recording.id} + inline + from={from} + seed="reactions" + fromLabel="Recording" + fromHint="<channel>/<videoId> of a recording with its speakers (diarization.json)" + fromPlaceholder="channel/videoId" + submitLabel="Find the clips" + onCancel={cancel} + /> + ) : null; case "video-report": return data.kinds.report ? ( <NewProjectMenu diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -25,7 +25,7 @@ Inbox cannot disagree about what is wrong with one. | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | | `index [--rebuild] [--prune] [--since MS] [--json]` | the cache | -| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` | scaffold | +| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO] [--no-analyze]` | scaffold | | `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there | | `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch | | `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building | @@ -47,6 +47,7 @@ Inbox cannot disagree about what is wrong with one. | `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in | | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | +| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | A project argument is an exact id, a directory, or a **unique** basename. Two projects answering to one name is reported, never resolved by picking one. @@ -211,3 +212,29 @@ umtool new quartering-slow-news --seed phrase \ --channels the-quartering,jeremy-hambly,quartering-live,cornbreadman \ --prefer the-quartering-rumble --exclude 'slow news \w+,? jeremy' ``` + +**`--seed reactions`** (release 35) is the clip finder's first pass over a long +recording — a stream, a podcast, a reaction video — and needs its speakers: +`diarization.json` beside it (`archilyzer diarize backfill --scope +video:<channel>/<id>`; the refusal names it). The host is the speaker with the +most short turns spread across the whole recording, the subject the one with +the most seconds among the rest; every host laugh and every host comment of +1.5 s of words or more is a moment; a clip runs from the start of the subject's +sentence that set it up (at most 20 s back) through the reaction to the next +pause, merged with its neighbours, ranked into `--target` seconds (default 600). +The used proposals become clips `r001…`, each with `assist: {by: "assistant", +proposal, score, why, original}`, chronological, hard cuts +(`render.transition: 0`); `reactions.json` beside the manifest keeps the whole +analysis and every proposal, used or not. The seed reads laughs from the +transcript alone; `umtool new` then runs `umtool clips analyze` (the laugh scan +and the voices on the sound) unless `--no-analyze`. `--laugh-min X` sets the laugh +bar and `--scope FROM:TO` reads only that part of the recording (a stream that +reacts to two videos, one at a time); both are kept for the next pass. The new-project form's seed +"highlights" (and Create's **Highlights from a recording**) does the same and +starts the scan as a job. + +```sh +archilyzer diarize backfill --scope video:some-channel/abc123 +umtool new some-stream-highlights --seed reactions --from some-channel/abc123 --target 600 +umtool clips propose some-stream-highlights --host 1 # the other speaker is the host +``` diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -50,6 +50,7 @@ travel. umtool never reorders as a side effect of a window edit. "note": "…", // why it is in the cut (editorial, for humans) "correction": "…", // what the REPORT got wrong here; never rendered "verdict": "confirmed", // or "incorrect"; absent = nobody has looked yet + "assist": { "by": "assistant", … }, // the clip finder's provenance (see "Highlights"); never rendered "chapter": "…", // chapter title; falls back to date + title "section": 2, "sectionEnter": true, "lock": true, "lockStart": true, "lockEnd": true } @@ -942,6 +943,107 @@ fallback?, inReference?, why?}}}` — keyed by the source moment, as the rulings are, so a re-seed keeps it. A clip with no window on disk, or no speech in it, has `score: null` and says why. +## Highlights: the clip finder + +A long recording cut down to its best moments — a stream, a podcast, a host +reacting to a narrated video — starts as clips **proposed** from the recording +itself, never as a finished cut. `umtool new <slug> --seed reactions --from +<channel>/<id>` (or Create → **Highlights from a recording**) writes the first +proposals; `umtool clips analyze <project>` runs the scans and proposes again; +`umtool clips propose` proposes again from what is there. Every step is local +signal processing and two small local models; nothing calls a model you talk +to, and the whole loop can be done by hand in the clip editor. + +What it reads, and what it does without: + +- **Speakers** — `diarization.json` beside the recording (the editor's diarize + job, or `archilyzer diarize backfill --scope video:<channel>/<id>`). Required. +- **Words** — `<project>/words.json` (`pnpm ops transcribe {path, words: true, + out: "<project>/words.json"}`), else whisper.cpp's word offsets in the corpus + `transcript.json`, else the cues with each cue's words spread over it. +- **The sound** — the recording's `audio.*`, else a local source that covers it + (a saved video). Without it, laughs come from the transcript alone. +- **The laugh model** — CED-mini (sherpa-onnx `AudioTagging`, AudioSet's 527 + classes) at `.diarize/models/sherpa-onnx-ced-mini-audio-tagging-2024-04-19/` + (`AUDIO_TAG_MODEL`). Without it: the transcript's laugh markers (`[laughter]`, + `haha`, `lol`, `lmao`) and the host's loud wordless bursts. + +The steps (over the **scope**, when one is set: `--scope FROM:TO`, or the form's +From/To — turns, words and laugh windows outside it are not read, and the +recording ends at its `to`): + +1. **Roles.** The host is the speaker with the most turns under 8 s times the + widest spread over the recording (a reaction stream's host interjects all the + way through; the narrated video talks in long runs); the subject is the one + with the most seconds among the rest; a speaker under 1 % of the speech is + never either by itself. A third cluster whose voice centroid (TitaNet-small + over its longest turns that overlap nobody: 24 for the two clusters with the + most seconds, 6 for each other) is 0.6 or more like the host's or the + subject's takes that role (`sameAs`). A diarization that splits the stream + into 30 clusters is normal; the small ones that match neither voice stay + `other`. Your word beats all of it: **This is the host** in the + clip editor, or `--host N`, is kept (`how: "operator"`) until you change it. +2. **Laughs.** CED-mini over 1 s windows every 0.5 s; the laughter family + (Laughter, Giggle, Snicker, Belly laugh, Chuckle — not Baby laughter) summed, + at most 1; runs at or over `laughMin` (0.25) are laughs, joined across a 0.5 s + gap, each the speaker's who was talking (a host turn that overlaps makes it + the host's — he laughs over the video). Then **the voice decides** when it + can: each laugh's seconds (at least 1.5 s, centred) are embedded and compared + with the host's and the subject's centroids (`voice: {host, subject}` on the + laugh); at 0.2 or more and 0.1 above the other, the laugh is that speaker's + (`by: "voice"`) — a narrated video's voice-acted laugh is the subject's, the + host laughing over a narrated line is the host's. Laugh voices are kept in + the voices scan, so a pass with a new laugh bar or scope embeds only the new + ones (it reads the sound for those). +3. **Moments.** Every laugh (its strength × its length, squashed to 0–1, weighed + by who laughed: the host 1, nobody 0.8, another speaker 0.6, the subject 0.5, + the subject by voice 0.3) + and every host turn with 1.5 s of words or more (half its length, half the + strongest laugh around it). +4. **Proposals.** From the start of the subject's sentence that set the moment + up (the latest sentence start at least 3 s before it, at most `setupMax` 20 s + back) through the reaction (the host's turn, at most 12 s past a laugh) to + the next pause (at most 1.5 s), edges in the gaps between words; overlapping + spans merged, spans closer than `mergeGap` (6 s) merged while the whole fits + `clipMax` (75 s); a longer one keeps its end and starts on the latest + sentence that fits; a shorter one than 5 s is widened to 5 s about its middle, + edges in the word gaps. Ranked by score into `target` seconds (600, 3 % over + allowed) — a proposal scoring under 0.2, or under 5 s, is never used; the rest + stay in `reactions.json` with `used: false`, for the clip editor's unused list. +5. **Clips.** Each used proposal is a clip `r001…` — the cut is the proposal, + the window 1.5 s wider each side for trimming, `quote` its words — with + `assist: {by: "assistant", proposal, score, why, original, edits: []}`, in + time order, hard cuts (`render.transition: 0`). + +**A proposal pass never touches your work.** A clip whose `assist.by` is +`"operator"` (the first edit flips it), a clip with no `assist`, one ruled in +`montage-rulings.json` and one with a `lock*` stays exactly as it is; a +proposal that covers half of one is that clip, and its seconds count toward the +target first. Untouched assistant clips are moved in place (the same id) or +removed; new ones take the next `r` numbers. A proposal keeps its id from pass +to pass while it overlaps its old self by half. The manifest is written through +its writer (an undo point, `auto-before-clips-propose`), `reactions.json` +whole. Params and your roles are kept in `reactions.json` for the next pass. + +The scans are cached in `<project>/scans/<channel>--<video>.audio.json` (each +window's level and laugh score) and `.voices.json` (a centroid per speaker), +reused while the sound file, the model and the diarization are the same +(`--rescan` makes them again). A 2.5-hour stream's laugh scan is about 18,500 +windows, a few minutes on one CPU thread. + +`reactions.json`: `{version: 1, source: {channel, video, duration (the scope's end), words: +"words.json" | null, wordsFrom, diarization: {generatedAt, engine}, audio?, +audioKind?}, params: {target, laughMin, mergeGap, setupMax, clipMax, scope: [from, to|null] | null}, +speakers: [{index, role: "host"|"subject"|"other", label, seconds, turns, how: +"auto"|"operator", sameAs?}], turns: [{start, end, speaker}], laughs: [{start, +end, score, speaker: n|null, src?: "text"|"energy", voice?: {host, subject}, by?: "voice"}], moments: [{id, t, end, +kind: "laugh"|"comment", score, speaker: n|null, text}], proposals: [{id, start, +end, score, moments, used, clipId: "r001"|null, why}], laughSource: +"model"|"text"|"text+energy", scans: {laughs, voices}, madeAt, proposedAt, +rolesChangedAt?}`. The clip editor changes only a speaker's role, through +`setSpeakerRole` (`yt-dlp-transcript-common/lib/clips/reactions.mjs`), which +records `rolesChangedAt` so the page can offer Re-propose. + ## Reviewing assistant clips: the clip editor When an assistant made the clips (the clip finder's highlights, release 35: diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { BOARD_CASE } from "./fixtures/research-fixture.mjs"; +import { writeReactionCorpus } from "yt-dlp-transcript-common/testing/clips/reactionStream.mjs"; import * as urls from "./urls"; import { WARM_TIMEOUT, warm } from "./warm"; @@ -19,12 +20,14 @@ import { WARM_TIMEOUT, warm } from "./warm"; // video-board R2's hand-off: the plan, then the project // video-article the chain's steps, then the chain as a umtool job // video-recording /?from= (the editor's hand-off) prefilled → a project +// video-highlights the clip finder's seed on a synthetic stream → a project +// with proposed clips, then "Find the clips" as a job // video-report the sweep reports on disk → a project // song a song // // WRITES (each removed after): .umtool/research/p5-*, articles/p5-board, // p5-board/, p5-rec/, p5-rep/, reports/videos/p5-song/; a chain job on -// zeta i1, cancelled +// zeta i1, cancelled; channels/synth-reacts (a synthetic stream) and p35-hl/ // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -43,6 +46,8 @@ const WRITTEN = [ "p5-rec", "p5-rep", "reports/videos/p5-song", + "channels/synth-reacts", + "p35-hl", ]; const clean = () => { for (const p of WRITTEN) rmSync(path.join(FIXTURE, p), { recursive: true, force: true }); @@ -62,8 +67,8 @@ test("the lines, grouped Research · Article · Video · Song; the policy chip l await page.goto(urls.createHref()); await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("What are you making?"); await expect(page.locator("[data-make-group]")).toHaveText([/^Research/, /^Article/, /^Video/, /^Song/]); - // Nine: R5 added "A recurring report" under Article. - await expect(page.locator("[data-make-line]")).toHaveCount(9); + // Ten: R5 added "A recurring report" under Article; release 35 "Highlights from a recording" under Video. + await expect(page.locator("[data-make-line]")).toHaveCount(10); // The boards and the reports on disk are counted on their lines. await expect(line(page, "article-board")).toContainText(/ · \d+ quotes?/); await expect(line(page, "video-report")).toContainText(/ · \d+ found/); @@ -221,6 +226,41 @@ test("Video from a recording: the editor's /?from= lands here prefilled, and mak expect(manifestOf("p5-rec").provenance.channelSlug).toBe("testchan"); }); +test("Highlights from a recording: the clip finder proposes clips marked by the assistant, then finds the clips as a job", async ({ page, request }) => { + // A synthetic reaction stream with its speakers (diarization.json), no sound. + writeReactionCorpus(path.join(FIXTURE, "channels"), { channel: "synth-reacts", video: "react001" }); + await page.goto(urls.createHref({ make: "video-highlights" })); + const f = form(page, "video-highlights"); + await f.locator("[data-new-from]").fill("synth-reacts/react001"); + const seed = f.locator("[data-new-seed]"); + await expect(seed).toHaveValue("reactions"); + await expect(seed.locator("option[value=reactions]")).toBeEnabled(); + await expect(f.locator("[data-new-target]")).toHaveValue("600"); + await f.locator("[data-new-target]").fill("60"); + await f.locator("[data-new-laugh-min]").fill("0.15"); + await f.locator("[data-new-scope-to]").fill("500"); + await f.locator("[data-new-slug]").fill("p35-hl"); + await f.getByRole("button", { name: "Find the clips" }).click(); + await page.waitForURL(/\/projects\/p35-hl$/, { timeout: 20_000 }); + const m = manifestOf("p35-hl"); + expect(m.render.transition).toBe(0); + expect(m.timeline.length).toBeGreaterThan(0); + for (const c of m.timeline) { + expect(c.assist.by).toBe("assistant"); + expect(c.cutStart).toBeGreaterThanOrEqual(c.start); + } + const reactions = () => JSON.parse(readFileSync(path.join(FIXTURE, "p35-hl", "reactions.json"), "utf8")); + expect(reactions().params.target).toBe(60); + expect(reactions().params.laughMin).toBe(0.15); + expect(reactions().params.scope).toEqual([0, 500]); + // "Find the clips" ran as umtool's job: the CLI, with no sound on disk, proposes from the transcript. + await expect.poll(async () => (await (await request.get("/api/jobs")).json()).running, { timeout: 60_000 }).toBeNull(); + const summary = (await (await request.get("/api/report/clips?project=p35-hl")).json()).reactions; + expect(summary.speakers.map((s: { role: string }) => s.role)).toEqual(["host", "subject"]); + expect(summary.used).toBeGreaterThan(0); + expect(summary.laughSource).toBe("text"); +}); + test("Video from a sweep report: the reports on disk are offered, and one becomes a project", async ({ page }) => { await page.goto(urls.createHref({ make: "video-report" })); const f = form(page, "video-report"); diff --git a/umtool/e2e/visual-audit.spec.ts b/umtool/e2e/visual-audit.spec.ts @@ -55,7 +55,7 @@ const PAGES: [string, string][] = [ ["bench-review", urls.reviewHref("reports/media-review-fixture", { view: "list" })], ["bench-clips", urls.clipDeckHref("reports/clip-deck-fixture", { show: "all" })], ["create", urls.createHref()], - ...(["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-report", "song"] as const).map( + ...(["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-highlights", "video-report", "song"] as const).map( (make) => [`create-${make}`, urls.createHref({ make })] as [string, string], ), ["tools", urls.toolsHref()], diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -155,10 +155,11 @@ export function articlesHref(q: ArticlesQuery = {}): string { * video-article a video from an article: the chain over an iteration * video-board a video from a board (R2's hand-off) * video-recording a video from a recording (`from` = <channel>/<id> or a share URL) + * video-highlights highlights from a long recording: the clip finder's seed (release 35) * video-report a video from a sweep report on disk * song a song */ -export const MAKES = ["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-report", "song"] as const; +export const MAKES = ["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-highlights", "video-report", "song"] as const; export type Make = (typeof MAKES)[number]; export const isMake = (v: unknown): v is Make => typeof v === "string" && (MAKES as readonly string[]).includes(v); 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, normalizeScope } 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 }; } /** @@ -241,9 +247,9 @@ const capNote = (max, kept, found) => * (common/lib/montage/phraseScan.mjs `capInstances`); the rest are listed in * phrase-scan.json as `skippedByCap`. No `max`: the output is what it was. * - * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null }} args + * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | null }} args */ -export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null }) { +export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null }) { if (!SLUG_RE.test(String(slug ?? ""))) { throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`); } @@ -281,10 +287,16 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site throw new Error(`--max must be a whole number of clips from 1 to ${MAX_PHRASE_CAP}`); } const capped = max !== null && max !== undefined; + if ((laughMin !== undefined || scope) && seed !== "reactions") throw new Error("--laugh-min and --scope go with --seed reactions"); + if (laughMin !== undefined && !(Number.isFinite(laughMin) && laughMin >= PARAM_BOUNDS.laughMin[0] && laughMin <= PARAM_BOUNDS.laughMin[1])) { + throw new Error(`--laugh-min must be a number from ${PARAM_BOUNDS.laughMin[0]} to ${PARAM_BOUNDS.laughMin[1]}`); + } + const reactionsScope = seed === "reactions" ? normalizeScope(scope) : null; 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 the frames seed's length budget (or the reactions seed's): 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 +380,32 @@ 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 } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(reactionsScope ? { scope: reactionsScope } : {}), + }); + 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)`); + if (reactionsScope) notes.push(`only ${reactionsScope[0]}–${reactionsScope[1] ?? "the end"} s of the recording is read (--scope)`); + 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 +415,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 +454,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/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts @@ -15,7 +15,8 @@ export type NewProjectBody = { from?: string | null; siteOrigin?: string | null; seed?: string | null; - // The frames seed's length budget, seconds (release 32: the form's "target"). + // The frames seed's length budget, seconds (release 32: the form's "target"); + // release 35: the reactions seed's (the clip finder's target, default 600). target?: number | string | null; brand?: string | null; // The phrase seed (release 33): a regular expression, the channels to scan @@ -30,6 +31,9 @@ export type NewProjectBody = { scan?: { id?: string; row?: string } | null; // The phrase seed's cap (release 35): N instances spread across the years. max?: number | string | null; + // The reactions seed (release 35 C1): the laugh bar and the part of the recording read. + laughMin?: number | string | null; + scope?: [number | string | null, number | string | null] | null; }; /** @@ -82,7 +86,11 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str ...(body.max !== undefined && body.max !== null && body.max !== "" ? { max: Number(body.max) } : {}), } : {}), - ...(body.seed === "frames" && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}), + ...(body.seed === "reactions" && body.laughMin !== undefined && body.laughMin !== null && body.laughMin !== "" ? { laughMin: Number(body.laughMin) } : {}), + ...(body.seed === "reactions" && Array.isArray(body.scope) + ? { scope: [body.scope[0] === null || body.scope[0] === "" ? 0 : Number(body.scope[0]), body.scope[1] === null || body.scope[1] === "" ? null : Number(body.scope[1])] as [number, number | null] } + : {}), + ...((body.seed === "frames" || body.seed === "reactions") && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}), }); result = { ...r, href: `/projects/${r.id}` }; } catch (e) { 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"; @@ -1133,6 +1134,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,648 @@ +// 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, + laughKey, + laughVoiceSpan, + normalizeParams, + 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 { embedSpans, 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, 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<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, laughVoices } = 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, + laughVoices, + 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, laughMin, scope }) { + const rec = await loadRecording({ channelsDir, channel, video }); + const params = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}) }; + const pass = proposalPass({ rec, params }); + 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, engine = null, dry = false, now = new Date(), say = () => {} }) { + 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 = mergeParams(sameSource ? previous.params : null, params); + const s = scans === undefined ? await readScans(project.dir, rec.channel, rec.video) : scans; + const isProtected = await rulingsGuard(project.dir, manifest); + const passOf = (sc) => proposalPass({ rec, scans: sc, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now }); + 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 <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", + "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)", + "--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", "--to", "--scope", "--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) { + /** @type {Record<string, unknown>} */ + 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") out.scope = "all"; + else { + const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(v); + if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), or all`); + out.scope = [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null]; + } + } + 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 <channel>/<id>` (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}: <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})` : ""}`); + if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}–${doc.params.scope[1] ?? "end"} s`); + 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}`); + 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(); + const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video; + const { scope } = mergeParams(sameSource ? previous.params : null, params); + 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 }); + 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, laughMin?: number, scope?: [number, number | null] }} [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] ?? ""}`); + 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,286 @@ +// 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("the scope: --scope / --from S --to S, kept in reactions.json params, `all` clears it; the seed takes it", async () => { + const f = await fixture(); + try { + const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, scope: [300, 450], laughMin: 0.15 }); + await pointAt(r.dir, f.channelsDir); + let doc = await readReactions(r.dir); + assert.deepEqual(doc.params.scope, [300, 450]); + assert.equal(doc.params.laughMin, 0.15); + assert.equal(doc.source.duration, 450); + assert.ok(doc.proposals.every((p) => p.end > 300 && p.start < 450)); + assert.equal(await clipsCommand(["propose", "reacts", "--from", "0", "--to", "200"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + doc = await readReactions(r.dir); + assert.deepEqual(doc.params.scope, [0, 200]); + assert.ok(doc.turns.every((t) => t.end <= 200)); + assert.equal(await clipsCommand(["propose", "reacts", "--to", "250"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + assert.deepEqual((await readReactions(r.dir)).params.scope, [0, 250]); + assert.equal(await clipsCommand(["propose", "reacts", "--scope", "400:"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + assert.deepEqual((await readReactions(r.dir)).params.scope, [400, null]); + assert.equal(await clipsCommand(["propose", "reacts", "--scope", "all"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + assert.equal((await readReactions(r.dir)).params.scope, null); + const bad = quiet(); + assert.equal(await clipsCommand(["propose", "reacts", "--scope", "9-3"], { reportsRoot: f.reportsRoot, ...bad }), 2); + assert.equal(await clipsCommand(["propose", "reacts", "--scope", "500:100"], { reportsRoot: f.reportsRoot, ...quiet() }), 2); + await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "x1", from: "synth-reacts/react001", seed: "chapters", channelsDir: f.channelsDir, laughMin: 0.2 }), /go with --seed reactions/); + } 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"); + // Each laugh's voice, checked against the host's and the subject's (the fake embedder's "voices"). + assert.ok(doc.laughs.every((l) => l.voice && Number.isFinite(l.voice.host) && Number.isFinite(l.voice.subject)), JSON.stringify(doc.laughs)); + assert.equal(Object.keys(JSON.parse(await readFile(path.join(r.dir, "scans", "synth-reacts--react001.voices.json"), "utf8")).laughs).length, 3); + 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/lib/scaffold-frames.test.mjs b/umtool/lib/scaffold-frames.test.mjs @@ -73,13 +73,13 @@ test("seedsFor (release 32): what a video ref can be seeded from — its digest, const channelsDir = path.join(tmp, "channels"); const dir = path.join(channelsDir, "synth-poker", "data", "synthstream1"); await mkdir(dir, { recursive: true }); - assert.deepEqual(await seedsFor({ channelsDir, from: "synth-poker/synthstream1" }), { video: true, chapters: false, frames: false }); + assert.deepEqual(await seedsFor({ channelsDir, from: "synth-poker/synthstream1" }), { video: true, chapters: false, frames: false, reactions: false }); await writeFile(path.join(dir, "frame-scan.poker.json"), JSON.stringify(SCAN)); - assert.deepEqual(await seedsFor({ channelsDir, from: "synth-poker/synthstream1" }), { video: true, chapters: false, frames: true }); + assert.deepEqual(await seedsFor({ channelsDir, from: "synth-poker/synthstream1" }), { video: true, chapters: false, frames: true, reactions: false }); await writeFile(path.join(dir, "ai-digest.json"), "{}"); - assert.deepEqual(await seedsFor({ channelsDir, from: "https://archive.example/?v=synth-poker%2Fsynthstream1&t=5" }), { video: true, chapters: true, frames: true }); - assert.deepEqual(await seedsFor({ channelsDir, from: "notes.md" }), { video: false, chapters: false, frames: false }); - assert.deepEqual(await seedsFor({ channelsDir, from: null }), { video: false, chapters: false, frames: false }); + assert.deepEqual(await seedsFor({ channelsDir, from: "https://archive.example/?v=synth-poker%2Fsynthstream1&t=5" }), { video: true, chapters: true, frames: true, reactions: false }); + assert.deepEqual(await seedsFor({ channelsDir, from: "notes.md" }), { video: false, chapters: false, frames: false, reactions: false }); + assert.deepEqual(await seedsFor({ channelsDir, from: null }), { video: false, chapters: false, frames: false, reactions: false }); } finally { await rm(tmp, { recursive: true, force: true }); } diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -181,6 +181,10 @@ export default defineConfig({ // TitaNet venv -- the same command line and JSON, no python, no model. `VOICE_MATCH_PYTHON=${process.execPath} ` + `VOICE_MATCH_SCRIPT=${path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs")} VOICE_MATCH_MODEL=fake.onnx ` + + // The clip finder's laugh scan (release 35): the test kit's fake tagger, the same way. + `AUDIO_TAG_PYTHON=${process.execPath} ` + + `AUDIO_TAG_SCRIPT=${path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "common", "testing", "audio", "fakeAudioTag.mjs")} ` + + `AUDIO_TAG_MODEL=${path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "common", "testing", "audio", "fakeAudioTag.mjs")} ` + APP_SERVER, port: PORT, reuseExistingServer: false, 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}`));