commit daa6f119a15b886ea90c671c76809a48df6d2fe0
parent aeaf1933b4e33870b332c7091ca27ebb7d64cc4b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 14:19:15 -0400
Merge branch 'main' into r36/find-clips
# Conflicts:
# editor/CHANGELOG.md
# plans/FACTS.md
Diffstat:
33 files changed, 2247 insertions(+), 79 deletions(-)
diff --git a/common/lib/clips/assist.d.mts b/common/lib/clips/assist.d.mts
@@ -33,14 +33,16 @@ export type AssistClip = {
cite: number;
quote: string;
assist: Assist;
+ citeUrl?: string;
};
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 watchUrlAt(url: string | null | undefined, seconds: number): string | null;
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[] },
+ o: { id: string; channel: string; video: string; duration?: number; words?: Word[]; citeUrlAt?: ((s: number) => string | null) | null },
): AssistClip;
export function fixedClips(timeline: unknown[], o: { channel: string; video: string; isProtected?: (e: any) => boolean }): { id: string; start: number; end: number }[];
export function applyProposals(
@@ -52,6 +54,7 @@ export function applyProposals(
duration?: number;
words?: Word[];
isProtected?: (e: any) => boolean;
+ citeUrlAt?: ((s: number) => string | null) | null;
},
): {
timeline: any[];
diff --git a/common/lib/clips/assist.mjs b/common/lib/clips/assist.mjs
@@ -91,17 +91,49 @@ export const isAssistantClip = (e) => isObj(e) && e.type === "clip" && isObj(e.a
export const cutOf = (e) => (num(e?.cutStart) && num(e?.cutEnd) ? { start: e.cutStart, end: e.cutEnd } : { start: e.start, end: e.end });
/**
+ * A platform's watch page at a second (release 36: a clip of a channel that is
+ * on no site links its source there): YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`,
+ * Rumble `start=<s>`, anything else `t=<s>` β added with `&` or `?`, an
+ * existing one of the same name replaced. Null for a URL that is not one.
+ * @param {string | null | undefined} url the recording's `webpage_url`
+ * @param {number} seconds
+ * @returns {string | null}
+ */
+export function watchUrlAt(url, seconds) {
+ if (typeof url !== "string" || !/^https?:\/\//i.test(url)) return null;
+ let host;
+ try {
+ host = new URL(url).hostname.toLowerCase().replace(/^(?:www|m)\./, "");
+ } catch {
+ return null;
+ }
+ const s = Math.max(0, Math.floor(Number(seconds) || 0));
+ const youtube = host === "youtube.com" || host === "youtu.be" || host.endsWith(".youtube.com");
+ const twitch = host === "twitch.tv" || host.endsWith(".twitch.tv");
+ const key = host === "rumble.com" ? "start" : "t";
+ const value = youtube ? `${s}s` : twitch ? `${Math.floor(s / 3600)}h${Math.floor((s % 3600) / 60)}m${s % 60}s` : String(s);
+ const hash = url.indexOf("#");
+ const base = hash >= 0 ? url.slice(0, hash) : url;
+ const frag = hash >= 0 ? url.slice(hash) : "";
+ // A targeted edit (no URLSearchParams round trip, which re-escapes every other parameter).
+ const stripped = base.replace(new RegExp(`([?&])${key}=[^&]*(&|$)`), (_m, a, b) => (b ? a : "")).replace(/[?&]$/, "");
+ return `${stripped}${stripped.includes("?") ? "&" : "?"}${key}=${value}${frag}`;
+}
+
+/**
* 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.
+ * side for trimming, inside the recording. `citeUrlAt` (release 36: a
+ * site-less channel) gives the clip a `citeUrl` at its cite.
* @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
+ * @param {{ id: string, channel: string, video: string, duration?: number, words?: { w: string, start: number, end: number }[], citeUrlAt?: ((s: number) => string | null) | null }} o
*/
-export function clipFromProposal(p, { id, channel, video, duration = Infinity, words = [] }) {
+export function clipFromProposal(p, { id, channel, video, duration = Infinity, words = [], citeUrlAt = null }) {
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));
+ const link = citeUrlAt ? citeUrlAt(Math.floor(cutStart)) : null;
return {
type: "clip",
id,
@@ -121,6 +153,7 @@ export function clipFromProposal(p, { id, channel, video, duration = Infinity, w
original: { start, end: Math.max(end, cutEnd), cutStart, cutEnd },
edits: [],
},
+ ...(link ? { citeUrl: link } : {}),
};
}
@@ -165,10 +198,15 @@ export function fixedClips(timeline, { channel, video, isProtected = () => false
* Returns the timeline, the proposals with their `clipId` (null when unused),
* and what changed.
* @param {any[]} timeline
+ * With `citeUrlAt` (release 36: the channel is on no site), every clip the
+ * pass adds or moves carries `citeUrl` = the platform's page at its cite; a
+ * moved clip's link is re-pointed only when it is that derived link (or it has
+ * none) β a link somebody wrote stays.
* @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
+ * channel: string, video: string, duration?: number, words?: { w: string, start: number, end: number }[], isProtected?: (e: any) => boolean,
+ * citeUrlAt?: ((s: number) => string | null) | null }} o
*/
-export function applyProposals(timeline, { proposals, channel, video, duration = Infinity, words = [], isProtected = () => false }) {
+export function applyProposals(timeline, { proposals, channel, video, duration = Infinity, words = [], isProtected = () => false, citeUrlAt = null }) {
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();
@@ -189,17 +227,20 @@ export function applyProposals(timeline, { proposals, channel, video, duration =
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 fresh = clipFromProposal(p, { id: have.id, channel: have.channel ?? channel, video, duration, words, citeUrlAt });
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;
+ // The derived link follows the cite; one written by somebody else stays.
+ const relink = !!fresh.citeUrl && have.citeUrl !== fresh.citeUrl && (!have.citeUrl || have.citeUrl === citeUrlAt?.(have.cite ?? Math.floor(have.cutStart ?? have.start)));
+ if (same && !relink) 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 });
+ if (relink) have.citeUrl = fresh.citeUrl;
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 });
+ const clip = clipFromProposal(p, { id: nextClipId(used), channel, video, duration, words, citeUrlAt });
out.push(clip);
changes.added.push(clip.id);
return { ...p, clipId: clip.id };
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/lib/clips/links.test.ts b/common/lib/clips/links.test.ts
@@ -0,0 +1,43 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { applyProposals, clipFromProposal, watchUrlAt } from "./assist.mjs";
+
+test("watchUrlAt: the platform's page at a second, in its own form; an existing one replaced; not a URL, null", () => {
+ assert.equal(watchUrlAt("https://www.youtube.com/watch?v=abc", 128.9), "https://www.youtube.com/watch?v=abc&t=128s");
+ assert.equal(watchUrlAt("https://www.youtube.com/watch?v=abc&t=5s", 3), "https://www.youtube.com/watch?v=abc&t=3s");
+ assert.equal(watchUrlAt("https://youtu.be/abc", 4), "https://youtu.be/abc?t=4s");
+ assert.equal(watchUrlAt("https://www.twitch.tv/videos/123", 3725), "https://www.twitch.tv/videos/123?t=1h2m5s");
+ assert.equal(watchUrlAt("https://rumble.com/v2abc-title.html", 61), "https://rumble.com/v2abc-title.html?start=61");
+ assert.equal(watchUrlAt("https://odysee.com/@a:1/b:2", 7), "https://odysee.com/@a:1/b:2?t=7");
+ assert.equal(watchUrlAt("https://example.com/x?t=1&y=2#h", 8), "https://example.com/x?y=2&t=8#h");
+ assert.equal(watchUrlAt("not a url", 3), null);
+ assert.equal(watchUrlAt(null, 3), null);
+});
+
+const P = (id: string, start: number, end: number, used = true) => ({ id, start, end, score: 0.5, why: "host laughs", used });
+const linkAt = (s: number) => watchUrlAt("https://www.youtube.com/watch?v=vid", s);
+
+test("applyProposals with citeUrlAt: added clips link their second; a moved clip's derived link follows it; a link somebody wrote stays", () => {
+ const clip = clipFromProposal(P("p001", 10.4, 20), { id: "r001", channel: "ch", video: "vid", citeUrlAt: linkAt });
+ assert.equal(clip.citeUrl, "https://www.youtube.com/watch?v=vid&t=10s");
+ assert.equal("citeUrl" in clipFromProposal(P("p001", 10.4, 20), { id: "r001", channel: "ch", video: "vid" }), false);
+
+ const first = applyProposals([], { proposals: [P("p001", 10, 20), P("p002", 40, 50)], channel: "ch", video: "vid", citeUrlAt: linkAt });
+ assert.deepEqual(first.timeline.map((e) => e.citeUrl), ["https://www.youtube.com/watch?v=vid&t=10s", "https://www.youtube.com/watch?v=vid&t=40s"]);
+ // A hand-written link (a mirror) on r002; r001 moves: its derived link follows, r002's stays.
+ const tl = first.timeline.map((e) => ({ ...e }));
+ tl[1].citeUrl = "https://mirror.example/x?t=40";
+ const second = applyProposals(tl, { proposals: [P("p001", 12, 20), P("p002", 42, 50)], channel: "ch", video: "vid", citeUrlAt: linkAt });
+ assert.deepEqual(second.timeline.map((e) => [e.id, e.cite, e.citeUrl]), [
+ ["r001", 12, "https://www.youtube.com/watch?v=vid&t=12s"],
+ ["r002", 42, "https://mirror.example/x?t=40"],
+ ]);
+ // A clip from before the rule (no link) gains one even when nothing else moved; without the rule nothing changes.
+ const bare = first.timeline.map(({ citeUrl: _c, ...e }) => e);
+ const third = applyProposals(bare, { proposals: [P("p001", 10, 20), P("p002", 40, 50)], channel: "ch", video: "vid", citeUrlAt: linkAt });
+ assert.deepEqual(third.changes.updated, ["r001", "r002"]);
+ assert.ok(third.timeline.every((e) => e.citeUrl));
+ const plain = applyProposals(bare, { proposals: [P("p001", 10, 20), P("p002", 40, 50)], channel: "ch", video: "vid" });
+ assert.equal(plain.changes.kept, 2);
+ assert.ok(plain.timeline.every((e) => !("citeUrl" in e)));
+});
diff --git a/common/lib/clips/reactions.d.mts b/common/lib/clips/reactions.d.mts
@@ -1,4 +1,5 @@
-import type { Laugh, Moment, Params, Role, Speaker, Turn } from "./clips.mjs";
+import type { Laugh, Moment, Params, ReactionsChat, Role, Speaker, Turn } from "./clips.mjs";
+import type { Segment } from "./segments.mjs";
export const REACTIONS_FILE: string;
export const REACTIONS_VERSION: 1;
@@ -35,6 +36,11 @@ export type ReactionsDoc = {
rolesChangedAt?: string;
laughSource?: "model" | "text" | "text+energy";
scans?: Record<string, unknown>;
+ /** Release 36: the narrated-video spans auto-scope found, and which one the scope is (null: a scope by hand, or none). */
+ segments?: Segment[];
+ segment?: string | null;
+ /** Release 36: the chat replay's signal, or null when there is none. */
+ chat?: ReactionsChat | null;
};
export function reactionsFileOf(dir: string): string;
diff --git a/common/lib/clips/segments.d.mts b/common/lib/clips/segments.d.mts
@@ -0,0 +1,12 @@
+export const SEGMENT_WINDOW_S: number;
+export const SEGMENT_HOP_S: number;
+export const SEGMENT_MIN_SUBJECT_S: number;
+export const SEGMENT_DOMINANCE: number;
+export const SEGMENT_MIN_S: number;
+export const SEGMENT_TAIL_S: number;
+
+export type Segment = { id: string; from: number; to: number; subject: number; host: number | null; why: string };
+
+export function findSegments(o: { turns: unknown; duration?: number; host?: number | null; operator?: Record<string, string> }): Segment[];
+export function pickSegment<S extends { id: string; from: number; to: number }>(segments: S[], id?: string | null): S | null;
+export function scopeOverlapsSegment(scope: [number, number | null] | null | undefined, segment: { from: number; to: number }, duration: number): boolean;
diff --git a/common/lib/clips/segments.mjs b/common/lib/clips/segments.mjs
@@ -0,0 +1,173 @@
+// Auto-scope (release 36 B1): where, in a long recording, each narrated video
+// is. A reaction stream plays one video, then another; the host talks over
+// both and between them. Release 35 cut the Nik Drop from one video at a time
+// with a scope read off the speaker clusters by hand; this finds the spans.
+//
+// From the speaker turns alone (diarization.json), pure, deterministic:
+//
+// the host the cluster assignRoles calls the host over the whole
+// recording (or the operator's), left out of the counting:
+// he talks all the way through, so he never marks a video
+// windows SEGMENT_WINDOW_S long, every SEGMENT_HOP_S: each window's
+// subject is the cluster with the most seconds in turns of at
+// least SHORT_TURN_S (a narrated video talks in long runs),
+// counted when it has SEGMENT_MIN_SUBJECT_S of them and
+// SEGMENT_DOMINANCE of the long-turn time
+// a span consecutive windows with the same subject; its edges are
+// that subject's first and last long turn inside them
+// joined neighbouring spans of one subject are one (a dip between
+// them); spans under SEGMENT_MIN_S are dropped
+// the tail the host-only time after a video's last line β the host's
+// reaction to it β folded into it, up to SEGMENT_TAIL_S and
+// never past the next video's first line; its end on a turn's
+// end. The time before a video's first line (an intro, the
+// host between videos past the tail) belongs to no segment.
+//
+// β `[{ id: "s1", from, to, subject, host, why }]`, chronological. Roles are
+// still assigned per segment (the analysis runs on the segment's turns with
+// the scope); this only says where the segments are.
+//
+// Plain ESM with a .d.mts beside it.
+import { SHORT_TURN_S, assignRoles, cleanTurns } from "./clips.mjs";
+
+export const SEGMENT_WINDOW_S = 300;
+export const SEGMENT_HOP_S = 30;
+/** A window's subject has at least this many seconds of long turns in it⦠*/
+export const SEGMENT_MIN_SUBJECT_S = 60;
+/** β¦and at least this share of the window's long-turn time (the host's left out). */
+export const SEGMENT_DOMINANCE = 0.6;
+/** A segment shorter than this is dropped. */
+export const SEGMENT_MIN_S = 180;
+/** The host-only time after a video's last line folded into it: at most this. */
+export const SEGMENT_TAIL_S = 300;
+
+const round = (x, d = 2) => Math.round(x * 10 ** d) / 10 ** d;
+const overlap = (a0, a1, b0, b1) => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0));
+
+/**
+ * The narrated-video spans of a recording.
+ * @param {{ turns: unknown, duration?: number, host?: number | null, operator?: Record<string, string> }} o
+ * `host`: the host's cluster when it is known (the operator's word); else assignRoles' over the whole recording
+ * @returns {{ id: string, from: number, to: number, subject: number, host: number | null, why: string }[]}
+ */
+export function findSegments({ turns, duration = 0, host = null, operator = {} }) {
+ const ts = cleanTurns(turns);
+ if (!ts.length) return [];
+ const end = Math.max(Number(duration) || 0, ...ts.map((t) => t.end));
+ let hostIx = Number.isInteger(host) && /** @type {number} */ (host) >= 0 ? /** @type {number} */ (host) : null;
+ if (hostIx === null) {
+ const roles = assignRoles({ turns: ts, duration: end, operator });
+ hostIx = roles.find((s) => s.role === "host")?.index ?? null;
+ }
+ const long = ts.filter((t) => t.speaker !== hostIx && t.end - t.start >= SHORT_TURN_S);
+
+ // The windows, and each one's subject (or none).
+ const starts = [];
+ for (let a = 0; a + SEGMENT_WINDOW_S < end; a += SEGMENT_HOP_S) starts.push(a);
+ const lastStart = Math.max(0, end - SEGMENT_WINDOW_S);
+ if (!starts.length || starts[starts.length - 1] < lastStart) starts.push(lastStart);
+ const labels = starts.map((a) => {
+ const b = Math.min(end, a + SEGMENT_WINDOW_S);
+ /** @type {Map<number, number>} */
+ const by = new Map();
+ let total = 0;
+ for (const t of long) {
+ if (t.start >= b) break;
+ const o = overlap(t.start, t.end, a, b);
+ if (o <= 0) continue;
+ by.set(t.speaker, (by.get(t.speaker) ?? 0) + o);
+ total += o;
+ }
+ let best = null;
+ for (const [s, sec] of by) if (!best || sec > best.sec || (sec === best.sec && s < best.s)) best = { s, sec };
+ if (!best || best.sec < SEGMENT_MIN_SUBJECT_S || best.sec / total < SEGMENT_DOMINANCE) return { a, b, subject: null };
+ return { a, b, subject: best.s };
+ });
+
+ // Runs of one subject, edged on that subject's long turns inside them.
+ /** @type {{ from: number, to: number, subject: number }[]} */
+ let spans = [];
+ for (let i = 0; i < labels.length; ) {
+ const s = labels[i].subject;
+ let j = i;
+ while (j + 1 < labels.length && labels[j + 1].subject === s) j += 1;
+ if (s !== null) {
+ const a = labels[i].a;
+ const b = labels[j].b;
+ const own = long.filter((t) => t.speaker === s && t.end > a && t.start < b);
+ if (own.length) spans.push({ from: own[0].start, to: Math.max(...own.map((t) => t.end)), subject: s });
+ }
+ i = j + 1;
+ }
+ const join = (list) => {
+ const out = [];
+ for (const sp of list) {
+ const last = out[out.length - 1];
+ if (last && last.subject === sp.subject) last.to = Math.max(last.to, sp.to);
+ else out.push({ ...sp });
+ }
+ // Interleaved edges (a window can see two videos' lines): the later one starts after the earlier one ends.
+ for (let k = 1; k < out.length; k += 1) out[k].from = Math.max(out[k].from, out[k - 1].to);
+ return out.filter((sp) => sp.to > sp.from);
+ };
+ spans = join(spans);
+ spans = join(spans.filter((sp) => sp.to - sp.from >= SEGMENT_MIN_S));
+
+ return spans.map((sp, k) => {
+ const next = spans[k + 1];
+ const limit = Math.min(next ? next.from : end, sp.to + SEGMENT_TAIL_S);
+ // The tail ends on the last turn that ends inside it (a turn is never cut).
+ let to = sp.to;
+ for (const t of ts) {
+ if (t.start >= limit) break;
+ if (t.end <= limit && t.end > to) to = t.end;
+ }
+ let subjectLong = 0;
+ let allLong = 0;
+ for (const t of long) {
+ const o = overlap(t.start, t.end, sp.from, sp.to);
+ allLong += o;
+ if (t.speaker === sp.subject) subjectLong += o;
+ }
+ const pct = Math.floor((100 * subjectLong) / (allLong || 1));
+ const tail = round(to - sp.to, 0);
+ const why =
+ `subject ${sp.subject} holds ${pct}% of long-turn time` +
+ (tail >= 1 ? `; ${tail} s after its last line kept (the host's reaction)` : "");
+ return { id: `s${k + 1}`, from: round(sp.from), to: round(to), subject: sp.subject, host: hostIx, why };
+ });
+}
+
+/**
+ * The segment a run is scoped to: the one named, else the longest (the
+ * earliest of equals). Null when there are none; an unknown id throws.
+ * @template {{ id: string, from: number, to: number }} S
+ * @param {S[]} segments
+ * @param {string | null} [id]
+ * @returns {S | null}
+ */
+export function pickSegment(segments, id = null) {
+ const list = Array.isArray(segments) ? segments : [];
+ if (id !== null && id !== undefined && id !== "") {
+ const hit = list.find((s) => s.id === id);
+ if (!hit) throw new Error(`no segment ${id}${list.length ? ` (there are ${list.map((s) => s.id).join(", ")})` : " (no segments were found)"}`);
+ return hit;
+ }
+ let best = null;
+ for (const s of list) if (!best || s.to - s.from > best.to - best.from) best = s;
+ return best;
+}
+
+/**
+ * Whether a project's scope (`[from, to|null]`, or null for the whole
+ * recording) covers a segment: they share at least half of the shorter one.
+ * @param {[number, number | null] | null | undefined} scope
+ * @param {{ from: number, to: number }} segment
+ * @param {number} duration the recording's (a scope open at the end runs to it)
+ */
+export function scopeOverlapsSegment(scope, segment, duration) {
+ const a = Array.isArray(scope) ? Number(scope[0]) || 0 : 0;
+ const b = Array.isArray(scope) && scope[1] !== null && scope[1] !== undefined ? Number(scope[1]) : Math.max(Number(duration) || 0, segment.to);
+ const o = overlap(a, b, segment.from, segment.to);
+ return o > 0 && o >= 0.5 * Math.min(b - a, segment.to - segment.from);
+}
diff --git a/common/lib/clips/segments.test.ts b/common/lib/clips/segments.test.ts
@@ -0,0 +1,77 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { SEGMENT_MIN_S, SEGMENT_TAIL_S, findSegments, pickSegment, scopeOverlapsSegment } from "./segments.mjs";
+import { HOST, SUBJECT, TWO_HOST, TWO_SUBJECT_A, TWO_SUBJECT_B, TWO_VIDEOS, reactionStream, twoVideoStream } from "../../testing/clips/reactionStream.mjs";
+
+test("findSegments: two narrated videos in one stream; the host's intro is not one, his reaction after a video is folded into it", () => {
+ const s = twoVideoStream();
+ const segs = findSegments({ turns: s.turns, duration: s.duration });
+ assert.equal(segs.length, 2);
+ const [a, b] = segs;
+ assert.deepEqual([a.id, a.subject, a.host], ["s1", TWO_SUBJECT_A, TWO_HOST]);
+ assert.deepEqual([b.id, b.subject, b.host], ["s2", TWO_SUBJECT_B, TWO_HOST]);
+ // Each starts on its video's first line (the intro and the time between are not a video's)β¦
+ assert.equal(a.from, TWO_VIDEOS[0][0]);
+ assert.equal(b.from, TWO_VIDEOS[1][0]);
+ // β¦and ends on a turn's end inside SEGMENT_TAIL_S after its last line: the host's
+ // turn 1350β1420 runs past 1100 + 300, so the tail stops at the turn before it.
+ assert.equal(a.to, 1347);
+ assert.ok(a.to - TWO_VIDEOS[0][1] <= SEGMENT_TAIL_S);
+ // The second: its outro to the stream's last turn; the host's 100 s pause inside it does not split it.
+ assert.equal(b.to, 2390);
+ assert.match(a.why, /^subject 1 holds \d+% of long-turn time; 247 s after its last line kept/);
+ // Deterministic.
+ assert.deepEqual(findSegments({ turns: s.turns, duration: s.duration }), segs);
+ // The operator's host gives the same answer; a cluster named host is left out of the counting.
+ assert.deepEqual(findSegments({ turns: s.turns, duration: s.duration, host: TWO_HOST }), segs);
+ assert.deepEqual(findSegments({ turns: s.turns, duration: s.duration, operator: { [TWO_HOST]: "host" } }), segs);
+});
+
+test("findSegments: one narrated video is one segment; a tail never runs into the next video; a short span is dropped", () => {
+ const one = reactionStream();
+ const segs = findSegments({ turns: one.turns, duration: one.duration });
+ assert.equal(segs.length, 1);
+ assert.deepEqual([segs[0].from, segs[0].to, segs[0].subject, segs[0].host], [0, 600, SUBJECT, HOST]);
+
+ // Two videos with only 60 s of host between them: the tail stops at the next video's first line.
+ const turns = [];
+ for (let t = 0; t < 600; t += 60) turns.push({ start: t, end: t + 55, speaker: 1 }, { start: t + 55, end: t + 59, speaker: 0 });
+ for (let t = 610; t < 660; t += 6) turns.push({ start: t, end: t + 5, speaker: 0 });
+ for (let t = 660; t < 1260; t += 60) turns.push({ start: t, end: t + 55, speaker: 2 }, { start: t + 55, end: t + 59, speaker: 0 });
+ const two = findSegments({ turns, duration: 1260 });
+ assert.equal(two.length, 2);
+ assert.ok(two[0].to <= two[1].from, `${two[0].to} β€ ${two[1].from}`);
+ assert.equal(two[1].from, 660);
+
+ // A 2-minute clip of another narrator inside the host's talk: under SEGMENT_MIN_S, dropped.
+ const short = [];
+ for (let t = 0; t < 900; t += 6) short.push({ start: t, end: t + 5, speaker: 0 });
+ short.push({ start: 300, end: 360, speaker: 3 }, { start: 361, end: 420, speaker: 3 });
+ assert.ok(120 < SEGMENT_MIN_S);
+ assert.deepEqual(findSegments({ turns: short.sort((x, y) => x.start - y.start), duration: 900 }), []);
+ assert.deepEqual(findSegments({ turns: [], duration: 100 }), []);
+});
+
+test("pickSegment: the one named, else the longest; an unknown id is refused; none is null", () => {
+ const segs = [
+ { id: "s1", from: 0, to: 100 },
+ { id: "s2", from: 200, to: 500 },
+ { id: "s3", from: 600, to: 900 },
+ ];
+ assert.equal(pickSegment(segs)?.id, "s2");
+ assert.equal(pickSegment(segs, "s3")?.id, "s3");
+ assert.throws(() => pickSegment(segs, "s9"), /no segment s9 \(there are s1, s2, s3\)/);
+ assert.equal(pickSegment([]), null);
+});
+
+test("scopeOverlapsSegment: half of the shorter shared; an open scope runs to the end; the whole recording covers every segment", () => {
+ const seg = { from: 1000, to: 2000 };
+ assert.equal(scopeOverlapsSegment([0, 1900], seg, 3000), true);
+ assert.equal(scopeOverlapsSegment([0, 1200], seg, 3000), false);
+ assert.equal(scopeOverlapsSegment([1500, null], seg, 3000), true);
+ assert.equal(scopeOverlapsSegment(null, seg, 3000), true);
+ assert.equal(scopeOverlapsSegment([2100, 2900], seg, 3000), false);
+ // The live case's shape: a hand scope 0β6300 and the auto-scope's first segment.
+ assert.equal(scopeOverlapsSegment([0, 6300], { from: 292.68, to: 6318.09 }, 9367), true);
+ assert.equal(scopeOverlapsSegment([0, 6300], { from: 6501.93, to: 9276.01 }, 9367), false);
+});
diff --git a/common/package.json b/common/package.json
@@ -33,9 +33,11 @@
"./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",
+ "./lib/clips/segments.mjs": "./lib/clips/segments.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -30,6 +30,7 @@ transcript, channel or person goes in these fixtures, ever.
| `audio/syntheticVoice.mjs` | Release 34 N2: synthetic "voices" for the speaker-similarity tests β `syntheticVoice({f0, formants, seconds, phase})` (additive harmonics shaped by formant resonances, a syllable envelope and a vibrato; `phase` makes another take of the same voice), `withSilence`, and `VOICE_A` / `VOICE_B`, two voices TitaNet-small tells apart (cosine ~0.98 within a voice, ~0.63 across, measured). |
| `audio/fakeSpeakerEmbed.mjs` | Release 34 N2: a stand-in for `scripts/speaker-embed.py` with its command line and JSON (`node fakeSpeakerEmbed.mjs --emb <x> <request.json>`): the "embedding" is the long-term spectrum (32 log-spaced Goertzel bands, dB, mean-removed, L2-normalised) β deterministic, and it separates `VOICE_A` from `VOICE_B`. Not a speaker model: set `VOICE_MATCH_PYTHON` to `node` and `VOICE_MATCH_SCRIPT` to it for a run with no python or model. |
| `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). |
+| `clips/reactionStream.mjs` | Release 35: a synthetic reaction stream (`reactionStream()`: a host interjecting over a narrated video β turns, words, cues, laugh windows; `reactionAudio()` its sound; `writeReactionCorpus(dir, o)` a channel on disk). Release 36: `twoVideoStream()` (an intro, video A by speaker 1, the host between, video B by speaker 2 with a pause and a stray cluster, an outro β what auto-scope reads), `reactionChat(o)` (a chat replay: a steady trickle and a burst of laugh tokens `lag` s after each laugh, `chatOnly` bursts), and `writeReactionCorpus`'s `two`, `chat` (live_chat.cues.json) and `meta` (keys into metadata.info.json) options. The "narration" is numbered filler words. |
| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted β `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. |
| `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. |
diff --git a/common/testing/clips/reactionStream.d.mts b/common/testing/clips/reactionStream.d.mts
@@ -14,5 +14,21 @@ export function reactionStream(o?: { hop?: number; window?: number; laughWords?:
export function reactionAudio(o?: { seconds?: number; rate?: number }): Float32Array;
export function writeReactionCorpus(
channelsDir: string,
- o?: { channel?: string; video?: string; diarization?: boolean; audio?: Buffer | null },
+ o?: { channel?: string; video?: string; diarization?: boolean; audio?: Buffer | null; two?: boolean; chat?: boolean | Parameters<typeof reactionChat>[0] | null; meta?: Record<string, unknown> | null },
): string;
+export const TWO_SECONDS: number;
+export const TWO_HOST: number;
+export const TWO_SUBJECT_A: number;
+export const TWO_SUBJECT_B: number;
+export const TWO_VIDEOS: readonly [number, number][];
+export const TWO_LAUGHS: readonly [number, number, number][];
+export function twoVideoStream(): ReturnType<typeof reactionStream>;
+export function reactionChat(o?: {
+ laughs?: readonly (readonly number[])[];
+ duration?: number;
+ lag?: number;
+ every?: number;
+ burstPerS?: number;
+ burstS?: number;
+ chatOnly?: readonly number[];
+}): { start: number; end: number; text: string }[];
diff --git a/common/testing/clips/reactionStream.mjs b/common/testing/clips/reactionStream.mjs
@@ -125,12 +125,15 @@ export function reactionAudio({ seconds = STREAM_SECONDS, rate = 16000 } = {}) {
/**
* 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]
+ * @param {{ channel?: string, video?: string, diarization?: boolean, audio?: Buffer | null, two?: boolean, chat?: boolean | Record<string, unknown> | null, meta?: Record<string, unknown> | null }} [o]
* `audio`: WAV bytes to write as audio.wav (encodeWav16(reactionAudio()));
- * `diarization` false leaves diarization.json out.
+ * `diarization` false leaves diarization.json out; `two`: the two-video
+ * stream (twoVideoStream) instead; `chat`: live_chat.cues.json beside it
+ * (reactionChat's options, `true` for its defaults); `meta`: keys merged
+ * into metadata.info.json (`webpage_url`, `channel`β¦).
*/
-export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", video = "react001", diarization = true, audio = null } = {}) {
- const s = reactionStream();
+export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", video = "react001", diarization = true, audio = null, two = false, chat = null, meta = null } = {}) {
+ const s = two ? twoVideoStream() : 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" }));
@@ -138,7 +141,14 @@ export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", vid
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 }));
+ writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: video, title: "Synthetic reaction stream", duration: s.duration, ...(meta ?? {}) }));
+ if (chat) {
+ const cues = reactionChat({ laughs: two ? TWO_LAUGHS : LAUGHS, duration: s.duration, ...(chat === true ? {} : chat) });
+ writeFileSync(
+ path.join(dir, "live_chat.cues.json"),
+ JSON.stringify({ version: 1, source: "live_chat", id: video, title: "Synthetic reaction stream", duration: s.duration, cues }),
+ );
+ }
if (diarization) {
const speakers = new Set(s.turns.map((t) => t.speaker)).size;
writeFileSync(
@@ -149,3 +159,134 @@ export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", vid
if (audio) writeFileSync(path.join(dir, "audio.wav"), audio);
return dir;
}
+
+// ---- release 36: two narrated videos in one stream, and its chat ----------------
+//
+// twoVideoStream() a host (0) introduces, reacts to video A (narrated by 1),
+// talks a while, reacts to video B (narrated by 2, with a
+// stray cluster 3 and a pause where the host talks over a
+// stopped video), then signs off β what auto-scope reads
+// reactionChat(o) a synthetic chat replay (live_chat.cues.json's cues):
+// a steady trickle of messages, and a burst of laugh
+// tokens `lag` seconds after each laugh (chat watches the
+// stream late), plus `chatOnly` bursts at times with no
+// laugh at all
+
+export const TWO_SECONDS = 2400;
+export const TWO_HOST = 0;
+export const TWO_SUBJECT_A = 1;
+export const TWO_SUBJECT_B = 2;
+/** Where each video's narration runs (its first line to its last). */
+export const TWO_VIDEOS = Object.freeze([
+ [120, 1100],
+ [1500, 2290],
+]);
+/** The host's laughs in the two-video stream: [start, end, strength], each in a gap of the narration. */
+export const TWO_LAUGHS = Object.freeze([
+ [355, 357.5, 0.8],
+ [775, 777, 0.7],
+ [1615, 1617.5, 0.8],
+ [2135, 2137, 0.7],
+]);
+
+/** Runs of `run` seconds with `gap` between them over [a, b]. */
+function runsOver(a, b, run, gap) {
+ const out = [];
+ for (let t = a; t < b; t += run + gap) out.push([t, Math.min(b, t + run)]);
+ return out;
+}
+
+export function twoVideoStream() {
+ const turns = [];
+ const subjectRuns = [];
+ const hostTurns = [];
+ // The intro: the host alone, in long turns too (he is not a video).
+ hostTurns.push([2, 30], [31, 62], [64, 118]);
+ // Video A: narration in 55 s runs, the host in the 5 s gaps.
+ for (const r of runsOver(120, 1100, 55, 5)) subjectRuns.push([...r, TWO_SUBJECT_A]);
+ // Between the videos: the host talks for 400 s (some long turns).
+ hostTurns.push([1103, 1130], [1132, 1135], [1137, 1180], [1182, 1186], [1190, 1260], [1262, 1266], [1270, 1340], [1342, 1347], [1350, 1420], [1425, 1497]);
+ // Video B: narration in 50 s runs; a stray cluster; the host pauses it at 1800 for 100 s.
+ for (const r of runsOver(1500, 1800, 50, 5)) subjectRuns.push([...r, TWO_SUBJECT_B]);
+ hostTurns.push([1801, 1830], [1832, 1836], [1838, 1870], [1872, 1898]);
+ for (const r of runsOver(1900, 2290, 50, 5)) subjectRuns.push([...r, TWO_SUBJECT_B]);
+ turns.push({ start: 1960.5, end: 1962, speaker: 3 });
+ // The outro.
+ hostTurns.push([2292, 2330], [2333, 2337], [2340, 2390]);
+ for (const [a, b, s] of subjectRuns) turns.push({ start: a, end: b, speaker: s });
+ // The host's interjections in the narration's gaps.
+ const gaps = [];
+ for (let i = 0; i + 1 < subjectRuns.length; i += 1) {
+ const [, b] = subjectRuns[i];
+ const [a2] = subjectRuns[i + 1];
+ if (a2 - b > 0.5 && a2 - b < 10) gaps.push([b, a2]);
+ }
+ for (const [a, b] of gaps) hostTurns.push([a, b]);
+ for (const [a, b] of hostTurns) turns.push({ start: a, end: b, speaker: TWO_HOST });
+ turns.sort((x, y) => x.start - y.start || x.speaker - y.speaker);
+
+ const words = [];
+ let k = 0;
+ for (const [a, b] of subjectRuns) {
+ 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 hostTurns) {
+ const laugh = TWO_LAUGHS.find(([s]) => s >= a - 0.01 && s < b);
+ let t = a + 0.1;
+ if (laugh) {
+ 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);
+ 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 hop = 0.5;
+ const window = 1;
+ const n = Math.floor((TWO_SECONDS - window) / hop) + 1;
+ const scores = Array.from({ length: n }, (_, i) => {
+ const a = i * hop;
+ const b = a + window;
+ const l = TWO_LAUGHS.find(([s, e]) => Math.min(b, e) - Math.max(a, s) >= window / 2);
+ return l ? l[2] : 0.02;
+ });
+ return { duration: TWO_SECONDS, turns, words, cues, laughScan: { t0: 0, hop, window, scores } };
+}
+
+const CHAT_LAUGHS = ["LUL", "lmao", "π", "hahaha", "KEKW", "W", "lol", "π€£", "LMFAO", "OMEGALUL"];
+const CHAT_FILLER = ["hello", "what is this", "first time here", "nice", "true", "ok", "is this live", "chat is slow"];
+
+/**
+ * A synthetic chat replay: cues `{start, end, text: "<viewer>: <message>"}`,
+ * as live_chat.cues.json carries them (normalizeLiveChat: end = start + 5).
+ * @param {{ laughs?: readonly (readonly number[])[], duration?: number, lag?: number, every?: number, burstPerS?: number, burstS?: number, chatOnly?: readonly number[] }} [o]
+ */
+export function reactionChat({ laughs = LAUGHS, duration = STREAM_SECONDS, lag = 6, every = 2, burstPerS = 5, burstS = 4, chatOnly = [] } = {}) {
+ const cues = [];
+ let n = 0;
+ for (let t = 0.7; t < duration; t += every) {
+ n += 1;
+ cues.push({ start: round3(t), end: round3(t + 5), text: `viewer${n % 37}: ${CHAT_FILLER[n % CHAT_FILLER.length]}` });
+ }
+ const bursts = [...laughs.map((l) => l[0] + lag), ...chatOnly];
+ for (const at of bursts) {
+ for (let i = 0; i < burstPerS * burstS; i += 1) {
+ const t = at + i / burstPerS;
+ if (t >= duration) break;
+ n += 1;
+ cues.push({ start: round3(t), end: round3(t + 5), text: `viewer${n % 37}: ${CHAT_LAUGHS[n % CHAT_LAUGHS.length]}` });
+ }
+ }
+ return cues.sort((a, b) => a.start - b.start);
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -4,6 +4,8 @@
- **Find clips: the clip finder from one button on the video page.** A video page's **Find clips** runs the whole chain umtool's clip finder needs, as one job: it saves the source video, transcribes the recording, makes its word timings (kept beside the transcript as `words.json`, so a second project from the same recording reuses them), fetches the stream's chat replay (YouTube), finds who speaks when, and then asks umtool to find the narrated-video segments and propose the clips. Each step whose output is already on disk is skipped, and the job's log says which ran and which were skipped. When it is done the panel links the umtool project and lists the segments it found, each with **Find clips in this part**. A target length can be given. When the workers are paused or the backfill lane is held, the step that needs them stops with a sentence saying so, and **Run while paused** runs this one video past them. The button is off, with a line saying why, when the editor has no `UMTOOL_URL`. The same from a terminal: `pnpm ops find-clips --json '{"slug","id"}'` (a `dryRun` lists what each step would do). Needs a restart of the editor.
- **Transcribe one video while the workers are paused.** With the transcription workers paused, the video page's Transcribe row offers **Transcribe now (workers paused)**: that one transcription runs on a worker the pause alone switched off, and the pause stays on β the worker is paused again when it finishes. A worker you drained, disabled by hand or that is marked degraded is never used, and the lanes stay held. `pnpm ops transcribe` and `transcribe-one` take `"whilePaused": true`.
- **Fetch a stream's chat replay on its own.** Media tools β **Fetch live chat** on a video page (`pnpm ops fetch-chat`) fetches the video's live chat and nothing else, paced like every YouTube request and on the platform's download queue, into the chat cues the index and the clip finder read. A video on another platform says there is no chat fetcher for it, as does a chat already fetched or a video that was never live.
+- **The clip finder finds each narrated video in a reaction stream, and listens to the chat.** A stream that reacts to one video and then another no longer needs its scope read off the speakers by hand: `umtool new <slug> --seed reactions --from <channel>/<id> --scope auto` reads the narrated video the speaker turns show (`--segment s2` names one, else the longest), with the host's reaction after the video kept and the roles found for that video alone; `umtool clips segments <project>` lists them. When the stream's chat replay is on disk, the moments the chat laughs together (lol, KEKW, π, a wall of W) become proposals too, moved back by how late the chat types β found by lining the chat up against the laughs heard in the sound, else 6 seconds β and always ranked below the host's own laugh; the analysis says the delay it found. Without a chat replay nothing changes. Needs a restart of umtool.
+- **Highlights of a channel that is on no site link the source and start with a clean look.** Each proposed clip links its platform page at its second (YouTube, Twitch, Rumbleβ¦), the channel's name is filled in from the video, and the cut starts with no header, no QR code, half-second fades through black and a β16 LUFS loudness target β no edits to the manifest needed. umtool's clips job also answers the editor directly (its `WORKER_TOKEN`), so the editor's Find clips makes or re-analyzes the project in one call; asking again for a video already cut analyzes that project again and leaves its cut exactly as it is, listing the new proposals (the chat's among them) for you to bring in.
- **A report video's cut can dip through black between clips.** `render.transitionStyle: "fadeblack"` (or `fadewhite`, `dissolve`; default `fade`) changes how the crossfade looks, not its length β for highlights where every clip shares one layout and a plain dissolve hides the jump.
- **Hop in on an assistant's clips in umtool: trim, split, merge, keep or cut them, and comment.** A report video whose cut is not a montage has a **Clip editor** on its Cut tab (`/projects/<id>/clips`). It loops the selected clip from what is on disk, and under it shows the clip's neighbourhood (Β± 60 s, or closer): the speaker turns coloured host and subject, the laughs, the words, the other clips, and the cut with a handle at each edge. Move the edges by dragging, typing, nudging (Β±0.1, Β±0.5, Β±2 s) or **Snap to words**; **Keep** / **Cut**; **Split here** at the playhead; **Merge with next**; **Add a clip** from a span dragged on the strip; **Restore the assistant's version**; **Bring in** a proposal the assistant left out. Each clip says whether it is "by the assistant" (with its score and why) or "edited by you", with its edit history. A comment on a clip is a note anchored to it, so an agent reading `umtool notes` can act on it and its reply shows in the clip's thread. **This is the host** on a speaker's turn corrects which voice is the host. Keys: space, J/L, I/O, S, M, K, X, β/β. A keep or cut follows its clip when an edit moves the clip's start. It works on any report video; a cut without the clip finder's speakers simply has no colours.
- **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first β how many per platform, how many already on disk β then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** β the same moment in the stream's YouTube upload (or Odysee) β and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10785,6 +10785,62 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
reader (`{doc, error}`). Re-propose = `POST /api/report/clips {project, mode: "propose"}` (a job), offered while
`rolesChangedAt > proposedAt` (the view carries both).
+## Release 36 lane B: auto-scope, the chat signal, site-less links, the clips route's `mode: "new"` (verified 2026-10-19, branch `r36/clip-analysis-2`)
+
+- **`reactions.json` gains** (all optional; absent in a release 35 file) `segments: [{id "s1"β¦, from, to, subject,
+ host, why}]` (every pass, from the whole recording's turns), `segment: "s1" | null` (the segment whose edges the
+ scope is, within 0.01 s; null for a scope by hand), `chat: {source "live_chat.cues.json", lagS, lag {how
+ "xcorr"|"default", r|null, why}, messages, bursts, bins {hop 2, rate[], laugh[]}} | null`; a moment's `kind` may be
+ `"chat"` (with `messages`). Types: `ReactionsDoc` in `common/lib/clips/reactions.d.mts`.
+- **Auto-scope** (`common/lib/clips/segments.mjs` `findSegments({turns, duration, host?, operator?})`): host =
+ the given/operator's, else assignRoles' over the whole recording, and left out of the counting; windows 300 s every
+ 30 s; a window's subject = the non-host cluster with the most seconds in turns β₯ SHORT_TURN_S (8), counted when β₯ 60 s
+ and β₯ 60 % of the window's non-host long-turn time; runs of one subject edged on that subject's first/last long turn
+ in the run; same-subject neighbours joined, spans < 180 s dropped (then joined again); the tail = the last turn end
+ β€ min(next span's from, to + 300 s); nothing before a span's first long turn is folded. `pickSegment(segs, id?)`
+ (the named, else the longest; unknown id throws), `scopeOverlapsSegment(scope, seg, duration)` (overlap β₯ half the
+ shorter; null scope = the whole). Live (`harmful-opinions/fGSRhEWc9M4`, audioSeconds 9367.858): s1 292.68β6318.09
+ (subject 4, host 1), s2 6501.93β9276.01 (subject 16).
+- **`--scope auto`** (CLI `umtool new --seed reactions` and `clips analyze|propose`; `--segment sN` implies it;
+ scaffold `scope: "auto"`, `segment`; job `clipsSteps({scope: "auto", segment})`): resolved against the recording
+ (`resolveParams` in `umtool/lib/report/reactions.mjs`) to the segment's numbers, written as `params.scope`; no
+ segment found β the whole recording, said in a note. `umtool clips segments <project> [--json]` re-finds them from
+ the diarization on disk.
+- **The chat** (`common/lib/clips/chat.mjs`; lib reads `live_chat.cues.json` itself β lib may not import controller):
+ the file must be `{version: number, source: "live_chat", cues: [{start, text: "<author>: <message>"}]}`; bins of 2 s
+ over [0, recording duration); a laugh = the message (after the first ": ") is W's alone, holds π/π€£, or a token
+ matching lol/lmao/lmfao/KEKW/LUL/OMEGALUL/rofl/hahaβ¦/:face-with-tears-of-joy: (`CHAT_LAUGH_RE`); lag = argmax Pearson
+ r of chat-laugh[k] vs CED-bin[k β s] (each 2 s bin the max window score centred in it) over s = 0..10 bins inside the
+ scope, parabola-refined, 0.1 s; no scan / no variance / r < 0.2 β 6 s; burst bin = laughs β₯ 3 and β₯ 2.5 Γ max(1,
+ median of Β±30 bins); runs (one quiet bin bridged) β moment t = start β lag, end = end β lag, wholly inside the scope,
+ score 0.6 Γ (1 β e^(βΞ£(laugh/base β 1)/6)), speaker by attributeLaughs; spans as a laugh's. With no chat (absent,
+ null, or no cues) `analyze` is release 35's output exactly (digests pinned in `chat.test.ts`).
+- **Site-less links** (`siteLessLinks(rec, manifest)` in `umtool/lib/report/reactions.mjs`, each seed and pass): when
+ `provenance.siteOrigin` is empty, metadata `webpage_url` is a URL, and no `<SITES_DIR>/*/site.json` WITH a non-empty
+ `siteUrl` lists the channel in `channels[].slug` or `citedChannels`, `applyProposals(β¦, {citeUrlAt})` writes
+ `citeUrl = watchUrlAt(webpage_url, cite)` (`common/lib/clips/assist.mjs`: youtube/youtu.be `t=<s>s`, twitch
+ `t=<h>h<m>m<s>s`, rumble.com `start=<s>`, else `t=<s>`; an existing same-name param replaced) on every clip it adds or
+ moves; a kept clip with no citeUrl gains it; a citeUrl that is not the derived one for its cite is never touched.
+ The seed then sets `render` to `SITELESS_LOOK` (`umtool/lib/projects/scaffold.mjs`: headerHeight 0, footerHeight 0,
+ qr false, transition 0.5, transitionStyle "fadeblack", loudness {target: -16}) instead of `transition: 0`, and
+ `provenance.channel` from metadata `channel` (else `uploader`) whenever it was empty. `report.mjs` `originUnused(m)`:
+ an EMPTY siteOrigin with every clip carrying an http(s) citeUrl and no card or post is no "dead QR origin" flag or
+ blocking decision. Nothing in lint/build refuses an unknown render key (verified: `lintManifest(β¦, {validators:
+ true})` on a seeded site-less manifest gives no render error).
+- **`/api/report/clips`** POST: `routeCaller(authorization, agentToken())` (`umtool/lib/annotations/agentAuth.mjs`) β
+ no header = the page, `Bearer <umtool's WORKER_TOKEN>` = the editor, else 401 `{error}`; every POST answers `jobId`
+ beside `job`. `{mode: "new", slug, from, target?, scope? ("auto" default | "all" | [from, to]), segment?,
+ wordsPath? (absolute)}` β `planClipsNew` (`umtool/lib/report/clipsNew.mjs`): 409 while any umtool job runs; the
+ recording loaded (404 no video dir, 400 no diarization); the span chosen; the reactions projects under REPORTS_ROOT
+ with the same `source.channel/video` whose `params.scope` covers the span (`scopeOverlapsSegment`), best overlap then
+ latest `proposedAt` β that project, untouched but for `words.json` copied in when it has none, analyzed with
+ `--keep-cut` (`created: false`; keepCut = every clip of the recording protected, every proposal not on an existing
+ clip `used: false`, the timeline returned as it was β not even re-sorted);
+ else `scaffoldReportVideo({slug, seed: "reactions", scope, segment, target})` (409 when the slug exists) + the words
+ copied (`created: true`); then ONE job `clips analyze <id>` β `{ok, jobId, job, project, created, segments,
+ segment (the chosen one's id), scope (the project's params.scope), href "/projects/<id>/clips", notes}`. GET
+ `?project=` adds `segments`, `segment`, `chat {source, lagS, lag, messages, bursts}`.
+
## Release 36 lane A: Find clips, run while paused, one video's chat (verified 2026-10-19, branch `r36/find-clips`)
- **Run while paused**: `WorkerPool.acquire(signal, {whilePaused: true})` may lease a worker that is `disabled`
diff --git a/plans/release-36/clip-analysis-2.md b/plans/release-36/clip-analysis-2.md
@@ -0,0 +1,114 @@
+# Release 36 lane B β `r36/clip-analysis-2`: auto-scope, the chat, site-less links (as shipped)
+
+The plan of record is [clip-finder-2.md](clip-finder-2.md); this lane is its analysis half, extending release 35
+C1's clip finder ([../release-35/clip-analysis.md](../release-35/clip-analysis.md)): where in a reaction stream each
+narrated video is, the stream's chat as a second ear, links and a look for a channel on no site, and the umtool
+route the editor's Find clips (lane A) calls. Lane D (the optional AI pass) builds on this branch.
+
+## What
+
+- **Auto-scope** β `common/lib/clips/segments.mjs` (pure, `.d.mts`): `findSegments({turns, duration, host?,
+ operator?})` β `[{id: "s1", from, to, subject, host, why}]`. The host (the operator's, else assignRoles' over the
+ whole recording) is left out of the counting; 300 s windows every 30 s; a window's subject is the non-host cluster
+ with the most seconds in turns β₯ 8 s, counted at β₯ 60 s and β₯ 60 % of that time; a run of one subject is a span
+ from its first long turn to its last; same-subject neighbours join, spans < 180 s drop; the host's talk after a
+ video's last line folds in (β€ 300 s, never past the next video's first line, ending on a turn's end); nothing
+ before a video's first line is folded. `pickSegment` (named, else the longest), `scopeOverlapsSegment`.
+ reactions.json gains `segments` and `segment` on every pass; roles stay per segment (the existing role code over
+ the scope's turns; the operator's roles win). `--scope auto` / `--segment sN` on `umtool new --seed reactions` and
+ `clips analyze|propose` (resolved to numbers, kept in `params.scope`), `umtool clips segments <project>`, the job's
+ `scope: "auto"`, and the Create form's **Video** picker (`[data-new-video]`: the longest, or the 1st/2nd/3rd found).
+- **The chat signal** β `common/lib/clips/chat.mjs`: `readChatCues` (reads `live_chat.cues.json` itself β lib may not
+ import controller, and the module is plain ESM), `isChatLaugh` (lol, lmao, lmfao, KEKW, LUL, OMEGALUL, rofl,
+ hahaβ¦, π, π€£, the `:face-with-tears-of-joy:` emote, a lone W), `chatBins` (2 s: messages, laughing messages),
+ `chatLag` (Pearson r over shifts 0β20 s against the CED score binned to 2 s, parabola-refined; no scan, no variance
+ or r < 0.2 β 6 s), `chatMoments` (β₯ 3 laughs and β₯ 2.5 Γ the Β±60 s median, at least 1; runs β a moment at start β
+ lag, scored β€ 0.6). `analyze` takes `chat` and adds `kind: "chat"` moments (a laugh's span rules; why "chat laughs
+ (N messages) β¦"); reactions.json `chat: {source, lagS, lag {how, r, why}, messages, bursts, bins {hop, rate[],
+ laugh[]}} | null`; `clips analyze` logs `chat: β¦ lag X s β β¦`. No chat file: release 35's analysis byte for byte.
+- **Site-less links** β `watchUrlAt(url, s)` (`common/lib/clips/assist.mjs`: YouTube `t=<s>s`, Twitch
+ `t=<h>h<m>m<s>s`, Rumble `start=<s>`, else `t=<s>`) and `applyProposals(β¦, {citeUrlAt})`: with no siteOrigin and the
+ channel on no PUBLIC site (a site.json with a `siteUrl` listing it), every clip the seed or a pass adds or moves
+ carries `citeUrl` at its cite; a derived link follows its clip, one somebody wrote stays (`siteLessLinks`,
+ `channelOnPublicSite` in `umtool/lib/report/reactions.mjs`). The seed fills `provenance.channel` from the metadata.
+- **The site-less look** β the seed writes `SITELESS_LOOK` (`umtool/lib/projects/scaffold.mjs`): `headerHeight 0,
+ footerHeight 0, qr false, transition 0.5, transitionStyle "fadeblack", loudness {target: -16}` (else hard cuts, as
+ before). Lint and the build refuse no unknown render key (checked: `lintManifest(β¦, {validators: true})` on a
+ seeded manifest), so `loudness` waits harmlessly for lane C's validator and renderer. An empty siteOrigin with every
+ clip linked (no card, no post) is no longer a "dead QR origin" flag or blocking decision (`report.mjs`
+ `originUnused`).
+- **The route** β `umtool/app/api/report/clips/route.ts`: every POST through `routeCaller` (`agentAuth.mjs`: no header
+ = the page, `Bearer <WORKER_TOKEN>` = the editor, else 401), every POST answers `jobId`; `mode: "new"`
+ (`umtool/lib/report/clipsNew.mjs` `planClipsNew`): a reactions project for the same recording whose scope covers the
+ chosen segment is analyzed again as it is, with `--keep-cut` (`created: false`: nothing in the cut moves, goes or
+ is added; the new proposals are listed unused), else `slug` is scaffolded with the reactions seed and
+ `wordsPath` copied in as `words.json` (`created: true`); then one `clips analyze` job β `{jobId, job, project,
+ created, segments, segment, scope, href, notes}`. GET `?project=` adds `segments`, `segment`, `chat`.
+- **Test kit** β `testing/clips/reactionStream.mjs`: `twoVideoStream()`, `reactionChat(o)`, and
+ `writeReactionCorpus`'s `two`, `chat`, `meta` options (synthetic only).
+
+## Interfaces (exported)
+
+`findSegments`, `pickSegment`, `scopeOverlapsSegment`, `SEGMENT_*` (segments.mjs); `readChatCues`, `isChatLaugh`,
+`chatMessage`, `chatBins`, `chatLag`, `chatMoments`, `CHAT_*` (chat.mjs); `watchUrlAt`, `applyProposals`'s and
+`clipFromProposal`'s `citeUrlAt` (assist.mjs); `findMoments`'s `chat`, `analyze`'s `chat` in and out (clips.mjs);
+umtool `recordingSegments`, `segmentOfScope`, `autoScope`, `resolveParams`, `projectSegments`, `channelOnPublicSite`,
+`siteLessLinks`, `chatLine` (reactions.mjs), `planClipsNew`, `parseNewBody`, `projectsCovering`, `ClipsNewError`
+(clipsNew.mjs), `routeCaller` (agentAuth.mjs), `SITELESS_LOOK` (scaffold.mjs), `originUnused` (report.mjs).
+
+## The live case's numbers
+
+`harmful-opinions/fGSRhEWc9M4` (audioSeconds 9367.9, read-only): s1 **292.68β6318.09** (subject 4, host 1; expected
+β 290β6300) and s2 **6501.93β9276.01** (subject 16; expected β 6500β9278) β every edge within 18 s. A dry
+`clips propose` on a copy of the first case's project gives the same moments, laughs, speakers and proposals as
+`main` (the brought-in comment now counts toward the target first, so both drop r021 and add r031 β release 35's
+rule, not this lane's); its 18 kept clips' hand-written citeUrls equal the derived ones, so none is re-pointed.
+With `--keep-cut` (what the editor's Find clips runs on an existing project) the same dry pass is `clips +0 ~0 -0`:
+21 clips in the cut, 657 s, the other 91 proposals listed unused.
+
+## Rulings followed
+
+- The UI works without AI: every step here is arithmetic over turns, words, the sound's scores and the chat; nothing
+ calls a model. Auto-scope has a form control; the chat needs nothing.
+- Release 35's proposal rules stand: an operator's, ruled or locked clip is never moved. A re-analysis from the
+ editor keeps the project's own scope and its whole cut (`--keep-cut`): the plan's "operator edits stand; chat
+ proposals show as unused".
+- No corpus content in fixtures; records state rulings.
+
+## Commits
+
+| sha | what |
+|---|---|
+| `1b636348` | clips: auto-scope β segments, `--scope auto` / `--segment`, `clips segments`; the test kit's two-video stream + chat |
+| `3a9a5c3c` | clips: the chat signal β chat moments, the lag; release 35's output pinned |
+| `76a205b1` | umtool: `/api/report/clips` β the worker token and `mode: "new"` |
+| `643ecaaf` | clips: site-less links and the site-less look; no dead-origin decision when every clip links itself |
+| `5164c59e` | umtool: the Create form's Video picker; docs, FACTS, CHANGELOG |
+| `c233df3d` | clips: `--keep-cut` β the editor's re-analysis of a project already cut leaves the cut as it is |
+| (this) | plans: this record |
+
+## Gates (all through the shared lock, from the worktree root)
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` β clean before every commit (six runs; the last at
+ `c233df3d`'s tree).
+- common `pnpm --filter yt-dlp-transcript-common test` β **4663 tests, 4661 pass, 2 skipped**, 0 fail. Before this
+ lane: 4651 (the first baseline run counted 4655, having picked up `segments.test.ts`'s 4 already on disk). New: 12
+ (`segments.test.ts` 4, `chat.test.ts` 6, `links.test.ts` 2).
+- `pnpm run test:scripts` β **1263 tests, 1259 pass, 4 skipped**, 0 fail. Before: 1255 (the baseline's 1256 held one
+ test of the new file). New: 8 in `umtool/lib/report/reactions-r36.test.mjs`; `reactions.test.mjs` unchanged and
+ green.
+- umtool `pnpm --filter umtool test` β 45 / 45 (unchanged).
+- `pnpm archilyzer docs env --check`, `docs cli --check`, `docs files --check` β clean (no env, CLI row or schema
+ touched).
+- e2e (umtool, `E2E_MODE=dev`, one run): `create.spec.ts` + `clip-editor.spec.ts` β **14 passed, 0 failed, 1.7 min**
+ (three new create tests: the route's `mode: "new"` + 401 + `created: false`; the Video picker; the existing
+ Highlights test unchanged and green). Run with `--keep-cut` in the tree before its commit (the same code).
+- No build: the slice's e2e ran under `next dev`.
+
+## Found and left
+
+- A plain `clips propose` on the first case's project (main's code and this branch alike) drops r021 and adds r031:
+ the operator's brought-in comment counts toward the 600 s target first. `--keep-cut` (the editor's path) does not.
+- `render.loudness` is written but drawn by nobody until lane C's renderer; its validator is lane C's.
+- The clip editor does not show `segments` or the chat's lag yet (GET `?project=` carries them; lanes C/D own that
+ page).
diff --git a/plans/release-37/wayback-pages.md b/plans/release-37/wayback-pages.md
@@ -0,0 +1,143 @@
+# Wayback pages β non-video Wayback Machine captures as first-class records (plan)
+
+Operator, 2026-10-19 (during a research case): "you should plan out a real first class feature for non-video
+wayback captures". Today a Wayback capture enters the corpus only when it is a capture OF A VIDEO (`import-video` with
+a `web.archive.org` URL β yt-dlp's extractor β `wayback.json`). Everything else a case leans on β a Tumblr post from
+2014, a deleted X account, a Google Doc that was taken down after a legal letter, a forum post, a personal site, a
+channel's old About page β can only be cited as a bare `page` citation (`{url, title?, archiveUrl?}`, CITATIONS.md):
+no record, no text in search, no moment page, no screenshot, nothing the MCP can read. `detectPlatform` already says
+page captures are "a different kind of record" (common/lib/platform.ts / detectPlatform.mjs ~45); README.md:190 calls
+them "a source of their own". This plan makes them that source.
+
+## The rules it is built under
+
+- **The UI works without AI.** Scanning, choosing, importing, re-checking and citing are buttons; no model anywhere.
+- **Polite.** Every request to archive.org goes through `ArchiveOrgClient`'s pacing (one stream, 2 s gap, 429/503
+ waited out) on the `platform:archive.org` queue. CDX listings are paged and bounded; a scan never fetches bodies.
+- **Reuse the posts store.** A page capture is a `Post` on a new platform, so shards, `posts-archive` dedupe,
+ `upsertPosts`, the LMDB `posts` sub-DB, search, export, `get_post`, the `/m/<channel>/<id>/` moment page,
+ `capture-posts` screenshots and `copyCitedPostCaptures` all work with no new reader.
+- **Private by rule where the source is.** A capture of x.com/twitter.com follows `social.x.visibility` exactly as X
+ posts do; every other capture is public like any channel, and a private site holds anything.
+- **Provenance is never lost.** Every record carries the original URL, the capture timestamp, the replay URL and the
+ raw (`id_`) URL; citations show "Original (may be gone)" + "Wayback Machine copy, <date>" (`waybackCitationLinks`).
+
+## What a record is
+
+A **page record** = one captured state of one page. Channel platform: `"webpage"` (added to `Platform`,
+`PostPlatform`, `POST_PLATFORM_VALUES`, `isPostPlatform`, `postPlatformLabel` β "Web page", `parsePost`,
+channel-config coercions + `channelConfigSchema.ts`, CHANNEL.md regenerated).
+
+`Post` gains one optional object, the way `forum?` exists today:
+
+```
+page?: {
+ originalUrl, captureTs, waybackUrl, rawUrl, // = WaybackProvenance (common/lib/wayback.ts:129)
+ title?, mimetype?, digest?, status?, // from CDX
+ kind: "generic" | "tumblr-post" | "tumblr-index" | "tweet" | "x-profile" | "forum-post" | "gdoc" | "yt-about" | β¦,
+ publishedAt?, // the content's own date when the extractor can read it
+ versionOf?, // id of the first capture of the same originalUrl
+}
+```
+
+- `id` = `<captureTs>-<short hash of originalUrl>` for a whole page; an extractor that splits one capture into many
+ records (a Tumblr index, an X profile timeline, a forum page) uses the item's own id (`tumblr-<postId>`,
+ `tweet-<statusId>`, `kf-<postId>`) so the same item seen in two captures is ONE record (upsert, latest wins, first
+ capture kept in `page.firstSeenTs`).
+- `createdAt` = `publishedAt` when known, else the capture time (the sort key is "when it was said", not "when the
+ crawler came by"); `uploadDate` derived as today.
+- `author` = the page's author when the extractor knows it (Tumblr blog, X handle, forum member), else the host.
+- `text` = the extracted readable text; `links[]`, `media[]` (images with their own Wayback URLs) from the page.
+- `threadId` = hash(originalUrl) so the versions of one page group as a thread (`groupIntoThreads`), and a tweet's
+ conversation groups the way X records do.
+- On disk beside the shards: `channels/<slug>/pages/<captureTs>-<hash>/raw.html.gz` + `capture.json`
+ (`{originalUrl, captureTs, digest, mimetype, bytes, sha256, fetchedAt, extractor, extractorVersion}`) β the raw body
+ is kept so an improved extractor re-derives records offline (`archilyzer wayback pages reextract <slug>`).
+
+## What a channel is
+
+A **Wayback pages channel** = a named scope of captures: `config.wayback = {targets:[{url, match:"exact"|"prefix"|
+"host"|"domain", from?, to?, mime?:["text/html"], include?, exclude?}], collapse:"digest"}`. Examples: a Tumblr blog (host, a date range), an X profile (prefix), a
+Google Doc (prefix), a Newgrounds user page (host), a group's old site (domain), a YouTube channel's About page
+(exact), one blog post (exact).
+Created from the New channel form ("Wayback pages" β detected for a `web.archive.org` URL that is not a video, or
+chosen; targets edited as rows), or `pnpm ops create-channel` with a `web.archive.org/web/*/<target>*` URL (handling as for
+other social channels). One target per channel is the common case; several are allowed (one person's sites).
+
+## Slices (dependency graph: S1 β S2 β {S3, S4} β S5; S3 and S4 run in parallel)
+
+### S1 β the client, the record, one-page import (`wayback-pages/core`)
+- `WaybackClient.getCapture(ts, url, {raw:true})` (the `id_` form) through the same `ArchiveOrgClient` gap; a 2 MB
+ cap (configurable), text/html + text/plain + application/json only; redirects followed inside web.archive.org only.
+- The record shape above, platform registration, `pages/` storage, the generic extractor (a real main-content
+ extraction over `htmlReader.ts` β strip Wayback's injected toolbar/scripts, nav, footer; keep headings, paragraphs,
+ link text, image alts; title; `<meta>` dates/authors/og: tags), and `upsertPosts`.
+- `import-page {slug, url}` β a Wayback replay URL (or `{url: original, at: "YYYYMMDD[hhmmss]"}` β nearest capture via
+ CDX): an ops action, a job kind on `platform:archive.org` (`needsText`), a CLI, a channel-page "Import a capture"
+ field. Refused when the capture is a video (points at `import-video`).
+- Tests: `fakeWayback.mjs` extended with `id_` HTML bodies (a generic article, a page whose capture is the toolbar
+ wrapper), CDX for them; extractor unit tests; the job end to end on the fake.
+
+### S2 β scan and choose (`wayback-pages/scan`)
+- `wayback-scan {slug, dryRun?}`: CDX over every target (paged with `showResumeKey`, `collapse=digest`, status 200,
+ mime filter, date bounds, a hard row cap per run with resume) β `channels/<slug>/wayback-scan.json`: every distinct
+ (url, digest) with first/last capture, count by year and by path prefix. No bodies.
+- Channel page **Captures** tab: the scan as a table (path, first/last seen, versions, imported?), filters by year and
+ path, select β **Import selected** (one `import-page` job each, queued on archive.org's pace), **Import all in
+ range**. Shows what is already imported and what changed since.
+- The download lane does NOT pick these up automatically (no unattended crawling of a host) unless the channel opts in
+ with `wayback.auto: true` (then the lane imports new scan rows at the archive.org pace).
+- Tests: CDX paging + resume on the fake; dedupe by digest; the table's e2e spec.
+
+### S3 β site extractors (`wayback-pages/extractors`, parallel with S4)
+One module per kind, each a pure function `(html, captureUrl) β records[]`, versioned, unit-tested on fixtures saved
+from synthetic pages (no real captures committed):
+- **Tumblr**: a post page β one `tumblr-post` record (post id, date, tags, reblog-of, body, images); a blog index /
+ archive page β one record per post on it (with the index's capture as provenance).
+- **X / Twitter**: an old-layout profile capture (2012β2022 HTML timeline) β one `tweet` record per tweet on it
+ (status id, date, text, reply/quote refs β the shape X posts already use, so threads join); a status page β
+ one tweet; the new JS layout's captures that hold only the shell β a `generic` record flagged "no content in this
+ capture". Private by `social.x.visibility`.
+- **Forums (XenForo)**: reuse `parseXenforoThreadPage` (common/social/xenforoParse.ts:673) on a captured thread page
+ β `forum-post` records that merge with a live forum channel's ids when the thread is the same.
+- **Google Docs**: `mobilebasic` / `pub` / `preview` captures β the document's text with headings; the edit-page shell
+ β flagged as no content (and the scan suggests the `mobilebasic` URL to look for).
+- **YouTube channel About / channel page**: description, links, join date, counts β one `yt-about` record per capture
+ (how a channel described itself in 2014 vs now).
+- **Generic** stays the fallback for everything else (Newgrounds pages, personal sites, articles).
+
+### S4 β renders, citations, moment page (`wayback-pages/cite`, parallel with S3)
+- `capture-posts` on a webpage channel renders the capture's replay URL (`if_` modifier: no toolbar) in the existing
+ headless Chromium (`playwrightRuntime.ts`, `forumSession.ts`) β `posts-media/<id>/shot.png`, full page and, for a
+ split record, clipped to the item's element (the `shootForumPost` pattern); images saved through their own Wayback
+ URLs.
+- The moment page and every citation surface show the capture: text, shot, "Original (may be gone)", "Wayback
+ Machine copy, <date>", the version list ("4 captures of this page; text changed on β¦").
+- A `page` citation that carries `archiveUrl` gets an **Import this capture** action in the report editor that turns
+ it into a `post` citation of the new record (the old one kept as the fallback), and `reports-prepare` copies the
+ shot like any post capture.
+- MCP: `get_post` returns `page`; `search_transcripts` can filter `platform: "webpage"`; `/corpus.json` lists the
+ channel kind.
+
+### S5 β liveness and saving what is still up (`wayback-pages/live`)
+- `check-post-availability` for webpage records = the ORIGINAL URL's state (HEAD/GET through `webPacer`, never
+ Wayback): `available` / `deleted` (404/410, a platform's "doesn't exist" page) / `error` β "deleted" now means the
+ Wayback copy is the only copy, and reports say so with the existing source-gone labels.
+- **Save Page Now** (optional, behind archive.org S3 keys in settings): "Ask the Wayback Machine to capture this now"
+ on a live page or a whole scan target, paced, the resulting capture imported β for pages likely to be taken down.
+- `find-copy` learns page citations: a cited page whose original is gone β the nearest capture imported.
+
+## Out of scope (named so they are not assumed)
+archive.today / archive.ph (a second archive with no CDX; a later source on the same record shape), WARC import
+(the same `pages/` storage would take it), crawling live sites directly (web-fetch stays read-only), video captures
+(stay `import-video`).
+
+## First case
+A private research site: a person's old blog, their X/Twitter accounts, a since-deleted document and account,
+their Newgrounds and group sites, two channels' About pages, a third party's blog post β the target list lives with
+the case's research notes, not here.
+
+## Gates
+Unit (extractors on synthetic fixtures, client pacing, CDX paging, upsert of split records), common + editor suites,
+an editor e2e for the Captures tab and Import selected, docs (`OPERATING.md` "Import from β¦ the Wayback Machine",
+COMMANDS.md, CHANNEL.md, FACTS "page records", CITATIONS.md), CHANGELOG. No real archive.org in any test.
diff --git a/umtool/app/api/report/clips/route.ts b/umtool/app/api/report/clips/route.ts
@@ -1,5 +1,8 @@
import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
-import { projectRef } from "@/lib/projects";
+import { invalidateProjects, projectRef } from "@/lib/projects";
+import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs";
+import { ClipsNewError, planClipsNew } from "@/lib/report/clipsNew.mjs";
+import { clipEditorHref } from "@/lib/hrefs";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { clipsSteps } from "@/lib/report/reactions.mjs";
@@ -16,8 +19,14 @@ export const dynamic = "force-dynamic";
//
// GET ?job=<id>[&since=&sinceEvent=] that job
// GET ?project=<id> the project's reactions.json summary, and the job running, if any
-// POST { project, mode?: "analyze" | "propose", from?: "<channel>/<id>", target?: seconds, host?: speaker }
+// POST { project, mode?: "analyze" | "propose", from?: "<channel>/<id>", target?: seconds, host?: speaker,
+// scope?: [from, to] | "auto" | "all", segment?: "s1" } β { jobId, job }
+// POST { mode: "new", slug, from: "<channel>/<id>", target?, scope?: "auto" (default) | "all" | [from, to],
+// segment?, wordsPath? } (release 36: the editor's Find clips) β { jobId, job, project, created, segments,
+// segment, scope, href, notes } β a reactions project for the same recording whose scope covers the
+// chosen one is analyzed again (`created: false`), else `slug` is scaffolded (lib/report/clipsNew.mjs)
// ?cancel=<job> stop it
+// A POST with no Authorization header is the app's page; `Bearer <WORKER_TOKEN>` the editor; any other: 401.
export async function GET(request: Request) {
const url = new URL(request.url);
const headers = { "cache-control": "no-store" };
@@ -46,6 +55,9 @@ export async function GET(request: Request) {
usedSeconds: Math.round(used.reduce((n, p) => n + (p.end - p.start), 0)),
proposedAt: doc.proposedAt ?? null,
rolesChangedAt: doc.rolesChangedAt ?? null,
+ segments: Array.isArray(doc.segments) ? doc.segments : null,
+ segment: doc.segment ?? null,
+ chat: doc.chat ? { source: doc.chat.source, lagS: doc.chat.lagS, lag: doc.chat.lag ?? null, messages: doc.chat.messages ?? null, bursts: doc.chat.bursts ?? null } : null,
}
: null,
running: running && running.project === project.id && running.kind.startsWith("clips-") ? jobView(running) : null,
@@ -56,6 +68,8 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const url = new URL(request.url);
+ const who = routeCaller(request.headers.get("authorization"), agentToken(), "/api/report/clips");
+ if (!who.ok) return Response.json({ error: who.error }, { status: who.status });
const cancel = url.searchParams.get("cancel");
if (cancel) {
const { cancelJob } = await import("@/lib/jobs");
@@ -63,6 +77,7 @@ export async function POST(request: Request) {
}
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
+ if (body.mode === "new") return startNew(body);
const project = await projectRef(String(body.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
if (!kindMakesTakes(project.kind)) return Response.json({ error: "clips are found for a report video" }, { status: 400 });
@@ -75,11 +90,49 @@ export async function POST(request: Request) {
...(typeof body.from === "string" ? { from: body.from } : {}),
...(typeof body.target === "number" ? { target: body.target } : {}),
...(typeof body.host === "number" ? { host: body.host } : {}),
+ ...(Array.isArray(body.scope) || body.scope === "auto" || body.scope === "all" ? { scope: body.scope as [number, number | null] | "auto" | "all" } : {}),
+ ...(typeof body.segment === "string" ? { segment: body.segment } : {}),
});
try {
const job = startJob(plan.kind, plan.steps, { project: project.id });
- return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } });
+ return Response.json({ ok: true, jobId: job.id, job: jobView(job) }, { headers: { "cache-control": "no-store" } });
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 });
}
}
+
+/** `mode: "new"`: the project found or scaffolded, then `clips analyze` as one job. */
+async function startNew(body: Record<string, unknown>) {
+ const running = runningJob();
+ if (running) {
+ return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
+ }
+ let r: Awaited<ReturnType<typeof planClipsNew>>;
+ try {
+ r = await planClipsNew(body);
+ } catch (e) {
+ const status = e instanceof ClipsNewError ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+ }
+ invalidateProjects();
+ try {
+ const job = startJob(r.plan.kind, r.plan.steps, { project: r.project.id });
+ return Response.json(
+ {
+ ok: true,
+ jobId: job.id,
+ job: jobView(job),
+ project: r.project.id,
+ created: r.created,
+ segments: r.segments,
+ segment: r.segment,
+ scope: r.scope,
+ href: clipEditorHref(r.project.id),
+ notes: r.notes,
+ },
+ { headers: { "cache-control": "no-store" } },
+ );
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e), project: r.project.id, created: r.created }, { status: 409 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -714,9 +714,10 @@ function usage() {
" channel's copy where it has one (a twin by date and duration); a context matching --exclude",
" is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances",
" spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")",
- " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO] [--no-analyze]: the clip finder on a long",
+ " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]: the clip finder on a long",
" recording (needs its diarization.json): highlights proposed from the host's laughs and comments,",
- " then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze",
+ " then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze; --scope auto reads the",
+ " narrated video auto-scope finds in the speakers' turns (--segment names one, else the longest)",
" [--brand archilyzer-media] render.brand: the report-to-video brand preset",
" umtool doctor [--json] exit 1 if the report pipeline is missing a tool",
" or the media root is set and not there; the roots, and a leftover old cache",
@@ -745,7 +746,7 @@ function usage() {
" umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> β¦] [--instances F] [--dry] [--json]",
" a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json",
" umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params]",
- " umtool clips propose <project> [--host N] [params] [--dry] | show <project>",
+ " umtool clips propose <project> [--host N] [params] [--dry] | show <project> | segments <project>",
" the clip finder: the laugh scan + voices on the recording's sound, then clips proposed",
" (setup β reaction β tail) into the manifest (assist: by the assistant) and reactions.json;",
" params --target S --laugh-min X --merge-gap S --setup-max S --clip-max S; a clip you edited is never moved",
@@ -1139,10 +1140,11 @@ async function cmdIndex() {
// Scaffolding. The writer is lib/projects/scaffold.mjs, shared with the route.
// ---------------------------------------------------------------------------
-/** `--scope FROM:TO` (seconds; either side may be empty). */
+/** `--scope FROM:TO` (seconds; either side may be empty), or `auto` (release 36: the narrated video auto-scope finds). */
function parseScopeFlag(v) {
+ if (String(v) === "auto") return "auto";
const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(String(v));
- if (!m) die(`--scope ${v}: FROM:TO in seconds (either may be empty)`);
+ if (!m) die(`--scope ${v}: FROM:TO in seconds (either may be empty), or auto`);
return [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null];
}
@@ -1154,7 +1156,7 @@ async function cmdNew() {
" [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" +
" [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" +
" [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]\n" +
- " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO] [--no-analyze]]",
+ " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]]",
);
}
const kind = val("--kind") ?? "report-video";
@@ -1182,6 +1184,7 @@ async function cmdNew() {
...(val("--max") != null ? { max: Number(val("--max")) } : {}),
...(val("--laugh-min") != null ? { laughMin: Number(val("--laugh-min")) } : {}),
...(val("--scope") != null ? { scope: parseScopeFlag(val("--scope")) } : {}),
+ ...(val("--segment") != null ? { segment: val("--segment") } : {}),
});
} catch (e) {
die(e?.message ?? String(e));
diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx
@@ -38,6 +38,8 @@ import { useHydrated } from "@/components/ui/use-hydrated";
// (seconds, default 600), [data-new-laugh-min] and the scope [data-new-scope-from]/
// [data-new-scope-to]; creating one starts "Find the clips" (the laugh scan
// and the voices, then proposals) as a job, and opens the project.
+// Release 36 B1: [data-new-video] picks the narrated video auto-scope finds
+// ("auto": the longest, or the 1st/2nd/3rd found) instead of From s / To s.
type Brand = { id: string; label: string };
type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null };
@@ -51,6 +53,7 @@ const FIELD_HINT: Record<string, string> = {
highlights: "the highlights' length: the proposed clips ranked into this many seconds (10 to 7200)",
laughMin: "how sure the sound model must be that a second is laughter, 0.01 to 1 (default 0.25; lower finds more)",
scope: "read only this part of the recording, in seconds (empty: from the start / to the end)",
+ video: "which narrated video to cut: found from the speaker who talks in long runs, or the From s / To s you type",
phrase: "a regular expression, any case β e.g. slow[ ,]+news (day|week)",
channels: "the channel slugs to scan, separated by commas",
prefer: "the channel to cut from where it holds a copy of the same stream (optional)",
@@ -111,6 +114,7 @@ export default function NewProjectMenu({
const [laughMin, setLaughMin] = useState("0.25");
const [scopeFrom, setScopeFrom] = useState("");
const [scopeTo, setScopeTo] = useState("");
+ const [video, setVideo] = useState("");
// What the video can be seeded from (null: not asked yet, or not a video).
const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean; reactions: boolean } | null>(null);
const [brand, setBrand] = useState("");
@@ -161,7 +165,8 @@ export default function NewProjectMenu({
if (seed === "reactions") {
body.target = Number(hlTarget);
if (laughMin.trim()) body.laughMin = Number(laughMin.trim());
- if (scopeFrom.trim() || scopeTo.trim()) body.scope = [scopeFrom.trim() || null, scopeTo.trim() || null];
+ if (video) Object.assign(body, { scope: "auto" }, video !== "auto" ? { segment: video } : {});
+ else if (scopeFrom.trim() || scopeTo.trim()) body.scope = [scopeFrom.trim() || null, scopeTo.trim() || null];
}
}
if (fields.includes("brand") && brand) body.brand = brand;
@@ -385,11 +390,20 @@ export default function NewProjectMenu({
<Field label="Laugh min">
<Input value={laughMin} onChange={(e) => setLaughMin(e.target.value)} inputMode="decimal" aria-label={`laugh min β ${FIELD_HINT.laughMin}`} title={FIELD_HINT.laughMin} data-new-laugh-min className="num w-20" />
</Field>
+ <Field label="Video">
+ <Select value={video} onChange={(e) => setVideo(e.target.value)} aria-label={`video β ${FIELD_HINT.video}`} title={FIELD_HINT.video} data-new-video>
+ <option value="">From s / To s</option>
+ <option value="auto">the longest one found</option>
+ <option value="s1">the 1st found</option>
+ <option value="s2">the 2nd found</option>
+ <option value="s3">the 3rd found</option>
+ </Select>
+ </Field>
<Field label="From s">
- <Input value={scopeFrom} onChange={(e) => setScopeFrom(e.target.value)} inputMode="numeric" placeholder="start" aria-label={`from seconds β ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-from className="num w-20" />
+ <Input disabled={!!video} value={scopeFrom} onChange={(e) => setScopeFrom(e.target.value)} inputMode="numeric" placeholder="start" aria-label={`from seconds β ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-from className="num w-20" />
</Field>
<Field label="To s">
- <Input value={scopeTo} onChange={(e) => setScopeTo(e.target.value)} inputMode="numeric" placeholder="end" aria-label={`to seconds β ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-to className="num w-20" />
+ <Input disabled={!!video} value={scopeTo} onChange={(e) => setScopeTo(e.target.value)} inputMode="numeric" placeholder="end" aria-label={`to seconds β ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-to className="num w-20" />
</Field>
</>
)}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -25,7 +25,7 @@ Inbox cannot disagree about what is wrong with one.
| `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note β¦]` | edit a window |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
| `index [--rebuild] [--prune] [--since MS] [--json]` | the cache |
-| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` Β· `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` Β· `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO] [--no-analyze]` | scaffold |
+| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` Β· `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` Β· `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold |
| `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there |
| `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none β and a report's deliverables (`clips/`, `share-*/`) and its switch |
| `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back β copied, mirrored, verified first; run when nothing is building |
@@ -47,7 +47,7 @@ Inbox cannot disagree about what is wrong with one.
| `fallback <project> --dry-run [--json]` Β· `fallback <project> [--clip <id> β¦] [--json]` Β· `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) β recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in |
| `phrases "<phrase>" ["<phrase>" β¦] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase |
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> β¦] [--reference-channel <slug> β¦] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice β `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
-| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` Β· `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` Β· `clips show <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
+| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` Β· `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` Β· `clips show <project> [--json]` Β· `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
A project argument is an exact id, a directory, or a **unique** basename. Two
projects answering to one name is reported, never resolved by picking one.
@@ -229,7 +229,14 @@ analysis and every proposal, used or not. The seed reads laughs from the
transcript alone; `umtool new` then runs `umtool clips analyze` (the laugh scan
and the voices on the sound) unless `--no-analyze`. `--laugh-min X` sets the laugh
bar and `--scope FROM:TO` reads only that part of the recording (a stream that
-reacts to two videos, one at a time); both are kept for the next pass. The new-project form's seed
+reacts to two videos, one at a time); both are kept for the next pass.
+`--scope auto` (release 36) reads the narrated video auto-scope finds in the
+speaker turns β `--segment s2` names one, else the longest β and writes the
+numbers it chose; `umtool clips segments <project>` lists the segments. When no
+site carries the channel (and no `--site-origin` is given), each clip links its
+platform page at its second (`citeUrl`), `provenance.channel` comes from the
+metadata, and the render starts with no header, no QR, 0.5 s fades through
+black and `loudness: {target: -16}`. The new-project form's seed
"highlights" (and Create's **Highlights from a recording**) does the same and
starts the scan as a job.
@@ -237,4 +244,6 @@ starts the scan as a job.
archilyzer diarize backfill --scope video:some-channel/abc123
umtool new some-stream-highlights --seed reactions --from some-channel/abc123 --target 600
umtool clips propose some-stream-highlights --host 1 # the other speaker is the host
+umtool new second-half --seed reactions --from some-channel/abc123 --scope auto --segment s2
+umtool clips segments second-half
```
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -998,6 +998,28 @@ What it reads, and what it does without:
classes) at `.diarize/models/sherpa-onnx-ced-mini-audio-tagging-2024-04-19/`
(`AUDIO_TAG_MODEL`). Without it: the transcript's laugh markers (`[laughter]`,
`haha`, `lol`, `lmao`) and the host's loud wordless bursts.
+- **The chat** (release 36) β `live_chat.cues.json` beside the recording (the
+ editor writes it for a YouTube stream's chat replay). Without it, nothing
+ below changes: the analysis is release 35's, byte for byte.
+
+**Which part of the recording: auto-scope** (release 36). A reaction stream
+plays one narrated video, then another, with the host talking over both and
+between them. `--scope auto` (the editor's Find clips uses it) reads the
+narrated video the speaker turns show: 5-minute windows every 30 s, each
+window's subject the speaker (not the host) with the most seconds in turns of
+8 s or more β at least 60 s of them and 60 % of that time; a run of windows
+with one subject is a **segment**, from that speaker's first long turn to its
+last; neighbouring runs of one subject join, and a segment under 3 minutes is
+dropped. The host's talk after a video's last line β his reaction to it β is
+folded into it, up to 5 minutes and never past the next video's first line,
+ending on a turn's end; the time before a video's first line (an intro, the
+host between videos past that) is in no segment. `--segment s2` names one,
+else the longest is read; `umtool clips segments <project>` lists them
+(`reactions.json` `segments: [{id, from, to, subject, host, why}]`, and
+`segment`, the one the scope is). The roles are still found per segment (the
+subject of one video is not the next one's). On the first case (a 2.6-hour
+stream reacting to two videos) it finds 292.7β6318.1 s (subject 4) and
+6501.9β9276.0 s (subject 16).
The steps (over the **scope**, when one is set: `--scope FROM:TO`, or the form's
From/To β turns, words and laugh windows outside it are not read, and the
@@ -1030,7 +1052,19 @@ recording ends at its `to`):
by who laughed: the host 1, nobody 0.8, another speaker 0.6, the subject 0.5,
the subject by voice 0.3)
and every host turn with 1.5 s of words or more (half its length, half the
- strongest laugh around it).
+ strongest laugh around it). With a chat replay, every **chat burst** too
+ (`kind: "chat"`): the chat in 2 s bins β messages, and messages with a laugh
+ token (lol, lmao, lmfao, KEKW, LUL, OMEGALUL, rofl, hahaβ¦, π, π€£, a lone W);
+ a bin with 3 laughs or more and 2.5 Γ the median of the minute either side
+ is a burst; a run of them is a moment at its start minus the chat's **lag**,
+ scored up to 0.6 (below what a host laugh can score). The lag is how late the
+ chat laughs: the chat-laugh bins lined up against the laugh scan's score at
+ every shift from 0 to 20 s, the best (refined between bins); with no scan, or
+ a best correlation under 0.2, 6 s. `clips analyze` says which
+ (`chat: β¦ lag 6.4 s β cross-correlated with the laugh scan (r 0.8)`), and
+ `reactions.json` keeps `chat: {source, lagS, lag: {how, r, why}, messages,
+ bursts, bins: {hop, rate[], laugh[]}}` (null without a replay). A chat burst's
+ reaction runs as a laugh's does; its why reads "chat laughs (N messages)β¦".
4. **Proposals.** From the start of the subject's sentence that set the moment
up (the latest sentence start at least 3 s before it, at most `setupMax` 20 s
back) through the reaction (the host's turn, at most 12 s past a laugh) to
@@ -1046,6 +1080,30 @@ recording ends at its `to`):
`assist: {by: "assistant", proposal, score, why, original, edits: []}`, in
time order, hard cuts (`render.transition: 0`).
+**A channel on no site** (release 36): with no `siteOrigin` and the channel in
+no public site's `channels`/`citedChannels` (a `site.json` with a `siteUrl`),
+there is no archive page for a QR, so each clip the seed or a pass writes links
+its platform page at its second (`citeUrl` from the metadata's `webpage_url`:
+YouTube `&t=<s>s`, Twitch `?t=<h>h<m>m<s>s`, Rumble `?start=<s>`, anything else
+`t=<s>`), and a moved clip's link follows it (a link you wrote stays). The seed
+writes `provenance.channel` from the metadata and the look chosen for a
+one-video cut: `render` `headerHeight: 0, footerHeight: 0, qr: false,
+transition: 0.5, transitionStyle: "fadeblack", loudness: {target: -16}`. With
+every clip linked, an empty `siteOrigin` is not a blocking decision.
+
+**From the editor** (release 36): `POST /api/report/clips {mode: "new", slug,
+from: "<channel>/<id>", target?, scope? ("auto", the default | "all" | [from,
+to]), segment?, wordsPath?}` with `Authorization: Bearer <WORKER_TOKEN>` (no
+header is the app's own page; any other is a 401) β the editor's **Find clips**.
+A reactions project for the same recording whose scope covers the chosen
+segment is analyzed again as it is (`created: false`: its scope, its params and
+its cut stay β the pass runs with `--keep-cut`, so no clip is moved, removed or
+added and the new proposals, the chat's among them, are listed unused for the
+clip editor's Bring in); else `slug` is made with the reactions seed and
+`wordsPath` copied in as `words.json` (`created: true`). Either way `clips
+analyze` runs as one job: `{jobId, job, project, created, segments, segment,
+scope, href, notes}`; `GET ?job=<id>` follows it.
+
**A proposal pass never touches your work.** A clip whose `assist.by` is
`"operator"` (the first edit flips it), a clip with no `assist`, one ruled in
`montage-rulings.json` and one with a `lock*` stays exactly as it is; a
@@ -1071,7 +1129,8 @@ end, score, speaker: n|null, src?: "text"|"energy", voice?: {host, subject}, by?
kind: "laugh"|"comment", score, speaker: n|null, text}], proposals: [{id, start,
end, score, moments, used, clipId: "r001"|null, why}], laughSource:
"model"|"text"|"text+energy", scans: {laughs, voices}, madeAt, proposedAt,
-rolesChangedAt?}`. The clip editor changes only a speaker's role, through
+rolesChangedAt?, segments?, segment?, chat?}` (a moment's `kind` may be `"chat"`,
+with `messages`). The clip editor changes only a speaker's role, through
`setSpeakerRole` (`yt-dlp-transcript-common/lib/clips/reactions.mjs`), which
records `rolesChangedAt` so the page can offer Re-propose.
diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts
@@ -48,6 +48,10 @@ const WRITTEN = [
"reports/videos/p5-song",
"channels/synth-reacts",
"p35-hl",
+ "channels/synth-two",
+ "p36-find",
+ "p36-find-again",
+ "p36-ui",
];
const clean = () => {
for (const p of WRITTEN) rmSync(path.join(FIXTURE, p), { recursive: true, force: true });
@@ -261,6 +265,61 @@ test("Highlights from a recording: the clip finder proposes clips marked by the
expect(summary.laughSource).toBe("text");
});
+test("Find clips from the editor (release 36): mode new with the worker token scaffolds the segment's project and analyzes it; asked again, the same project; a wrong token is refused", async ({ request }) => {
+ // A synthetic stream that reacts to two narrated videos, with its chat replay; no sound.
+ writeReactionCorpus(path.join(FIXTURE, "channels"), {
+ channel: "synth-two",
+ video: "two001",
+ two: true,
+ chat: true,
+ meta: { webpage_url: "https://www.youtube.com/watch?v=two001", channel: "Synth Two" },
+ });
+ const ask = (data: Record<string, unknown>, token = "umtool-e2e-token") =>
+ request.post("/api/report/clips", { headers: { authorization: `Bearer ${token}` }, data });
+ const wrong = await ask({ mode: "new", slug: "p36-find", from: "synth-two/two001" }, "not-the-token");
+ expect(wrong.status()).toBe(401);
+ expect(existsSync(path.join(FIXTURE, "p36-find"))).toBe(false);
+ const r = await ask({ mode: "new", slug: "p36-find", from: "synth-two/two001", scope: "auto", segment: "s2", target: 120 });
+ expect(r.ok()).toBe(true);
+ const made = await r.json();
+ expect(made).toMatchObject({ project: "p36-find", created: true, segment: "s2", scope: [1500, 2390], href: "/projects/p36-find/clips" });
+ expect(made.segments.map((s: { id: string }) => s.id)).toEqual(["s1", "s2"]);
+ // A channel on no site: each clip links its YouTube page at its second; the site-less look.
+ const m = manifestOf("p36-find");
+ expect(m.provenance.channel).toBe("Synth Two");
+ expect(m.render).toMatchObject({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", loudness: { target: -16 } });
+ for (const c of m.timeline) expect(c.citeUrl).toBe(`https://www.youtube.com/watch?v=two001&t=${c.cite}s`);
+ const done = async (id: string) => (await (await request.get(`/api/report/clips?job=${id}`)).json()).state;
+ await expect.poll(() => done(made.jobId), { timeout: 60_000 }).toBe("done");
+ const summary = (await (await request.get("/api/report/clips?project=p36-find")).json()).reactions;
+ expect(summary.segment).toBe("s2");
+ expect(summary.segments.length).toBe(2);
+ expect(summary.chat.lagS).toBe(6);
+ expect(summary.used).toBeGreaterThan(0);
+ // Asked again for the same video's s2: that project, analyzed again (not a second one).
+ const again = await (await ask({ mode: "new", slug: "p36-find-again", from: "synth-two/two001", segment: "s2" })).json();
+ expect(again).toMatchObject({ project: "p36-find", created: false });
+ await expect.poll(() => done(again.jobId), { timeout: 60_000 }).toBe("done");
+ expect(existsSync(path.join(FIXTURE, "p36-find-again"))).toBe(false);
+});
+
+test("Highlights from a recording, the video found for you: the form's Video picks the 2nd narrated video", async ({ page, request }) => {
+ writeReactionCorpus(path.join(FIXTURE, "channels"), { channel: "synth-two", video: "two001", two: true });
+ await page.goto(urls.createHref({ make: "video-highlights" }));
+ const f = form(page, "video-highlights");
+ await f.locator("[data-new-from]").fill("synth-two/two001");
+ await expect(f.locator("[data-new-seed]")).toHaveValue("reactions");
+ await f.locator("[data-new-video]").selectOption("s2");
+ await expect(f.locator("[data-new-scope-from]")).toBeDisabled();
+ await f.locator("[data-new-slug]").fill("p36-ui");
+ await f.getByRole("button", { name: "Find the clips" }).click();
+ await page.waitForURL(/\/projects\/p36-ui$/, { timeout: 20_000 });
+ const r = JSON.parse(readFileSync(path.join(FIXTURE, "p36-ui", "reactions.json"), "utf8"));
+ expect(r.params.scope).toEqual([1500, 2390]);
+ expect(r.segment).toBe("s2");
+ await expect.poll(async () => (await (await request.get("/api/jobs")).json()).running, { timeout: 60_000 }).toBeNull();
+});
+
test("Video from a sweep report: the reports on disk are offered, and one becomes a project", async ({ page }) => {
await page.goto(urls.createHref({ make: "video-report" }));
const f = form(page, "video-report");
diff --git a/umtool/lib/annotations/agentAuth.mjs b/umtool/lib/annotations/agentAuth.mjs
@@ -130,6 +130,22 @@ export function noteWriter(authorization, token) {
}
/**
+ * Who is calling an editor-facing route (release 36: /api/report/clips): the
+ * same rule as noteWriter. No Authorization header is the app's own page (as
+ * before); `Bearer <umtool's WORKER_TOKEN>` is the editor (or an agent); any
+ * other header is a 401.
+ * @param {string | null | undefined} authorization
+ * @param {string} token umtool's WORKER_TOKEN ("" for none)
+ * @param {string} [what] the route, for the refusal
+ * @returns {{ ok: true, by: "page" | "worker" } | { ok: false, status: 401, error: string }}
+ */
+export function routeCaller(authorization, token, what = "this route") {
+ const w = noteWriter(authorization, token);
+ if (w.ok) return { ok: true, by: w.by === "agent" ? "worker" : "page" };
+ return { ok: false, status: 401, error: w.error.replace(/^notes:/, `${what}:`).replace("no agent can write here", "no editor can call it") };
+}
+
+/**
* The POST: one op on a target's notes, by whoever the header proves. A refusal
* is `{ status, body: { error } }`; a write `{ status: 200, body }` with what
* writeNote returns. A stale token or a refused op THROWS (the route's
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -91,6 +91,21 @@ const DEAD_ORIGIN =
export const isDeadOrigin = (o) => !o || typeof o !== "string" || DEAD_ORIGIN.test(o);
+/**
+ * A cut with NO siteOrigin whose every clip carries its own `citeUrl` (release
+ * 36: a site-less reactions cut links each clip's platform page), with no
+ * card and no post that would need the archive: no QR is built from the
+ * origin, so its absence is not a defect. A dead origin that IS set (localhost)
+ * still is one.
+ */
+export const originUnused = (m) => {
+ if (m?.provenance?.siteOrigin) return false;
+ const tl = Array.isArray(m?.timeline) ? m.timeline : [];
+ const clips = tl.filter((e) => e?.type === "clip");
+ return clips.length > 0 && clips.every((c) => typeof c.citeUrl === "string" && /^https?:\/\//.test(c.citeUrl)) && !tl.some((e) => e?.type === "card") && !(Array.isArray(m?.posts) && m.posts.length);
+};
+const originDead = (m) => isDeadOrigin(m?.provenance?.siteOrigin) && !originUnused(m);
+
const stat0 = (p) => stat(p).then((s) => s, () => null);
export const manifestPath = (dir) => path.join(dir, MANIFEST_NAME);
@@ -682,7 +697,7 @@ export async function summariseReport(ctx) {
if (build.built) facts.push(`${(build.finalSize / 1e6).toFixed(0)} MB`);
const flags = [];
- if (isDeadOrigin(m?.provenance?.siteOrigin)) flags.push("dead QR origin");
+ if (originDead(m)) flags.push("dead QR origin");
if (!m?.provenance?.channelSlug) flags.push("no channelSlug");
if (build.stale) flags.push("older than its manifest");
if (sourcesDead) flags.push(`${sourcesDead} dead source${sourcesDead === 1 ? "" : "s"}`);
@@ -726,7 +741,7 @@ export async function summariseReport(ctx) {
...(sourcesMissing ? { "sources-missing": String(sourcesMissing) } : {}),
...(cueGaps ? { "cue-gaps": String(cueGaps) } : {}),
...(build.built ? { built: "1", "final-bytes": String(build.finalSize + build.fullSize) } : {}),
- ...(isDeadOrigin(m?.provenance?.siteOrigin) ? { "dead-origin": "1" } : {}),
+ ...(originDead(m) ? { "dead-origin": "1" } : {}),
},
// Kept for the project page and the decisions pass, so neither re-reads.
manifest: m,
@@ -827,7 +842,7 @@ export async function reportDecisions(ctx, summary) {
// --- the manifest itself -------------------------------------------------
const origin = m.provenance?.siteOrigin;
- if (isDeadOrigin(origin)) {
+ if (originDead(m)) {
add(
"manifest-invalid",
"provenance.siteOrigin",
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -17,6 +17,9 @@ export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
export const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
export const SEEDS = ["chapters", "frames", "phrase", "reactions"];
+/** The render keys a site-less, one-video reactions cut starts with (release 36: the operator's choice on the first case). */
+export const SITELESS_LOOK = Object.freeze({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", loudness: Object.freeze({ target: -16 }) });
+
/**
* A manifest skeleton, and deliberately an EMPTY timeline.
*
@@ -247,9 +250,9 @@ const capNote = (max, kept, found) =>
* (common/lib/montage/phraseScan.mjs `capInstances`); the rest are listed in
* phrase-scan.json as `skippedByCap`. No `max`: the output is what it was.
*
- * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | null }} args
+ * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | "auto" | null, segment?: string | null, sitesDir?: string }} args
*/
-export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null }) {
+export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null, segment = null, sitesDir = undefined }) {
if (!SLUG_RE.test(String(slug ?? ""))) {
throw new Error(`"${slug}" will not route β use lower-case letters, digits and dashes`);
}
@@ -287,11 +290,14 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
throw new Error(`--max must be a whole number of clips from 1 to ${MAX_PHRASE_CAP}`);
}
const capped = max !== null && max !== undefined;
- if ((laughMin !== undefined || scope) && seed !== "reactions") throw new Error("--laugh-min and --scope go with --seed reactions");
+ if ((laughMin !== undefined || scope || segment) && seed !== "reactions") throw new Error("--laugh-min, --scope and --segment go with --seed reactions");
+ if (segment && !/^s\d+$/.test(String(segment))) throw new Error(`--segment ${segment}: a segment id (s1, s2, β¦)`);
+ if (segment && scope && scope !== "auto") throw new Error("--segment goes with --scope auto (or alone)");
if (laughMin !== undefined && !(Number.isFinite(laughMin) && laughMin >= PARAM_BOUNDS.laughMin[0] && laughMin <= PARAM_BOUNDS.laughMin[1])) {
throw new Error(`--laugh-min must be a number from ${PARAM_BOUNDS.laughMin[0]} to ${PARAM_BOUNDS.laughMin[1]}`);
}
- const reactionsScope = seed === "reactions" ? normalizeScope(scope) : null;
+ // Release 36: `auto` (or a `segment`) is the narrated video auto-scope finds in the recording.
+ const reactionsScope = seed !== "reactions" ? null : scope === "auto" || segment ? "auto" : normalizeScope(scope);
if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed");
if (target !== undefined && seed !== "frames" && seed !== "reactions") throw new Error("--target is the frames seed's length budget (or the reactions seed's): give it with --seed frames or --seed reactions");
const [tLo, tHi] = seed === "reactions" ? PARAM_BOUNDS.target : [10, 3600];
@@ -390,17 +396,34 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
const pass = await seedReactions({
channelsDir, channel: src.channel, video: src.video,
...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(reactionsScope ? { scope: reactionsScope } : {}),
+ ...(segment ? { segment: String(segment) } : {}),
+ siteOrigin: provenance.siteOrigin ?? null,
+ ...(sitesDir ? { sitesDir } : {}),
});
doc.timeline = pass.timeline;
- // Hard cuts: a highlights reel.
- doc.render.transition = 0;
+ if (!doc.provenance.channel && pass.rec.meta?.channel) doc.provenance.channel = pass.rec.meta.channel;
+ if (pass.siteLess) {
+ // Release 36: a channel on no site β each clip links its platform page at
+ // its second (no QR to an archive that does not have it), and the look the
+ // operator chose for a one-video cut: no header, no QR, fades through black,
+ // even loudness (render.loudness is lane C's; until its validator lands it
+ // is a key the build ignores).
+ Object.assign(doc.render, SITELESS_LOOK, { loudness: { ...SITELESS_LOOK.loudness } });
+ const platform = /^youtube/i.test(pass.rec.meta?.extractor ?? "") ? "YouTube" : pass.rec.meta?.extractor ?? "its platform";
+ notes.push(`no site carries ${src.channel}: each clip links ${platform}'s page at its second (citeUrl); the look: no header, no QR, ${SITELESS_LOOK.transition} s fades through black, ${SITELESS_LOOK.loudness.target} LUFS`);
+ } else {
+ // Hard cuts: a highlights reel.
+ doc.render.transition = 0;
+ }
seeded = doc.timeline.length;
reactionsSeeded = pass;
const used = pass.doc.proposals.filter((p) => p.used);
const host = pass.doc.speakers.find((s) => s.role === "host");
notes.push(`${pass.doc.proposals.length} proposal(s), ${used.length} in the cut: ${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of a ${pass.doc.params.target} s target (--target)`);
notes.push(`the host: speaker ${host ? host.index : "?"} of ${pass.doc.speakers.length} (by turn statistics β flip it in the clip editor or with umtool clips propose ${slug} --host N)`);
- if (reactionsScope) notes.push(`only ${reactionsScope[0]}β${reactionsScope[1] ?? "the end"} s of the recording is read (--scope)`);
+ notes.push(...(pass.notes ?? []));
+ const read = pass.doc.params.scope;
+ if (read) notes.push(`only ${read[0]}β${read[1] ?? "the end"} s of the recording is read (--scope${reactionsScope === "auto" ? ` auto${pass.doc.segment ? `: ${pass.doc.segment}` : ""}` : ""}; umtool clips segments ${slug} lists the narrated videos)`);
notes.push(`laughs from the transcript only (${pass.doc.laughs.length}); umtool clips analyze ${slug} runs the laugh scan and the voices on the sound, then proposes again`);
if (pass.rec.wordsFrom === "cues") notes.push("no word timings: edges sit on the cues; pnpm ops transcribe {path, words:true, out: <project>/words.json} gives words, then umtool clips propose");
if (!pass.doc.proposals.length) notes.push("nothing to propose: no host comments or laughs were found");
diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts
@@ -33,7 +33,9 @@ export type NewProjectBody = {
max?: number | string | null;
// The reactions seed (release 35 C1): the laugh bar and the part of the recording read.
laughMin?: number | string | null;
- scope?: [number | string | null, number | string | null] | null;
+ scope?: [number | string | null, number | string | null] | "auto" | null;
+ // Release 36: with scope "auto", the segment auto-scope found to read (s1, s2β¦; else the longest).
+ segment?: string | null;
};
/**
@@ -87,6 +89,9 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
}
: {}),
...(body.seed === "reactions" && body.laughMin !== undefined && body.laughMin !== null && body.laughMin !== "" ? { laughMin: Number(body.laughMin) } : {}),
+ ...(body.seed === "reactions" && (body.scope === "auto" || (typeof body.segment === "string" && body.segment))
+ ? { scope: "auto" as const, ...(typeof body.segment === "string" && body.segment ? { segment: body.segment } : {}) }
+ : {}),
...(body.seed === "reactions" && Array.isArray(body.scope)
? { scope: [body.scope[0] === null || body.scope[0] === "" ? 0 : Number(body.scope[0]), body.scope[1] === null || body.scope[1] === "" ? null : Number(body.scope[1])] as [number, number | null] }
: {}),
diff --git a/umtool/lib/report/clipsNew.mjs b/umtool/lib/report/clipsNew.mjs
@@ -0,0 +1,196 @@
+// "Find clips" from the editor (release 36 B5): `POST /api/report/clips
+// {mode: "new", slug, from: "<channel>/<id>", target?, scope?, segment?,
+// wordsPath?}` β a recording to a clip-finder project and its analysis, as
+// ONE call. The editor's find-clips job (release 36 lane A) makes the words,
+// the chat and the speakers first, then asks this.
+//
+// the scope "auto" (the default) is the narrated video auto-scope finds
+// (lib/clips/segments.mjs): `segment` names one, else the
+// longest; `[from, to]` is a scope by hand; "all" the whole
+// a project already made for the same recording whose scope covers the
+// chosen one (scopeOverlapsSegment) is analyzed AGAIN, as it
+// is β its scope, its params, and its cut: `--keep-cut`, so
+// no clip is moved, removed or added and the new proposals
+// (the chat's among them) are listed unused for the clip
+// editor β `created: false`; else a new project `slug` is
+// scaffolded with the reactions seed β `created: true`
+// the words `wordsPath` (an absolute path to a words file, `{words:
+// [{w, start, end}]}` as `pnpm ops transcribe {words: true,
+// out}` writes) is copied in as <project>/words.json β into
+// an existing project only when it has none
+// the job `clips analyze` (the laugh scan, the voices, then a
+// proposal pass), one step on the app's runner
+//
+// Plain ESM: the route calls it, and its tests run with bare node.
+import { copyFile, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { PARAM_BOUNDS, cleanWords, normalizeScope } from "yt-dlp-transcript-common/lib/clips/clips.mjs";
+import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+import { pickSegment, scopeOverlapsSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs";
+import { REPORTS_ROOT } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { GLOBAL_CHANNELS_DIR } from "../projects/report.mjs";
+import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs";
+import { walkProjects } from "../projects/walk.mjs";
+import { ClipsError, WORDS_FILE, clipsSteps, loadRecording, recordingSegments } from "./reactions.mjs";
+
+/** A refusal with the HTTP status the route answers. */
+export class ClipsNewError extends ClipsError {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+const WORDS_MAX_BYTES = 256 * 1024 * 1024;
+
+/** The request's fields, checked. */
+export function parseNewBody(body) {
+ const b = body && typeof body === "object" ? body : {};
+ const slug = String(b.slug ?? "").trim().toLowerCase();
+ if (!SLUG_RE.test(slug)) throw new ClipsNewError(`slug "${b.slug ?? ""}": lower-case letters, digits and dashes`);
+ const m = /^([^/]+)\/([^/]+)$/.exec(String(b.from ?? ""));
+ if (!m || !CHANNEL_SLUG_RE.test(m[1]) || !CHANNEL_SLUG_RE.test(m[2])) throw new ClipsNewError(`from "${b.from ?? ""}": <channel>/<videoId>`);
+ let target;
+ if (b.target !== undefined && b.target !== null && b.target !== "") {
+ target = Number(b.target);
+ const [lo, hi] = PARAM_BOUNDS.target;
+ if (!Number.isFinite(target) || target < lo || target > hi) throw new ClipsNewError(`target must be ${lo}..${hi} seconds`);
+ }
+ /** @type {"auto" | "all" | [number, number | null]} */
+ let scope = "auto";
+ if (b.scope === "all") scope = "all";
+ else if (Array.isArray(b.scope)) {
+ try {
+ scope = normalizeScope(b.scope) ?? "all";
+ } catch (e) {
+ throw new ClipsNewError(e instanceof Error ? e.message : String(e));
+ }
+ } else if (b.scope !== undefined && b.scope !== null && b.scope !== "auto") throw new ClipsNewError(`scope: "auto", "all" or [from, to]`);
+ const segment = typeof b.segment === "string" && b.segment ? b.segment : null;
+ if (segment && !/^s\d+$/.test(segment)) throw new ClipsNewError(`segment "${segment}": s1, s2, β¦`);
+ if (segment && scope !== "auto") throw new ClipsNewError("segment goes with scope \"auto\"");
+ const wordsPath = typeof b.wordsPath === "string" && b.wordsPath ? b.wordsPath : null;
+ if (wordsPath && !path.isAbsolute(wordsPath)) throw new ClipsNewError("wordsPath must be an absolute path");
+ return { slug, channel: m[1], video: m[2], target, scope, segment, wordsPath };
+}
+
+/** The words file, checked: a regular file holding words. */
+async function checkWords(file) {
+ const s = await stat(file).catch(() => null);
+ if (!s || !s.isFile()) throw new ClipsNewError(`wordsPath ${file}: no such file`, 404);
+ if (s.size > WORDS_MAX_BYTES) throw new ClipsNewError(`wordsPath ${file}: too large`);
+ let doc;
+ try {
+ doc = JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ throw new ClipsNewError(`wordsPath ${file}: not JSON`);
+ }
+ const list = Array.isArray(doc) ? doc : Array.isArray(doc?.words) ? doc.words : null;
+ if (!list || !cleanWords(list).length) throw new ClipsNewError(`wordsPath ${file} holds no words ({ words: [{ w, start, end }] })`);
+}
+
+/**
+ * The reactions projects already made for this recording whose scope covers
+ * `span` β the best cover first (the most overlap, then the latest pass).
+ */
+export async function projectsCovering({ reportsRoot, channel, video, span, duration }) {
+ const out = [];
+ for (const p of await walkProjects(reportsRoot)) {
+ if (!kindMakesTakes(p.kind)) continue;
+ const doc = await readReactions(p.dir);
+ if (!doc || doc.source?.channel !== channel || doc.source?.video !== video) continue;
+ const scope = doc.params?.scope ?? null;
+ if (!scopeOverlapsSegment(scope, span, duration)) continue;
+ const a = Array.isArray(scope) ? scope[0] : 0;
+ const b = Array.isArray(scope) && scope[1] !== null ? scope[1] : duration;
+ out.push({ project: p, overlap: Math.max(0, Math.min(b, span.to) - Math.max(a, span.from)), at: String(doc.proposedAt ?? "") });
+ }
+ return out.sort((x, y) => y.overlap - x.overlap || (y.at > x.at ? 1 : y.at < x.at ? -1 : 0)).map((x) => x.project);
+}
+
+/**
+ * Plan a `mode: "new"` request: the project (found or scaffolded), the job's
+ * steps, and what the editor is told. Scaffolds and copies the words; does
+ * not start the job (the route does, on lib/jobs.ts).
+ * @param {unknown} body
+ * @param {{ reportsRoot?: string, channelsDir?: string, sitesDir?: string }} [o]
+ */
+export async function planClipsNew(body, { reportsRoot = REPORTS_ROOT, channelsDir = GLOBAL_CHANNELS_DIR(), sitesDir = undefined } = {}) {
+ const req = parseNewBody(body);
+ let rec;
+ try {
+ rec = await loadRecording({ channelsDir, channel: req.channel, video: req.video });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ throw new ClipsNewError(msg, /no video directory/.test(msg) ? 404 : 400);
+ }
+ const segments = recordingSegments(rec);
+ let span;
+ let segment = null;
+ if (req.scope === "auto") {
+ try {
+ segment = pickSegment(segments, req.segment);
+ } catch (e) {
+ throw new ClipsNewError(e instanceof Error ? e.message : String(e));
+ }
+ span = segment ? { from: segment.from, to: segment.to } : { from: 0, to: rec.duration };
+ } else if (req.scope === "all") span = { from: 0, to: rec.duration };
+ else span = { from: req.scope[0], to: req.scope[1] ?? rec.duration };
+
+ const [existing] = await projectsCovering({ reportsRoot, channel: req.channel, video: req.video, span, duration: rec.duration });
+ const notes = [];
+ let project;
+ let created;
+ if (existing) {
+ project = { id: existing.id, dir: existing.dir, kind: existing.kind };
+ created = false;
+ notes.push(`${existing.id} already reads this part of ${req.channel}/${req.video}: analyzed again with its scope and its cut kept as they are (the new proposals are listed, unused)`);
+ if (req.wordsPath) {
+ if (await stat(path.join(project.dir, WORDS_FILE)).then(() => true, () => false)) notes.push(`${WORDS_FILE} kept (the project has one)`);
+ else {
+ await checkWords(req.wordsPath);
+ await copyFile(req.wordsPath, path.join(project.dir, WORDS_FILE));
+ notes.push(`${WORDS_FILE} copied in`);
+ }
+ }
+ } else {
+ if (req.wordsPath) await checkWords(req.wordsPath);
+ let r;
+ try {
+ r = await scaffoldReportVideo({
+ root: reportsRoot,
+ slug: req.slug,
+ from: `${req.channel}/${req.video}`,
+ seed: "reactions",
+ channelsDir,
+ ...(sitesDir ? { sitesDir } : {}),
+ ...(req.target !== undefined ? { target: req.target } : {}),
+ ...(req.scope === "auto" ? { scope: "auto", ...(req.segment ? { segment: req.segment } : {}) } : req.scope === "all" ? {} : { scope: req.scope }),
+ });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ throw new ClipsNewError(msg, /already exists/.test(msg) ? 409 : 400);
+ }
+ project = { id: r.id, dir: r.dir, kind: "report-video" };
+ created = true;
+ notes.push(...r.notes);
+ if (req.wordsPath) {
+ await copyFile(req.wordsPath, path.join(r.dir, WORDS_FILE));
+ notes.push(`${WORDS_FILE} copied in`);
+ }
+ }
+ const doc = await readReactions(project.dir);
+ const plan = clipsSteps(project, { mode: "analyze", ...(created ? {} : { keepCut: true }) });
+ return {
+ project,
+ created,
+ segments,
+ // The segment chosen (auto-scope's); an existing project keeps its own scope.
+ segment: segment?.id ?? doc?.segment ?? null,
+ scope: doc?.params?.scope ?? null,
+ plan,
+ notes,
+ };
+}
diff --git a/umtool/lib/report/reactions-r36.test.mjs b/umtool/lib/report/reactions-r36.test.mjs
@@ -0,0 +1,298 @@
+// The clip finder, round two (release 36 lane B): auto-scope over a synthetic
+// two-video stream, the chat signal from a synthetic chat replay, site-less
+// links and the default look, and the route's `mode: "new"` job β all over
+// the test kit's synthetic corpus (no python, no model, no network).
+//
+// 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 { 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, 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, audio: audio ? encodeWav16(reactionAudio()) : null });
+ return { root, channelsDir, reportsRoot, sitesDir };
+}
+
+async function pointAt(dir, channelsDir) {
+ const file = path.join(dir, "video.manifest.json");
+ const m = JSON.parse(await readFile(file, "utf8"));
+ m.provenance.channelsDir = path.relative(dir, channelsDir);
+ await writeFile(file, JSON.stringify(m, null, 2));
+ return m;
+}
+
+test("auto-scope: --scope auto reads the longest narrated video, --segment names one; roles per segment; clips segments lists them", async () => {
+ const f = await fixture();
+ try {
+ const a = await scaffoldReportVideo({ root: f.reportsRoot, slug: "first", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, scope: "auto", sitesDir: f.sitesDir });
+ let doc = await readReactions(a.dir);
+ assert.deepEqual(doc.params.scope, [120, 1347]);
+ assert.equal(doc.segment, "s1");
+ assert.deepEqual(doc.segments.map((g) => [g.id, g.from, g.to, g.subject, g.host]), [["s1", 120, 1347, TWO_SUBJECT_A, 0], ["s2", 1500, 2390, TWO_SUBJECT_B, 0]]);
+ assert.equal(doc.speakers.find((s) => s.role === "subject")?.index, TWO_SUBJECT_A);
+ assert.ok(a.notes.some((n) => /auto-scope: s1, 120β1347 s/.test(n)), a.notes.join("\n"));
+
+ const b = await scaffoldReportVideo({ root: f.reportsRoot, slug: "second", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s2", sitesDir: f.sitesDir });
+ doc = await readReactions(b.dir);
+ assert.deepEqual(doc.params.scope, [1500, 2390]);
+ assert.equal(doc.segment, "s2");
+ // The subject of THIS segment: the role code runs on the segment's turns.
+ assert.equal(doc.speakers.find((s) => s.role === "subject")?.index, TWO_SUBJECT_B);
+ assert.equal(doc.speakers.find((s) => s.role === "host")?.index, 0);
+ assert.ok(doc.proposals.every((p) => p.start >= 1500 && p.end <= 2390));
+
+ await pointAt(b.dir, f.channelsDir);
+ const q = quiet();
+ assert.equal(await clipsCommand(["segments", "second"], { reportsRoot: f.reportsRoot, ...q }), 0);
+ assert.match(q.lines.join("\n"), /s1 +120\.0β1347\.0/);
+ assert.match(q.lines.join("\n"), /s2 +1500\.0β2390\.0 .*\(this project's scope\)/);
+ const j = quiet();
+ assert.equal(await clipsCommand(["segments", "second", "--json"], { reportsRoot: f.reportsRoot, ...j }), 0);
+ assert.equal(JSON.parse(j.lines[0]).segment, "s2");
+
+ // Re-scoped from the CLI to the other video; an unknown segment is refused.
+ await pointAt(a.dir, f.channelsDir);
+ assert.equal(await clipsCommand(["propose", "first", "--segment", "s2"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ doc = await readReactions(a.dir);
+ assert.deepEqual([doc.params.scope, doc.segment], [[1500, 2390], "s2"]);
+ const bad = quiet();
+ assert.equal(await clipsCommand(["propose", "first", "--segment", "s9"], { reportsRoot: f.reportsRoot, ...bad }), 2);
+ assert.match(bad.lines.join("\n"), /no segment s9 \(there are s1, s2\)/);
+ assert.equal(await clipsCommand(["propose", "first", "--scope", "10:20", "--segment", "s1"], { reportsRoot: f.reportsRoot, ...quiet() }), 2);
+ await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "x", from: "synth-reacts/react001", seed: "chapters", channelsDir: f.channelsDir, segment: "s1" }), /go with --seed reactions/);
+
+ // The job step carries it.
+ const argv = clipsSteps({ id: "first" }, { mode: "analyze", scope: "auto", segment: "s2" }).steps[0].argv;
+ assert.deepEqual(argv.slice(argv.indexOf("--scope"), argv.indexOf("--scope") + 4), ["--scope", "auto", "--segment", "s2"]);
+ } finally {
+ 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 });
+ }
+});
+
+test("mode new (the editor's Find clips): a project scaffolded for the chosen segment with the words copied in; asked again, the same project analyzed again", async () => {
+ const f = await fixture({ chat: true });
+ const { planClipsNew, parseNewBody } = await import("./clipsNew.mjs");
+ try {
+ const wordsPath = path.join(f.root, "words-out.json");
+ const { twoVideoStream } = await import("yt-dlp-transcript-common/testing/clips/reactionStream.mjs");
+ await writeFile(wordsPath, JSON.stringify({ path: "/x", words: twoVideoStream().words }));
+ const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir };
+ const a = await planClipsNew({ mode: "new", slug: "find-b", from: "synth-reacts/react001", scope: "auto", segment: "s2", wordsPath, target: 120 }, opts);
+ assert.equal(a.created, true);
+ assert.equal(a.project.id, "find-b");
+ assert.equal(a.segment, "s2");
+ assert.deepEqual(a.scope, [1500, 2390]);
+ assert.deepEqual(a.segments.map((g) => g.id), ["s1", "s2"]);
+ assert.deepEqual(JSON.parse(await readFile(path.join(a.dir ?? a.project.dir, "words.json"), "utf8")).words.length, twoVideoStream().words.length);
+ assert.equal(a.plan.kind, "clips-analyze find-b");
+ assert.deepEqual(a.plan.steps[0].argv.slice(5, 8), ["clips", "analyze", "find-b"]);
+ const doc = await readReactions(a.project.dir);
+ assert.ok(doc.chat, "the chat replay read");
+
+ // An operator's clip in it; then the editor asks again for the same video's s2: the SAME project, as it is.
+ const mf = path.join(a.project.dir, "video.manifest.json");
+ const m = JSON.parse(await readFile(mf, "utf8"));
+ m.timeline[0].assist.by = "operator";
+ await writeFile(mf, JSON.stringify(m, null, 2));
+ const again = await planClipsNew({ mode: "new", slug: "find-b-2", from: "synth-reacts/react001", segment: "s2", wordsPath }, opts);
+ assert.equal(again.created, false);
+ assert.equal(again.project.id, "find-b");
+ assert.ok(again.notes.some((n) => /words\.json kept/.test(n)));
+ assert.equal(JSON.parse(await readFile(mf, "utf8")).timeline[0].assist.by, "operator");
+ // The other video is a new project; the default scope is auto (the longest: s1).
+ const b = await planClipsNew({ mode: "new", slug: "find-a", from: "synth-reacts/react001" }, opts);
+ assert.deepEqual([b.created, b.segment, b.scope], [true, "s1", [120, 1347]]);
+ // A slug already taken by another recording's project: 409. Refusals: 400 / 404.
+ await assert.rejects(planClipsNew({ mode: "new", slug: "find-a", from: "synth-reacts/react001", scope: [0, 60] }, opts), (e) => e.status === 409);
+ await assert.rejects(planClipsNew({ mode: "new", slug: "zz", from: "synth-reacts/nope" }, opts), (e) => e.status === 404);
+ await assert.rejects(planClipsNew({ mode: "new", slug: "zz", from: "synth-reacts/react001", segment: "s7" }, opts), (e) => e.status === 400 && /no segment s7/.test(e.message));
+ assert.throws(() => parseNewBody({ slug: "Bad Slug", from: "a/b" }), /slug/);
+ assert.throws(() => parseNewBody({ slug: "ok", from: "../b" }), /from/);
+ assert.throws(() => parseNewBody({ slug: "ok", from: "a/b", wordsPath: "rel/words.json" }), /absolute/);
+ assert.throws(() => parseNewBody({ slug: "ok", from: "a/b", scope: [0, 10], segment: "s1" }), /segment goes with scope "auto"/);
+ assert.deepEqual(parseNewBody({ slug: "ok", from: "a/b", scope: [0, 10] }).scope, [0, 10]);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
+test("the route's caller: no header is the page, umtool's WORKER_TOKEN the editor, anything else a 401", async () => {
+ const { routeCaller } = await import("../annotations/agentAuth.mjs");
+ assert.deepEqual(routeCaller(null, "tok"), { ok: true, by: "page" });
+ assert.deepEqual(routeCaller("Bearer tok", "tok"), { ok: true, by: "worker" });
+ const wrong = routeCaller("Bearer nope", "tok", "/api/report/clips");
+ assert.equal(wrong.ok, false);
+ assert.equal(wrong.status, 401);
+ assert.match(wrong.error, /^\/api\/report\/clips: that bearer token is not umtool's WORKER_TOKEN/);
+ assert.match(routeCaller("Bearer tok", "", "/api/report/clips").error, /holds no WORKER_TOKEN, so no editor can call it/);
+ assert.equal(routeCaller("Basic x", "tok").ok, false);
+});
+
+test("a channel on no site: each clip links its platform page, provenance.channel from the metadata, the site-less look; no dead-origin decision", async () => {
+ const meta = { webpage_url: "https://www.youtube.com/watch?v=react001", channel: "Synth Reacts Channel", extractor_key: "Youtube" };
+ const f = await fixture({ meta });
+ const { lintManifest } = await import("umtool-report-to-video/lint");
+ const { decisionsFor, summarise } = await import("../projects/core.mjs");
+ const { walkProjects } = await import("../projects/walk.mjs");
+ const { SITELESS_LOOK } = await import("../projects/scaffold.mjs");
+ try {
+ const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "siteless", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s1", target: 120, sitesDir: f.sitesDir });
+ const m = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8"));
+ assert.ok(m.timeline.length > 0);
+ for (const c of m.timeline) assert.equal(c.citeUrl, `https://www.youtube.com/watch?v=react001&t=${c.cite}s`);
+ assert.equal(m.provenance.channel, "Synth Reacts Channel");
+ assert.equal(m.provenance.siteOrigin, "");
+ assert.deepEqual(
+ { headerHeight: m.render.headerHeight, footerHeight: m.render.footerHeight, qr: m.render.qr, transition: m.render.transition, transitionStyle: m.render.transitionStyle, loudness: m.render.loudness },
+ { ...SITELESS_LOOK, loudness: { target: -16 } },
+ );
+ assert.ok(r.notes.some((n) => /no site carries synth-reacts: each clip links YouTube's page/.test(n)), r.notes.join("\n"));
+ // The build's validators and lint take it (render.loudness is a key they do not refuse).
+ const lint = lintManifest(m, { validators: true });
+ assert.deepEqual(lint.errors.filter((e) => /loudness|transition|qr|render/i.test(e)), []);
+ // No siteOrigin is not a defect here: every clip links itself.
+ const [ref] = (await walkProjects(f.reportsRoot)).filter((p) => p.id === "siteless");
+ assert.ok(!(await decisionsFor(ref, f.reportsRoot)).some((d) => d.target === "provenance.siteOrigin"));
+ assert.ok(!(await summarise(ref, f.reportsRoot)).flags.includes("dead QR origin"));
+
+ // A later pass keeps the rule: every clip it writes links itself.
+ await pointAt(r.dir, f.channelsDir);
+ assert.equal(await clipsCommand(["propose", "siteless", "--target", "300"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ const after = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8"));
+ assert.ok(after.timeline.length > m.timeline.length);
+ for (const c of after.timeline) assert.equal(c.citeUrl, `https://www.youtube.com/watch?v=react001&t=${c.cite}s`);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
+test("a channel on a public site, or a recording with no watch page: no links written, hard cuts as before", async () => {
+ const meta = { webpage_url: "https://www.youtube.com/watch?v=react001", channel: "Synth Reacts Channel" };
+ const f = await fixture({ meta });
+ const g = await fixture();
+ try {
+ await mkdir(path.join(f.sitesDir, "synthsite"), { recursive: true });
+ await writeFile(path.join(f.sitesDir, "synthsite", "site.json"), JSON.stringify({ siteId: "synthsite", siteUrl: "https://synth.example", channels: [{ slug: "synth-reacts" }] }));
+ // A private site (no siteUrl) does not count.
+ await mkdir(path.join(g.sitesDir, "private"), { recursive: true });
+ await writeFile(path.join(g.sitesDir, "private", "site.json"), JSON.stringify({ siteId: "private", channels: [{ slug: "synth-reacts" }] }));
+ const { channelOnPublicSite } = await import("./reactions.mjs");
+ assert.equal(await channelOnPublicSite("synth-reacts", f.sitesDir), true);
+ assert.equal(await channelOnPublicSite("synth-reacts", g.sitesDir), false);
+ for (const [x, slug] of [[f, "onsite"], [g, "nopage"]]) {
+ const r = await scaffoldReportVideo({ root: x.reportsRoot, slug, from: "synth-reacts/react001", seed: "reactions", channelsDir: x.channelsDir, target: 120, sitesDir: x.sitesDir });
+ const m = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.render.transition, 0, slug);
+ assert.equal(m.render.headerHeight, 56, slug);
+ assert.ok(m.timeline.every((c) => !("citeUrl" in c)), slug);
+ }
+ // The site's channel still gets its name from the metadata.
+ assert.equal(JSON.parse(await readFile(path.join(f.reportsRoot, "onsite", "video.manifest.json"), "utf8")).provenance.channel, "Synth Reacts Channel");
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ await rm(g.root, { recursive: true, force: true });
+ }
+});
+
+test("--keep-cut: a pass that lists without touching the cut β no clip moved, removed or added; the editor's re-analysis uses it", async () => {
+ const f = await fixture({ chat: true });
+ try {
+ const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "kept", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s1", target: 60, sitesDir: f.sitesDir });
+ await pointAt(r.dir, f.channelsDir);
+ const mf = path.join(r.dir, "video.manifest.json");
+ const before = await readFile(mf, "utf8");
+ const q = quiet();
+ assert.equal(await clipsCommand(["propose", "kept", "--keep-cut", "--target", "900"], { reportsRoot: f.reportsRoot, ...q }), 0, q.lines.join("\n"));
+ assert.deepEqual(JSON.parse(await readFile(mf, "utf8")).timeline, JSON.parse(before).timeline);
+ const doc = await readReactions(r.dir);
+ const clipIds = JSON.parse(before).timeline.map((c) => c.id).sort();
+ assert.deepEqual(doc.proposals.filter((p) => p.used).map((p) => p.clipId).sort(), clipIds);
+ assert.ok(doc.proposals.some((p) => !p.used), "the rest listed, unused");
+ assert.match(q.lines.join("\n"), /clips \+0 ~0 -0/);
+ // Without it, the larger target adds clips.
+ assert.equal(await clipsCommand(["propose", "kept", "--target", "900"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ assert.ok(JSON.parse(await readFile(mf, "utf8")).timeline.length > clipIds.length);
+ // The job step carries it; the editor's re-analysis of an existing project asks for it.
+ assert.ok(clipsSteps({ id: "kept" }, { mode: "analyze", keepCut: true }).steps[0].argv.includes("--keep-cut"));
+ const { planClipsNew } = await import("./clipsNew.mjs");
+ const again = await planClipsNew({ mode: "new", slug: "kept-2", from: "synth-reacts/react001", segment: "s1" }, { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir });
+ assert.equal(again.created, false);
+ assert.ok(again.plan.steps[0].argv.includes("--keep-cut"));
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs
@@ -24,9 +24,12 @@
// 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";
+import { readdir, readFile, rename, stat, writeFile, mkdir } from "node:fs/promises";
import path from "node:path";
import {
DEFAULT_PARAMS,
@@ -38,9 +41,11 @@ import {
normalizeParams,
wordsFromCues,
} from "yt-dlp-transcript-common/lib/clips/clips.mjs";
-import { applyProposals, fixedClips } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { applyProposals, fixedClips, watchUrlAt } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { REACTIONS_FILE, operatorRoles, readReactions, writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { embedSpans, resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs";
+import { SEGMENT_MIN_S, findSegments, pickSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs";
+import { readChatCues } from "yt-dlp-transcript-common/lib/clips/chat.mjs";
import { clockOffset, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources";
@@ -49,6 +54,7 @@ import { clipMomentKey, readMontageRulings } from "umtool-report-to-video/montag
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { kindMakesTakes } from "../projects/kinds.mjs";
import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
+import { SITES_DIR } from "../paths.mjs";
import { replaceManifest, manifestToken, StaleToken } from "./manifest.mjs";
import { REPO_ROOT } from "../paths.mjs";
import { UMTOOL_DIR } from "./driver.mjs";
@@ -104,6 +110,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 {
@@ -115,6 +122,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,
};
}
@@ -254,9 +263,13 @@ function scanInputs(scans) {
* @param {{ rec: any, scans?: any, params?: Record<string, unknown>, operator?: Record<string, string>, previous?: any,
* timeline?: any[], isProtected?: (e: any) => boolean, audio?: { path: string, kind: string } | null, now?: Date }} o
*/
-export function proposalPass({ rec, scans = null, params = {}, operator = {}, previous = null, timeline = [], isProtected = () => false, audio = null, now = new Date() }) {
+export function proposalPass({ rec, scans = null, params = {}, operator = {}, previous = null, timeline = [], isProtected = () => false, audio = null, now = new Date(), citeUrlAt = null, keepCut = false }) {
const { laughScan, centroids, laughVoices } = scanInputs(scans);
- const fixed = fixedClips(timeline, { channel: rec.channel, video: rec.video, isProtected });
+ const segments = recordingSegments(rec, operator);
+ // `keepCut` (release 36: the editor's Find clips on a project already cut):
+ // every clip stays as it is and nothing is added β the pass only lists.
+ const guard = keepCut ? () => true : isProtected;
+ const fixed = fixedClips(timeline, { channel: rec.channel, video: rec.video, isProtected: guard });
const a = analyze({
turns: rec.turns,
duration: rec.duration,
@@ -268,8 +281,10 @@ 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 proposals = keepCut ? a.proposals.map((p) => (p.fixedClip ? p : { ...p, used: false })) : a.proposals;
+ const applied = applyProposals(timeline, { proposals, channel: rec.channel, video: rec.video, duration: a.duration, words: cleanWords(rec.words), isProtected: guard, citeUrlAt });
const madeAt = now.toISOString();
const doc = {
version: 1,
@@ -289,6 +304,9 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr
moments: a.moments,
proposals: applied.proposals.map((p) => ({ id: p.id, start: p.start, end: p.end, score: p.score, moments: p.moments ?? [], used: p.used, clipId: p.clipId, why: p.why })),
laughSource: a.laughSource,
+ segments,
+ segment: segmentOfScope(segments, a.params.scope),
+ chat: a.chat,
scans: {
laughs: scans?.audio ? { model: scans.audio.model?.file ?? null, windows: scans.audio.windows, madeAt: scans.audio.madeAt ?? null } : null,
voices: scans?.voices ? { model: scans.voices.model ?? null, madeAt: scans.voices.madeAt ?? null } : null,
@@ -296,7 +314,105 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr
madeAt: previous?.madeAt ?? madeAt,
proposedAt: madeAt,
};
- return { doc, timeline: applied.timeline, changes: applied.changes, analysis: a };
+ // Kept means kept: not even re-sorted.
+ return { doc, timeline: keepCut ? timeline : applied.timeline, changes: applied.changes, analysis: a };
+}
+
+// ---- site-less links (release 36 B3) ---------------------------------------------------
+
+/**
+ * Whether a channel is on a public site: in a `site.json`'s `channels` (or
+ * `citedChannels`) with a `siteUrl` to link to. A private site (no siteUrl)
+ * does not count: nobody else can open its links.
+ * @param {string} channel
+ * @param {string} [sitesDir]
+ */
+export async function channelOnPublicSite(channel, sitesDir = SITES_DIR) {
+ let ids;
+ try {
+ ids = await readdir(sitesDir);
+ } catch {
+ return false;
+ }
+ for (const id of ids) {
+ const site = await readJson(path.join(/* turbopackIgnore: true */ sitesDir, id, "site.json"));
+ if (!site || typeof site.siteUrl !== "string" || !site.siteUrl.trim()) continue;
+ const pool = [...(Array.isArray(site.channels) ? site.channels.map((c) => c?.slug) : []), ...(Array.isArray(site.citedChannels) ? site.citedChannels : [])];
+ if (pool.includes(channel)) return true;
+ }
+ return false;
+}
+
+/**
+ * The link rule for a pass: with no siteOrigin and the channel on no public
+ * site, each clip the pass writes links its platform page at its cite
+ * (watchUrlAt over the recording's `webpage_url`); else null (the QR's link
+ * is the site's, as before).
+ * @returns {Promise<((s: number) => string | null) | null>}
+ */
+export async function siteLessLinks(rec, manifest, { sitesDir = SITES_DIR } = {}) {
+ const origin = manifest?.provenance?.siteOrigin;
+ if (typeof origin === "string" && origin.trim()) return null;
+ const url = rec.meta?.webpageUrl ?? null;
+ if (!watchUrlAt(url, 0)) return null;
+ if (await channelOnPublicSite(rec.channel, sitesDir)) return null;
+ return (s) => watchUrlAt(url, s);
+}
+
+// ---- auto-scope (release 36 B1) -----------------------------------------------------
+
+/** The host the operator named, if any (`{index: role}`). */
+function operatorHost(operator) {
+ const k = Object.entries(operator ?? {}).find(([, v]) => v === "host")?.[0];
+ return k === undefined ? null : Number(k);
+}
+
+/** The recording's narrated-video segments (lib/clips/segments.mjs), the operator's host left out of the counting. */
+export function recordingSegments(rec, operator = {}) {
+ return findSegments({ turns: rec.turns, duration: rec.duration, host: operatorHost(operator) });
+}
+
+/** The segment a scope is (its edges within 0.01 s), or null. */
+export function segmentOfScope(segments, scope) {
+ if (!Array.isArray(scope)) return null;
+ const hit = segments.find((g) => Math.abs(g.from - scope[0]) < 0.01 && scope[1] !== null && Math.abs(g.to - scope[1]) < 0.01);
+ return hit ? hit.id : null;
+}
+
+/**
+ * `--scope auto`: the segment named (`segment`), else the longest. When the
+ * recording has none (no cluster holds the long turns for SEGMENT_MIN_S), the
+ * whole recording is read and `note` says so.
+ * @returns {{ scope: [number, number] | null, segment: any, segments: any[], note: string }}
+ */
+export function autoScope(rec, { segment = null, operator = {} } = {}) {
+ const segments = recordingSegments(rec, operator);
+ let seg;
+ try {
+ seg = pickSegment(segments, segment);
+ } catch (e) {
+ throw new ClipsError(e instanceof Error ? e.message : String(e));
+ }
+ if (!seg) {
+ return { scope: null, segment: null, segments, note: `auto-scope: no narrated video found (no speaker holds the long turns for ${SEGMENT_MIN_S} s) β the whole recording is read` };
+ }
+ const list = segments.map((g) => `${g.id} ${Math.round(g.from)}β${Math.round(g.to)} s`).join(", ");
+ return { scope: [seg.from, seg.to], segment: seg, segments, note: `auto-scope: ${seg.id}, ${Math.round(seg.from)}β${Math.round(seg.to)} s (${seg.why}); segments: ${list}` };
+}
+
+/** Params with `scope: "auto"` (and `segment`) resolved against the recording; anything else as given. */
+export function resolveParams(rec, params, operator = {}, say = () => {}) {
+ if (params?.scope !== "auto" && !(params?.segment && params?.scope === undefined)) return params;
+ const r = autoScope(rec, { segment: params.segment ?? null, operator });
+ say(r.note);
+ const { segment: _s, ...rest } = params;
+ return { ...rest, scope: r.scope ?? "all" };
+}
+
+/** The chat in one line: its messages, the lag found and how. */
+export function chatLine(chat) {
+ const how = chat.lag?.how === "xcorr" ? chat.lag.why : `the default (${chat.lag?.why ?? "no lag found"})`;
+ return `chat: ${chat.messages} message(s), ${chat.bursts} laugh burst(s); lag ${chat.lagS} s β ${how}`;
}
/** What a pass did, in one line. */
@@ -307,6 +423,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}` : "")
);
}
@@ -332,11 +449,14 @@ async function rulingsGuard(dir, manifest) {
* what it returns; `umtool clips analyze` then runs the scans and re-proposes.
* @param {{ channelsDir: string, channel: string, video: string, target?: number }} o
*/
-export async function seedReactions({ channelsDir, channel, video, target, laughMin, scope }) {
+export async function seedReactions({ channelsDir, channel, video, target, laughMin, scope, segment = null, siteOrigin = null, sitesDir = SITES_DIR }) {
const rec = await loadRecording({ channelsDir, channel, video });
- const params = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}) };
- const pass = proposalPass({ rec, params });
- return { ...pass, rec };
+ const citeUrlAt = await siteLessLinks(rec, { provenance: { siteOrigin: siteOrigin ?? "" } }, { sitesDir });
+ const notes = [];
+ const given = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}), ...(segment ? { segment } : {}) };
+ const params = resolveParams(rec, given, {}, (n) => notes.push(n));
+ const pass = proposalPass({ rec, params: { ...params, ...(params.scope === "all" ? { scope: null } : {}) }, citeUrlAt });
+ return { ...pass, rec, notes, siteLess: !!citeUrlAt };
}
/**
@@ -347,7 +467,7 @@ export async function seedReactions({ channelsDir, channel, video, target, laugh
* @param {{ project: { id: string, dir: string }, from?: { channel: string, video: string } | null, params?: Record<string, unknown>,
* host?: number | null, wordsFile?: string | null, scans?: any, audio?: any, dry?: boolean, now?: Date }} o
*/
-export async function proposeProject({ project, from = null, params = {}, host = null, wordsFile = null, scans = undefined, audio = null, engine = null, dry = false, now = new Date(), say = () => {} }) {
+export async function proposeProject({ project, from = null, params = {}, host = null, wordsFile = null, scans = undefined, audio = null, engine = null, dry = false, now = new Date(), say = () => {}, sitesDir = SITES_DIR, keepCut = false }) {
for (let attempt = 0; ; attempt += 1) {
const token = await manifestToken(project.dir);
const manifest = await readManifest(project.dir);
@@ -365,10 +485,11 @@ export async function proposeProject({ project, from = null, params = {}, host =
operator[host] = "host";
}
const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video;
- const merged = mergeParams(sameSource ? previous.params : null, params);
+ const merged = mergeParams(sameSource ? previous.params : null, resolveParams(rec, params, operator, attempt === 0 ? say : () => {}));
const s = scans === undefined ? await readScans(project.dir, rec.channel, rec.video) : scans;
const isProtected = await rulingsGuard(project.dir, manifest);
- const passOf = (sc) => proposalPass({ rec, scans: sc, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now });
+ const citeUrlAt = await siteLessLinks(rec, manifest, { sitesDir });
+ const passOf = (sc) => proposalPass({ rec, scans: sc, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now, citeUrlAt, keepCut });
let pass = passOf(s);
// Each laugh's voice (release 35, the live case): embedded once and kept in
// the voices scan, so a pass with a new laughMin or scope embeds only the new ones.
@@ -431,9 +552,10 @@ export function mergeParams(prev, given = {}) {
// ---- the CLI ----------------------------------------------------------------------
export const CLIPS_USAGE = [
- "usage: umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--progress ndjson] [--json]",
- " umtool clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]",
+ "usage: umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--keep-cut] [--progress ndjson] [--json]",
+ " umtool clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--keep-cut] [--dry] [--json]",
" umtool clips show <project> [--json]",
+ " umtool clips segments <project> [--json]",
"",
"The clip finder: a long recording (a stream, a podcast) to proposed clips, written to the",
`manifest (each marked "assist": by the assistant) and to <project>/${REACTIONS_FILE}.`,
@@ -444,8 +566,11 @@ export const CLIPS_USAGE = [
"params: --target S (the cut's length, default 600) --laugh-min X (0..1, default 0.25)",
" --merge-gap S (6) --setup-max S (20) --clip-max S (75); kept in reactions.json for the next run",
"scope: --scope FROM:TO (seconds; TO may be empty: to the end; `all` clears it), or --from S / --to S with numbers:",
- " only that part of the recording is read (a stream that reacts to two videos, one at a time)",
+ " only that part of the recording is read (a stream that reacts to two videos, one at a time);",
+ " --scope auto: the narrated video found in the speakers' turns (--segment s2 names one, else the longest)",
+ " segments the narrated-video spans auto-scope finds in the recording (where one long-turn speaker holds the floor)",
"--host N speaker N is the host (your word: kept until you change it)",
+ "--keep-cut propose without touching the cut: every clip stays, nothing is added (the proposals are listed)",
"A clip you have edited (assist.by \"operator\"), ruled, locked or added is never moved or removed.",
"Needs diarization.json beside the recording (archilyzer diarize backfill --scope video:<channel>/<id>).",
`Words: <project>/${WORDS_FILE} (pnpm ops transcribe {path, words:true, out}), else the corpus transcript.`,
@@ -455,7 +580,7 @@ export const CLIPS_USAGE = [
const PARAM_FLAGS = { "--target": "target", "--laugh-min": "laughMin", "--merge-gap": "mergeGap", "--setup-max": "setupMax", "--clip-max": "clipMax" };
function parse(args) {
- const valued = new Set(["--from", "--to", "--scope", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]);
+ const valued = new Set(["--from", "--to", "--scope", "--segment", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]);
/** @type {Record<string, string[]>} */
const flags = {};
const positional = [];
@@ -482,13 +607,20 @@ export function paramsFromFlags(p) {
};
if (p.has("--scope")) {
const v = String(p.one("--scope"));
- if (v === "all") out.scope = "all";
+ if (v === "all" || v === "auto") out.scope = v;
else {
const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(v);
- if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), or all`);
+ if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), auto, or all`);
out.scope = [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null];
}
}
+ if (p.has("--segment")) {
+ const id = String(p.one("--segment"));
+ if (!/^s\d+$/.test(id)) throw new ClipsError(`--segment ${id}: a segment id (s1, s2, β¦; umtool clips segments <project> lists them)`);
+ if (out.scope !== undefined && out.scope !== "auto") throw new ClipsError("--segment goes with --scope auto (or alone)");
+ out.scope = "auto";
+ out.segment = id;
+ }
if (p.has("--from") && isSeconds(p.one("--from"))) out.scopeFrom = secs("--from", p.one("--from"));
if (p.has("--to")) out.scopeTo = secs("--to", p.one("--to"));
for (const [flag, key] of Object.entries(PARAM_FLAGS)) {
@@ -525,10 +657,12 @@ function showLines(doc) {
const src = doc.source;
lines.push(`${src.channel}/${src.video} ${Math.round(src.duration)} s words: ${src.wordsFrom ?? (src.words ? src.words : "cues")} diarization: ${src.diarization?.generatedAt ?? "?"}`);
for (const s of doc.speakers) lines.push(` speaker ${s.index} ${s.label.padEnd(10)} ${s.role.padEnd(8)} ${String(Math.round(s.seconds)).padStart(6)} s ${String(s.turns).padStart(5)} turns ${s.how}${s.sameAs !== undefined ? ` (same voice as ${s.sameAs})` : ""}`);
- if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}β${doc.params.scope[1] ?? "end"} s`);
+ if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}β${doc.params.scope[1] ?? "end"} s${doc.segment ? ` (segment ${doc.segment})` : ""}`);
+ if (Array.isArray(doc.segments) && doc.segments.length) lines.push(` segments: ${doc.segments.map((g) => `${g.id} ${Math.round(g.from)}β${Math.round(g.to)} s (subject ${g.subject})`).join(", ")}`);
const byVoice = doc.laughs.filter((l) => l.by === "voice").length;
const voiced = doc.laughs.filter((l) => l.voice).length;
lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}${voiced ? `; ${voiced} voice-checked, ${byVoice} re-attributed by voice` : ""}), moments: ${doc.moments.length}`);
+ if (doc.chat) lines.push(` ${chatLine(doc.chat)}`);
const used = doc.proposals.filter((p) => p.used);
lines.push(` proposals: ${doc.proposals.length}, in the cut: ${used.length} (${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of ${doc.params.target} s)`);
for (const p of used) lines.push(` ${p.id} ${(p.clipId ?? "-").padEnd(5)} ${p.start.toFixed(1).padStart(8)}β${p.end.toFixed(1).padEnd(8)} ${p.score.toFixed(2)} ${p.why}`);
@@ -537,6 +671,34 @@ function showLines(doc) {
}
/**
+ * The recording's segments for `umtool clips segments`: found afresh from the
+ * diarization on disk (the operator's host from reactions.json left out), with
+ * which one the project's scope is.
+ */
+export async function projectSegments(project, { from = null } = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new ClipsError(`${project.id} has no manifest`);
+ const previous = await readReactions(project.dir);
+ const src = from ?? (previous ? { channel: previous.source.channel, video: previous.source.video } : null);
+ if (!src) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} yet β say which recording: --from <channel>/<id>`);
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ if (!channelsDir) throw new ClipsError("no channels directory (CHANNELS_DIR)");
+ const rec = await loadRecording({ channelsDir, channel: src.channel, video: src.video, projectDir: project.dir });
+ const segments = recordingSegments(rec, operatorRoles(previous));
+ const scope = previous && previous.source.channel === rec.channel && previous.source.video === rec.video ? previous.params?.scope ?? null : null;
+ return { channel: rec.channel, video: rec.video, duration: Math.round(rec.duration * 100) / 100, scope, segment: segmentOfScope(segments, scope), segments };
+}
+
+function segmentLines(r) {
+ const lines = [`${r.channel}/${r.video} ${Math.round(r.duration)} s ${r.segments.length} segment(s)${r.scope ? `; this project reads ${r.scope[0]}β${r.scope[1] ?? "end"} s` : ""}`];
+ for (const g of r.segments) {
+ lines.push(` ${g.id} ${g.from.toFixed(1).padStart(8)}β${g.to.toFixed(1).padEnd(8)} ${String(Math.round(g.to - g.from)).padStart(5)} s subject ${g.subject}, host ${g.host ?? "?"} ${g.why}${g.id === r.segment ? " (this project's scope)" : ""}`);
+ }
+ if (!r.segments.length) lines.push(" none: no speaker holds the long turns for long enough (a scope by hand: --scope FROM:TO)");
+ return lines;
+}
+
+/**
* `umtool clips β¦`
* @param {string[]} args everything after `clips`
* @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, tagger?: any, engine?: any, now?: Date }} [opts]
@@ -545,11 +707,16 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con
try {
const sub = args[0];
const p = parse(args.slice(1));
- if (!sub || sub === "--help" || sub === "help" || p.has("--help") || !["analyze", "propose", "show"].includes(sub)) {
+ if (!sub || sub === "--help" || sub === "help" || p.has("--help") || !["analyze", "propose", "show", "segments"].includes(sub)) {
log(CLIPS_USAGE);
return sub && sub !== "--help" && sub !== "help" && !p.has("--help") ? 2 : 0;
}
const project = await pickProject(p.positional[0], reportsRoot);
+ if (sub === "segments") {
+ const r = await projectSegments(project, { from: parseFrom(p.one("--from")) });
+ log(p.has("--json") ? JSON.stringify(r, null, 1) : segmentLines(r).join("\n"));
+ return 0;
+ }
if (sub === "show") {
const doc = await readReactions(project.dir);
if (!doc) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} β umtool clips analyze ${project.id} --from <channel>/<id>`);
@@ -590,7 +757,7 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con
} else {
const t0 = Date.now();
const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video;
- const { scope } = mergeParams(sameSource ? previous.params : null, params);
+ const { scope } = mergeParams(sameSource ? previous.params : null, resolveParams(rec, params, operatorRoles(previous)));
scans = await scanRecording({
projectDir: project.dir, rec, audio, laughs: !p.has("--no-laughs"), voices: !p.has("--no-voices"), rescan: p.has("--rescan"),
tagger, engine, scope, onProgress: emit, say,
@@ -599,11 +766,12 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con
}
}
emit({ phase: "propose" });
- const r = await proposeProject({ project, from, params, host, wordsFile: p.one("--words") ?? null, scans, audio, engine, dry: p.has("--dry"), now, say });
+ const r = await proposeProject({ project, from, params, host, wordsFile: p.one("--words") ?? null, scans, audio, engine, dry: p.has("--dry"), now, say, keepCut: p.has("--keep-cut") });
emit({ phase: "done", proposals: r.doc.proposals.length, used: r.doc.proposals.filter((x) => x.used).length, changes: r.changes });
if (p.has("--json")) log(JSON.stringify({ written: r.written, changes: r.changes, reactions: r.doc }, null, 1));
else {
if (!ndjson) log(showLines(r.doc).join("\n"));
+ else if (r.doc.chat) say(chatLine(r.doc.chat));
say(`${r.written ? "" : "(dry run, nothing written) "}${passSummary(r.doc, r.changes)}`);
}
return 0;
@@ -621,7 +789,7 @@ const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin",
* running this command, nice'd (the laugh scan is CPU for a few minutes on a
* long stream, one thread; the proposal pass is arithmetic).
* @param {{ id: string }} project
- * @param {{ mode?: "analyze" | "propose", from?: string, target?: number, host?: number, laughMin?: number, scope?: [number, number | null] }} [req]
+ * @param {{ mode?: "analyze" | "propose", from?: string, target?: number, host?: number, laughMin?: number, scope?: [number, number | null] | "auto" | "all", segment?: string, keepCut?: boolean }} [req]
*/
export function clipsSteps(project, req = {}) {
const mode = req.mode === "propose" ? "propose" : "analyze";
@@ -631,6 +799,9 @@ export function clipsSteps(project, req = {}) {
if (Number.isInteger(req.host) && /** @type {number} */ (req.host) >= 0) argv.push("--host", String(req.host));
if (num(req.laughMin) && req.laughMin >= PARAM_BOUNDS.laughMin[0] && req.laughMin <= PARAM_BOUNDS.laughMin[1]) argv.push("--laugh-min", String(req.laughMin));
if (Array.isArray(req.scope) && num(req.scope[0]) && (req.scope[1] === null || num(req.scope[1]))) argv.push("--scope", `${req.scope[0]}:${req.scope[1] ?? ""}`);
+ else if (req.scope === "auto" || req.scope === "all") argv.push("--scope", req.scope);
+ if (typeof req.segment === "string" && /^s\d+$/.test(req.segment) && req.scope !== "all" && !Array.isArray(req.scope)) argv.push("--segment", req.segment);
+ if (req.keepCut === true) argv.push("--keep-cut");
argv.push("--progress", "ndjson");
return {
kind: `clips-${mode} ${project.id}`,