Archilyzer · Source

archilyzer

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

commit 2af9d165266be0b29705ec19b982a5152675b2a9
parent 74e70fac29663d486fa204eb0cbbd6425ad6098c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 00:11:20 -0400

common: the clip finder's arithmetic -- roles, laughs, moments, proposals, reactions.json, the assist key (release 35 C1, slice 1)

common/lib/clips/: pure functions over turns, words and laugh windows
(clips.mjs), the manifest clip's `assist` key with its validator and the
one proposal-to-clip writer (assist.mjs), and reactions.json's reader,
atomic writer and setSpeakerRole (reactions.mjs, for the clip editor). The
test kit gains a synthetic reaction stream (testing/clips/reactionStream.mjs).

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

Diffstat:
Acommon/lib/clips/assist.d.mts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/assist.mjs | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/clips.d.mts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/clips.mjs | 755+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/clips.test.ts | 332+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/reactions.d.mts | 44++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/reactions.mjs | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 4++++
Acommon/testing/clips/reactionStream.d.mts | 18++++++++++++++++++
Acommon/testing/clips/reactionStream.mjs | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 1768 insertions(+), 0 deletions(-)

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,90 @@ +export const REACTIONS_VERSION: 1; +export type Params = { target: number; laughMin: number; mergeGap: number; setupMax: number; clipMax: number }; +export const DEFAULT_PARAMS: Readonly<Params>; +export const PARAM_BOUNDS: Readonly<Record<keyof Params, [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 }>; +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 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" }; +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 cleanTurns(turns: unknown): Turn[]; +export function turnStats(turns: Turn[], duration: 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 }): 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 }[]; 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; + 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,755 @@ +// 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 }); + +/** 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 }); +/** 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; + +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; + } + return out; +} + +// ---- 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) { + const dur = Math.max(duration || 0, ...turns.map((t) => t.end), 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.min(SPREAD_BINS - 1, Math.floor((t.start / 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 }) { + const stats = turnStats(turns, duration); + 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 score = (1 - Math.exp(-raw / 1.5)) * LAUGH_WEIGHT[roleOf(roles, l.speaker)]; + 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 } = m; + const { 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; + } + 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)` : ""), + }; + }); +} + +/** + * 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 (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 turns = cleanTurns(o.turns); + const words = cleanWords(o.words); + const duration = Math.max(Number(o.duration) || 0, turns.at(-1)?.end ?? 0); + const speakers = assignRoles({ turns, duration, operator: o.operator ?? {}, centroids: o.centroids ?? null }); + const scan = o.laughScan ?? null; + 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 = attributeLaughs(laughsRaw, turns, speakers); + 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 } : {}) })), + moments, + proposals: ranked, + }; +} diff --git a/common/lib/clips/clips.test.ts b/common/lib/clips/clips.test.ts @@ -0,0 +1,332 @@ +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 { + DEFAULT_PARAMS, + analyze, + 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", () => { + 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.1 }, + ]; + 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]]); +}); + +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,92 @@ +// `<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 + * speaker the ANALYSIS gave it (they become "other" until the next pass); + * the operator's own marks stay. Records `rolesChangedAt`, so a page can say + * 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.how !== "operator" && o.sameAs !== index) { + o.role = "other"; + o.label = labelOf("other", o.index); + 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/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/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; +}