commit f5542f3117cc7a7a49fec6c8e17aa250b60728d8
parent 323693922df9ac6a7d0b0de6d0ee2435ee0bca9a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 01:25:20 -0400
clips: the live case's findings -- a scope, centroids over the longest turns, each laugh's voice checked, laughMin in the seed and the form, a floor under the ranking (release 35 C1)
- params.scope [from, to|null]: turns, words and laugh windows outside it are
not read; --scope FROM:TO|all, numeric --from/--to, the seed, the form.
- Voice centroids from the longest clean turns: 24 for the two biggest
clusters, 6 for the rest.
- Every laugh's span embedded (kept in the voices scan) and scored against the
host's and subject's centroids: host >= 0.2 and 0.1 over the subject makes
it the host's, the mirror the subject's (`by: "voice"`), else the overlap
rule; `voice: {host, subject}` on each laugh. A narrator's laugh weighs 0.3.
- Proposals under 5 s are widened to 5 s; the ranking never uses one under
5 s or under score 0.2.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
18 files changed, 573 insertions(+), 95 deletions(-)
diff --git a/common/lib/clips/clips.d.mts b/common/lib/clips/clips.d.mts
@@ -1,7 +1,8 @@
export const REACTIONS_VERSION: 1;
-export type Params = { target: number; laughMin: number; mergeGap: number; setupMax: number; clipMax: number };
+export type Scope = [number, number | null];
+export type Params = { target: number; laughMin: number; mergeGap: number; setupMax: number; clipMax: number; scope: Scope | null };
export const DEFAULT_PARAMS: Readonly<Params>;
-export const PARAM_BOUNDS: Readonly<Record<keyof Params, [number, number]>>;
+export const PARAM_BOUNDS: Readonly<Record<Exclude<keyof Params, "scope">, [number, number]>>;
export const SHORT_TURN_S: number;
export const SPREAD_BINS: number;
export const MIN_SPEAKER_SHARE: number;
@@ -12,7 +13,7 @@ export const LAUGH_CLASSES: readonly number[];
export const SCAN_WINDOW_S: number;
export const SCAN_HOP_S: number;
export const LAUGH_BRIDGE_S: number;
-export const LAUGH_WEIGHT: Readonly<{ host: number; none: number; other: number; subject: number }>;
+export const LAUGH_WEIGHT: Readonly<{ host: number; none: number; other: number; subject: number; subjectVoice: number }>;
export const TEXT_LAUGH: Readonly<{ score: number; before: number; after: number }>;
export const TEXT_LAUGH_RE: RegExp;
export const ENERGY_BURST_DB: number;
@@ -26,19 +27,33 @@ export const SILENCE_GAP_S: number;
export const SENTENCE_GAP_S: number;
export const TARGET_SLACK: number;
export const SAME_CLIP_OVERLAP: number;
+export const CLIP_MIN_S: number;
+export const USE_MIN_SCORE: number;
+export const VOICE_MIN: number;
+export const VOICE_MARGIN: number;
export type Turn = { start: number; end: number; speaker: number };
export type Word = { w: string; start: number; end: number; cueStart?: true; conf?: number };
export type Speaker = { index: number; role: Role; label: string; seconds: number; turns: number; how: "auto" | "operator"; sameAs?: number };
-export type Laugh = { start: number; end: number; score: number; speaker: number | null; src?: "text" | "energy" };
+export type Laugh = { start: number; end: number; score: number; speaker: number | null; src?: "text" | "energy"; voice?: { host: number; subject: number }; by?: "voice" };
export type Moment = { id: string; t: number; end: number; kind: "laugh" | "comment"; score: number; speaker: number | null; text: string };
export type Proposal = { id: string; start: number; end: number; score: number; moments: string[]; why: string; used: boolean; clipId?: string | null; fixedClip?: string };
export type LaughScan = { t0?: number; hop?: number; window?: number; scores?: number[] | null; energy?: number[] | null };
export function normalizeParams(given?: Record<string, unknown>): Params;
+export function normalizeScope(v: unknown): Scope | null;
+export function laughKey(l: { start: number; end: number }): string;
+export function laughVoiceSpan(l: { start: number; end: number }): { start: number; dur: number };
+export function voiceLaughs<L extends { start: number; end: number; speaker: number | null }>(
+ laughs: L[],
+ speakers: { index: number; role: string; seconds: number }[],
+ centroids: Record<string, number[] | null> | null,
+ laughVoices: Map<string, number[]> | Record<string, number[]> | null,
+): (L & { voice?: { host: number; subject: number }; by?: "voice" })[];
+export function widenTo(words: Word[], start: number, end: number, min: number, duration?: number): { start: number; end: number };
export function cleanTurns(turns: unknown): Turn[];
-export function turnStats(turns: Turn[], duration: number): { index: number; seconds: number; turns: number; short: number; spread: number; meanTurn: number }[];
-export function assignRoles(o: { turns: Turn[]; duration: number; operator?: Record<string, string>; centroids?: Record<string, number[] | null> | null }): Speaker[];
+export function turnStats(turns: Turn[], duration: number, from?: number): { index: number; seconds: number; turns: number; short: number; spread: number; meanTurn: number }[];
+export function assignRoles(o: { turns: Turn[]; duration: number; operator?: Record<string, string>; centroids?: Record<string, number[] | null> | null; from?: number }): Speaker[];
export function roleMap(speakers: { index: number; role: string }[]): Map<number, string>;
export function wordsFromCues(cues: { start: number; end: number; text?: string }[]): Word[];
export function cleanWords(words: unknown): Word[];
@@ -56,7 +71,7 @@ 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 }[]; 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[] }): Moment[];
export function momentSpan(
m: { t: number; end: number; kind: "laugh" | "comment" },
o: { turns: Turn[]; speakers: { index: number; role: string }[]; words: Word[]; sentences: number[]; setupMax: number; duration: number },
@@ -76,6 +91,7 @@ export function analyze(o: {
operator?: Record<string, string>;
centroids?: Record<string, number[] | null> | null;
laughScan?: LaughScan | null;
+ laughVoices?: Map<string, number[]> | Record<string, number[]> | null;
previous?: { id: string; start: number; end: number }[];
fixed?: { id: string; start: number; end: number }[];
}): {
diff --git a/common/lib/clips/clips.mjs b/common/lib/clips/clips.mjs
@@ -25,7 +25,7 @@
export const REACTIONS_VERSION = 1;
/** The defaults `reactions.json` records under `params`. */
-export const DEFAULT_PARAMS = Object.freeze({ target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75 });
+export const DEFAULT_PARAMS = Object.freeze({ target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75, scope: null });
/** The bounds a param is accepted within (the CLI and the form say so). */
export const PARAM_BOUNDS = Object.freeze({
@@ -61,7 +61,7 @@ export const SCAN_HOP_S = 0.5;
/** Two laugh runs closer than this are one laugh. */
export const LAUGH_BRIDGE_S = 0.5;
/** What a laugh's score is weighted by, by who was talking when it was heard. */
-export const LAUGH_WEIGHT = Object.freeze({ host: 1, none: 0.8, other: 0.6, subject: 0.5 });
+export const LAUGH_WEIGHT = Object.freeze({ host: 1, none: 0.8, other: 0.6, subject: 0.5, subjectVoice: 0.3 });
/** A transcript marker's laugh: its score, and the seconds around the word. */
export const TEXT_LAUGH = Object.freeze({ score: 0.5, before: 0.3, after: 0.7 });
export const TEXT_LAUGH_RE = /^[[(]?(?:laugh(?:s|ter|ing)?|chuckles?|giggles?)[\])]?$|^(?:ha){2,}h?$|^(?:he){2,}h?$|^l+o+l+$|^lmf?ao+$|^rofl$/i;
@@ -89,6 +89,14 @@ export const SENTENCE_GAP_S = 0.6;
export const TARGET_SLACK = 0.03;
/** A proposal overlapping a clip already in the cut by this share is that clip. */
export const SAME_CLIP_OVERLAP = 0.5;
+/** A proposal shorter than this is widened to it around its moment (snapped); shorter ones are never used. */
+export const CLIP_MIN_S = 5;
+/** A proposal scoring under this is never used by the ranking (it stays listed). */
+export const USE_MIN_SCORE = 0.2;
+/** A laugh's voice is the host's when its similarity to the host is at least this… */
+export const VOICE_MIN = 0.2;
+/** …and at least this much more than to the subject (and the mirror for the subject). */
+export const VOICE_MARGIN = 0.1;
const round = (x, d = 2) => (Number.isFinite(x) ? Math.round(x * 10 ** d) / 10 ** d : null);
const clamp01 = (x) => Math.max(0, Math.min(1, x));
@@ -109,9 +117,29 @@ export function normalizeParams(given = {}) {
if (!Number.isFinite(n) || n < lo || n > hi) throw new Error(`${k} must be a number from ${lo} to ${hi}, not ${JSON.stringify(v)}`);
out[k] = n;
}
+ out.scope = normalizeScope(given?.scope);
return out;
}
+/**
+ * The part of the recording the analysis reads: `[from, to]` seconds, or null
+ * for the whole of it (release 35: a stream that reacts to two videos is cut
+ * from one at a time). `to` may be null (to the end).
+ * @param {unknown} v
+ * @returns {[number, number | null] | null}
+ */
+export function normalizeScope(v) {
+ if (v === undefined || v === null || v === "all") return null;
+ if (!Array.isArray(v) || v.length !== 2) throw new Error(`scope must be [from, to] in seconds (or null), not ${JSON.stringify(v)}`);
+ const from = v[0] === null ? 0 : Number(v[0]);
+ const to = v[1] === null ? null : Number(v[1]);
+ if (!Number.isFinite(from) || from < 0 || (to !== null && (!Number.isFinite(to) || to <= from))) {
+ throw new Error(`scope must be [from, to] with 0 ≤ from < to, not ${JSON.stringify(v)}`);
+ }
+ if (from === 0 && to === null) return null;
+ return [from, to];
+}
+
// ---- turns ------------------------------------------------------------------------
/**
@@ -133,8 +161,8 @@ export function cleanTurns(turns) {
* @param {{ start: number, end: number, speaker: number }[]} turns
* @param {number} duration
*/
-export function turnStats(turns, duration) {
- const dur = Math.max(duration || 0, ...turns.map((t) => t.end), 1);
+export function turnStats(turns, duration, from = 0) {
+ const dur = Math.max((duration || 0) - from, ...turns.map((t) => t.end - from), 1);
/** @type {Map<number, { index: number, seconds: number, turns: number, short: number, bins: Set<number> }>} */
const by = new Map();
for (const t of turns) {
@@ -144,7 +172,7 @@ export function turnStats(turns, duration) {
s.seconds += len;
s.turns += 1;
if (len < SHORT_TURN_S) s.short += 1;
- s.bins.add(Math.min(SPREAD_BINS - 1, Math.floor((t.start / dur) * SPREAD_BINS)));
+ s.bins.add(Math.max(0, Math.min(SPREAD_BINS - 1, Math.floor(((t.start - from) / dur) * SPREAD_BINS))));
}
return [...by.values()]
.sort((a, b) => a.index - b.index)
@@ -168,8 +196,8 @@ export function turnStats(turns, duration) {
* operator?: Record<string, string>, centroids?: Record<string, number[] | null> | null }} o
* @returns {{ index: number, role: "host"|"subject"|"other", label: string, seconds: number, turns: number, how: "auto"|"operator", sameAs?: number }[]}
*/
-export function assignRoles({ turns, duration, operator = {}, centroids = null }) {
- const stats = turnStats(turns, duration);
+export function assignRoles({ turns, duration, operator = {}, centroids = null, from = 0 }) {
+ const stats = turnStats(turns, duration, from);
const total = stats.reduce((n, s) => n + s.seconds, 0) || 1;
const op = new Map();
for (const [k, v] of Object.entries(operator ?? {})) {
@@ -496,7 +524,9 @@ export function findMoments({ turns, speakers, laughs, words }) {
const roles = roleMap(speakers);
const laughMoments = laughs.map((l) => {
const raw = l.score * (l.end - l.start);
- const score = (1 - Math.exp(-raw / 1.5)) * LAUGH_WEIGHT[roleOf(roles, l.speaker)];
+ const who = roleOf(roles, l.speaker);
+ const weight = who === "subject" && l.by === "voice" ? LAUGH_WEIGHT.subjectVoice : LAUGH_WEIGHT[who];
+ const score = (1 - Math.exp(-raw / 1.5)) * weight;
return { t: l.start, end: l.end, kind: /** @type {const} */ ("laugh"), score: round(score, 3), speaker: l.speaker };
});
const comments = [];
@@ -613,8 +643,7 @@ export function buildProposals({ moments, turns, speakers, words, duration, para
} else merged.push({ ...s, scores: [...s.scores], moments: [...s.moments], whys: [...s.whys] });
}
return merged.map((m) => {
- let { start } = m;
- const { end } = m;
+ let { start, end } = m;
if (end - start > p.clipMax) {
const from = end - p.clipMax;
const fit = sentences.find((t) => t >= from && t < end - 1);
@@ -622,6 +651,7 @@ export function buildProposals({ moments, turns, speakers, words, duration, para
start = snapEdge(words, start, "start");
if (end - start > p.clipMax) start = end - p.clipMax;
}
+ if (end - start < CLIP_MIN_S) ({ start, end } = widenTo(words, start, end, CLIP_MIN_S, duration));
const sorted = [...m.scores].sort((a, b) => b - a);
const score = clamp01(sorted[0] + 0.1 * sorted.slice(1).reduce((a, b) => a + b, 0));
const whys = [...new Set(m.whys)];
@@ -636,6 +666,21 @@ export function buildProposals({ moments, turns, speakers, words, duration, para
}
/**
+ * A span shorter than `min` widened to it about its middle, inside [0,
+ * duration], each edge snapped into the gap between words (outward).
+ */
+export function widenTo(words, start, end, min, duration = Infinity) {
+ const lim = Number.isFinite(duration) && duration > 0 ? duration : Infinity;
+ const mid = (start + end) / 2;
+ let a = Math.max(0, mid - min / 2);
+ let b = Math.min(lim, a + min);
+ a = Math.max(0, b - min);
+ a = Math.min(start, snapEdge(words, a, "start"));
+ b = Math.max(end, Math.min(lim, snapEdge(words, b, "end")));
+ return { start: round(a), end: round(b) };
+}
+
+/**
* Ids that stay put across a re-proposal: a proposal overlapping a previous
* one by at least half (of the longer of the two) takes its id; the rest get
* the next free numbers, chronologically.
@@ -698,7 +743,8 @@ export function rankIntoTarget(proposals, { target, fixed = [] }) {
const order = proposals.filter((p) => !state.has(p.id)).sort((a, b) => b.score - a.score || a.start - b.start);
for (const p of order) {
const d = p.end - p.start;
- if (total + d <= limit) {
+ if (d < CLIP_MIN_S - 0.01 || p.score < USE_MIN_SCORE) state.set(p.id, { used: false });
+ else if (total + d <= limit) {
total += d;
state.set(p.id, { used: true });
} else state.set(p.id, { used: false });
@@ -721,11 +767,19 @@ export function rankIntoTarget(proposals, { target, fixed = [] }) {
*/
export function analyze(o) {
const params = normalizeParams(o.params);
- const turns = cleanTurns(o.turns);
- const words = cleanWords(o.words);
- const duration = Math.max(Number(o.duration) || 0, turns.at(-1)?.end ?? 0);
- const speakers = assignRoles({ turns, duration, operator: o.operator ?? {}, centroids: o.centroids ?? null });
- const scan = o.laughScan ?? null;
+ const whole = Math.max(Number(o.duration) || 0, cleanTurns(o.turns).at(-1)?.end ?? 0);
+ const from = params.scope ? params.scope[0] : 0;
+ const to = params.scope ? Math.min(params.scope[1] ?? whole, whole) : whole;
+ const inScope = (a, b) => a >= from - 1e-9 && b <= to + 1e-9;
+ // Turns cut to the scope; words and laugh windows wholly inside it.
+ const turns = cleanTurns(o.turns)
+ .filter((t) => t.end > from && t.start < to)
+ .map((t) => ({ ...t, start: Math.max(t.start, from), end: Math.min(t.end, to) }))
+ .filter((t) => t.end - t.start > 0.01);
+ const words = cleanWords(o.words).filter((w) => inScope(w.start, w.end));
+ const duration = to;
+ const speakers = assignRoles({ turns, duration, operator: o.operator ?? {}, centroids: o.centroids ?? null, from });
+ const scan = scopeScan(o.laughScan ?? null, from, to);
let laughsRaw;
let laughSource;
if (scan && Array.isArray(scan.scores) && scan.scores.length) {
@@ -737,7 +791,7 @@ export function analyze(o) {
laughsRaw = [...fromText, ...fromEnergy].sort((a, b) => a.start - b.start);
laughSource = fromEnergy.length || (scan && Array.isArray(scan.energy)) ? "text+energy" : "text";
}
- const laughs = attributeLaughs(laughsRaw, turns, speakers);
+ const laughs = voiceLaughs(attributeLaughs(laughsRaw, turns, speakers), speakers, o.centroids ?? null, o.laughVoices ?? null);
const moments = findMoments({ turns, speakers, laughs, words });
const built = buildProposals({ moments, turns, speakers, words, duration, params });
const withIds = stableIds(built, o.previous ?? []);
@@ -748,8 +802,66 @@ export function analyze(o) {
laughSource,
speakers,
turns,
- laughs: laughs.map((l) => ({ start: l.start, end: l.end, score: l.score, speaker: l.speaker, ...(l.src && l.src !== "model" ? { src: l.src } : {}) })),
+ laughs: laughs.map((l) => ({
+ start: l.start, end: l.end, score: l.score, speaker: l.speaker,
+ ...(l.src && l.src !== "model" ? { src: l.src } : {}),
+ ...(l.voice ? { voice: l.voice } : {}),
+ ...(l.by === "voice" ? { by: "voice" } : {}),
+ })),
moments,
proposals: ranked,
};
}
+
+/** A laugh's key in a cache of laugh voices: its span, 2 dp. */
+export const laughKey = (l) => `${Number(l.start).toFixed(2)}-${Number(l.end).toFixed(2)}`;
+
+/** The seconds embedded for a laugh's voice: at least 1.5 s (at most 8), centred on it. */
+export function laughVoiceSpan(l) {
+ const d = Math.min(8, Math.max(1.5, l.end - l.start));
+ return { start: Math.max(0, (l.start + l.end) / 2 - d / 2), dur: d };
+}
+
+/** The laugh scan's windows wholly inside [from, to]. */
+function scopeScan(scan, from, to) {
+ if (!scan) return null;
+ const t0 = scan.t0 ?? 0;
+ const hop = scan.hop ?? SCAN_HOP_S;
+ const win = scan.window ?? SCAN_WINDOW_S;
+ const len = Math.max(scan.scores?.length ?? 0, scan.energy?.length ?? 0);
+ const a = Math.max(0, Math.ceil((from - t0) / hop - 1e-9));
+ const b = Math.min(len, Math.floor((to - win - t0) / hop + 1e-9) + 1);
+ if (a === 0 && b >= len) return scan;
+ const cut = (arr) => (Array.isArray(arr) ? arr.slice(a, Math.max(a, b)) : arr);
+ return { ...scan, t0: t0 + a * hop, scores: cut(scan.scores), energy: cut(scan.energy) };
+}
+
+/**
+ * Who laughed, by the voice (release 35, the live case: a narrated video's
+ * voice-acted laughs read as the host's by turn overlap, and the host laughing
+ * over a narrated line read as the subject's). With an embedding of the laugh
+ * (`laughVoices`, by laughKey) and the host's and subject's voice centroids,
+ * each laugh gets `voice: {host, subject}` (cosines, 3 dp) and is the host's
+ * when host ≥ VOICE_MIN and host − subject ≥ VOICE_MARGIN, the subject's on the
+ * mirror (`by: "voice"`); else the overlap rule's answer stands.
+ */
+export function voiceLaughs(laughs, speakers, centroids, laughVoices) {
+ if (!centroids || !laughVoices) return laughs;
+ const pick = (role) => speakers.filter((s) => s.role === role && Array.isArray(centroids[s.index])).sort((a, b) => b.seconds - a.seconds)[0];
+ const host = pick("host");
+ const subject = pick("subject");
+ if (!host || !subject) return laughs;
+ const H = centroids[host.index];
+ const S = centroids[subject.index];
+ const get = (k) => (laughVoices instanceof Map ? laughVoices.get(k) : laughVoices[k]);
+ return laughs.map((l) => {
+ const v = get(laughKey(l));
+ if (!Array.isArray(v)) return l;
+ const vh = round(cosineOf(v, H), 3);
+ const vs = round(cosineOf(v, S), 3);
+ const out = { ...l, voice: { host: vh, subject: vs } };
+ if (vh >= VOICE_MIN && vh - vs >= VOICE_MARGIN) return { ...out, speaker: host.index, by: "voice" };
+ if (vs >= VOICE_MIN && vs - vh >= VOICE_MARGIN) return { ...out, speaker: subject.index, by: "voice" };
+ return out;
+ });
+}
diff --git a/common/lib/clips/clips.test.ts b/common/lib/clips/clips.test.ts
@@ -4,8 +4,15 @@ import os from "node:os";
import path from "node:path";
import test from "node:test";
import {
+ CLIP_MIN_S,
DEFAULT_PARAMS,
+ USE_MIN_SCORE,
analyze,
+ laughKey,
+ laughVoiceSpan,
+ normalizeScope,
+ voiceLaughs,
+ widenTo,
assignRoles,
attributeLaughs,
buildProposals,
@@ -197,17 +204,98 @@ test("stableIds: a proposal that overlaps a previous one keeps its id; new ones
assert.deepEqual(again.map((p) => p.id), ["p001", "p003", "p002"]);
});
-test("rankIntoTarget: the best first while they fit; a proposal on a fixed clip is that clip", () => {
+test("rankIntoTarget: the best first while they fit; a proposal on a fixed clip is that clip; too short or too weak is never used", () => {
const props = [
{ id: "p001", start: 0, end: 30, score: 0.2 },
{ id: "p002", start: 40, end: 60, score: 0.9 },
{ id: "p003", start: 70, end: 100, score: 0.5 },
- { id: "p004", start: 110, end: 115, score: 0.1 },
+ { id: "p004", start: 110, end: 115, score: 0.3 },
];
const r = rankIntoTarget(props, { target: 60 });
assert.deepEqual(r.map((p) => [p.id, p.used]), [["p001", false], ["p002", true], ["p003", true], ["p004", true]]);
const f = rankIntoTarget(props, { target: 60, fixed: [{ id: "r009", start: 0, end: 25 }] });
assert.deepEqual(f.map((p) => [p.id, p.used, p.fixedClip ?? null]), [["p001", true, "r009"], ["p002", true, null], ["p003", false, null], ["p004", true, null]]);
+ // The floor: under CLIP_MIN_S, or scoring under USE_MIN_SCORE, stays listed and unused however much room is left.
+ const junk = rankIntoTarget(
+ [
+ { id: "p001", start: 0, end: 2, score: 0.9 },
+ { id: "p002", start: 10, end: 16, score: 0.106 },
+ { id: "p003", start: 20, end: 25, score: USE_MIN_SCORE },
+ ],
+ { target: 600 },
+ );
+ assert.deepEqual(junk.map((p) => [p.id, p.used]), [["p001", false], ["p002", false], ["p003", true]]);
+ assert.equal(CLIP_MIN_S, 5);
+});
+
+test("widenTo + buildProposals: a span under CLIP_MIN_S is widened about its middle, edges in the word gaps", () => {
+ const words = cleanWords(Array.from({ length: 40 }, (_, i) => ({ w: `w${i}`, start: i * 0.5, end: i * 0.5 + 0.4 })));
+ const w = widenTo(words, 9, 10, 5, 100);
+ assert.ok(w.end - w.start >= 5, JSON.stringify(w));
+ assert.ok(w.start <= 9 && w.end >= 10);
+ assert.ok(Math.abs((w.start + w.end) / 2 - 9.5) < 0.3);
+ // Inside the recording.
+ const edge = widenTo(words, 0, 1, 5, 100);
+ assert.equal(edge.start, 0);
+ assert.ok(edge.end >= 5);
+ // A lone short laugh with nothing around it still makes a 5 s proposal.
+ const speakers = [{ index: 0, role: "host", seconds: 10 }];
+ const moments = [{ id: "m001", t: 50, end: 51, kind: "laugh" as const, score: 0.5, speaker: 0, text: "" }];
+ const props = buildProposals({ moments, turns: [{ start: 49, end: 52, speaker: 0 }], speakers, words: [], duration: 100, params: {} });
+ assert.equal(props.length, 1);
+ assert.ok(props[0].end - props[0].start >= 5);
+});
+
+test("scope: only that part of the recording is read; normalizeParams keeps it", () => {
+ assert.equal(normalizeParams({}).scope, null);
+ assert.deepEqual(normalizeParams({ scope: [100, 300] }).scope, [100, 300]);
+ assert.deepEqual(normalizeParams({ scope: [100, null] }).scope, [100, null]);
+ assert.equal(normalizeParams({ scope: [0, null] }).scope, null);
+ assert.equal(normalizeParams({ scope: "all" }).scope, null);
+ assert.throws(() => normalizeScope([300, 100]), /0 ≤ from < to/);
+ assert.throws(() => normalizeScope("x"), /scope must be/);
+ const s = reactionStream();
+ const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { scope: [300, 450], target: 600 } });
+ assert.equal(a.duration, 450);
+ assert.deepEqual(a.params.scope, [300, 450]);
+ assert.ok(a.turns.every((t) => t.start >= 300 && t.end <= 450));
+ // The laugh at 340 is in; 95 and 520 are not.
+ assert.deepEqual(a.laughs.map((l) => Math.round(l.start)), [340]);
+ assert.ok(a.proposals.every((p) => p.end > 300 && p.start < 450));
+ assert.deepEqual(a.speakers.map((x) => [x.index, x.role]), [[0, "host"], [1, "subject"]]);
+});
+
+test("voiceLaughs: a laugh in the subject's voice is the subject's, the host's over a narrated line the host's; else the overlap rule", () => {
+ const speakers = [{ index: 1, role: "host", seconds: 100 }, { index: 4, role: "subject", seconds: 900 }, { index: 7, role: "other", seconds: 5 }];
+ const centroids = { 1: [1, 0, 0], 4: [0, 1, 0], 7: [0, 0, 1] };
+ const laughs = [
+ { start: 10, end: 12, score: 0.5, speaker: 1 }, // overlap said host, the voice is the narrator's
+ { start: 20, end: 21, score: 0.5, speaker: 4 }, // overlap said subject, the voice is the host's
+ { start: 30, end: 31, score: 0.5, speaker: 1 }, // neither voice clearly: the overlap stands
+ { start: 40, end: 41, score: 0.5, speaker: 4 }, // no embedding
+ ];
+ const voices = {
+ [laughKey(laughs[0])]: [0.05, 0.4, 0.1],
+ [laughKey(laughs[1])]: [0.3, 0.02, 0.1],
+ [laughKey(laughs[2])]: [0.15, 0.1, 0.9],
+ };
+ const got = voiceLaughs(laughs, speakers, centroids, voices);
+ assert.deepEqual(got.map((l) => [l.speaker, l.by ?? null]), [[4, "voice"], [1, "voice"], [1, null], [4, null]]);
+ assert.ok(got[0].voice && got[0].voice.subject > got[0].voice.host);
+ assert.equal(got[3].voice, undefined);
+ assert.deepEqual(laughVoiceSpan({ start: 10, end: 10.5 }), { start: 9.5, dur: 1.5 });
+ // Through analyze: the voice decides, and a narrator's laugh weighs less than a host's.
+ const s = reactionStream();
+ const a0 = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan });
+ const lv = Object.fromEntries(a0.laughs.map((l, i) => [laughKey(l), i === 0 ? [0, 1, 0] : [1, 0, 0]]));
+ const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, centroids: { 0: [1, 0, 0], 1: [0, 1, 0] }, laughVoices: lv });
+ assert.equal(a.laughs[0].speaker, SUBJECT);
+ assert.equal(a.laughs[0].by, "voice");
+ assert.deepEqual(a.laughs[0].voice, { host: 0, subject: 1 });
+ assert.equal(a.laughs[1].speaker, HOST);
+ const m0 = a.moments.find((m) => m.kind === "laugh" && m.t === a.laughs[0].start);
+ const was = a0.moments.find((m) => m.kind === "laugh" && m.t === a0.laughs[0].start);
+ assert.ok(m0 && was && m0.score < was.score * 0.5, `${m0?.score} vs ${was?.score}`);
});
test("analyze: deterministic; the model's laughs when there is a scan, the transcript's markers when there is none", () => {
diff --git a/common/lib/clips/scan.d.mts b/common/lib/clips/scan.d.mts
@@ -3,6 +3,7 @@ export const VOICES_VERSION: 1;
export const CHUNK_S: number;
export const CHUNKS_PER_GROUP: number;
export const CED_DIR: string;
+export const PIECES_MAIN: number;
export const PIECES_PER_SPEAKER: number;
export const PIECE_MIN_S: number;
export const PIECE_MAX_S: number;
@@ -59,3 +60,11 @@ export function speakerCentroids(o: {
ffmpeg?: string;
onProgress?: (e: Record<string, unknown>) => void;
}): Promise<{ version: number; model: string; speakers: Record<string, { centroid: number[] | null; pieces: number; kept: number }> }>;
+export function embedSpans(o: {
+ file: string;
+ clock?: number;
+ spans: { key: string; start: number; dur: number }[];
+ engine: { python: string; script: string; model: string; threads?: number };
+ scratch: string;
+ ffmpeg?: string;
+}): Promise<Map<string, number[]>>;
diff --git a/common/lib/clips/scan.mjs b/common/lib/clips/scan.mjs
@@ -9,11 +9,13 @@
// ffmpeg (voiceMatch's decodeSpan), so a 3-hour stream
// never sits in memory; one tagger process per group of
// chunks (the model loads once per group).
-// speakerCentroids a voice centroid per diarization cluster: up to
-// PIECES_PER_SPEAKER of its turns that overlap nobody
-// else, spread over the stream, voiced frames only,
+// speakerCentroids a voice centroid per diarization cluster: its longest
+// turns that overlap nobody (24 for the two clusters with
+// the most seconds, 6 for each other), voiced frames only,
// embedded with TitaNet-small (voiceMatch's embedWavs) and
// averaged robustly — what merges one voice split in two.
+// embedSpans spans embedded as they are: each laugh's voice, scored
+// against the host's and the subject's centroids.
//
// Deterministic for a given model and input; no network; no LLM.
//
@@ -33,7 +35,9 @@ export const CHUNK_S = 300;
export const CHUNKS_PER_GROUP = 4;
/** The default model directory under `<repo>/.diarize/models/`. */
export const CED_DIR = "sherpa-onnx-ced-mini-audio-tagging-2024-04-19";
-export const PIECES_PER_SPEAKER = 12;
+/** Pieces for the two clusters with the most seconds (the voices that matter), and for each of the rest. */
+export const PIECES_MAIN = 24;
+export const PIECES_PER_SPEAKER = 6;
/** A turn shorter than this is not used for a voice centroid. */
export const PIECE_MIN_S = 2;
/** A piece is at most this long. */
@@ -189,22 +193,50 @@ export async function runAudioScan(o) {
}
/**
- * Up to `n` of a cluster's turns for its voice: at least PIECE_MIN_S long,
- * overlapping no other cluster's turn, spread evenly over the stream (sorted
- * by start, every (len−1)/(n−1)-th), each cut to PIECE_MAX_S from its start.
+ * Up to `n` of a cluster's turns for its voice: the LONGEST of those at least
+ * PIECE_MIN_S long that overlap no other cluster's turn (when none is clean,
+ * the longest at all), each the middle PIECE_MAX_S of the turn (0.2 s in from
+ * either end), in time order.
* @param {{ start: number, end: number, speaker: number }[]} turns sorted
*/
export function centroidPieces(turns, speaker, n = PIECES_PER_SPEAKER) {
+ const own = turns.filter((t) => t.speaker === speaker && t.end - t.start >= PIECE_MIN_S);
const others = turns.filter((t) => t.speaker !== speaker);
- const clean = turns.filter(
- (t) => t.speaker === speaker && t.end - t.start >= PIECE_MIN_S && !others.some((o) => o.start < t.end && o.end > t.start),
- );
- let picked = clean;
- if (clean.length > n) {
- picked = [];
- for (let k = 0; k < n; k += 1) picked.push(clean[Math.round((k * (clean.length - 1)) / Math.max(1, n - 1))]);
+ const clean = own.filter((t) => !others.some((o) => o.start < t.end && o.end > t.start));
+ const pool = clean.length ? clean : own;
+ const picked = [...pool].sort((a, b) => b.end - b.start - (a.end - a.start) || a.start - b.start).slice(0, n).sort((a, b) => a.start - b.start);
+ return picked.map((t) => {
+ const d = Math.min(PIECE_MAX_S, t.end - t.start - 0.4);
+ return { start: round((t.start + t.end) / 2 - d / 2, 3), dur: round(d, 3) };
+ });
+}
+
+/**
+ * Embed spans of the sound as they are (no gate): a laugh's voice.
+ * @param {{ file: string, clock?: number, spans: { key: string, start: number, dur: number }[],
+ * engine: { python: string, script: string, model: string, threads?: number }, scratch: string, ffmpeg?: string }} o
+ * @returns {Promise<Map<string, number[]>>} key → embedding (5 dp); a span that would not embed is left out
+ */
+export async function embedSpans(o) {
+ const out = new Map();
+ if (!o.spans.length) return out;
+ await rm(o.scratch, { recursive: true, force: true });
+ await mkdir(o.scratch, { recursive: true });
+ const items = [];
+ for (const [k, sp] of o.spans.entries()) {
+ const x = await decodeSpan(o.file, Math.max(0, sp.start - (o.clock ?? 0)), sp.dur, { ffmpeg: o.ffmpeg });
+ if (x.length < SAMPLE_RATE * 0.5) continue;
+ const wav = path.join(o.scratch, `span-${k}.wav`);
+ await writeFile(wav, encodeWav16(x));
+ items.push({ id: sp.key, wav });
+ }
+ const emb = items.length ? await embedWavs(items, o.engine, o.scratch) : { items: new Map() };
+ for (const it of items) {
+ const v = emb.items.get(it.id)?.embedding;
+ if (Array.isArray(v)) out.set(it.id, v.map((x) => round(x, 5)));
}
- return picked.map((t) => ({ start: t.start, dur: Math.min(PIECE_MAX_S, t.end - t.start) }));
+ await rm(o.scratch, { recursive: true, force: true });
+ return out;
}
/**
@@ -220,10 +252,13 @@ export async function speakerCentroids(o) {
await rm(o.scratch, { recursive: true, force: true });
await mkdir(o.scratch, { recursive: true });
const speakers = [...new Set(o.turns.map((t) => t.speaker))].sort((a, b) => a - b);
+ const seconds = new Map();
+ for (const t of o.turns) seconds.set(t.speaker, (seconds.get(t.speaker) ?? 0) + t.end - t.start);
+ const main = new Set([...speakers].sort((a, b) => (seconds.get(b) ?? 0) - (seconds.get(a) ?? 0) || a - b).slice(0, 2));
const items = [];
const bySpeaker = new Map();
for (const s of speakers) {
- const pieces = centroidPieces(o.turns, s);
+ const pieces = centroidPieces(o.turns, s, main.has(s) ? PIECES_MAIN : PIECES_PER_SPEAKER);
bySpeaker.set(s, []);
for (const [k, p] of pieces.entries()) {
const v = voicedSamples(await decodeSpan(o.file, Math.max(0, p.start - clock), p.dur, { ffmpeg: o.ffmpeg }));
diff --git a/common/lib/clips/scan.test.ts b/common/lib/clips/scan.test.ts
@@ -41,18 +41,21 @@ test("windowLevels: one level per window, loud where the sound is", () => {
assert.ok(lv[4] > -10 && lv[0] < -100, JSON.stringify(lv));
});
-test("centroidPieces: long turns that overlap nobody, spread over the stream", () => {
+test("centroidPieces: the longest turns that overlap nobody (else the longest at all), the middle of each", () => {
const turns = [
{ start: 0, end: 10, speaker: 1 },
{ start: 9, end: 12, speaker: 0 },
{ start: 12, end: 13, speaker: 0 },
{ start: 20, end: 40, speaker: 0 },
];
- assert.deepEqual(centroidPieces(turns, 0), [{ start: 20, dur: 8 }]);
- assert.deepEqual(centroidPieces(turns, 1), []);
- const many = Array.from({ length: 30 }, (_, i) => ({ start: i * 10, end: i * 10 + 3, speaker: 0 }));
+ assert.deepEqual(centroidPieces(turns, 0), [{ start: 26, dur: 8 }]);
+ // Speaker 1's only turn overlaps speaker 0: with nothing clean, the longest at all.
+ assert.deepEqual(centroidPieces(turns, 1), [{ start: 1, dur: 8 }]);
+ const many = Array.from({ length: 30 }, (_, i) => ({ start: i * 10, end: i * 10 + 3 + (i % 3), speaker: 0 }));
const picked = centroidPieces(many, 0, 4);
- assert.deepEqual(picked.map((p) => p.start), [0, 100, 190, 290]);
+ // The four longest (5 s: i = 2, 5, 8, 11), in time order, each 0.2 s in from its ends.
+ assert.deepEqual(picked.map((p) => p.start), [20.2, 50.2, 80.2, 110.2]);
+ assert.ok(picked.every((p) => p.dur === 4.6));
});
test("tagWavs + runAudioScan (fake tagger): the laugh is heard where it is, energy everywhere, chunked", { skip: !ffmpeg && "no ffmpeg" }, async () => {
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,7 +1,7 @@
# Changelog
## [Unreleased]
-- **umtool proposes highlights from a long recording.** Create → **Highlights from a recording** (or the new-project form's seed "highlights", or `umtool new <slug> --seed reactions --from <channel>/<id> --target 600`) takes a stream or podcast whose speakers the editor has found (its diarization) and proposes clips: each runs from the line that set it up, through the host's laugh or comment, to the next pause. The host is the speaker who interjects all the way through (you can say otherwise: `--host N`, or the clip editor's "This is the host"). Laughs are heard by a small local sound model (CED-mini, installed under `.diarize/models/`), and without it read from the transcript ("[laughter]", "haha") and the host's loud wordless moments. The clips are ranked into the target length, put in the video manifest in time order with hard cuts, and each is marked as proposed by the assistant, with its score and why; the rest stay listed in `reactions.json` beside the manifest to bring in by hand. `umtool clips analyze <project>` runs the scans on the recording's sound (a few minutes for a 2.5-hour stream, kept for the next run) and proposes again; `umtool clips propose` proposes again after a change of host or length, and never moves or removes a clip you edited, ruled, locked or added. A recording with no diarization is refused with the command that makes it. Nothing calls an AI model, and nothing leaves the machine. Needs a restart of umtool.
+- **umtool proposes highlights from a long recording.** Create → **Highlights from a recording** (or the new-project form's seed "highlights", or `umtool new <slug> --seed reactions --from <channel>/<id> --target 600`) takes a stream or podcast whose speakers the editor has found (its diarization) and proposes clips: each runs from the line that set it up, through the host's laugh or comment, to the next pause. The host is the speaker who interjects all the way through (you can say otherwise: `--host N`, or the clip editor's "This is the host"). Laughs are heard by a small local sound model (CED-mini, installed under `.diarize/models/`), and without it read from the transcript ("[laughter]", "haha") and the host's loud wordless moments. The clips are ranked into the target length, put in the video manifest in time order with hard cuts, and each is marked as proposed by the assistant, with its score and why; the rest stay listed in `reactions.json` beside the manifest to bring in by hand. `umtool clips analyze <project>` runs the scans on the recording's sound (a few minutes for a 2.5-hour stream, kept for the next run) and proposes again; `umtool clips propose` proposes again after a change of host or length, and never moves or removes a clip you edited, ruled, locked or added. Each laugh is also checked against the host's and the narrator's voices, so a laugh voice-acted in the video he is watching is not taken for his. `--scope FROM:TO` (or the form's From/To) reads only part of a recording — a stream that reacts to two videos, one at a time — and the laugh bar is `--laugh-min` (the form's **Laugh min**). Proposals under five seconds or with a low score are listed but never put in the cut. A recording with no diarization is refused with the command that makes it. Nothing calls an AI model, and nothing leaves the machine. Needs a restart of umtool.
- **The report-video test suite passes in the Docker image.** Run inside `archilyzer:r33-umtool` (Debian's ffmpeg 7.1), six report-to-video tests failed that pass on a newer ffmpeg. Four came from how the tests drove ffmpeg, not from the videos it renders: they now run the graphs the way a build does. One compared against an older ffmpeg's timing drift, which 7.1 does not show; it is now only checked where the drift happens. The sixth needs a git checkout, which an image does not include, and now says so and skips. Nothing a build renders changed.
- **umtool scores who is speaking in each montage clip.** A montage's clip deck and its Cut tab have **Score the voices**: each clip's phrase (and a second either side, its speech only) is compared with the host's voice, and every Cut-tab row then reads `voice 0.43 · unsure` — likely, unsure or unlikely him — and the deck puts the doubtful clips first with their scores. The host's voice is the clips you ruled keep in the audition deck once there are three, or before that solo uploads of the channel found on disk (captioned, no speaker change in the captions, not a stream, no guest in the title, spread over the years); the picker beside the button chooses. It runs on this machine with the speaker model the diarization lane already uses — no network, no AI model — and takes about half a minute for 73 clips. It sorts and flags; whether it is him is still decided by ear. The scores are kept in `voice-match.json` beside the manifest, by the source moment, so a re-seeded montage keeps them. The same from a terminal: `umtool voice-match <project>`. Needs a restart of umtool.
- **A montage's closing wall is the right length on older ffmpeg.** With ffmpeg 7.1 (the umtool Docker image), a tile did not hold its last frame after saying its phrase and did not wait for its turn, so the wall came out short of the length its plan gives (23 frames on the test cut) and, with groups, tiles vanished instead of freezing. The tiles now hold and wait on ffmpeg 7.1 as they do on newer versions; renders on the newer ffmpeg are unchanged.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10605,14 +10605,14 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
- **`<project>/reactions.json`** `{version: 1, source {channel, video, duration, words: "words.json" | null, wordsFrom
"words.json"|"transcript.json"|"cues"|<--words basename>, diarization {generatedAt, engine}, audio?, audioKind?},
- params {target 600, laughMin 0.25, mergeGap 6, setupMax 20, clipMax 75}, speakers [{index, role "host"|"subject"|
+ params {target 600, laughMin 0.25, mergeGap 6, setupMax 20, clipMax 75, scope [from, to|null] | null}, speakers [{index, role "host"|"subject"|
"other", label "Host"|"Subject"|"Speaker N+1", seconds, turns, how "auto"|"operator", sameAs?}], turns [{start, end,
- speaker}], laughs [{start, end, score, speaker: n|null, src? "text"|"energy"}], moments [{id m001…, t, end, kind
+ speaker}], laughs [{start, end, score, speaker: n|null, src? "text"|"energy", voice? {host, subject}, by? "voice"}], moments [{id m001…, t, end, kind
"laugh"|"comment", score, speaker: n|null, text}], proposals [{id p001…, start, end, score, moments[], used, clipId
"r001"|null, why}], laughSource "model"|"text"|"text+energy", scans {laughs {model, windows, madeAt} | null, voices
{model, madeAt} | null}, madeAt, proposedAt, rolesChangedAt?}`. The plan's shape (plans/release-35/clip-finder.md)
- plus the optional keys `wordsFrom`, `audio*`, `sameAs`, `src`, `laughSource`, `scans`, `madeAt`, `proposedAt`,
- `rolesChangedAt`, and `speaker: null` on a laugh/moment heard in no turn. Writers: `writeReactions` (tmp + rename,
+ plus the optional keys `wordsFrom`, `audio*`, `sameAs`, `src`, `voice`, `by`, `params.scope`, `laughSource`, `scans`,
+ `madeAt`, `proposedAt`, `rolesChangedAt`, and `speaker: null` on a laugh/moment heard in no turn. Writers: `writeReactions` (tmp + rename,
whole) from the analysis, and `setSpeakerRole(dir, index, role|null)` (the clip editor's only write): role +
`how: "operator"`, every OTHER speaker that held that host/subject role → "other"/auto (one host, one subject; a
`sameAs` of this one keeps it); null hands it back (`how: "auto"`); stamps `rolesChangedAt`. Module
@@ -10652,3 +10652,15 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
lib/jobs.ts step `nice -n 10 node umtool/bin/umtool.mjs clips <mode> <id> … --progress ndjson` (events `{ev: "clips",
phase: load|laughs|voices|propose|done, …}`), timeout 90 min (analyze) / 5 min (propose). GET `?project=` summarizes
reactions.json. The new-project form posts `mode: "analyze"` right after creating a reactions project.
+- **The scope** (`params.scope`, the live case's addendum): turns cut to [from, to], words and laugh windows wholly
+ inside it, `duration` = to, the role spread measured over the scope; voice centroids from the scope's turns (the
+ voices cache key carries it, `scope: "<from>-<to|end>"|"all"`). CLI `--scope FROM:TO|all`, or numeric `--from S` /
+ `--to S` (one end; a non-numeric `--from` is the recording); the form's From s / To s; the seed's `scope`.
+- **Laugh voices**: every laugh's span (≥ 1.5 s, ≤ 8 s, centred; `laughVoiceSpan`) embedded raw (`embedSpans`, no gate)
+ and kept in `.voices.json` `laughs {"<start>-<end>" (2 dp): embedding}` across re-scans of the same file; a propose
+ embeds only missing ones (it opens the sound). `voiceLaughs`: cosine to the centroid of the host (resp. subject)
+ speaker with the most seconds; ≥ 0.2 and ≥ 0.1 over the other → that speaker, `by: "voice"`; else the overlap rule.
+ A laugh the voice gives the subject weighs 0.3 (LAUGH_WEIGHT.subjectVoice). Centroid pieces: the longest clean turns
+ ≥ 2 s (else the longest at all), 24 for the two clusters with the most seconds, 6 for the rest, each the middle ≤ 8 s.
+- **The floor**: a proposal under CLIP_MIN_S (5 s) is widened to 5 s about its middle (`widenTo`, snapped outward)
+ before ranking; `rankIntoTarget` never uses one under 5 s or scoring under USE_MIN_SCORE (0.2) — it stays listed.
diff --git a/plans/release-35/clip-analysis.md b/plans/release-35/clip-analysis.md
@@ -39,12 +39,27 @@ speaker turns, words and sound to clip proposals in a report-video manifest, eac
its sound, and `writeReactionCorpus`), `testing/audio/fakeAudioTag.mjs` (the shim's stand-in: it hears the
stream's 1.5 kHz laugh tone). The umtool e2e app runs the fake tagger (`AUDIO_TAG_*` in playwright.config.ts).
+### The live case's findings, folded in (the orchestrator's run on the first case)
+
+- **Scope**: `params.scope: [from, to|null] | null` — turns cut to it, words and laugh windows wholly inside it,
+ duration = its end; CLI `--scope FROM:TO|all` or numeric `--from S --to S` (the plan's `--from <channel>/<id>`
+ keeps its meaning: a number is the scope); the seed and the form (From s / To s) take it.
+- **Centroids computed in `clips analyze`**: the longest clean turns, 24 for the two clusters with the most seconds,
+ 6 for each other (30 clusters at threshold 0.9 on the live case; host and subject at cosine 0.02).
+- **Laugh voice check**: each laugh's span (≥ 1.5 s, centred) embedded; host if host ≥ 0.2 and host − subject ≥ 0.1,
+ subject on the mirror (`by: "voice"`), else the overlap rule; `voice: {host, subject}` on every checked laugh; a
+ laugh the voice gives the subject weighs 0.3. Embeddings kept in the voices scan.
+- **laughMin** settable from the CLI (`--laugh-min`, already), the seed (`umtool new … --laugh-min`) and the form
+ (**Laugh min**); default stays 0.25.
+- **The floor**: proposals under 5 s are widened to 5 s (snapped) before ranking; `rankIntoTarget` never uses one
+ under 5 s or under score 0.2.
+
## The shapes (owned here; C2 codes against them)
Exactly the plan's, plus optional keys (FACTS.md, "Release 35 lane C1"): `source.wordsFrom`, `source.audio`,
`source.audioKind`, `speakers[].sameAs`, `laughs[].src` ("text" | "energy"; absent = the model), `laughSource`,
`scans`, `madeAt`, `proposedAt`, `rolesChangedAt`; `speaker: null` on a laugh or moment heard in no turn; an unused
-proposal has `clipId: null`. A proposal's `start`/`end` IS the clip's cut (`cutStart`/`cutEnd`); the clip's
+proposal has `clipId: null`; laughs may carry `voice: {host, subject}` and `by: "voice"`; `params.scope`. A proposal's `start`/`end` IS the clip's cut (`cutStart`/`cutEnd`); the clip's
window is 1.5 s wider each side (`assist.original` carries all four).
## Rulings followed
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -713,7 +713,7 @@ 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] [--no-analyze]: the clip finder on a long",
+ " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO] [--no-analyze]: the clip finder on a long",
" recording (needs its diarization.json): highlights proposed from the host's laughs and comments,",
" then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze",
" [--brand archilyzer-media] render.brand: the report-to-video brand preset",
@@ -1135,6 +1135,13 @@ async function cmdIndex() {
// Scaffolding. The writer is lib/projects/scaffold.mjs, shared with the route.
// ---------------------------------------------------------------------------
+/** `--scope FROM:TO` (seconds; either side may be empty). */
+function parseScopeFlag(v) {
+ const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(String(v));
+ if (!m) die(`--scope ${v}: FROM:TO in seconds (either may be empty)`);
+ return [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null];
+}
+
async function cmdNew() {
const slug = positional[0];
if (!slug) {
@@ -1143,7 +1150,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>] [--no-analyze]]",
+ " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO] [--no-analyze]]",
);
}
const kind = val("--kind") ?? "report-video";
@@ -1169,6 +1176,8 @@ async function cmdNew() {
}
: {}),
...(val("--max") != null ? { max: Number(val("--max")) } : {}),
+ ...(val("--laugh-min") != null ? { laughMin: Number(val("--laugh-min")) } : {}),
+ ...(val("--scope") != null ? { scope: parseScopeFlag(val("--scope")) } : {}),
});
} catch (e) {
die(e?.message ?? String(e));
diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx
@@ -35,7 +35,8 @@ import { useHydrated } from "@/components/ui/use-hydrated";
// Release 35: [data-new-max] caps the reel at N instances spread across the years.
// Release 35 C1: [data-new-seed] offers "highlights" (the clip finder, when the
// recording has its speakers: diarization.json), its target in [data-new-target]
-// (seconds, default 600); creating one starts "Find the clips" (the laugh scan
+// (seconds, default 600), [data-new-laugh-min] and the scope [data-new-scope-from]/
+// [data-new-scope-to]; creating one starts "Find the clips" (the laugh scan
// and the voices, then proposals) as a job, and opens the project.
type Brand = { id: string; label: string };
@@ -48,6 +49,8 @@ const FIELD_HINT: Record<string, string> = {
seed: "seed the timeline from the video's digest chapters, or from its frame scan's events (review each)",
target: "the frame-scan cut's length budget: the events ranked into this many seconds (10 to 3600)",
highlights: "the highlights' length: the proposed clips ranked into this many seconds (10 to 7200)",
+ laughMin: "how sure the sound model must be that a second is laughter, 0.01 to 1 (default 0.25; lower finds more)",
+ scope: "read only this part of the recording, in seconds (empty: from the start / to the end)",
phrase: "a regular expression, any case — e.g. slow[ ,]+news (day|week)",
channels: "the channel slugs to scan, separated by commas",
prefer: "the channel to cut from where it holds a copy of the same stream (optional)",
@@ -105,6 +108,9 @@ export default function NewProjectMenu({
const [max, setMax] = useState("");
const [target, setTarget] = useState("240");
const [hlTarget, setHlTarget] = useState("600");
+ const [laughMin, setLaughMin] = useState("0.25");
+ const [scopeFrom, setScopeFrom] = useState("");
+ const [scopeTo, setScopeTo] = useState("");
// What the video can be seeded from (null: not asked yet, or not a video).
const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean; reactions: boolean } | null>(null);
const [brand, setBrand] = useState("");
@@ -152,7 +158,11 @@ export default function NewProjectMenu({
} else if (fields.includes("seed") && seed && seed !== "phrase" && looksLikeVideo) {
body.seed = seed;
if (seed === "frames") body.target = Number(target);
- if (seed === "reactions") body.target = Number(hlTarget);
+ if (seed === "reactions") {
+ body.target = Number(hlTarget);
+ if (laughMin.trim()) body.laughMin = Number(laughMin.trim());
+ if (scopeFrom.trim() || scopeTo.trim()) body.scope = [scopeFrom.trim() || null, scopeTo.trim() || null];
+ }
}
if (fields.includes("brand") && brand) body.brand = brand;
const res = await fetch("/api/projects/new", {
@@ -370,6 +380,19 @@ export default function NewProjectMenu({
/>
</Field>
)}
+ {asksSeed && seed === "reactions" && (
+ <>
+ <Field label="Laugh min">
+ <Input value={laughMin} onChange={(e) => setLaughMin(e.target.value)} inputMode="decimal" aria-label={`laugh min — ${FIELD_HINT.laughMin}`} title={FIELD_HINT.laughMin} data-new-laugh-min className="num w-20" />
+ </Field>
+ <Field label="From s">
+ <Input value={scopeFrom} onChange={(e) => setScopeFrom(e.target.value)} inputMode="numeric" placeholder="start" aria-label={`from seconds — ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-from className="num w-20" />
+ </Field>
+ <Field label="To s">
+ <Input value={scopeTo} onChange={(e) => setScopeTo(e.target.value)} inputMode="numeric" placeholder="end" aria-label={`to seconds — ${FIELD_HINT.scope}`} title={FIELD_HINT.scope} data-new-scope-to className="num w-20" />
+ </Field>
+ </>
+ )}
<div className="flex items-center gap-2 pb-px">
<Button type="submit" variant="go" disabled={!hydrated || busy || !slug.trim()} data-new-create>
{busy ? "Creating…" : submitLabel}
diff --git a/umtool/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>]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--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>]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO] [--no-analyze]` | scaffold |
| `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there |
| `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch |
| `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building |
@@ -45,7 +45,7 @@ Inbox cannot disagree about what is wrong with one.
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `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), 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]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
A project argument is an exact id, a directory, or a **unique** basename. Two
projects answering to one name is reported, never resolved by picking one.
@@ -225,7 +225,9 @@ proposal, score, why, original}`, chronological, hard cuts
(`render.transition: 0`); `reactions.json` beside the manifest keeps the whole
analysis and every proposal, used or not. The seed reads laughs from the
transcript alone; `umtool new` then runs `umtool clips analyze` (the laugh scan
-and the voices on the sound) unless `--no-analyze`. The new-project form's seed
+and the voices on the sound) unless `--no-analyze`. `--laugh-min X` sets the laugh
+bar and `--scope FROM:TO` reads only that part of the recording (a stream that
+reacts to two videos, one at a time); both are kept for the next pass. The new-project form's seed
"highlights" (and Create's **Highlights from a recording**) does the same and
starts the scan as a job.
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -931,23 +931,36 @@ What it reads, and what it does without:
(`AUDIO_TAG_MODEL`). Without it: the transcript's laugh markers (`[laughter]`,
`haha`, `lol`, `lmao`) and the host's loud wordless bursts.
-The steps:
+The steps (over the **scope**, when one is set: `--scope FROM:TO`, or the form's
+From/To — turns, words and laugh windows outside it are not read, and the
+recording ends at its `to`):
1. **Roles.** The host is the speaker with the most turns under 8 s times the
widest spread over the recording (a reaction stream's host interjects all the
way through; the narrated video talks in long runs); the subject is the one
with the most seconds among the rest; a speaker under 1 % of the speech is
- never either by itself. A third cluster whose voice centroid (TitaNet-small,
- a few clean turns each) is 0.6 or more like the host's or the subject's takes
- that role (`sameAs`). Your word beats all of it: **This is the host** in the
+ never either by itself. A third cluster whose voice centroid (TitaNet-small
+ over its longest turns that overlap nobody: 24 for the two clusters with the
+ most seconds, 6 for each other) is 0.6 or more like the host's or the
+ subject's takes that role (`sameAs`). A diarization that splits the stream
+ into 30 clusters is normal; the small ones that match neither voice stay
+ `other`. Your word beats all of it: **This is the host** in the
clip editor, or `--host N`, is kept (`how: "operator"`) until you change it.
2. **Laughs.** CED-mini over 1 s windows every 0.5 s; the laughter family
(Laughter, Giggle, Snicker, Belly laugh, Chuckle — not Baby laughter) summed,
at most 1; runs at or over `laughMin` (0.25) are laughs, joined across a 0.5 s
gap, each the speaker's who was talking (a host turn that overlaps makes it
- the host's — he laughs over the video).
+ the host's — he laughs over the video). Then **the voice decides** when it
+ can: each laugh's seconds (at least 1.5 s, centred) are embedded and compared
+ with the host's and the subject's centroids (`voice: {host, subject}` on the
+ laugh); at 0.2 or more and 0.1 above the other, the laugh is that speaker's
+ (`by: "voice"`) — a narrated video's voice-acted laugh is the subject's, the
+ host laughing over a narrated line is the host's. Laugh voices are kept in
+ the voices scan, so a pass with a new laugh bar or scope embeds only the new
+ ones (it reads the sound for those).
3. **Moments.** Every laugh (its strength × its length, squashed to 0–1, weighed
- by who laughed: the host 1, nobody 0.8, another speaker 0.6, the subject 0.5)
+ by who laughed: the host 1, nobody 0.8, another speaker 0.6, the subject 0.5,
+ the subject by voice 0.3)
and every host turn with 1.5 s of words or more (half its length, half the
strongest laugh around it).
4. **Proposals.** From the start of the subject's sentence that set the moment
@@ -956,9 +969,10 @@ The steps:
the next pause (at most 1.5 s), edges in the gaps between words; overlapping
spans merged, spans closer than `mergeGap` (6 s) merged while the whole fits
`clipMax` (75 s); a longer one keeps its end and starts on the latest
- sentence that fits. Ranked by score into `target` seconds (600, 3 % over
- allowed); the rest stay in `reactions.json` with `used: false`, for the
- clip editor's unused list.
+ sentence that fits; a shorter one than 5 s is widened to 5 s about its middle,
+ edges in the word gaps. Ranked by score into `target` seconds (600, 3 % over
+ allowed) — a proposal scoring under 0.2, or under 5 s, is never used; the rest
+ stay in `reactions.json` with `used: false`, for the clip editor's unused list.
5. **Clips.** Each used proposal is a clip `r001…` — the cut is the proposal,
the window 1.5 s wider each side for trimming, `quote` its words — with
`assist: {by: "assistant", proposal, score, why, original, edits: []}`, in
@@ -980,12 +994,12 @@ reused while the sound file, the model and the diarization are the same
(`--rescan` makes them again). A 2.5-hour stream's laugh scan is about 18,500
windows, a few minutes on one CPU thread.
-`reactions.json`: `{version: 1, source: {channel, video, duration, words:
+`reactions.json`: `{version: 1, source: {channel, video, duration (the scope's end), words:
"words.json" | null, wordsFrom, diarization: {generatedAt, engine}, audio?,
-audioKind?}, params: {target, laughMin, mergeGap, setupMax, clipMax},
+audioKind?}, params: {target, laughMin, mergeGap, setupMax, clipMax, scope: [from, to|null] | null},
speakers: [{index, role: "host"|"subject"|"other", label, seconds, turns, how:
"auto"|"operator", sameAs?}], turns: [{start, end, speaker}], laughs: [{start,
-end, score, speaker: n|null, src?: "text"|"energy"}], moments: [{id, t, end,
+end, score, speaker: n|null, src?: "text"|"energy", voice?: {host, subject}, by?: "voice"}], moments: [{id, t, end,
kind: "laugh"|"comment", score, speaker: n|null, text}], proposals: [{id, start,
end, score, moments, used, clipId: "r001"|null, why}], laughSource:
"model"|"text"|"text+energy", scans: {laughs, voices}, madeAt, proposedAt,
diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts
@@ -237,6 +237,8 @@ test("Highlights from a recording: the clip finder proposes clips marked by the
await expect(seed.locator("option[value=reactions]")).toBeEnabled();
await expect(f.locator("[data-new-target]")).toHaveValue("600");
await f.locator("[data-new-target]").fill("60");
+ await f.locator("[data-new-laugh-min]").fill("0.15");
+ await f.locator("[data-new-scope-to]").fill("500");
await f.locator("[data-new-slug]").fill("p35-hl");
await f.getByRole("button", { name: "Find the clips" }).click();
await page.waitForURL(/\/projects\/p35-hl$/, { timeout: 20_000 });
@@ -249,6 +251,8 @@ test("Highlights from a recording: the clip finder proposes clips marked by the
}
const reactions = () => JSON.parse(readFileSync(path.join(FIXTURE, "p35-hl", "reactions.json"), "utf8"));
expect(reactions().params.target).toBe(60);
+ expect(reactions().params.laughMin).toBe(0.15);
+ expect(reactions().params.scope).toEqual([0, 500]);
// "Find the clips" ran as umtool's job: the CLI, with no sound on disk, proposes from the transcript.
await expect.poll(async () => (await (await request.get("/api/jobs")).json()).running, { timeout: 60_000 }).toBeNull();
const summary = (await (await request.get("/api/report/clips?project=p35-hl")).json()).reactions;
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -8,7 +8,7 @@ import path from "node:path";
import { BRAND_IDS } from "umtool-report-to-video/brand-ids";
import { FRAMES_CUT_DEFAULTS, framesCut } from "umtool-report-to-video/frames-cut";
import { capInstances, instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs";
-import { PARAM_BOUNDS } from "yt-dlp-transcript-common/lib/clips/clips.mjs";
+import { PARAM_BOUNDS, normalizeScope } from "yt-dlp-transcript-common/lib/clips/clips.mjs";
import { writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs";
@@ -247,9 +247,9 @@ const capNote = (max, kept, found) =>
* (common/lib/montage/phraseScan.mjs `capInstances`); the rest are listed in
* phrase-scan.json as `skippedByCap`. No `max`: the output is what it was.
*
- * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null }} args
+ * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | null }} args
*/
-export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null }) {
+export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null }) {
if (!SLUG_RE.test(String(slug ?? ""))) {
throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
}
@@ -287,6 +287,11 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
throw new Error(`--max must be a whole number of clips from 1 to ${MAX_PHRASE_CAP}`);
}
const capped = max !== null && max !== undefined;
+ if ((laughMin !== undefined || scope) && seed !== "reactions") throw new Error("--laugh-min and --scope go with --seed reactions");
+ if (laughMin !== undefined && !(Number.isFinite(laughMin) && laughMin >= PARAM_BOUNDS.laughMin[0] && laughMin <= PARAM_BOUNDS.laughMin[1])) {
+ throw new Error(`--laugh-min must be a number from ${PARAM_BOUNDS.laughMin[0]} to ${PARAM_BOUNDS.laughMin[1]}`);
+ }
+ const reactionsScope = seed === "reactions" ? normalizeScope(scope) : null;
if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed");
if (target !== undefined && seed !== "frames" && 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];
@@ -382,7 +387,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
let reactionsSeeded = null;
if (seed === "reactions") {
const { seedReactions } = await import("../report/reactions.mjs");
- const pass = await seedReactions({ channelsDir, channel: src.channel, video: src.video, ...(target !== undefined ? { target } : {}) });
+ const pass = await seedReactions({
+ channelsDir, channel: src.channel, video: src.video,
+ ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(reactionsScope ? { scope: reactionsScope } : {}),
+ });
doc.timeline = pass.timeline;
// Hard cuts: a highlights reel.
doc.render.transition = 0;
@@ -392,6 +400,7 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
const host = pass.doc.speakers.find((s) => s.role === "host");
notes.push(`${pass.doc.proposals.length} proposal(s), ${used.length} in the cut: ${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of a ${pass.doc.params.target} s target (--target)`);
notes.push(`the host: speaker ${host ? host.index : "?"} of ${pass.doc.speakers.length} (by turn statistics — flip it in the clip editor or with umtool clips propose ${slug} --host N)`);
+ if (reactionsScope) notes.push(`only ${reactionsScope[0]}–${reactionsScope[1] ?? "the end"} s of the recording is read (--scope)`);
notes.push(`laughs from the transcript only (${pass.doc.laughs.length}); umtool clips analyze ${slug} runs the laugh scan and the voices on the sound, then proposes again`);
if (pass.rec.wordsFrom === "cues") notes.push("no word timings: edges sit on the cues; pnpm ops transcribe {path, words:true, out: <project>/words.json} gives words, then umtool clips propose");
if (!pass.doc.proposals.length) notes.push("nothing to propose: no host comments or laughs were found");
diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts
@@ -31,6 +31,9 @@ export type NewProjectBody = {
scan?: { id?: string; row?: string } | null;
// The phrase seed's cap (release 35): N instances spread across the years.
max?: number | string | null;
+ // The reactions seed (release 35 C1): the laugh bar and the part of the recording read.
+ laughMin?: number | string | null;
+ scope?: [number | string | null, number | string | null] | null;
};
/**
@@ -83,6 +86,10 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
...(body.max !== undefined && body.max !== null && body.max !== "" ? { max: Number(body.max) } : {}),
}
: {}),
+ ...(body.seed === "reactions" && body.laughMin !== undefined && body.laughMin !== null && body.laughMin !== "" ? { laughMin: Number(body.laughMin) } : {}),
+ ...(body.seed === "reactions" && Array.isArray(body.scope)
+ ? { scope: [body.scope[0] === null || body.scope[0] === "" ? 0 : Number(body.scope[0]), body.scope[1] === null || body.scope[1] === "" ? null : Number(body.scope[1])] as [number, number | null] }
+ : {}),
...((body.seed === "frames" || body.seed === "reactions") && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}),
});
result = { ...r, href: `/projects/${r.id}` };
diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs
@@ -33,11 +33,14 @@ import {
PARAM_BOUNDS,
analyze,
cleanWords,
+ laughKey,
+ laughVoiceSpan,
+ normalizeParams,
wordsFromCues,
} from "yt-dlp-transcript-common/lib/clips/clips.mjs";
import { applyProposals, fixedClips } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { REACTIONS_FILE, operatorRoles, readReactions, writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
-import { resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs";
+import { embedSpans, resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs";
import { clockOffset, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources";
@@ -173,7 +176,7 @@ async function readSettings() {
* laughs?: boolean, voices?: boolean, rescan?: boolean, tagger?: any, engine?: any,
* onProgress?: (e: Record<string, unknown>) => void, say?: (s: string) => void }} o
*/
-export async function scanRecording({ projectDir, rec, audio, laughs = true, voices = true, rescan = false, tagger = null, engine = null, onProgress = () => {}, say = () => {} }) {
+export async function scanRecording({ projectDir, rec, audio, laughs = true, voices = true, rescan = false, tagger = null, engine = null, scope = null, onProgress = () => {}, say = () => {} }) {
const settings = tagger && engine ? null : await readSettings();
const tag = tagger ?? resolveTagger({ repoRoot: REPO_ROOT, settings });
const emb = engine ?? resolveEngine({ repoRoot: REPO_ROOT, settings });
@@ -203,13 +206,18 @@ export async function scanRecording({ projectDir, rec, audio, laughs = true, voi
}
if (voices) {
const c = cached.voices;
- if (!rescan && c && sameKey(c.source, key) && c.diarization === rec.diarization.generatedAt && c.engineModel === path.basename(emb.model)) {
+ const scopeKey = scope ? `${scope[0]}-${scope[1] ?? "end"}` : "all";
+ if (!rescan && c && sameKey(c.source, key) && c.diarization === rec.diarization.generatedAt && c.engineModel === path.basename(emb.model) && (c.scope ?? "all") === scopeKey) {
say("voices: cached");
} else if (!engine && !(await isFile(emb.model))) {
say(`voices: no speaker model at ${emb.model} — no centroid merge (set VOICE_MATCH_MODEL)`);
} else {
say("voices: a centroid per speaker");
- const turns = rec.turns.filter((t) => t && num(t.start) && num(t.end) && t.end > t.start && Number.isInteger(t.speaker));
+ const [a, b] = scope ? [scope[0], scope[1] ?? Infinity] : [-Infinity, Infinity];
+ // The scope's turns, cut to it: the voices of THIS part of the recording.
+ const turns = rec.turns
+ .filter((t) => t && num(t.start) && num(t.end) && t.end > t.start && Number.isInteger(t.speaker) && t.end > a && t.start < b)
+ .map((t) => ({ start: Math.max(t.start, a), end: Math.min(t.end, b), speaker: t.speaker }));
const v = await speakerCentroids({
file: audio.path,
clock: audio.clock,
@@ -218,7 +226,9 @@ export async function scanRecording({ projectDir, rec, audio, laughs = true, voi
scratch: path.join(/* turbopackIgnore: true */ projectDir, ".clips-work"),
onProgress: (e) => onProgress({ phase: "voices", ...e }),
});
- out.voices = { ...v, engineModel: path.basename(emb.model), source: key, diarization: rec.diarization.generatedAt, madeAt: new Date().toISOString() };
+ // Laugh voices are embeddings of the sound, whatever the centroids: kept across a re-scan of the same file.
+ const keptLaughs = c && sameKey(c.source, key) && c.engineModel === path.basename(emb.model) ? c.laughs ?? {} : {};
+ out.voices = { ...v, engineModel: path.basename(emb.model), scope: scopeKey, laughs: keptLaughs, source: key, diarization: rec.diarization.generatedAt, madeAt: new Date().toISOString() };
await writeWhole(scanFile(projectDir, rec.channel, rec.video, "voices"), out.voices);
out.ran.push("voices");
}
@@ -234,7 +244,8 @@ function scanInputs(scans) {
const laughScan = a ? { t0: a.t0 ?? 0, hop: a.hop, window: a.window, scores: Array.isArray(a.laugh) ? a.laugh : null, energy: Array.isArray(a.energy) ? a.energy : null } : null;
const v = scans?.voices?.speakers ?? null;
const centroids = v ? Object.fromEntries(Object.entries(v).map(([k, s]) => [k, s?.centroid ?? null])) : null;
- return { laughScan, centroids };
+ const laughVoices = scans?.voices?.laughs && typeof scans.voices.laughs === "object" ? scans.voices.laughs : null;
+ return { laughScan, centroids, laughVoices };
}
/**
@@ -244,7 +255,7 @@ function scanInputs(scans) {
* timeline?: any[], isProtected?: (e: any) => boolean, audio?: { path: string, kind: string } | null, now?: Date }} o
*/
export function proposalPass({ rec, scans = null, params = {}, operator = {}, previous = null, timeline = [], isProtected = () => false, audio = null, now = new Date() }) {
- const { laughScan, centroids } = scanInputs(scans);
+ const { laughScan, centroids, laughVoices } = scanInputs(scans);
const fixed = fixedClips(timeline, { channel: rec.channel, video: rec.video, isProtected });
const a = analyze({
turns: rec.turns,
@@ -254,6 +265,7 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr
operator,
centroids,
laughScan,
+ laughVoices,
previous: previous?.proposals ?? [],
fixed,
});
@@ -320,9 +332,10 @@ 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 }) {
+export async function seedReactions({ channelsDir, channel, video, target, laughMin, scope }) {
const rec = await loadRecording({ channelsDir, channel, video });
- const pass = proposalPass({ rec, params: target !== undefined ? { target } : {} });
+ const params = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}) };
+ const pass = proposalPass({ rec, params });
return { ...pass, rec };
}
@@ -334,7 +347,7 @@ export async function seedReactions({ channelsDir, channel, video, target }) {
* @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, dry = false, now = new Date() }) {
+export async function proposeProject({ project, from = null, params = {}, host = null, wordsFile = null, scans = undefined, audio = null, engine = null, dry = false, now = new Date(), say = () => {} }) {
for (let attempt = 0; ; attempt += 1) {
const token = await manifestToken(project.dir);
const manifest = await readManifest(project.dir);
@@ -352,10 +365,34 @@ 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 = { ...(sameSource ? previous.params : {}), ...Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== null)) };
+ const merged = mergeParams(sameSource ? previous.params : null, params);
const s = scans === undefined ? await readScans(project.dir, rec.channel, rec.video) : scans;
const isProtected = await rulingsGuard(project.dir, manifest);
- const pass = proposalPass({ rec, scans: s, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now });
+ const passOf = (sc) => proposalPass({ rec, scans: sc, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now });
+ let pass = passOf(s);
+ // Each laugh's voice (release 35, the live case): embedded once and kept in
+ // the voices scan, so a pass with a new laughMin or scope embeds only the new ones.
+ if (s?.voices?.speakers) {
+ const have = s.voices.laughs ?? {};
+ const missing = pass.doc.laughs.filter((l) => !have[laughKey(l)]);
+ if (missing.length) {
+ const sound = audio ?? (await recordingAudio({ channelsDir, channel: rec.channel, video: rec.video, videoDir: rec.videoDir, duration: rec.duration }));
+ const emb = engine ?? resolveEngine({ repoRoot: REPO_ROOT, settings: await readSettings() });
+ if (sound && (engine || (await isFile(emb.model)))) {
+ say(`laugh voices: ${missing.length} laugh(s) to check against the host's and the subject's voices`);
+ const got = await embedSpans({
+ file: sound.path,
+ clock: sound.clock,
+ spans: missing.map((l) => ({ key: laughKey(l), ...laughVoiceSpan(l) })),
+ engine: emb,
+ scratch: path.join(/* turbopackIgnore: true */ project.dir, ".clips-work"),
+ });
+ const voices = { ...s.voices, laughs: { ...have, ...Object.fromEntries(got) } };
+ if (!dry) await writeWhole(scanFile(project.dir, rec.channel, rec.video, "voices"), voices);
+ pass = passOf({ ...s, voices });
+ } else say(`laugh voices: ${missing.length} laugh(s) not checked (no sound or no speaker model)`);
+ }
+ }
if (!sameSource || !previous) pass.doc.madeAt = now.toISOString();
if (dry) return { ...pass, rec, written: false };
try {
@@ -369,6 +406,28 @@ export async function proposeProject({ project, from = null, params = {}, host =
}
}
+/**
+ * The params of a pass: the file's (when it is the same recording), the
+ * given over them. `scopeFrom` / `scopeTo` change one end of the file's scope;
+ * `scope: "all"` clears it.
+ */
+export function mergeParams(prev, given = {}) {
+ const out = { ...(prev ?? {}) };
+ for (const [k, v] of Object.entries(given ?? {})) {
+ if (v === undefined || v === null || k === "scopeFrom" || k === "scopeTo") continue;
+ out[k] = v;
+ }
+ if (given?.scopeFrom !== undefined || given?.scopeTo !== undefined) {
+ const was = Array.isArray(out.scope) ? out.scope : [0, null];
+ out.scope = [given.scopeFrom ?? was[0], given.scopeTo ?? was[1]];
+ }
+ try {
+ return normalizeParams(out);
+ } catch (e) {
+ throw new ClipsError(e instanceof Error ? e.message : String(e));
+ }
+}
+
// ---- the CLI ----------------------------------------------------------------------
export const CLIPS_USAGE = [
@@ -384,6 +443,8 @@ export const CLIPS_USAGE = [
" show the speakers, the laughs, what is in the cut",
"params: --target S (the cut's length, default 600) --laugh-min X (0..1, default 0.25)",
" --merge-gap S (6) --setup-max S (20) --clip-max S (75); kept in reactions.json for the next run",
+ "scope: --scope FROM:TO (seconds; TO may be empty: to the end; `all` clears it), or --from S / --to S with numbers:",
+ " only that part of the recording is read (a stream that reacts to two videos, one at a time)",
"--host N speaker N is the host (your word: kept until you change it)",
"A clip you have edited (assist.by \"operator\"), ruled, locked or added is never moved or removed.",
"Needs diarization.json beside the recording (archilyzer diarize backfill --scope video:<channel>/<id>).",
@@ -394,7 +455,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", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]);
+ const valued = new Set(["--from", "--to", "--scope", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]);
/** @type {Record<string, string[]>} */
const flags = {};
const positional = [];
@@ -412,7 +473,24 @@ function parse(args) {
/** The params given on the command line, each checked against its bounds. */
export function paramsFromFlags(p) {
+ /** @type {Record<string, unknown>} */
const out = {};
+ const secs = (flag, v) => {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 0) throw new ClipsError(`${flag} takes seconds ≥ 0, not ${v}`);
+ return n;
+ };
+ if (p.has("--scope")) {
+ const v = String(p.one("--scope"));
+ if (v === "all") out.scope = "all";
+ else {
+ const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(v);
+ if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), or all`);
+ out.scope = [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null];
+ }
+ }
+ if (p.has("--from") && isSeconds(p.one("--from"))) out.scopeFrom = secs("--from", p.one("--from"));
+ if (p.has("--to")) out.scopeTo = secs("--to", p.one("--to"));
for (const [flag, key] of Object.entries(PARAM_FLAGS)) {
if (!p.has(flag)) continue;
const v = Number(p.one(flag));
@@ -423,8 +501,11 @@ export function paramsFromFlags(p) {
return out;
}
+const isSeconds = (v) => /^\d+(?:\.\d+)?$/.test(String(v ?? ""));
+
+/** `--from <channel>/<id>` (a number is the scope's start instead). */
function parseFrom(v) {
- if (v === undefined) return null;
+ if (v === undefined || isSeconds(v)) return null;
const m = /^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(String(v));
if (!m) throw new ClipsError(`--from ${v}: <channel>/<videoId>`);
return { channel: m[1], video: m[2] };
@@ -444,7 +525,10 @@ 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})` : ""}`);
- lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}), moments: ${doc.moments.length}`);
+ if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}–${doc.params.scope[1] ?? "end"} s`);
+ const byVoice = doc.laughs.filter((l) => l.by === "voice").length;
+ const voiced = doc.laughs.filter((l) => l.voice).length;
+ lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}${voiced ? `; ${voiced} voice-checked, ${byVoice} re-attributed by voice` : ""}), moments: ${doc.moments.length}`);
const used = doc.proposals.filter((p) => p.used);
lines.push(` proposals: ${doc.proposals.length}, in the cut: ${used.length} (${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of ${doc.params.target} s)`);
for (const p of used) lines.push(` ${p.id} ${(p.clipId ?? "-").padEnd(5)} ${p.start.toFixed(1).padStart(8)}–${p.end.toFixed(1).padEnd(8)} ${p.score.toFixed(2)} ${p.why}`);
@@ -505,15 +589,17 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con
scans = await readScans(project.dir, rec.channel, rec.video);
} else {
const t0 = Date.now();
+ const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video;
+ const { scope } = mergeParams(sameSource ? previous.params : null, params);
scans = await scanRecording({
projectDir: project.dir, rec, audio, laughs: !p.has("--no-laughs"), voices: !p.has("--no-voices"), rescan: p.has("--rescan"),
- tagger, engine, onProgress: emit, say,
+ tagger, engine, scope, onProgress: emit, say,
});
if (scans.ran.length) say(`scanned (${scans.ran.join(", ")}) in ${Math.round((Date.now() - t0) / 1000)} s`);
}
}
emit({ phase: "propose" });
- const r = await proposeProject({ project, from, params, host, wordsFile: p.one("--words") ?? null, scans, audio, dry: p.has("--dry"), now });
+ const r = await proposeProject({ project, from, params, host, wordsFile: p.one("--words") ?? null, scans, audio, engine, dry: p.has("--dry"), now, say });
emit({ phase: "done", proposals: r.doc.proposals.length, used: r.doc.proposals.filter((x) => x.used).length, changes: r.changes });
if (p.has("--json")) log(JSON.stringify({ written: r.written, changes: r.changes, reactions: r.doc }, null, 1));
else {
@@ -535,7 +621,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 }} [req]
+ * @param {{ mode?: "analyze" | "propose", from?: string, target?: number, host?: number, laughMin?: number, scope?: [number, number | null] }} [req]
*/
export function clipsSteps(project, req = {}) {
const mode = req.mode === "propose" ? "propose" : "analyze";
@@ -543,6 +629,8 @@ export function clipsSteps(project, req = {}) {
if (typeof req.from === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(req.from)) argv.push("--from", req.from);
if (num(req.target) && req.target >= PARAM_BOUNDS.target[0] && req.target <= PARAM_BOUNDS.target[1]) argv.push("--target", String(req.target));
if (Number.isInteger(req.host) && /** @type {number} */ (req.host) >= 0) argv.push("--host", String(req.host));
+ if (num(req.laughMin) && req.laughMin >= PARAM_BOUNDS.laughMin[0] && req.laughMin <= PARAM_BOUNDS.laughMin[1]) argv.push("--laugh-min", String(req.laughMin));
+ if (Array.isArray(req.scope) && num(req.scope[0]) && (req.scope[1] === null || num(req.scope[1]))) argv.push("--scope", `${req.scope[0]}:${req.scope[1] ?? ""}`);
argv.push("--progress", "ndjson");
return {
kind: `clips-${mode} ${project.id}`,
diff --git a/umtool/lib/report/reactions.test.mjs b/umtool/lib/report/reactions.test.mjs
@@ -176,6 +176,35 @@ test("clips propose: params kept, a host flip is the operator's, ids stable, an
}
});
+test("the scope: --scope / --from S --to S, kept in reactions.json params, `all` clears it; the seed takes it", async () => {
+ const f = await fixture();
+ try {
+ const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "reacts", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, scope: [300, 450], laughMin: 0.15 });
+ await pointAt(r.dir, f.channelsDir);
+ let doc = await readReactions(r.dir);
+ assert.deepEqual(doc.params.scope, [300, 450]);
+ assert.equal(doc.params.laughMin, 0.15);
+ assert.equal(doc.source.duration, 450);
+ assert.ok(doc.proposals.every((p) => p.end > 300 && p.start < 450));
+ assert.equal(await clipsCommand(["propose", "reacts", "--from", "0", "--to", "200"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ doc = await readReactions(r.dir);
+ assert.deepEqual(doc.params.scope, [0, 200]);
+ assert.ok(doc.turns.every((t) => t.end <= 200));
+ assert.equal(await clipsCommand(["propose", "reacts", "--to", "250"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ assert.deepEqual((await readReactions(r.dir)).params.scope, [0, 250]);
+ assert.equal(await clipsCommand(["propose", "reacts", "--scope", "400:"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ assert.deepEqual((await readReactions(r.dir)).params.scope, [400, null]);
+ assert.equal(await clipsCommand(["propose", "reacts", "--scope", "all"], { reportsRoot: f.reportsRoot, ...quiet() }), 0);
+ assert.equal((await readReactions(r.dir)).params.scope, null);
+ const bad = quiet();
+ assert.equal(await clipsCommand(["propose", "reacts", "--scope", "9-3"], { reportsRoot: f.reportsRoot, ...bad }), 2);
+ assert.equal(await clipsCommand(["propose", "reacts", "--scope", "500:100"], { reportsRoot: f.reportsRoot, ...quiet() }), 2);
+ await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "x1", from: "synth-reacts/react001", seed: "chapters", channelsDir: f.channelsDir, laughMin: 0.2 }), /go with --seed reactions/);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
test("clips propose reads <project>/words.json when there is one", async () => {
const f = await fixture();
try {
@@ -210,6 +239,9 @@ test("clips analyze (fake tagger + fake embedder): the scans, cached in the proj
assert.equal(doc.scans.laughs.model, "fakeAudioTag.mjs");
assert.equal(doc.scans.voices.model, "fake-spectrum");
assert.equal(doc.source.audio, "audio.wav");
+ // Each laugh's voice, checked against the host's and the subject's (the fake embedder's "voices").
+ assert.ok(doc.laughs.every((l) => l.voice && Number.isFinite(l.voice.host) && Number.isFinite(l.voice.subject)), JSON.stringify(doc.laughs));
+ assert.equal(Object.keys(JSON.parse(await readFile(path.join(r.dir, "scans", "synth-reacts--react001.voices.json"), "utf8")).laughs).length, 3);
await stat(path.join(r.dir, "scans", "synth-reacts--react001.audio.json"));
await stat(path.join(r.dir, "scans", "synth-reacts--react001.voices.json"));
// Again: both cached.