commit fde9a111c8a718f0b886d59c643abd54197ebef2
parent df0f21ea7c0660684608c33b506985b7e7a30038
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 11:58:49 -0400
clips: the chat signal -- a stream's chat replay as chat moments, its lag cross-correlated with the laugh scan
common/lib/clips/chat.mjs: live_chat.cues.json read directly (lib may not
import controller), 2 s bins of messages and laugh tokens (lol, lmao, lmfao,
KEKW, LUL, OMEGALUL, rofl, hahaβ¦, the laughing emoji, a lone W), the lag in
0..20 s against the CED score (6 s when there is no scan or the peak is
under r 0.2), bursts at 2.5x the local median as `chat` moments at t - lag,
scored under 0.6 (a host laugh weighs 1). reactions.json gains `chat`
({source, lagS, lag, messages, bursts, bins}) or null; the analyze log names
the lag. No chat file: release 35's analysis byte for byte (digests of its
output over the synthetic streams pinned in the test).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 506 insertions(+), 14 deletions(-)
diff --git a/common/lib/clips/chat.d.mts b/common/lib/clips/chat.d.mts
@@ -0,0 +1,25 @@
+export const CHAT_FILE: string;
+export const CHAT_BIN_S: number;
+export const CHAT_LAG_MAX_S: number;
+export const CHAT_LAG_DEFAULT_S: number;
+export const CHAT_LAG_MIN_R: number;
+export const CHAT_BURST_RATIO: number;
+export const CHAT_BURST_MIN: number;
+export const CHAT_MEDIAN_HALF_S: number;
+export const CHAT_WEIGHT: number;
+export const CHAT_LAUGH_RE: RegExp;
+
+export type ChatBins = { hop: number; rate: number[]; laugh: number[] };
+export type ChatLag = { lagS: number; how: "xcorr" | "default"; r: number | null; why: string };
+export type ChatMoment = { t: number; end: number; score: number; messages: number };
+
+export function chatMessage(text: string): string;
+export function isChatLaugh(text: string): boolean;
+export function readChatCues(videoDir: string): Promise<{ source: string; cues: { start: number; text: string }[] } | null>;
+export function chatBins(cues: { start: number; text: string }[], o: { duration: number; hop?: number }): ChatBins;
+export function chatLag(
+ laugh: number[],
+ scan: { t0?: number; hop?: number; window?: number; scores?: number[] | null } | null,
+ o?: { from?: number; to?: number; hop?: number },
+): ChatLag;
+export function chatMoments(bins: { hop: number; laugh: number[] }, o: { lagS: number; from?: number; to?: number }): ChatMoment[];
diff --git a/common/lib/clips/chat.mjs b/common/lib/clips/chat.mjs
@@ -0,0 +1,222 @@
+// The chat signal (release 36 B2): a live stream's chat replay as a second
+// ear for the clip finder. When the room laughs, the chat says so β a burst of
+// "lol", "KEKW", π β a few seconds AFTER the moment (the viewers watch the
+// stream late, and type). From `live_chat.cues.json` (the editor writes it
+// beside a YouTube video: common/controller/normalizeLiveChat.ts), pure apart
+// from the one reader:
+//
+// bins CHAT_BIN_S bins over the recording: messages, and messages
+// holding a laugh token (isChatLaugh)
+// the lag the chat-laugh series cross-correlated with the laugh scan's
+// score (CED), searched 0..CHAT_LAG_MAX_S; a weak peak (or no
+// scan) β CHAT_LAG_DEFAULT_S
+// moments a bin with at least CHAT_BURST_MIN laughs and CHAT_BURST_RATIO
+// Γ the local median (Β±CHAT_MEDIAN_HALF_S, at least 1) is a
+// burst; a run of them is a `chat` moment at (t β lag), scored
+// under CHAT_WEIGHT β always below what a host laugh can score
+//
+// No chat file: nothing here runs, and the analysis is what it was.
+//
+// lib may not import controller (and this is plain ESM run by bare node), so
+// the file is read here directly: `{version, source: "live_chat", cues:
+// [{start, end, text: "<author>: <message>"}]}` (normalizeLiveChat's shape;
+// readNormalizedLiveChat's checks).
+//
+// Plain ESM with a .d.mts beside it.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+
+export const CHAT_FILE = "live_chat.cues.json";
+export const CHAT_BIN_S = 2;
+export const CHAT_LAG_MAX_S = 20;
+export const CHAT_LAG_DEFAULT_S = 6;
+/** A cross-correlation peak under this is weak: the default lag is used. */
+export const CHAT_LAG_MIN_R = 0.2;
+export const CHAT_BURST_RATIO = 2.5;
+export const CHAT_BURST_MIN = 3;
+export const CHAT_MEDIAN_HALF_S = 60;
+/** A chat moment's score is at most this (a host laugh's weight is 1). */
+export const CHAT_WEIGHT = 0.6;
+
+/** A word of chat that is a laugh: lol, lmao, lmfao, KEKW, LUL, OMEGALUL, rofl, hahaβ¦, as a word or an emote's :name:. */
+export const CHAT_LAUGH_RE = /^:?(?:l+o+l+|lmf?ao+|kekw|lul|omegalul|rofl|(?:ha){2,}h?|face[_-]with[_-]tears[_-]of[_-]joy|rolling[_-]on[_-]the[_-]floor[_-]laughing|joy)\:?$/i;
+const LAUGH_EMOJI_RE = /[\u{1F602}\u{1F923}]/u;
+/** "W" alone (or a few of them): the chat's cheer. */
+const LONE_W_RE = /^[Ww](?:\s+[Ww])*!*$/;
+
+const round = (x, d = 2) => Math.round(x * 10 ** d) / 10 ** d;
+const num = (x) => typeof x === "number" && Number.isFinite(x);
+
+/** A chat cue's message, the author ("<author>: ") taken off. */
+export function chatMessage(text) {
+ const s = String(text ?? "");
+ const i = s.indexOf(": ");
+ return i >= 0 ? s.slice(i + 2) : s;
+}
+
+/** Whether a chat message laughs. */
+export function isChatLaugh(text) {
+ const msg = chatMessage(text).trim();
+ if (!msg) return false;
+ if (LONE_W_RE.test(msg) || LAUGH_EMOJI_RE.test(msg)) return true;
+ return msg.split(/\s+/).some((tok) => CHAT_LAUGH_RE.test(tok.replace(/^[^\p{L}\p{N}:]+|[^\p{L}\p{N}:]+$/gu, "")));
+}
+
+/**
+ * The chat replay beside a recording, or null when there is none (or it is
+ * not one).
+ * @param {string} videoDir
+ * @returns {Promise<{ source: string, cues: { start: number, text: string }[] } | null>}
+ */
+export async function readChatCues(videoDir) {
+ let doc;
+ try {
+ doc = JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ videoDir, CHAT_FILE), "utf8"));
+ } catch {
+ return null;
+ }
+ if (!doc || typeof doc.version !== "number" || doc.source !== "live_chat" || !Array.isArray(doc.cues)) return null;
+ const cues = doc.cues.filter((c) => c && num(c.start) && c.start >= 0 && typeof c.text === "string").map((c) => ({ start: c.start, text: c.text }));
+ return { source: CHAT_FILE, cues };
+}
+
+/**
+ * Messages and laughing messages per bin, over [0, duration).
+ * @param {{ start: number, text: string }[]} cues
+ * @param {{ duration: number, hop?: number }} o
+ * @returns {{ hop: number, rate: number[], laugh: number[] }}
+ */
+export function chatBins(cues, { duration, hop = CHAT_BIN_S }) {
+ const n = Math.max(0, Math.ceil((Number(duration) || 0) / hop));
+ const rate = new Array(n).fill(0);
+ const laugh = new Array(n).fill(0);
+ for (const c of cues ?? []) {
+ if (!c || !num(c.start) || c.start < 0) continue;
+ const k = Math.floor(c.start / hop);
+ if (k >= n) continue;
+ rate[k] += 1;
+ if (isChatLaugh(c.text)) laugh[k] += 1;
+ }
+ return { hop, rate, laugh };
+}
+
+function pearson(xs, ys) {
+ const n = xs.length;
+ if (n < 3) return null;
+ let mx = 0;
+ let my = 0;
+ for (let i = 0; i < n; i += 1) {
+ mx += xs[i];
+ my += ys[i];
+ }
+ mx /= n;
+ my /= n;
+ let sxy = 0;
+ let sxx = 0;
+ let syy = 0;
+ for (let i = 0; i < n; i += 1) {
+ const a = xs[i] - mx;
+ const b = ys[i] - my;
+ sxy += a * b;
+ sxx += a * a;
+ syy += b * b;
+ }
+ return sxx > 0 && syy > 0 ? sxy / Math.sqrt(sxx * syy) : null;
+}
+
+/**
+ * How late the chat laughs: the shift (0..CHAT_LAG_MAX_S) that best lines
+ * the chat-laugh bins up with the laugh scan's scores (each bin the
+ * strongest window centred in it), refined between bins on the peak's
+ * parabola; CHAT_LAG_DEFAULT_S when there is no scan or the peak's
+ * correlation is under CHAT_LAG_MIN_R.
+ * @param {number[]} laugh the chat-laugh bins
+ * @param {{ t0?: number, hop?: number, window?: number, scores?: number[] | null } | null} scan
+ * @param {{ from?: number, to?: number, hop?: number }} [o]
+ * @returns {{ lagS: number, how: "xcorr" | "default", r: number | null, why: string }}
+ */
+export function chatLag(laugh, scan, { from = 0, to = Infinity, hop = CHAT_BIN_S } = {}) {
+ const fallback = (why, r = null) => ({ lagS: CHAT_LAG_DEFAULT_S, how: /** @type {const} */ ("default"), r, why });
+ const scores = scan && Array.isArray(scan.scores) ? scan.scores : null;
+ if (!scores || !scores.length) return fallback("no laugh scores to line the chat up with");
+ const n = laugh.length;
+ const ced = new Array(n).fill(0);
+ const t0 = scan.t0 ?? 0;
+ const sh = scan.hop ?? 0.5;
+ const win = scan.window ?? 1;
+ scores.forEach((s, i) => {
+ if (!num(s)) return;
+ const k = Math.floor((t0 + i * sh + win / 2) / hop);
+ if (k >= 0 && k < n && s > ced[k]) ced[k] = s;
+ });
+ const k0 = Math.max(0, Math.ceil(from / hop));
+ const k1 = Math.min(n, Number.isFinite(to) ? Math.floor(to / hop) : n);
+ const shifts = Math.floor(CHAT_LAG_MAX_S / hop);
+ const rs = [];
+ for (let s = 0; s <= shifts; s += 1) {
+ const xs = [];
+ const ys = [];
+ for (let k = k0 + s; k < k1; k += 1) {
+ xs.push(laugh[k]);
+ ys.push(ced[k - s]);
+ }
+ rs.push(pearson(xs, ys));
+ }
+ let best = -1;
+ rs.forEach((r, i) => {
+ if (r !== null && (best < 0 || r > /** @type {number} */ (rs[best]))) best = i;
+ });
+ if (best < 0) return fallback("the chat or the scan does not vary");
+ const r = /** @type {number} */ (rs[best]);
+ if (r < CHAT_LAG_MIN_R) return fallback(`a weak peak (r ${round(r, 2)})`, round(r, 3));
+ let at = best;
+ const a = rs[best - 1];
+ const c = rs[best + 1];
+ if (a !== null && a !== undefined && c !== null && c !== undefined) {
+ const d = a - 2 * r + c;
+ if (d < 0) at = best + Math.max(-0.5, Math.min(0.5, (0.5 * (a - c)) / d));
+ }
+ const lagS = round(Math.max(0, Math.min(CHAT_LAG_MAX_S, at * hop)), 1);
+ return { lagS, how: "xcorr", r: round(r, 3), why: `cross-correlated with the laugh scan (r ${round(r, 2)})` };
+}
+
+/**
+ * The chat's bursts as moments, moved back by the lag; only those wholly
+ * inside [from, to].
+ * @param {{ hop: number, laugh: number[] }} bins
+ * @param {{ lagS: number, from?: number, to?: number }} o
+ * @returns {{ t: number, end: number, score: number, messages: number }[]}
+ */
+export function chatMoments(bins, { lagS, from = 0, to = Infinity }) {
+ const { hop, laugh } = bins;
+ const n = laugh.length;
+ const half = Math.round(CHAT_MEDIAN_HALF_S / hop);
+ const base = laugh.map((_, k) => {
+ const w = laugh.slice(Math.max(0, k - half), Math.min(n, k + half + 1)).sort((x, y) => x - y);
+ return Math.max(1, w[Math.floor(w.length / 2)] ?? 0);
+ });
+ const burst = laugh.map((v, k) => v >= CHAT_BURST_MIN && v >= CHAT_BURST_RATIO * base[k]);
+ const out = [];
+ for (let k = 0; k < n; ) {
+ if (!burst[k]) {
+ k += 1;
+ continue;
+ }
+ let j = k;
+ // A run: burst bins, one quiet bin between them allowed.
+ while (j + 1 < n && (burst[j + 1] || (j + 2 < n && burst[j + 2]))) j += burst[j + 1] ? 1 : 2;
+ let messages = 0;
+ let strength = 0;
+ for (let i = k; i <= j; i += 1) {
+ messages += laugh[i];
+ strength += Math.max(0, laugh[i] / base[i] - 1);
+ }
+ const t = Math.max(0, k * hop - lagS);
+ const end = Math.max(t + hop, (j + 1) * hop - lagS);
+ if (t >= from - 1e-9 && end <= to + 1e-9) {
+ out.push({ t: round(t), end: round(end), score: round(CHAT_WEIGHT * (1 - Math.exp(-strength / 6)), 3), messages });
+ }
+ k = j + 1;
+ }
+ return out;
+}
diff --git a/common/lib/clips/chat.test.ts b/common/lib/clips/chat.test.ts
@@ -0,0 +1,117 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import {
+ CHAT_LAG_DEFAULT_S,
+ CHAT_WEIGHT,
+ chatBins,
+ chatLag,
+ chatMessage,
+ chatMoments,
+ isChatLaugh,
+ readChatCues,
+} from "./chat.mjs";
+import { LAUGH_WEIGHT, analyze } from "./clips.mjs";
+import { LAUGHS, reactionChat, reactionStream, twoVideoStream } from "../../testing/clips/reactionStream.mjs";
+
+test("isChatLaugh: the laugh tokens, as words, emotes or emoji; the author is not the message", () => {
+ for (const t of ["a: lol", "b: LMAOOO", "c: lmfao", "d: KEKW KEKW", "e: LUL", "f: OMEGALUL", "g: hahaha", "h: HAHA", "i: π", "j: that's it π€£", "k: W", "l: w w", "m: :face-with-tears-of-joy:", "n: lol."]) {
+ assert.equal(isChatLaugh(t), true, t);
+ }
+ for (const t of ["a: what", "b: Wow", "c: ha", "d: lolipop", "e: W rizz", "lol: hello", "", "f: Whale"]) assert.equal(isChatLaugh(t), false, t);
+ assert.equal(chatMessage("viewer: hi: there"), "hi: there");
+});
+
+test("chatBins: messages and laughing messages per 2 s bin", () => {
+ const b = chatBins([{ start: 0.5, text: "a: hi" }, { start: 1.9, text: "b: lol" }, { start: 2, text: "c: lol" }, { start: 9.9, text: "d: x" }, { start: 50, text: "late" }], { duration: 10 });
+ assert.deepEqual(b, { hop: 2, rate: [2, 1, 0, 0, 1], laugh: [1, 1, 0, 0, 0] });
+});
+
+test("chatLag: the chat's delay found against the laugh scan; the default when there is no scan or no clear peak", () => {
+ const s = reactionStream();
+ for (const lag of [6, 12, 3]) {
+ const b = chatBins(reactionChat({ lag }), { duration: s.duration });
+ const got = chatLag(b.laugh, s.laughScan);
+ assert.equal(got.how, "xcorr");
+ assert.ok(Math.abs(got.lagS - lag) <= 1.5, `lag ${lag}: found ${got.lagS}`);
+ }
+ const b = chatBins(reactionChat({}), { duration: s.duration });
+ assert.deepEqual(chatLag(b.laugh, null), { lagS: CHAT_LAG_DEFAULT_S, how: "default", r: null, why: "no laugh scores to line the chat up with" });
+ // A scan that does not vary has nothing to line up with.
+ assert.equal(chatLag(b.laugh, { ...s.laughScan, scores: s.laughScan.scores.map(() => 0.1) }).how, "default");
+ // Chat that laughs at random times: a weak peak.
+ const random = chatBins(reactionChat({ laughs: [[40, 41], [170, 171], [450, 451]], lag: 0 }), { duration: s.duration });
+ const weak = chatLag(random.laugh, s.laughScan);
+ assert.equal(weak.how, "default");
+ assert.match(weak.why, /weak peak/);
+});
+
+test("chatMoments: a burst over the local median is a moment, moved back by the lag; only inside the scope; under a host laugh's weight", () => {
+ const s = reactionStream();
+ const b = chatBins(reactionChat({ lag: 6, chatOnly: [200] }), { duration: s.duration });
+ const ms = chatMoments(b, { lagS: 6 });
+ assert.equal(ms.length, LAUGHS.length + 1);
+ for (const [start] of LAUGHS) assert.ok(ms.some((m) => Math.abs(m.t - start) <= 2), `a moment near ${start}`);
+ assert.ok(ms.some((m) => Math.abs(m.t - 194) <= 2), "the chat-only burst");
+ assert.ok(ms.every((m) => m.score > 0 && m.score <= CHAT_WEIGHT && m.messages >= 3));
+ assert.ok(CHAT_WEIGHT < LAUGH_WEIGHT.host);
+ assert.deepEqual(chatMoments(b, { lagS: 6, from: 300, to: 400 }).map((m) => Math.round(m.t)), [340]);
+ // A steady trickle with no burst: nothing.
+ assert.deepEqual(chatMoments(chatBins(reactionChat({ laughs: [] }), { duration: 600 }), { lagS: 6 }), []);
+});
+
+test("readChatCues: live_chat.cues.json beside the recording, or null", async () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "chat-"));
+ try {
+ assert.equal(await readChatCues(dir), null);
+ writeFileSync(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "whisper", cues: [] }));
+ assert.equal(await readChatCues(dir), null);
+ writeFileSync(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [{ start: 1, end: 6, text: "a: lol" }, { start: "x", text: "b" }] }));
+ assert.deepEqual(await readChatCues(dir), { source: "live_chat.cues.json", cues: [{ start: 1, text: "a: lol" }] });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// Release 35's clips.mjs (a62cdc98) over the synthetic streams, hashed: with
+// no chat the analysis must be EXACTLY what it was.
+const RELEASE_35 = { "one-model": "0fbdc3b365476394", "one-text": "fe4990b2624fa99f", "two-model": "8a7c1e0c8e1418c0", "two-text": "f631bc75e4d205b3" };
+const digest = (x: unknown) => createHash("sha256").update(JSON.stringify(x)).digest("hex").slice(0, 16);
+
+test("analyze: no chat is release 35 byte for byte; a chat replay adds `chat` moments and the lag", () => {
+ for (const [name, s] of [["one", reactionStream()], ["two", twoVideoStream()]] as const) {
+ for (const mode of ["model", "text"] as const) {
+ const o = { turns: s.turns, duration: s.duration, words: s.words, params: { target: 120 }, laughScan: mode === "model" ? s.laughScan : null };
+ for (const chat of [undefined, null, { cues: [] }]) {
+ const a = analyze({ ...o, chat });
+ assert.equal(digest({ moments: a.moments, proposals: a.proposals, laughs: a.laughs, speakers: a.speakers }), RELEASE_35[`${name}-${mode}`], `${name}-${mode} chat ${JSON.stringify(chat)}`);
+ assert.equal(a.chat, null);
+ }
+ }
+ }
+ const s = reactionStream();
+ const cues = reactionChat({ lag: 6, chatOnly: [200] });
+ const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, params: { target: 120 }, laughScan: s.laughScan, chat: { source: "live_chat.cues.json", cues } });
+ assert.ok(a.chat);
+ assert.equal(a.chat.source, "live_chat.cues.json");
+ assert.equal(a.chat.lag.how, "xcorr");
+ assert.ok(Math.abs(a.chat.lagS - 6) <= 1.5);
+ assert.equal(a.chat.messages, cues.length);
+ assert.equal(a.chat.bins.hop, 2);
+ assert.equal(a.chat.bins.rate.length, 300);
+ const chats = a.moments.filter((m) => m.kind === "chat");
+ assert.equal(chats.length, 4);
+ // The chat-only burst (no laugh there) becomes a proposal of its own, said plainly.
+ const lone = a.proposals.find((p) => p.moments.some((id) => chats.find((m) => m.id === id && Math.abs(m.t - 194) < 3)));
+ assert.ok(lone, "a proposal for the chat-only burst");
+ assert.match(lone.why, /chat laughs \(20 messages\)/);
+ // A host laugh still outscores the chat it caused.
+ const host = a.moments.filter((m) => m.kind === "laugh").reduce((x, m) => Math.max(x, m.score), 0);
+ assert.ok(chats.every((m) => m.score < host));
+ // Scoped: only the scope's bursts.
+ const scoped = analyze({ turns: s.turns, duration: s.duration, words: s.words, params: { scope: [300, 450] }, laughScan: s.laughScan, chat: { cues } });
+ assert.deepEqual(scoped.moments.filter((m) => m.kind === "chat").map((m) => Math.round(m.t / 10) * 10), [340]);
+});
diff --git a/common/lib/clips/clips.d.mts b/common/lib/clips/clips.d.mts
@@ -36,7 +36,15 @@ export type Turn = { start: number; end: number; speaker: number };
export type Word = { w: string; start: number; end: number; cueStart?: true; conf?: number };
export type Speaker = { index: number; role: Role; label: string; seconds: number; turns: number; how: "auto" | "operator"; sameAs?: number };
export type Laugh = { start: number; end: number; score: number; speaker: number | null; src?: "text" | "energy"; voice?: { host: number; subject: number }; by?: "voice" };
-export type Moment = { id: string; t: number; end: number; kind: "laugh" | "comment"; score: number; speaker: number | null; text: string };
+export type Moment = { id: string; t: number; end: number; kind: "laugh" | "comment" | "chat"; score: number; speaker: number | null; text: string; messages?: number };
+export type ReactionsChat = {
+ source: string;
+ lagS: number;
+ lag: { how: "xcorr" | "default"; r: number | null; why: string };
+ messages: number;
+ bursts: number;
+ bins: { hop: number; rate: number[]; laugh: number[] };
+};
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 };
@@ -71,12 +79,18 @@ export function energyLaughs(
o: { words: Word[]; turns: Turn[]; speakers: { index: number; role: string }[] },
): { start: number; end: number; score: number; src: "energy" }[];
export function attributeLaughs<L extends { start: number; end: number }>(laughs: L[], turns: Turn[], speakers: { index: number; role: string }[]): (L & { speaker: number | null })[];
-export function findMoments(o: { turns: Turn[]; speakers: { index: number; role: string }[]; laughs: { start: number; end: number; score: number; speaker: number | null; by?: string }[]; words: Word[] }): Moment[];
+export function findMoments(o: {
+ turns: Turn[];
+ speakers: { index: number; role: string }[];
+ laughs: { start: number; end: number; score: number; speaker: number | null; by?: string }[];
+ words: Word[];
+ chat?: { t: number; end: number; score: number; messages: number; speaker?: number | null }[];
+}): Moment[];
export function momentSpan(
- m: { t: number; end: number; kind: "laugh" | "comment" },
+ m: { t: number; end: number; kind: "laugh" | "comment" | "chat" },
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 momentWhy(m: { t: number; end: number; kind: "laugh" | "comment" | "chat"; speakerRole?: string; messages?: number }, 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 }>(
@@ -94,6 +108,7 @@ export function analyze(o: {
laughVoices?: Map<string, number[]> | Record<string, number[]> | null;
previous?: { id: string; start: number; end: number }[];
fixed?: { id: string; start: number; end: number }[];
+ chat?: { source?: string; cues: { start: number; text: string }[] } | null;
}): {
params: Params;
duration: number;
@@ -103,4 +118,5 @@ export function analyze(o: {
laughs: Laugh[];
moments: Moment[];
proposals: (Proposal & { used: boolean })[];
+ chat: ReactionsChat | null;
};
diff --git a/common/lib/clips/clips.mjs b/common/lib/clips/clips.mjs
@@ -20,7 +20,12 @@
// 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;
@@ -515,12 +520,14 @@ const roleOf = (roles, speaker) => (speaker === null || speaker === undefined ?
* 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β¦.
+ * 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 }) {
+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);
@@ -538,7 +545,12 @@ export function findMoments({ turns, speakers, laughs, words }) {
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 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")}`,
@@ -547,7 +559,8 @@ export function findMoments({ turns, speakers, laughs, words }) {
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),
+ text: m.kind === "comment" ? textIn(words, m.t, m.end) : textIn(words, m.t - 6, m.end + 1),
+ ...(m.kind === "chat" ? { messages: m.messages } : {}),
}));
}
@@ -590,7 +603,8 @@ export function momentSpan(m, { turns, speakers, words, sentences, setupMax, dur
setupStart = own && own.start > t - setupMax ? Math.min(own.start, t - 0.5) : t - 2;
}
let reactionEnd = m.end;
- if (m.kind === "laugh") {
+ // 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);
@@ -602,6 +616,10 @@ export function momentSpan(m, { turns, speakers, words, sentences, setupMax, dur
/** 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);
@@ -763,7 +781,8 @@ export function rankIntoTarget(proposals, { target, fixed = [] }) {
* @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
+ * 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);
@@ -792,7 +811,24 @@ export function analyze(o) {
laughSource = fromEnergy.length || (scan && Array.isArray(scan.energy)) ? "text+energy" : "text";
}
const laughs = voiceLaughs(attributeLaughs(laughsRaw, turns, speakers), speakers, o.centroids ?? null, o.laughVoices ?? null);
- const moments = findMoments({ turns, speakers, laughs, words });
+ // 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 ?? [] });
@@ -810,6 +846,7 @@ export function analyze(o) {
})),
moments,
proposals: ranked,
+ chat,
};
}
diff --git a/common/package.json b/common/package.json
@@ -33,6 +33,7 @@
"./components/*": "./components/*.tsx",
"./lib/citations/respell.mjs": "./lib/citations/respell.mjs",
"./lib/clips/assist.mjs": "./lib/clips/assist.mjs",
+ "./lib/clips/chat.mjs": "./lib/clips/chat.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",
diff --git a/umtool/lib/report/reactions-r36.test.mjs b/umtool/lib/report/reactions-r36.test.mjs
@@ -5,29 +5,45 @@
//
// Run with: pnpm test:scripts
import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
+import { fileURLToPath } from "node:url";
-import { TWO_SUBJECT_A, TWO_SUBJECT_B, writeReactionCorpus } from "yt-dlp-transcript-common/testing/clips/reactionStream.mjs";
+import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { TWO_SUBJECT_A, TWO_SUBJECT_B, reactionAudio, writeReactionCorpus } from "yt-dlp-transcript-common/testing/clips/reactionStream.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { scaffoldReportVideo } from "../projects/scaffold.mjs";
import { clipsCommand, clipsSteps } from "./reactions.mjs";
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const KIT = path.resolve(HERE, "..", "..", "..", "common", "testing", "audio");
+const TAGGER = { python: process.execPath, script: path.join(KIT, "fakeAudioTag.mjs"), model: path.join(KIT, "fakeAudioTag.mjs"), labels: "none.csv", threads: 1, available: true };
+const ENGINE = { python: process.execPath, script: path.join(KIT, "fakeSpeakerEmbed.mjs"), model: "fake.onnx", threads: 1 };
+const hasFfmpeg = (() => {
+ try {
+ execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+})();
+
const quiet = () => {
const lines = [];
return { lines, log: (s) => lines.push(s), err: (s) => lines.push(s) };
};
/** A corpus with the two-video stream (and optionally its chat), and a reports root. */
-async function fixture({ two = true, chat = null, meta = null } = {}) {
+async function fixture({ two = true, chat = null, meta = null, audio = false } = {}) {
const root = await mkdtemp(path.join(tmpdir(), "clips36-"));
const channelsDir = path.join(root, "channels");
const reportsRoot = path.join(root, "reports");
const sitesDir = path.join(root, "sites");
await mkdir(sitesDir, { recursive: true });
- writeReactionCorpus(channelsDir, { two, chat, meta });
+ writeReactionCorpus(channelsDir, { two, chat, meta, audio: audio ? encodeWav16(reactionAudio()) : null });
return { root, channelsDir, reportsRoot, sitesDir };
}
@@ -86,3 +102,43 @@ test("auto-scope: --scope auto reads the longest narrated video, --segment names
await rm(f.root, { recursive: true, force: true });
}
});
+
+test("the chat signal: a replay beside the recording adds chat moments; the seed (no scan) takes the default lag; no replay changes nothing", async () => {
+ const f = await fixture({ two: false, chat: { lag: 6, chatOnly: [200] } });
+ const g = await fixture({ two: false });
+ try {
+ const a = await scaffoldReportVideo({ root: f.reportsRoot, slug: "chat", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 120, sitesDir: f.sitesDir });
+ const doc = await readReactions(a.dir);
+ assert.ok(doc.chat);
+ assert.equal(doc.chat.source, "live_chat.cues.json");
+ assert.deepEqual([doc.chat.lagS, doc.chat.lag.how], [6, "default"]);
+ assert.equal(doc.chat.bins.hop, 2);
+ assert.ok(doc.moments.some((m) => m.kind === "chat" && m.messages >= 3));
+ const b = await scaffoldReportVideo({ root: g.reportsRoot, slug: "chat", from: "synth-reacts/react001", seed: "reactions", channelsDir: g.channelsDir, target: 120, sitesDir: g.sitesDir });
+ const none = await readReactions(b.dir);
+ assert.equal(none.chat, null);
+ assert.ok(none.moments.every((m) => m.kind !== "chat"));
+ // The chat-only burst is a proposal the plain stream does not have.
+ assert.ok(doc.proposals.length > none.proposals.length);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ await rm(g.root, { recursive: true, force: true });
+ }
+});
+
+test("clips analyze with a chat replay: the lag cross-correlated with the laugh scan, named in the log", { skip: !hasFfmpeg && "no ffmpeg" }, async () => {
+ const f = await fixture({ two: false, audio: true, chat: { lag: 8 } });
+ try {
+ const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "chat", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 60, sitesDir: f.sitesDir });
+ await pointAt(r.dir, f.channelsDir);
+ const q = quiet();
+ assert.equal(await clipsCommand(["analyze", "chat", "--no-voices", "--progress", "ndjson"], { reportsRoot: f.reportsRoot, ...q, tagger: TAGGER, engine: ENGINE }), 0, q.lines.join("\n"));
+ const doc = await readReactions(r.dir);
+ assert.equal(doc.laughSource, "model");
+ assert.equal(doc.chat.lag.how, "xcorr", JSON.stringify(doc.chat.lag));
+ assert.ok(Math.abs(doc.chat.lagS - 8) <= 2, `lag ${doc.chat.lagS}`);
+ assert.match(q.lines.join("\n"), new RegExp(`chat: \\d+ message\\(s\\), \\d+ laugh burst\\(s\\); lag ${doc.chat.lagS} s β cross-correlated with the laugh scan`));
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs
@@ -24,6 +24,9 @@
// the laugh model CED-mini under .diarize/models/ (AUDIO_TAG_MODEL): the
// laugh scores; without it, the transcript's markers plus
// the host's wordless energy bursts
+// the chat live_chat.cues.json beside the recording (release 36):
+// the room's laugh bursts as `chat` moments; without it,
+// nothing changes
//
// Nothing here calls a model but the local ones; nothing touches the network.
import { readFile, rename, stat, writeFile, mkdir } from "node:fs/promises";
@@ -42,6 +45,7 @@ import { applyProposals, fixedClips } from "yt-dlp-transcript-common/lib/clips/a
import { REACTIONS_FILE, operatorRoles, readReactions, writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { embedSpans, resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs";
import { SEGMENT_MIN_S, findSegments, pickSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs";
+import { readChatCues } from "yt-dlp-transcript-common/lib/clips/chat.mjs";
import { clockOffset, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources";
@@ -105,6 +109,7 @@ export async function loadRecording({ channelsDir, channel, video, projectDir =
}
}
if (!words) words = wordsFromCues(Array.isArray(cuesDoc?.cues) ? cuesDoc.cues : []);
+ const chat = await readChatCues(videoDir);
const turnsEnd = Math.max(...diar.turns.map((t) => (num(t?.end) ? t.end : 0)));
const duration = [diar.audioSeconds, meta?.duration, cuesDoc?.duration].find((d) => num(d) && d > 0) ?? turnsEnd;
return {
@@ -116,6 +121,8 @@ export async function loadRecording({ channelsDir, channel, video, projectDir =
diarization: { generatedAt: typeof diar.generatedAt === "string" ? diar.generatedAt : null, engine: typeof diar.engine?.engine === "string" ? diar.engine.engine : null },
words,
wordsFrom,
+ chat,
+ meta: meta ? { webpageUrl: typeof meta.webpage_url === "string" ? meta.webpage_url : null, channel: typeof meta.channel === "string" ? meta.channel : typeof meta.uploader === "string" ? meta.uploader : null, extractor: typeof meta.extractor_key === "string" ? meta.extractor_key : typeof meta.extractor === "string" ? meta.extractor : null } : null,
};
}
@@ -270,6 +277,7 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr
laughVoices,
previous: previous?.proposals ?? [],
fixed,
+ chat: rec.chat ?? null,
});
const applied = applyProposals(timeline, { proposals: a.proposals, channel: rec.channel, video: rec.video, duration: a.duration, words: cleanWords(rec.words), isProtected });
const madeAt = now.toISOString();
@@ -293,6 +301,7 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr
laughSource: a.laughSource,
segments,
segment: segmentOfScope(segments, a.params.scope),
+ chat: a.chat,
scans: {
laughs: scans?.audio ? { model: scans.audio.model?.file ?? null, windows: scans.audio.windows, madeAt: scans.audio.madeAt ?? null } : null,
voices: scans?.voices ? { model: scans.voices.model ?? null, madeAt: scans.voices.madeAt ?? null } : null,
@@ -353,6 +362,12 @@ export function resolveParams(rec, params, operator = {}, say = () => {}) {
return { ...rest, scope: r.scope ?? "all" };
}
+/** The chat in one line: its messages, the lag found and how. */
+export function chatLine(chat) {
+ const how = chat.lag?.how === "xcorr" ? chat.lag.why : `the default (${chat.lag?.why ?? "no lag found"})`;
+ return `chat: ${chat.messages} message(s), ${chat.bursts} laugh burst(s); lag ${chat.lagS} s β ${how}`;
+}
+
/** What a pass did, in one line. */
export function passSummary(doc, changes) {
const used = doc.proposals.filter((p) => p.used);
@@ -361,6 +376,7 @@ export function passSummary(doc, changes) {
return (
`${doc.proposals.length} proposal(s), ${used.length} in the cut (${Math.round(seconds)} s of a ${doc.params.target} s target); ` +
`laughs: ${doc.laughs.length} (${doc.laughSource}); host: speaker ${host}` +
+ (doc.chat ? `; chat: ${doc.chat.bursts} burst(s), lag ${doc.chat.lagS} s` : "") +
(changes ? `; clips +${changes.added.length} ~${changes.updated.length} -${changes.removed.length}` : "")
);
}
@@ -596,6 +612,7 @@ function showLines(doc) {
const byVoice = doc.laughs.filter((l) => l.by === "voice").length;
const voiced = doc.laughs.filter((l) => l.voice).length;
lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}${voiced ? `; ${voiced} voice-checked, ${byVoice} re-attributed by voice` : ""}), moments: ${doc.moments.length}`);
+ if (doc.chat) lines.push(` ${chatLine(doc.chat)}`);
const used = doc.proposals.filter((p) => p.used);
lines.push(` proposals: ${doc.proposals.length}, in the cut: ${used.length} (${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of ${doc.params.target} s)`);
for (const p of used) lines.push(` ${p.id} ${(p.clipId ?? "-").padEnd(5)} ${p.start.toFixed(1).padStart(8)}β${p.end.toFixed(1).padEnd(8)} ${p.score.toFixed(2)} ${p.why}`);
@@ -704,6 +721,7 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con
if (p.has("--json")) log(JSON.stringify({ written: r.written, changes: r.changes, reactions: r.doc }, null, 1));
else {
if (!ndjson) log(showLines(r.doc).join("\n"));
+ else if (r.doc.chat) say(chatLine(r.doc.chat));
say(`${r.written ? "" : "(dry run, nothing written) "}${passSummary(r.doc, r.changes)}`);
}
return 0;