// 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. // // Release 36 B2: a stream's chat replay, when there is one, adds `chat` // moments (lib/clips/chat.mjs) — the room laughing, moved back by the chat's // lag. Without one, everything here is what it was. // // Plain ESM with a .d.mts beside it, so umtool's CLI runs it with bare node. import { chatBins, chatLag, chatMoments } from "./chat.mjs"; 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} [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 }>} */ 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, centroids?: Record | 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} */ 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} 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), and (release 36) every chat burst given * (`chat`, scored by chat.mjs, under a host laugh's weight). 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, chat = [] }) { 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 chats = (chat ?? []).map((c) => ({ t: c.t, end: c.end, kind: /** @type {const} */ ("chat"), score: round(c.score, 3), speaker: c.speaker ?? null, messages: c.messages })); // With no chat, the order (and so every id) is exactly release 35's. const RANK = { laugh: 0, comment: 1, chat: 2 }; const all = chats.length ? [...laughMoments, ...comments, ...chats].sort((a, b) => a.t - b.t || RANK[a.kind] - RANK[b.kind]) : [...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 === "comment" ? textIn(words, m.t, m.end) : textIn(words, m.t - 6, m.end + 1), ...(m.kind === "chat" ? { messages: m.messages } : {}), })); } // ---- 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; // A chat burst is the room's laugh: its reaction runs as a laugh's does. if (m.kind === "laugh" || m.kind === "chat") { 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) { if (m.kind === "chat") { const n = `chat laughs (${m.messages ?? "?"} messages)`; return span.setupBy === "subject" ? `${n} ${fmtS(span.setupSeconds)} after the narrated line` : `${n} for ${fmtS(m.end - m.t)}`; } 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} */ 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, * operator?: Record, centroids?: Record | 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 }[], * chat?: { source?: string, cues: { start: number, text: string }[] } | null }} 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); // The chat (release 36 B2): bins over the whole recording, the lag against // the scope's laugh scan, the bursts inside the scope. let chat = null; let chatFound = []; if (o.chat && Array.isArray(o.chat.cues) && o.chat.cues.length) { const bins = chatBins(o.chat.cues, { duration: whole }); const lag = chatLag(bins.laugh, scan && Array.isArray(scan.scores) && scan.scores.length ? scan : null, { from, to }); chatFound = attributeLaughs(chatMoments(bins, { lagS: lag.lagS, from, to }), turns, speakers); chat = { source: o.chat.source ?? "live_chat.cues.json", lagS: lag.lagS, lag: { how: lag.how, r: lag.r, why: lag.why }, messages: o.chat.cues.length, bursts: chatFound.length, bins: { hop: bins.hop, rate: bins.rate, laugh: bins.laugh }, }; } const moments = findMoments({ turns, speakers, laughs, words, chat: chatFound }); 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, chat, }; } /** 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; }); }