Archilyzer · Source

archilyzer

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

commit df0f21ea7c0660684608c33b506985b7e7a30038
parent f3796b3c4ad879c278a888deda02076690a17b0c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 11:50:17 -0400

clips: auto-scope -- the narrated-video segments of a recording, --scope auto / --segment, umtool clips segments

common/lib/clips/segments.mjs findSegments: 5-min windows every 30 s, the
subject = the non-host cluster with the most long-turn seconds (60 s and 60 %
at least), runs of one subject edged on its long turns, short spans dropped,
the host's reaction after a video folded in (300 s at most, never past the
next video's first line, ending on a turn's end). reactions.json gains
`segments` and `segment`; roles stay per segment (the scope). The test kit
gains a two-video stream and a synthetic chat replay.

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

Diffstat:
Acommon/lib/clips/segments.d.mts | 12++++++++++++
Acommon/lib/clips/segments.mjs | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/clips/segments.test.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/testing/clips/reactionStream.d.mts | 18+++++++++++++++++-
Mcommon/testing/clips/reactionStream.mjs | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/bin/umtool.mjs | 15+++++++++------
Mumtool/lib/projects/scaffold.mjs | 16+++++++++++-----
Mumtool/lib/projects/scaffold.ts | 7++++++-
Aumtool/lib/report/reactions-r36.test.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/reactions.mjs | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
11 files changed, 655 insertions(+), 31 deletions(-)

diff --git a/common/lib/clips/segments.d.mts b/common/lib/clips/segments.d.mts @@ -0,0 +1,12 @@ +export const SEGMENT_WINDOW_S: number; +export const SEGMENT_HOP_S: number; +export const SEGMENT_MIN_SUBJECT_S: number; +export const SEGMENT_DOMINANCE: number; +export const SEGMENT_MIN_S: number; +export const SEGMENT_TAIL_S: number; + +export type Segment = { id: string; from: number; to: number; subject: number; host: number | null; why: string }; + +export function findSegments(o: { turns: unknown; duration?: number; host?: number | null; operator?: Record<string, string> }): Segment[]; +export function pickSegment<S extends { id: string; from: number; to: number }>(segments: S[], id?: string | null): S | null; +export function scopeOverlapsSegment(scope: [number, number | null] | null | undefined, segment: { from: number; to: number }, duration: number): boolean; diff --git a/common/lib/clips/segments.mjs b/common/lib/clips/segments.mjs @@ -0,0 +1,173 @@ +// Auto-scope (release 36 B1): where, in a long recording, each narrated video +// is. A reaction stream plays one video, then another; the host talks over +// both and between them. Release 35 cut the Nik Drop from one video at a time +// with a scope read off the speaker clusters by hand; this finds the spans. +// +// From the speaker turns alone (diarization.json), pure, deterministic: +// +// the host the cluster assignRoles calls the host over the whole +// recording (or the operator's), left out of the counting: +// he talks all the way through, so he never marks a video +// windows SEGMENT_WINDOW_S long, every SEGMENT_HOP_S: each window's +// subject is the cluster with the most seconds in turns of at +// least SHORT_TURN_S (a narrated video talks in long runs), +// counted when it has SEGMENT_MIN_SUBJECT_S of them and +// SEGMENT_DOMINANCE of the long-turn time +// a span consecutive windows with the same subject; its edges are +// that subject's first and last long turn inside them +// joined neighbouring spans of one subject are one (a dip between +// them); spans under SEGMENT_MIN_S are dropped +// the tail the host-only time after a video's last line — the host's +// reaction to it — folded into it, up to SEGMENT_TAIL_S and +// never past the next video's first line; its end on a turn's +// end. The time before a video's first line (an intro, the +// host between videos past the tail) belongs to no segment. +// +// → `[{ id: "s1", from, to, subject, host, why }]`, chronological. Roles are +// still assigned per segment (the analysis runs on the segment's turns with +// the scope); this only says where the segments are. +// +// Plain ESM with a .d.mts beside it. +import { SHORT_TURN_S, assignRoles, cleanTurns } from "./clips.mjs"; + +export const SEGMENT_WINDOW_S = 300; +export const SEGMENT_HOP_S = 30; +/** A window's subject has at least this many seconds of long turns in it… */ +export const SEGMENT_MIN_SUBJECT_S = 60; +/** …and at least this share of the window's long-turn time (the host's left out). */ +export const SEGMENT_DOMINANCE = 0.6; +/** A segment shorter than this is dropped. */ +export const SEGMENT_MIN_S = 180; +/** The host-only time after a video's last line folded into it: at most this. */ +export const SEGMENT_TAIL_S = 300; + +const round = (x, d = 2) => Math.round(x * 10 ** d) / 10 ** d; +const overlap = (a0, a1, b0, b1) => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0)); + +/** + * The narrated-video spans of a recording. + * @param {{ turns: unknown, duration?: number, host?: number | null, operator?: Record<string, string> }} o + * `host`: the host's cluster when it is known (the operator's word); else assignRoles' over the whole recording + * @returns {{ id: string, from: number, to: number, subject: number, host: number | null, why: string }[]} + */ +export function findSegments({ turns, duration = 0, host = null, operator = {} }) { + const ts = cleanTurns(turns); + if (!ts.length) return []; + const end = Math.max(Number(duration) || 0, ...ts.map((t) => t.end)); + let hostIx = Number.isInteger(host) && /** @type {number} */ (host) >= 0 ? /** @type {number} */ (host) : null; + if (hostIx === null) { + const roles = assignRoles({ turns: ts, duration: end, operator }); + hostIx = roles.find((s) => s.role === "host")?.index ?? null; + } + const long = ts.filter((t) => t.speaker !== hostIx && t.end - t.start >= SHORT_TURN_S); + + // The windows, and each one's subject (or none). + const starts = []; + for (let a = 0; a + SEGMENT_WINDOW_S < end; a += SEGMENT_HOP_S) starts.push(a); + const lastStart = Math.max(0, end - SEGMENT_WINDOW_S); + if (!starts.length || starts[starts.length - 1] < lastStart) starts.push(lastStart); + const labels = starts.map((a) => { + const b = Math.min(end, a + SEGMENT_WINDOW_S); + /** @type {Map<number, number>} */ + const by = new Map(); + let total = 0; + for (const t of long) { + if (t.start >= b) break; + const o = overlap(t.start, t.end, a, b); + if (o <= 0) continue; + by.set(t.speaker, (by.get(t.speaker) ?? 0) + o); + total += o; + } + let best = null; + for (const [s, sec] of by) if (!best || sec > best.sec || (sec === best.sec && s < best.s)) best = { s, sec }; + if (!best || best.sec < SEGMENT_MIN_SUBJECT_S || best.sec / total < SEGMENT_DOMINANCE) return { a, b, subject: null }; + return { a, b, subject: best.s }; + }); + + // Runs of one subject, edged on that subject's long turns inside them. + /** @type {{ from: number, to: number, subject: number }[]} */ + let spans = []; + for (let i = 0; i < labels.length; ) { + const s = labels[i].subject; + let j = i; + while (j + 1 < labels.length && labels[j + 1].subject === s) j += 1; + if (s !== null) { + const a = labels[i].a; + const b = labels[j].b; + const own = long.filter((t) => t.speaker === s && t.end > a && t.start < b); + if (own.length) spans.push({ from: own[0].start, to: Math.max(...own.map((t) => t.end)), subject: s }); + } + i = j + 1; + } + const join = (list) => { + const out = []; + for (const sp of list) { + const last = out[out.length - 1]; + if (last && last.subject === sp.subject) last.to = Math.max(last.to, sp.to); + else out.push({ ...sp }); + } + // Interleaved edges (a window can see two videos' lines): the later one starts after the earlier one ends. + for (let k = 1; k < out.length; k += 1) out[k].from = Math.max(out[k].from, out[k - 1].to); + return out.filter((sp) => sp.to > sp.from); + }; + spans = join(spans); + spans = join(spans.filter((sp) => sp.to - sp.from >= SEGMENT_MIN_S)); + + return spans.map((sp, k) => { + const next = spans[k + 1]; + const limit = Math.min(next ? next.from : end, sp.to + SEGMENT_TAIL_S); + // The tail ends on the last turn that ends inside it (a turn is never cut). + let to = sp.to; + for (const t of ts) { + if (t.start >= limit) break; + if (t.end <= limit && t.end > to) to = t.end; + } + let subjectLong = 0; + let allLong = 0; + for (const t of long) { + const o = overlap(t.start, t.end, sp.from, sp.to); + allLong += o; + if (t.speaker === sp.subject) subjectLong += o; + } + const pct = Math.floor((100 * subjectLong) / (allLong || 1)); + const tail = round(to - sp.to, 0); + const why = + `subject ${sp.subject} holds ${pct}% of long-turn time` + + (tail >= 1 ? `; ${tail} s after its last line kept (the host's reaction)` : ""); + return { id: `s${k + 1}`, from: round(sp.from), to: round(to), subject: sp.subject, host: hostIx, why }; + }); +} + +/** + * The segment a run is scoped to: the one named, else the longest (the + * earliest of equals). Null when there are none; an unknown id throws. + * @template {{ id: string, from: number, to: number }} S + * @param {S[]} segments + * @param {string | null} [id] + * @returns {S | null} + */ +export function pickSegment(segments, id = null) { + const list = Array.isArray(segments) ? segments : []; + if (id !== null && id !== undefined && id !== "") { + const hit = list.find((s) => s.id === id); + if (!hit) throw new Error(`no segment ${id}${list.length ? ` (there are ${list.map((s) => s.id).join(", ")})` : " (no segments were found)"}`); + return hit; + } + let best = null; + for (const s of list) if (!best || s.to - s.from > best.to - best.from) best = s; + return best; +} + +/** + * Whether a project's scope (`[from, to|null]`, or null for the whole + * recording) covers a segment: they share at least half of the shorter one. + * @param {[number, number | null] | null | undefined} scope + * @param {{ from: number, to: number }} segment + * @param {number} duration the recording's (a scope open at the end runs to it) + */ +export function scopeOverlapsSegment(scope, segment, duration) { + const a = Array.isArray(scope) ? Number(scope[0]) || 0 : 0; + const b = Array.isArray(scope) && scope[1] !== null && scope[1] !== undefined ? Number(scope[1]) : Math.max(Number(duration) || 0, segment.to); + const o = overlap(a, b, segment.from, segment.to); + return o > 0 && o >= 0.5 * Math.min(b - a, segment.to - segment.from); +} diff --git a/common/lib/clips/segments.test.ts b/common/lib/clips/segments.test.ts @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { SEGMENT_MIN_S, SEGMENT_TAIL_S, findSegments, pickSegment, scopeOverlapsSegment } from "./segments.mjs"; +import { HOST, SUBJECT, TWO_HOST, TWO_SUBJECT_A, TWO_SUBJECT_B, TWO_VIDEOS, reactionStream, twoVideoStream } from "../../testing/clips/reactionStream.mjs"; + +test("findSegments: two narrated videos in one stream; the host's intro is not one, his reaction after a video is folded into it", () => { + const s = twoVideoStream(); + const segs = findSegments({ turns: s.turns, duration: s.duration }); + assert.equal(segs.length, 2); + const [a, b] = segs; + assert.deepEqual([a.id, a.subject, a.host], ["s1", TWO_SUBJECT_A, TWO_HOST]); + assert.deepEqual([b.id, b.subject, b.host], ["s2", TWO_SUBJECT_B, TWO_HOST]); + // Each starts on its video's first line (the intro and the time between are not a video's)… + assert.equal(a.from, TWO_VIDEOS[0][0]); + assert.equal(b.from, TWO_VIDEOS[1][0]); + // …and ends on a turn's end inside SEGMENT_TAIL_S after its last line: the host's + // turn 1350–1420 runs past 1100 + 300, so the tail stops at the turn before it. + assert.equal(a.to, 1347); + assert.ok(a.to - TWO_VIDEOS[0][1] <= SEGMENT_TAIL_S); + // The second: its outro to the stream's last turn; the host's 100 s pause inside it does not split it. + assert.equal(b.to, 2390); + assert.match(a.why, /^subject 1 holds \d+% of long-turn time; 247 s after its last line kept/); + // Deterministic. + assert.deepEqual(findSegments({ turns: s.turns, duration: s.duration }), segs); + // The operator's host gives the same answer; a cluster named host is left out of the counting. + assert.deepEqual(findSegments({ turns: s.turns, duration: s.duration, host: TWO_HOST }), segs); + assert.deepEqual(findSegments({ turns: s.turns, duration: s.duration, operator: { [TWO_HOST]: "host" } }), segs); +}); + +test("findSegments: one narrated video is one segment; a tail never runs into the next video; a short span is dropped", () => { + const one = reactionStream(); + const segs = findSegments({ turns: one.turns, duration: one.duration }); + assert.equal(segs.length, 1); + assert.deepEqual([segs[0].from, segs[0].to, segs[0].subject, segs[0].host], [0, 600, SUBJECT, HOST]); + + // Two videos with only 60 s of host between them: the tail stops at the next video's first line. + const turns = []; + for (let t = 0; t < 600; t += 60) turns.push({ start: t, end: t + 55, speaker: 1 }, { start: t + 55, end: t + 59, speaker: 0 }); + for (let t = 610; t < 660; t += 6) turns.push({ start: t, end: t + 5, speaker: 0 }); + for (let t = 660; t < 1260; t += 60) turns.push({ start: t, end: t + 55, speaker: 2 }, { start: t + 55, end: t + 59, speaker: 0 }); + const two = findSegments({ turns, duration: 1260 }); + assert.equal(two.length, 2); + assert.ok(two[0].to <= two[1].from, `${two[0].to} ≤ ${two[1].from}`); + assert.equal(two[1].from, 660); + + // A 2-minute clip of another narrator inside the host's talk: under SEGMENT_MIN_S, dropped. + const short = []; + for (let t = 0; t < 900; t += 6) short.push({ start: t, end: t + 5, speaker: 0 }); + short.push({ start: 300, end: 360, speaker: 3 }, { start: 361, end: 420, speaker: 3 }); + assert.ok(120 < SEGMENT_MIN_S); + assert.deepEqual(findSegments({ turns: short.sort((x, y) => x.start - y.start), duration: 900 }), []); + assert.deepEqual(findSegments({ turns: [], duration: 100 }), []); +}); + +test("pickSegment: the one named, else the longest; an unknown id is refused; none is null", () => { + const segs = [ + { id: "s1", from: 0, to: 100 }, + { id: "s2", from: 200, to: 500 }, + { id: "s3", from: 600, to: 900 }, + ]; + assert.equal(pickSegment(segs)?.id, "s2"); + assert.equal(pickSegment(segs, "s3")?.id, "s3"); + assert.throws(() => pickSegment(segs, "s9"), /no segment s9 \(there are s1, s2, s3\)/); + assert.equal(pickSegment([]), null); +}); + +test("scopeOverlapsSegment: half of the shorter shared; an open scope runs to the end; the whole recording covers every segment", () => { + const seg = { from: 1000, to: 2000 }; + assert.equal(scopeOverlapsSegment([0, 1900], seg, 3000), true); + assert.equal(scopeOverlapsSegment([0, 1200], seg, 3000), false); + assert.equal(scopeOverlapsSegment([1500, null], seg, 3000), true); + assert.equal(scopeOverlapsSegment(null, seg, 3000), true); + assert.equal(scopeOverlapsSegment([2100, 2900], seg, 3000), false); + // The live case's shape: a hand scope 0–6300 and the auto-scope's first segment. + assert.equal(scopeOverlapsSegment([0, 6300], { from: 292.68, to: 6318.09 }, 9367), true); + assert.equal(scopeOverlapsSegment([0, 6300], { from: 6501.93, to: 9276.01 }, 9367), false); +}); diff --git a/common/package.json b/common/package.json @@ -36,6 +36,7 @@ "./lib/clips/clips.mjs": "./lib/clips/clips.mjs", "./lib/clips/reactions.mjs": "./lib/clips/reactions.mjs", "./lib/clips/scan.mjs": "./lib/clips/scan.mjs", + "./lib/clips/segments.mjs": "./lib/clips/segments.mjs", "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", diff --git a/common/testing/clips/reactionStream.d.mts b/common/testing/clips/reactionStream.d.mts @@ -14,5 +14,21 @@ export function reactionStream(o?: { hop?: number; window?: number; laughWords?: export function reactionAudio(o?: { seconds?: number; rate?: number }): Float32Array; export function writeReactionCorpus( channelsDir: string, - o?: { channel?: string; video?: string; diarization?: boolean; audio?: Buffer | null }, + o?: { channel?: string; video?: string; diarization?: boolean; audio?: Buffer | null; two?: boolean; chat?: boolean | Parameters<typeof reactionChat>[0] | null; meta?: Record<string, unknown> | null }, ): string; +export const TWO_SECONDS: number; +export const TWO_HOST: number; +export const TWO_SUBJECT_A: number; +export const TWO_SUBJECT_B: number; +export const TWO_VIDEOS: readonly [number, number][]; +export const TWO_LAUGHS: readonly [number, number, number][]; +export function twoVideoStream(): ReturnType<typeof reactionStream>; +export function reactionChat(o?: { + laughs?: readonly (readonly number[])[]; + duration?: number; + lag?: number; + every?: number; + burstPerS?: number; + burstS?: number; + chatOnly?: readonly number[]; +}): { start: number; end: number; text: string }[]; diff --git a/common/testing/clips/reactionStream.mjs b/common/testing/clips/reactionStream.mjs @@ -125,12 +125,15 @@ export function reactionAudio({ seconds = STREAM_SECONDS, rate = 16000 } = {}) { /** * The stream as a channel on disk. Returns the video dir. * @param {string} channelsDir - * @param {{ channel?: string, video?: string, diarization?: boolean, audio?: Buffer | null, words?: boolean }} [o] + * @param {{ channel?: string, video?: string, diarization?: boolean, audio?: Buffer | null, two?: boolean, chat?: boolean | Record<string, unknown> | null, meta?: Record<string, unknown> | null }} [o] * `audio`: WAV bytes to write as audio.wav (encodeWav16(reactionAudio())); - * `diarization` false leaves diarization.json out. + * `diarization` false leaves diarization.json out; `two`: the two-video + * stream (twoVideoStream) instead; `chat`: live_chat.cues.json beside it + * (reactionChat's options, `true` for its defaults); `meta`: keys merged + * into metadata.info.json (`webpage_url`, `channel`…). */ -export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", video = "react001", diarization = true, audio = null } = {}) { - const s = reactionStream(); +export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", video = "react001", diarization = true, audio = null, two = false, chat = null, meta = null } = {}) { + const s = two ? twoVideoStream() : reactionStream(); const dir = path.join(channelsDir, channel, "data", video); mkdirSync(dir, { recursive: true }); writeFileSync(path.join(channelsDir, channel, "config.json"), JSON.stringify({ name: "Synth Reacts" })); @@ -138,7 +141,14 @@ export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", vid path.join(dir, "transcript.cues.json"), JSON.stringify({ id: video, title: "Synthetic reaction stream", source: "whisper", duration: s.duration, uploadDate: "20240102", cues: s.cues }), ); - writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: video, title: "Synthetic reaction stream", duration: s.duration })); + writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: video, title: "Synthetic reaction stream", duration: s.duration, ...(meta ?? {}) })); + if (chat) { + const cues = reactionChat({ laughs: two ? TWO_LAUGHS : LAUGHS, duration: s.duration, ...(chat === true ? {} : chat) }); + writeFileSync( + path.join(dir, "live_chat.cues.json"), + JSON.stringify({ version: 1, source: "live_chat", id: video, title: "Synthetic reaction stream", duration: s.duration, cues }), + ); + } if (diarization) { const speakers = new Set(s.turns.map((t) => t.speaker)).size; writeFileSync( @@ -149,3 +159,134 @@ export function writeReactionCorpus(channelsDir, { channel = "synth-reacts", vid if (audio) writeFileSync(path.join(dir, "audio.wav"), audio); return dir; } + +// ---- release 36: two narrated videos in one stream, and its chat ---------------- +// +// twoVideoStream() a host (0) introduces, reacts to video A (narrated by 1), +// talks a while, reacts to video B (narrated by 2, with a +// stray cluster 3 and a pause where the host talks over a +// stopped video), then signs off — what auto-scope reads +// reactionChat(o) a synthetic chat replay (live_chat.cues.json's cues): +// a steady trickle of messages, and a burst of laugh +// tokens `lag` seconds after each laugh (chat watches the +// stream late), plus `chatOnly` bursts at times with no +// laugh at all + +export const TWO_SECONDS = 2400; +export const TWO_HOST = 0; +export const TWO_SUBJECT_A = 1; +export const TWO_SUBJECT_B = 2; +/** Where each video's narration runs (its first line to its last). */ +export const TWO_VIDEOS = Object.freeze([ + [120, 1100], + [1500, 2290], +]); +/** The host's laughs in the two-video stream: [start, end, strength], each in a gap of the narration. */ +export const TWO_LAUGHS = Object.freeze([ + [355, 357.5, 0.8], + [775, 777, 0.7], + [1615, 1617.5, 0.8], + [2135, 2137, 0.7], +]); + +/** Runs of `run` seconds with `gap` between them over [a, b]. */ +function runsOver(a, b, run, gap) { + const out = []; + for (let t = a; t < b; t += run + gap) out.push([t, Math.min(b, t + run)]); + return out; +} + +export function twoVideoStream() { + const turns = []; + const subjectRuns = []; + const hostTurns = []; + // The intro: the host alone, in long turns too (he is not a video). + hostTurns.push([2, 30], [31, 62], [64, 118]); + // Video A: narration in 55 s runs, the host in the 5 s gaps. + for (const r of runsOver(120, 1100, 55, 5)) subjectRuns.push([...r, TWO_SUBJECT_A]); + // Between the videos: the host talks for 400 s (some long turns). + hostTurns.push([1103, 1130], [1132, 1135], [1137, 1180], [1182, 1186], [1190, 1260], [1262, 1266], [1270, 1340], [1342, 1347], [1350, 1420], [1425, 1497]); + // Video B: narration in 50 s runs; a stray cluster; the host pauses it at 1800 for 100 s. + for (const r of runsOver(1500, 1800, 50, 5)) subjectRuns.push([...r, TWO_SUBJECT_B]); + hostTurns.push([1801, 1830], [1832, 1836], [1838, 1870], [1872, 1898]); + for (const r of runsOver(1900, 2290, 50, 5)) subjectRuns.push([...r, TWO_SUBJECT_B]); + turns.push({ start: 1960.5, end: 1962, speaker: 3 }); + // The outro. + hostTurns.push([2292, 2330], [2333, 2337], [2340, 2390]); + for (const [a, b, s] of subjectRuns) turns.push({ start: a, end: b, speaker: s }); + // The host's interjections in the narration's gaps. + const gaps = []; + for (let i = 0; i + 1 < subjectRuns.length; i += 1) { + const [, b] = subjectRuns[i]; + const [a2] = subjectRuns[i + 1]; + if (a2 - b > 0.5 && a2 - b < 10) gaps.push([b, a2]); + } + for (const [a, b] of gaps) hostTurns.push([a, b]); + for (const [a, b] of hostTurns) turns.push({ start: a, end: b, speaker: TWO_HOST }); + turns.sort((x, y) => x.start - y.start || x.speaker - y.speaker); + + const words = []; + let k = 0; + for (const [a, b] of subjectRuns) { + for (let t = a + 0.2; t + 0.4 <= b - 0.2; t += 0.5) { + k += 1; + words.push({ w: k % 7 === 0 ? `n${k}.` : `n${k}`, start: round3(t), end: round3(t + 0.4) }); + } + } + for (const [a, b] of hostTurns) { + const laugh = TWO_LAUGHS.find(([s]) => s >= a - 0.01 && s < b); + let t = a + 0.1; + if (laugh) { + words.push({ w: "haha", start: round3(laugh[0] + 0.2), end: round3(laugh[1] - 0.2) }); + t = laugh[1] + 0.1; + } + let j = 0; + for (; t + 0.35 <= b - 0.1; t += 0.45) { + words.push({ w: HOST_WORDS[j % HOST_WORDS.length], start: round3(t), end: round3(t + 0.35) }); + j += 1; + } + } + words.sort((x, y) => x.start - y.start); + const cues = []; + for (let i = 0; i < words.length; i += 8) { + const run = words.slice(i, i + 8); + cues.push({ start: run[0].start, end: run[run.length - 1].end, text: run.map((w) => w.w).join(" ") }); + } + const hop = 0.5; + const window = 1; + const n = Math.floor((TWO_SECONDS - window) / hop) + 1; + const scores = Array.from({ length: n }, (_, i) => { + const a = i * hop; + const b = a + window; + const l = TWO_LAUGHS.find(([s, e]) => Math.min(b, e) - Math.max(a, s) >= window / 2); + return l ? l[2] : 0.02; + }); + return { duration: TWO_SECONDS, turns, words, cues, laughScan: { t0: 0, hop, window, scores } }; +} + +const CHAT_LAUGHS = ["LUL", "lmao", "😂", "hahaha", "KEKW", "W", "lol", "🤣", "LMFAO", "OMEGALUL"]; +const CHAT_FILLER = ["hello", "what is this", "first time here", "nice", "true", "ok", "is this live", "chat is slow"]; + +/** + * A synthetic chat replay: cues `{start, end, text: "<viewer>: <message>"}`, + * as live_chat.cues.json carries them (normalizeLiveChat: end = start + 5). + * @param {{ laughs?: readonly (readonly number[])[], duration?: number, lag?: number, every?: number, burstPerS?: number, burstS?: number, chatOnly?: readonly number[] }} [o] + */ +export function reactionChat({ laughs = LAUGHS, duration = STREAM_SECONDS, lag = 6, every = 2, burstPerS = 5, burstS = 4, chatOnly = [] } = {}) { + const cues = []; + let n = 0; + for (let t = 0.7; t < duration; t += every) { + n += 1; + cues.push({ start: round3(t), end: round3(t + 5), text: `viewer${n % 37}: ${CHAT_FILLER[n % CHAT_FILLER.length]}` }); + } + const bursts = [...laughs.map((l) => l[0] + lag), ...chatOnly]; + for (const at of bursts) { + for (let i = 0; i < burstPerS * burstS; i += 1) { + const t = at + i / burstPerS; + if (t >= duration) break; + n += 1; + cues.push({ start: round3(t), end: round3(t + 5), text: `viewer${n % 37}: ${CHAT_LAUGHS[n % CHAT_LAUGHS.length]}` }); + } + } + return cues.sort((a, b) => a.start - b.start); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -714,9 +714,10 @@ function usage() { " channel's copy where it has one (a twin by date and duration); a context matching --exclude", " is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances", " spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")", - " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO] [--no-analyze]: the clip finder on a long", + " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]: the clip finder on a long", " recording (needs its diarization.json): highlights proposed from the host's laughs and comments,", - " then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze", + " then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze; --scope auto reads the", + " narrated video auto-scope finds in the speakers' turns (--segment names one, else the longest)", " [--brand archilyzer-media] render.brand: the report-to-video brand preset", " umtool doctor [--json] exit 1 if the report pipeline is missing a tool", " or the media root is set and not there; the roots, and a leftover old cache", @@ -745,7 +746,7 @@ function usage() { " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]", " a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json", " umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params]", - " umtool clips propose <project> [--host N] [params] [--dry] | show <project>", + " umtool clips propose <project> [--host N] [params] [--dry] | show <project> | segments <project>", " the clip finder: the laugh scan + voices on the recording's sound, then clips proposed", " (setup → reaction → tail) into the manifest (assist: by the assistant) and reactions.json;", " params --target S --laugh-min X --merge-gap S --setup-max S --clip-max S; a clip you edited is never moved", @@ -1139,10 +1140,11 @@ async function cmdIndex() { // Scaffolding. The writer is lib/projects/scaffold.mjs, shared with the route. // --------------------------------------------------------------------------- -/** `--scope FROM:TO` (seconds; either side may be empty). */ +/** `--scope FROM:TO` (seconds; either side may be empty), or `auto` (release 36: the narrated video auto-scope finds). */ function parseScopeFlag(v) { + if (String(v) === "auto") return "auto"; const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(String(v)); - if (!m) die(`--scope ${v}: FROM:TO in seconds (either may be empty)`); + if (!m) die(`--scope ${v}: FROM:TO in seconds (either may be empty), or auto`); return [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null]; } @@ -1154,7 +1156,7 @@ async function cmdNew() { " [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" + " [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" + " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]\n" + - " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO] [--no-analyze]]", + " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]]", ); } const kind = val("--kind") ?? "report-video"; @@ -1182,6 +1184,7 @@ async function cmdNew() { ...(val("--max") != null ? { max: Number(val("--max")) } : {}), ...(val("--laugh-min") != null ? { laughMin: Number(val("--laugh-min")) } : {}), ...(val("--scope") != null ? { scope: parseScopeFlag(val("--scope")) } : {}), + ...(val("--segment") != null ? { segment: val("--segment") } : {}), }); } catch (e) { die(e?.message ?? String(e)); diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.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, laughMin?: number, scope?: [number, number | null] | null }} args + * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | "auto" | null, segment?: string | null }} args */ -export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null }) { +export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null, segment = null }) { if (!SLUG_RE.test(String(slug ?? ""))) { throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`); } @@ -287,11 +287,14 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site throw new Error(`--max must be a whole number of clips from 1 to ${MAX_PHRASE_CAP}`); } const capped = max !== null && max !== undefined; - if ((laughMin !== undefined || scope) && seed !== "reactions") throw new Error("--laugh-min and --scope go with --seed reactions"); + if ((laughMin !== undefined || scope || segment) && seed !== "reactions") throw new Error("--laugh-min, --scope and --segment go with --seed reactions"); + if (segment && !/^s\d+$/.test(String(segment))) throw new Error(`--segment ${segment}: a segment id (s1, s2, …)`); + if (segment && scope && scope !== "auto") throw new Error("--segment goes with --scope auto (or alone)"); if (laughMin !== undefined && !(Number.isFinite(laughMin) && laughMin >= PARAM_BOUNDS.laughMin[0] && laughMin <= PARAM_BOUNDS.laughMin[1])) { throw new Error(`--laugh-min must be a number from ${PARAM_BOUNDS.laughMin[0]} to ${PARAM_BOUNDS.laughMin[1]}`); } - const reactionsScope = seed === "reactions" ? normalizeScope(scope) : null; + // Release 36: `auto` (or a `segment`) is the narrated video auto-scope finds in the recording. + const reactionsScope = seed !== "reactions" ? null : scope === "auto" || segment ? "auto" : normalizeScope(scope); if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed"); if (target !== undefined && seed !== "frames" && seed !== "reactions") throw new Error("--target is the frames seed's length budget (or the reactions seed's): give it with --seed frames or --seed reactions"); const [tLo, tHi] = seed === "reactions" ? PARAM_BOUNDS.target : [10, 3600]; @@ -390,6 +393,7 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site const pass = await seedReactions({ channelsDir, channel: src.channel, video: src.video, ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(reactionsScope ? { scope: reactionsScope } : {}), + ...(segment ? { segment: String(segment) } : {}), }); doc.timeline = pass.timeline; // Hard cuts: a highlights reel. @@ -400,7 +404,9 @@ 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(...(pass.notes ?? [])); + const read = pass.doc.params.scope; + if (read) notes.push(`only ${read[0]}–${read[1] ?? "the end"} s of the recording is read (--scope${reactionsScope === "auto" ? ` auto${pass.doc.segment ? `: ${pass.doc.segment}` : ""}` : ""}; umtool clips segments ${slug} lists the narrated videos)`); notes.push(`laughs from the transcript only (${pass.doc.laughs.length}); umtool clips analyze ${slug} runs the laugh scan and the voices on the sound, then proposes again`); if (pass.rec.wordsFrom === "cues") notes.push("no word timings: edges sit on the cues; pnpm ops transcribe {path, words:true, out: <project>/words.json} gives words, then umtool clips propose"); if (!pass.doc.proposals.length) notes.push("nothing to propose: no host comments or laughs were found"); diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts @@ -33,7 +33,9 @@ export type NewProjectBody = { max?: number | string | null; // The reactions seed (release 35 C1): the laugh bar and the part of the recording read. laughMin?: number | string | null; - scope?: [number | string | null, number | string | null] | null; + scope?: [number | string | null, number | string | null] | "auto" | null; + // Release 36: with scope "auto", the segment auto-scope found to read (s1, s2…; else the longest). + segment?: string | null; }; /** @@ -87,6 +89,9 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str } : {}), ...(body.seed === "reactions" && body.laughMin !== undefined && body.laughMin !== null && body.laughMin !== "" ? { laughMin: Number(body.laughMin) } : {}), + ...(body.seed === "reactions" && (body.scope === "auto" || (typeof body.segment === "string" && body.segment)) + ? { scope: "auto" as const, ...(typeof body.segment === "string" && body.segment ? { segment: body.segment } : {}) } + : {}), ...(body.seed === "reactions" && Array.isArray(body.scope) ? { scope: [body.scope[0] === null || body.scope[0] === "" ? 0 : Number(body.scope[0]), body.scope[1] === null || body.scope[1] === "" ? null : Number(body.scope[1])] as [number, number | null] } : {}), diff --git a/umtool/lib/report/reactions-r36.test.mjs b/umtool/lib/report/reactions-r36.test.mjs @@ -0,0 +1,88 @@ +// The clip finder, round two (release 36 lane B): auto-scope over a synthetic +// two-video stream, the chat signal from a synthetic chat replay, site-less +// links and the default look, and the route's `mode: "new"` job — all over +// the test kit's synthetic corpus (no python, no model, no network). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { TWO_SUBJECT_A, TWO_SUBJECT_B, writeReactionCorpus } from "yt-dlp-transcript-common/testing/clips/reactionStream.mjs"; +import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { scaffoldReportVideo } from "../projects/scaffold.mjs"; +import { clipsCommand, clipsSteps } from "./reactions.mjs"; + +const quiet = () => { + const lines = []; + return { lines, log: (s) => lines.push(s), err: (s) => lines.push(s) }; +}; + +/** A corpus with the two-video stream (and optionally its chat), and a reports root. */ +async function fixture({ two = true, chat = null, meta = null } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "clips36-")); + const channelsDir = path.join(root, "channels"); + const reportsRoot = path.join(root, "reports"); + const sitesDir = path.join(root, "sites"); + await mkdir(sitesDir, { recursive: true }); + writeReactionCorpus(channelsDir, { two, chat, meta }); + return { root, channelsDir, reportsRoot, sitesDir }; +} + +async function pointAt(dir, channelsDir) { + const file = path.join(dir, "video.manifest.json"); + const m = JSON.parse(await readFile(file, "utf8")); + m.provenance.channelsDir = path.relative(dir, channelsDir); + await writeFile(file, JSON.stringify(m, null, 2)); + return m; +} + +test("auto-scope: --scope auto reads the longest narrated video, --segment names one; roles per segment; clips segments lists them", async () => { + const f = await fixture(); + try { + const a = await scaffoldReportVideo({ root: f.reportsRoot, slug: "first", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, scope: "auto", sitesDir: f.sitesDir }); + let doc = await readReactions(a.dir); + assert.deepEqual(doc.params.scope, [120, 1347]); + assert.equal(doc.segment, "s1"); + assert.deepEqual(doc.segments.map((g) => [g.id, g.from, g.to, g.subject, g.host]), [["s1", 120, 1347, TWO_SUBJECT_A, 0], ["s2", 1500, 2390, TWO_SUBJECT_B, 0]]); + assert.equal(doc.speakers.find((s) => s.role === "subject")?.index, TWO_SUBJECT_A); + assert.ok(a.notes.some((n) => /auto-scope: s1, 120–1347 s/.test(n)), a.notes.join("\n")); + + const b = await scaffoldReportVideo({ root: f.reportsRoot, slug: "second", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s2", sitesDir: f.sitesDir }); + doc = await readReactions(b.dir); + assert.deepEqual(doc.params.scope, [1500, 2390]); + assert.equal(doc.segment, "s2"); + // The subject of THIS segment: the role code runs on the segment's turns. + assert.equal(doc.speakers.find((s) => s.role === "subject")?.index, TWO_SUBJECT_B); + assert.equal(doc.speakers.find((s) => s.role === "host")?.index, 0); + assert.ok(doc.proposals.every((p) => p.start >= 1500 && p.end <= 2390)); + + await pointAt(b.dir, f.channelsDir); + const q = quiet(); + assert.equal(await clipsCommand(["segments", "second"], { reportsRoot: f.reportsRoot, ...q }), 0); + assert.match(q.lines.join("\n"), /s1 +120\.0–1347\.0/); + assert.match(q.lines.join("\n"), /s2 +1500\.0–2390\.0 .*\(this project's scope\)/); + const j = quiet(); + assert.equal(await clipsCommand(["segments", "second", "--json"], { reportsRoot: f.reportsRoot, ...j }), 0); + assert.equal(JSON.parse(j.lines[0]).segment, "s2"); + + // Re-scoped from the CLI to the other video; an unknown segment is refused. + await pointAt(a.dir, f.channelsDir); + assert.equal(await clipsCommand(["propose", "first", "--segment", "s2"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); + doc = await readReactions(a.dir); + assert.deepEqual([doc.params.scope, doc.segment], [[1500, 2390], "s2"]); + const bad = quiet(); + assert.equal(await clipsCommand(["propose", "first", "--segment", "s9"], { reportsRoot: f.reportsRoot, ...bad }), 2); + assert.match(bad.lines.join("\n"), /no segment s9 \(there are s1, s2\)/); + assert.equal(await clipsCommand(["propose", "first", "--scope", "10:20", "--segment", "s1"], { reportsRoot: f.reportsRoot, ...quiet() }), 2); + await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "x", from: "synth-reacts/react001", seed: "chapters", channelsDir: f.channelsDir, segment: "s1" }), /go with --seed reactions/); + + // The job step carries it. + const argv = clipsSteps({ id: "first" }, { mode: "analyze", scope: "auto", segment: "s2" }).steps[0].argv; + assert.deepEqual(argv.slice(argv.indexOf("--scope"), argv.indexOf("--scope") + 4), ["--scope", "auto", "--segment", "s2"]); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs @@ -41,6 +41,7 @@ import { 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 { embedSpans, resolveTagger, runAudioScan, speakerCentroids } from "yt-dlp-transcript-common/lib/clips/scan.mjs"; +import { SEGMENT_MIN_S, findSegments, pickSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs"; import { 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"; @@ -256,6 +257,7 @@ function scanInputs(scans) { */ export function proposalPass({ rec, scans = null, params = {}, operator = {}, previous = null, timeline = [], isProtected = () => false, audio = null, now = new Date() }) { const { laughScan, centroids, laughVoices } = scanInputs(scans); + const segments = recordingSegments(rec, operator); const fixed = fixedClips(timeline, { channel: rec.channel, video: rec.video, isProtected }); const a = analyze({ turns: rec.turns, @@ -289,6 +291,8 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr moments: a.moments, proposals: applied.proposals.map((p) => ({ id: p.id, start: p.start, end: p.end, score: p.score, moments: p.moments ?? [], used: p.used, clipId: p.clipId, why: p.why })), laughSource: a.laughSource, + segments, + segment: segmentOfScope(segments, a.params.scope), scans: { laughs: scans?.audio ? { model: scans.audio.model?.file ?? null, windows: scans.audio.windows, madeAt: scans.audio.madeAt ?? null } : null, voices: scans?.voices ? { model: scans.voices.model ?? null, madeAt: scans.voices.madeAt ?? null } : null, @@ -299,6 +303,56 @@ export function proposalPass({ rec, scans = null, params = {}, operator = {}, pr return { doc, timeline: applied.timeline, changes: applied.changes, analysis: a }; } +// ---- auto-scope (release 36 B1) ----------------------------------------------------- + +/** The host the operator named, if any (`{index: role}`). */ +function operatorHost(operator) { + const k = Object.entries(operator ?? {}).find(([, v]) => v === "host")?.[0]; + return k === undefined ? null : Number(k); +} + +/** The recording's narrated-video segments (lib/clips/segments.mjs), the operator's host left out of the counting. */ +export function recordingSegments(rec, operator = {}) { + return findSegments({ turns: rec.turns, duration: rec.duration, host: operatorHost(operator) }); +} + +/** The segment a scope is (its edges within 0.01 s), or null. */ +export function segmentOfScope(segments, scope) { + if (!Array.isArray(scope)) return null; + const hit = segments.find((g) => Math.abs(g.from - scope[0]) < 0.01 && scope[1] !== null && Math.abs(g.to - scope[1]) < 0.01); + return hit ? hit.id : null; +} + +/** + * `--scope auto`: the segment named (`segment`), else the longest. When the + * recording has none (no cluster holds the long turns for SEGMENT_MIN_S), the + * whole recording is read and `note` says so. + * @returns {{ scope: [number, number] | null, segment: any, segments: any[], note: string }} + */ +export function autoScope(rec, { segment = null, operator = {} } = {}) { + const segments = recordingSegments(rec, operator); + let seg; + try { + seg = pickSegment(segments, segment); + } catch (e) { + throw new ClipsError(e instanceof Error ? e.message : String(e)); + } + if (!seg) { + return { scope: null, segment: null, segments, note: `auto-scope: no narrated video found (no speaker holds the long turns for ${SEGMENT_MIN_S} s) — the whole recording is read` }; + } + const list = segments.map((g) => `${g.id} ${Math.round(g.from)}–${Math.round(g.to)} s`).join(", "); + return { scope: [seg.from, seg.to], segment: seg, segments, note: `auto-scope: ${seg.id}, ${Math.round(seg.from)}–${Math.round(seg.to)} s (${seg.why}); segments: ${list}` }; +} + +/** Params with `scope: "auto"` (and `segment`) resolved against the recording; anything else as given. */ +export function resolveParams(rec, params, operator = {}, say = () => {}) { + if (params?.scope !== "auto" && !(params?.segment && params?.scope === undefined)) return params; + const r = autoScope(rec, { segment: params.segment ?? null, operator }); + say(r.note); + const { segment: _s, ...rest } = params; + return { ...rest, scope: r.scope ?? "all" }; +} + /** What a pass did, in one line. */ export function passSummary(doc, changes) { const used = doc.proposals.filter((p) => p.used); @@ -332,11 +386,13 @@ async function rulingsGuard(dir, manifest) { * what it returns; `umtool clips analyze` then runs the scans and re-proposes. * @param {{ channelsDir: string, channel: string, video: string, target?: number }} o */ -export async function seedReactions({ channelsDir, channel, video, target, laughMin, scope }) { +export async function seedReactions({ channelsDir, channel, video, target, laughMin, scope, segment = null }) { const rec = await loadRecording({ channelsDir, channel, video }); - const params = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}) }; - const pass = proposalPass({ rec, params }); - return { ...pass, rec }; + const notes = []; + const given = { ...(target !== undefined ? { target } : {}), ...(laughMin !== undefined ? { laughMin } : {}), ...(scope ? { scope } : {}), ...(segment ? { segment } : {}) }; + const params = resolveParams(rec, given, {}, (n) => notes.push(n)); + const pass = proposalPass({ rec, params: { ...params, ...(params.scope === "all" ? { scope: null } : {}) } }); + return { ...pass, rec, notes }; } /** @@ -365,7 +421,7 @@ export async function proposeProject({ project, from = null, params = {}, host = operator[host] = "host"; } const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video; - const merged = mergeParams(sameSource ? previous.params : null, params); + const merged = mergeParams(sameSource ? previous.params : null, resolveParams(rec, params, operator, attempt === 0 ? say : () => {})); const s = scans === undefined ? await readScans(project.dir, rec.channel, rec.video) : scans; const isProtected = await rulingsGuard(project.dir, manifest); const passOf = (sc) => proposalPass({ rec, scans: sc, params: merged, operator, previous: sameSource ? previous : null, timeline: manifest.timeline ?? [], isProtected, audio, now }); @@ -434,6 +490,7 @@ export const CLIPS_USAGE = [ "usage: umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--progress ndjson] [--json]", " umtool clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]", " umtool clips show <project> [--json]", + " umtool clips segments <project> [--json]", "", "The clip finder: a long recording (a stream, a podcast) to proposed clips, written to the", `manifest (each marked "assist": by the assistant) and to <project>/${REACTIONS_FILE}.`, @@ -444,7 +501,9 @@ export const CLIPS_USAGE = [ "params: --target S (the cut's length, default 600) --laugh-min X (0..1, default 0.25)", " --merge-gap S (6) --setup-max S (20) --clip-max S (75); kept in reactions.json for the next run", "scope: --scope FROM:TO (seconds; TO may be empty: to the end; `all` clears it), or --from S / --to S with numbers:", - " only that part of the recording is read (a stream that reacts to two videos, one at a time)", + " only that part of the recording is read (a stream that reacts to two videos, one at a time);", + " --scope auto: the narrated video found in the speakers' turns (--segment s2 names one, else the longest)", + " segments the narrated-video spans auto-scope finds in the recording (where one long-turn speaker holds the floor)", "--host N speaker N is the host (your word: kept until you change it)", "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>).", @@ -455,7 +514,7 @@ export const CLIPS_USAGE = [ const PARAM_FLAGS = { "--target": "target", "--laugh-min": "laughMin", "--merge-gap": "mergeGap", "--setup-max": "setupMax", "--clip-max": "clipMax" }; function parse(args) { - const valued = new Set(["--from", "--to", "--scope", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]); + const valued = new Set(["--from", "--to", "--scope", "--segment", "--host", "--progress", "--words", ...Object.keys(PARAM_FLAGS)]); /** @type {Record<string, string[]>} */ const flags = {}; const positional = []; @@ -482,13 +541,20 @@ export function paramsFromFlags(p) { }; if (p.has("--scope")) { const v = String(p.one("--scope")); - if (v === "all") out.scope = "all"; + if (v === "all" || v === "auto") out.scope = v; else { const m = /^(\d+(?:\.\d+)?)?:(\d+(?:\.\d+)?)?$/.exec(v); - if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), or all`); + if (!m) throw new ClipsError(`--scope ${v}: FROM:TO in seconds (either may be empty), auto, or all`); out.scope = [m[1] ? Number(m[1]) : 0, m[2] ? Number(m[2]) : null]; } } + if (p.has("--segment")) { + const id = String(p.one("--segment")); + if (!/^s\d+$/.test(id)) throw new ClipsError(`--segment ${id}: a segment id (s1, s2, …; umtool clips segments <project> lists them)`); + if (out.scope !== undefined && out.scope !== "auto") throw new ClipsError("--segment goes with --scope auto (or alone)"); + out.scope = "auto"; + out.segment = id; + } if (p.has("--from") && isSeconds(p.one("--from"))) out.scopeFrom = secs("--from", p.one("--from")); if (p.has("--to")) out.scopeTo = secs("--to", p.one("--to")); for (const [flag, key] of Object.entries(PARAM_FLAGS)) { @@ -525,7 +591,8 @@ function showLines(doc) { const src = doc.source; lines.push(`${src.channel}/${src.video} ${Math.round(src.duration)} s words: ${src.wordsFrom ?? (src.words ? src.words : "cues")} diarization: ${src.diarization?.generatedAt ?? "?"}`); for (const s of doc.speakers) lines.push(` speaker ${s.index} ${s.label.padEnd(10)} ${s.role.padEnd(8)} ${String(Math.round(s.seconds)).padStart(6)} s ${String(s.turns).padStart(5)} turns ${s.how}${s.sameAs !== undefined ? ` (same voice as ${s.sameAs})` : ""}`); - if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}–${doc.params.scope[1] ?? "end"} s`); + if (doc.params.scope) lines.push(` scope: ${doc.params.scope[0]}–${doc.params.scope[1] ?? "end"} s${doc.segment ? ` (segment ${doc.segment})` : ""}`); + if (Array.isArray(doc.segments) && doc.segments.length) lines.push(` segments: ${doc.segments.map((g) => `${g.id} ${Math.round(g.from)}–${Math.round(g.to)} s (subject ${g.subject})`).join(", ")}`); const byVoice = doc.laughs.filter((l) => l.by === "voice").length; const voiced = doc.laughs.filter((l) => l.voice).length; lines.push(` laughs: ${doc.laughs.length} (${doc.laughSource ?? "?"}${voiced ? `; ${voiced} voice-checked, ${byVoice} re-attributed by voice` : ""}), moments: ${doc.moments.length}`); @@ -537,6 +604,34 @@ function showLines(doc) { } /** + * The recording's segments for `umtool clips segments`: found afresh from the + * diarization on disk (the operator's host from reactions.json left out), with + * which one the project's scope is. + */ +export async function projectSegments(project, { from = null } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new ClipsError(`${project.id} has no manifest`); + const previous = await readReactions(project.dir); + const src = from ?? (previous ? { channel: previous.source.channel, video: previous.source.video } : null); + if (!src) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} yet — say which recording: --from <channel>/<id>`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + if (!channelsDir) throw new ClipsError("no channels directory (CHANNELS_DIR)"); + const rec = await loadRecording({ channelsDir, channel: src.channel, video: src.video, projectDir: project.dir }); + const segments = recordingSegments(rec, operatorRoles(previous)); + const scope = previous && previous.source.channel === rec.channel && previous.source.video === rec.video ? previous.params?.scope ?? null : null; + return { channel: rec.channel, video: rec.video, duration: Math.round(rec.duration * 100) / 100, scope, segment: segmentOfScope(segments, scope), segments }; +} + +function segmentLines(r) { + const lines = [`${r.channel}/${r.video} ${Math.round(r.duration)} s ${r.segments.length} segment(s)${r.scope ? `; this project reads ${r.scope[0]}–${r.scope[1] ?? "end"} s` : ""}`]; + for (const g of r.segments) { + lines.push(` ${g.id} ${g.from.toFixed(1).padStart(8)}–${g.to.toFixed(1).padEnd(8)} ${String(Math.round(g.to - g.from)).padStart(5)} s subject ${g.subject}, host ${g.host ?? "?"} ${g.why}${g.id === r.segment ? " (this project's scope)" : ""}`); + } + if (!r.segments.length) lines.push(" none: no speaker holds the long turns for long enough (a scope by hand: --scope FROM:TO)"); + return lines; +} + +/** * `umtool clips …` * @param {string[]} args everything after `clips` * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, tagger?: any, engine?: any, now?: Date }} [opts] @@ -545,11 +640,16 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con try { const sub = args[0]; const p = parse(args.slice(1)); - if (!sub || sub === "--help" || sub === "help" || p.has("--help") || !["analyze", "propose", "show"].includes(sub)) { + if (!sub || sub === "--help" || sub === "help" || p.has("--help") || !["analyze", "propose", "show", "segments"].includes(sub)) { log(CLIPS_USAGE); return sub && sub !== "--help" && sub !== "help" && !p.has("--help") ? 2 : 0; } const project = await pickProject(p.positional[0], reportsRoot); + if (sub === "segments") { + const r = await projectSegments(project, { from: parseFrom(p.one("--from")) }); + log(p.has("--json") ? JSON.stringify(r, null, 1) : segmentLines(r).join("\n")); + return 0; + } if (sub === "show") { const doc = await readReactions(project.dir); if (!doc) throw new ClipsError(`${project.id} has no ${REACTIONS_FILE} — umtool clips analyze ${project.id} --from <channel>/<id>`); @@ -590,7 +690,7 @@ export async function clipsCommand(args, { reportsRoot = REPORTS_ROOT, log = con } else { const t0 = Date.now(); const sameSource = previous && previous.source.channel === rec.channel && previous.source.video === rec.video; - const { scope } = mergeParams(sameSource ? previous.params : null, params); + const { scope } = mergeParams(sameSource ? previous.params : null, resolveParams(rec, params, operatorRoles(previous))); scans = await scanRecording({ projectDir: project.dir, rec, audio, laughs: !p.has("--no-laughs"), voices: !p.has("--no-voices"), rescan: p.has("--rescan"), tagger, engine, scope, onProgress: emit, say, @@ -621,7 +721,7 @@ const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", * running this command, nice'd (the laugh scan is CPU for a few minutes on a * long stream, one thread; the proposal pass is arithmetic). * @param {{ id: string }} project - * @param {{ mode?: "analyze" | "propose", from?: string, target?: number, host?: number, laughMin?: number, scope?: [number, number | null] }} [req] + * @param {{ mode?: "analyze" | "propose", from?: string, target?: number, host?: number, laughMin?: number, scope?: [number, number | null] | "auto" | "all", segment?: string }} [req] */ export function clipsSteps(project, req = {}) { const mode = req.mode === "propose" ? "propose" : "analyze"; @@ -631,6 +731,8 @@ export function clipsSteps(project, req = {}) { if (Number.isInteger(req.host) && /** @type {number} */ (req.host) >= 0) argv.push("--host", String(req.host)); if (num(req.laughMin) && req.laughMin >= PARAM_BOUNDS.laughMin[0] && req.laughMin <= PARAM_BOUNDS.laughMin[1]) argv.push("--laugh-min", String(req.laughMin)); if (Array.isArray(req.scope) && num(req.scope[0]) && (req.scope[1] === null || num(req.scope[1]))) argv.push("--scope", `${req.scope[0]}:${req.scope[1] ?? ""}`); + else if (req.scope === "auto" || req.scope === "all") argv.push("--scope", req.scope); + if (typeof req.segment === "string" && /^s\d+$/.test(req.segment) && req.scope !== "all" && !Array.isArray(req.scope)) argv.push("--segment", req.segment); argv.push("--progress", "ndjson"); return { kind: `clips-${mode} ${project.id}`,