// The clip finder, round two (release 36 lane B): auto-scope over a synthetic // two-video stream, the chat signal from a synthetic chat replay, site-less // links and the default look, and the route's `mode: "new"` job — all over // the test kit's synthetic corpus (no python, no model, no network). // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { TWO_SUBJECT_A, TWO_SUBJECT_B, reactionAudio, writeReactionCorpus } from "yt-dlp-transcript-common/testing/clips/reactionStream.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { scaffoldReportVideo } from "../projects/scaffold.mjs"; import { clipsCommand, clipsSteps } from "./reactions.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const KIT = path.resolve(HERE, "..", "..", "..", "common", "testing", "audio"); const TAGGER = { python: process.execPath, script: path.join(KIT, "fakeAudioTag.mjs"), model: path.join(KIT, "fakeAudioTag.mjs"), labels: "none.csv", threads: 1, available: true }; const ENGINE = { python: process.execPath, script: path.join(KIT, "fakeSpeakerEmbed.mjs"), model: "fake.onnx", threads: 1 }; const hasFfmpeg = (() => { try { execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); return true; } catch { return false; } })(); const quiet = () => { const lines = []; return { lines, log: (s) => lines.push(s), err: (s) => lines.push(s) }; }; /** A corpus with the two-video stream (and optionally its chat), and a reports root. */ async function fixture({ two = true, chat = null, meta = null, audio = false } = {}) { const root = await mkdtemp(path.join(tmpdir(), "clips36-")); const channelsDir = path.join(root, "channels"); const reportsRoot = path.join(root, "reports"); const sitesDir = path.join(root, "sites"); await mkdir(sitesDir, { recursive: true }); writeReactionCorpus(channelsDir, { two, chat, meta, audio: audio ? encodeWav16(reactionAudio()) : null }); return { root, channelsDir, reportsRoot, sitesDir }; } async function pointAt(dir, channelsDir) { const file = path.join(dir, "video.manifest.json"); const m = JSON.parse(await readFile(file, "utf8")); m.provenance.channelsDir = path.relative(dir, channelsDir); await writeFile(file, JSON.stringify(m, null, 2)); return m; } test("auto-scope: --scope auto reads the longest narrated video, --segment names one; roles per segment; clips segments lists them", async () => { const f = await fixture(); try { const a = await scaffoldReportVideo({ root: f.reportsRoot, slug: "first", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, scope: "auto", sitesDir: f.sitesDir }); let doc = await readReactions(a.dir); assert.deepEqual(doc.params.scope, [120, 1347]); assert.equal(doc.segment, "s1"); assert.deepEqual(doc.segments.map((g) => [g.id, g.from, g.to, g.subject, g.host]), [["s1", 120, 1347, TWO_SUBJECT_A, 0], ["s2", 1500, 2390, TWO_SUBJECT_B, 0]]); assert.equal(doc.speakers.find((s) => s.role === "subject")?.index, TWO_SUBJECT_A); assert.ok(a.notes.some((n) => /auto-scope: s1, 120–1347 s/.test(n)), a.notes.join("\n")); const b = await scaffoldReportVideo({ root: f.reportsRoot, slug: "second", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s2", sitesDir: f.sitesDir }); doc = await readReactions(b.dir); assert.deepEqual(doc.params.scope, [1500, 2390]); assert.equal(doc.segment, "s2"); // The subject of THIS segment: the role code runs on the segment's turns. assert.equal(doc.speakers.find((s) => s.role === "subject")?.index, TWO_SUBJECT_B); assert.equal(doc.speakers.find((s) => s.role === "host")?.index, 0); assert.ok(doc.proposals.every((p) => p.start >= 1500 && p.end <= 2390)); await pointAt(b.dir, f.channelsDir); const q = quiet(); assert.equal(await clipsCommand(["segments", "second"], { reportsRoot: f.reportsRoot, ...q }), 0); assert.match(q.lines.join("\n"), /s1 +120\.0–1347\.0/); assert.match(q.lines.join("\n"), /s2 +1500\.0–2390\.0 .*\(this project's scope\)/); const j = quiet(); assert.equal(await clipsCommand(["segments", "second", "--json"], { reportsRoot: f.reportsRoot, ...j }), 0); assert.equal(JSON.parse(j.lines[0]).segment, "s2"); // Re-scoped from the CLI to the other video; an unknown segment is refused. await pointAt(a.dir, f.channelsDir); assert.equal(await clipsCommand(["propose", "first", "--segment", "s2"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); doc = await readReactions(a.dir); assert.deepEqual([doc.params.scope, doc.segment], [[1500, 2390], "s2"]); const bad = quiet(); assert.equal(await clipsCommand(["propose", "first", "--segment", "s9"], { reportsRoot: f.reportsRoot, ...bad }), 2); assert.match(bad.lines.join("\n"), /no segment s9 \(there are s1, s2\)/); assert.equal(await clipsCommand(["propose", "first", "--scope", "10:20", "--segment", "s1"], { reportsRoot: f.reportsRoot, ...quiet() }), 2); await assert.rejects(scaffoldReportVideo({ root: f.reportsRoot, slug: "x", from: "synth-reacts/react001", seed: "chapters", channelsDir: f.channelsDir, segment: "s1" }), /go with --seed reactions/); // The job step carries it. const argv = clipsSteps({ id: "first" }, { mode: "analyze", scope: "auto", segment: "s2" }).steps[0].argv; assert.deepEqual(argv.slice(argv.indexOf("--scope"), argv.indexOf("--scope") + 4), ["--scope", "auto", "--segment", "s2"]); } finally { await rm(f.root, { recursive: true, force: true }); } }); test("the chat signal: a replay beside the recording adds chat moments; the seed (no scan) takes the default lag; no replay changes nothing", async () => { const f = await fixture({ two: false, chat: { lag: 6, chatOnly: [200] } }); const g = await fixture({ two: false }); try { const a = await scaffoldReportVideo({ root: f.reportsRoot, slug: "chat", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 120, sitesDir: f.sitesDir }); const doc = await readReactions(a.dir); assert.ok(doc.chat); assert.equal(doc.chat.source, "live_chat.cues.json"); assert.deepEqual([doc.chat.lagS, doc.chat.lag.how], [6, "default"]); assert.equal(doc.chat.bins.hop, 2); assert.ok(doc.moments.some((m) => m.kind === "chat" && m.messages >= 3)); const b = await scaffoldReportVideo({ root: g.reportsRoot, slug: "chat", from: "synth-reacts/react001", seed: "reactions", channelsDir: g.channelsDir, target: 120, sitesDir: g.sitesDir }); const none = await readReactions(b.dir); assert.equal(none.chat, null); assert.ok(none.moments.every((m) => m.kind !== "chat")); // The chat-only burst is a proposal the plain stream does not have. assert.ok(doc.proposals.length > none.proposals.length); } finally { await rm(f.root, { recursive: true, force: true }); await rm(g.root, { recursive: true, force: true }); } }); test("clips analyze with a chat replay: the lag cross-correlated with the laugh scan, named in the log", { skip: !hasFfmpeg && "no ffmpeg" }, async () => { const f = await fixture({ two: false, audio: true, chat: { lag: 8 } }); try { const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "chat", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, target: 60, sitesDir: f.sitesDir }); await pointAt(r.dir, f.channelsDir); const q = quiet(); assert.equal(await clipsCommand(["analyze", "chat", "--no-voices", "--progress", "ndjson"], { reportsRoot: f.reportsRoot, ...q, tagger: TAGGER, engine: ENGINE }), 0, q.lines.join("\n")); const doc = await readReactions(r.dir); assert.equal(doc.laughSource, "model"); assert.equal(doc.chat.lag.how, "xcorr", JSON.stringify(doc.chat.lag)); assert.ok(Math.abs(doc.chat.lagS - 8) <= 2, `lag ${doc.chat.lagS}`); assert.match(q.lines.join("\n"), new RegExp(`chat: \\d+ message\\(s\\), \\d+ laugh burst\\(s\\); lag ${doc.chat.lagS} s — cross-correlated with the laugh scan`)); } finally { await rm(f.root, { recursive: true, force: true }); } }); test("mode new (the editor's Find clips): a project scaffolded for the chosen segment with the words copied in; asked again, the same project analyzed again", async () => { const f = await fixture({ chat: true }); const { planClipsNew, parseNewBody } = await import("./clipsNew.mjs"); try { const wordsPath = path.join(f.root, "words-out.json"); const { twoVideoStream } = await import("yt-dlp-transcript-common/testing/clips/reactionStream.mjs"); await writeFile(wordsPath, JSON.stringify({ path: "/x", words: twoVideoStream().words })); const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir }; const a = await planClipsNew({ mode: "new", slug: "find-b", from: "synth-reacts/react001", scope: "auto", segment: "s2", wordsPath, target: 120 }, opts); assert.equal(a.created, true); assert.equal(a.project.id, "find-b"); assert.equal(a.segment, "s2"); assert.deepEqual(a.scope, [1500, 2390]); assert.deepEqual(a.segments.map((g) => g.id), ["s1", "s2"]); assert.deepEqual(JSON.parse(await readFile(path.join(a.dir ?? a.project.dir, "words.json"), "utf8")).words.length, twoVideoStream().words.length); assert.equal(a.plan.kind, "clips-analyze find-b"); assert.deepEqual(a.plan.steps[0].argv.slice(5, 8), ["clips", "analyze", "find-b"]); const doc = await readReactions(a.project.dir); assert.ok(doc.chat, "the chat replay read"); // An operator's clip in it; then the editor asks again for the same video's s2: the SAME project, as it is. const mf = path.join(a.project.dir, "video.manifest.json"); const m = JSON.parse(await readFile(mf, "utf8")); m.timeline[0].assist.by = "operator"; await writeFile(mf, JSON.stringify(m, null, 2)); const again = await planClipsNew({ mode: "new", slug: "find-b-2", from: "synth-reacts/react001", segment: "s2", wordsPath }, opts); assert.equal(again.created, false); assert.equal(again.project.id, "find-b"); assert.ok(again.notes.some((n) => /words\.json kept/.test(n))); assert.equal(JSON.parse(await readFile(mf, "utf8")).timeline[0].assist.by, "operator"); // The other video is a new project; the default scope is auto (the longest: s1). const b = await planClipsNew({ mode: "new", slug: "find-a", from: "synth-reacts/react001" }, opts); assert.deepEqual([b.created, b.segment, b.scope], [true, "s1", [120, 1347]]); // A slug already taken by another recording's project: 409. Refusals: 400 / 404. await assert.rejects(planClipsNew({ mode: "new", slug: "find-a", from: "synth-reacts/react001", scope: [0, 60] }, opts), (e) => e.status === 409); await assert.rejects(planClipsNew({ mode: "new", slug: "zz", from: "synth-reacts/nope" }, opts), (e) => e.status === 404); await assert.rejects(planClipsNew({ mode: "new", slug: "zz", from: "synth-reacts/react001", segment: "s7" }, opts), (e) => e.status === 400 && /no segment s7/.test(e.message)); assert.throws(() => parseNewBody({ slug: "Bad Slug", from: "a/b" }), /slug/); assert.throws(() => parseNewBody({ slug: "ok", from: "../b" }), /from/); assert.throws(() => parseNewBody({ slug: "ok", from: "a/b", wordsPath: "rel/words.json" }), /absolute/); assert.throws(() => parseNewBody({ slug: "ok", from: "a/b", scope: [0, 10], segment: "s1" }), /segment goes with scope "auto"/); assert.deepEqual(parseNewBody({ slug: "ok", from: "a/b", scope: [0, 10] }).scope, [0, 10]); } finally { await rm(f.root, { recursive: true, force: true }); } }); test("the route's caller: no header is the page, umtool's WORKER_TOKEN the editor, anything else a 401", async () => { const { routeCaller } = await import("../annotations/agentAuth.mjs"); assert.deepEqual(routeCaller(null, "tok"), { ok: true, by: "page" }); assert.deepEqual(routeCaller("Bearer tok", "tok"), { ok: true, by: "worker" }); const wrong = routeCaller("Bearer nope", "tok", "/api/report/clips"); assert.equal(wrong.ok, false); assert.equal(wrong.status, 401); assert.match(wrong.error, /^\/api\/report\/clips: that bearer token is not umtool's WORKER_TOKEN/); assert.match(routeCaller("Bearer tok", "", "/api/report/clips").error, /holds no WORKER_TOKEN, so no editor can call it/); assert.equal(routeCaller("Basic x", "tok").ok, false); }); test("a channel on no site: each clip links its platform page, provenance.channel from the metadata, the site-less look; no dead-origin decision", async () => { const meta = { webpage_url: "https://www.youtube.com/watch?v=react001", channel: "Synth Reacts Channel", extractor_key: "Youtube" }; const f = await fixture({ meta }); const { lintManifest } = await import("umtool-report-to-video/lint"); const { decisionsFor, summarise } = await import("../projects/core.mjs"); const { walkProjects } = await import("../projects/walk.mjs"); const { SITELESS_LOOK } = await import("../projects/scaffold.mjs"); try { const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "siteless", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s1", target: 120, sitesDir: f.sitesDir }); const m = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8")); assert.ok(m.timeline.length > 0); for (const c of m.timeline) assert.equal(c.citeUrl, `https://www.youtube.com/watch?v=react001&t=${c.cite}s`); assert.equal(m.provenance.channel, "Synth Reacts Channel"); assert.equal(m.provenance.siteOrigin, ""); assert.deepEqual( { headerHeight: m.render.headerHeight, footerHeight: m.render.footerHeight, qr: m.render.qr, transition: m.render.transition, transitionStyle: m.render.transitionStyle, loudness: m.render.loudness, room: m.render.room }, { ...SITELESS_LOOK, loudness: { target: -16 }, room: { tail: true, head: true } }, ); assert.ok(r.notes.some((n) => /no site carries synth-reacts: each clip links YouTube's page/.test(n)), r.notes.join("\n")); // The build's validators and lint take it (render.loudness is a key they do not refuse). const lint = lintManifest(m, { validators: true }); assert.deepEqual(lint.errors.filter((e) => /loudness|transition|qr|render/i.test(e)), []); // No siteOrigin is not a defect here: every clip links itself. const [ref] = (await walkProjects(f.reportsRoot)).filter((p) => p.id === "siteless"); assert.ok(!(await decisionsFor(ref, f.reportsRoot)).some((d) => d.target === "provenance.siteOrigin")); assert.ok(!(await summarise(ref, f.reportsRoot)).flags.includes("dead QR origin")); // A later pass keeps the rule: every clip it writes links itself. await pointAt(r.dir, f.channelsDir); assert.equal(await clipsCommand(["propose", "siteless", "--target", "300"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); const after = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8")); assert.ok(after.timeline.length > m.timeline.length); for (const c of after.timeline) assert.equal(c.citeUrl, `https://www.youtube.com/watch?v=react001&t=${c.cite}s`); } finally { await rm(f.root, { recursive: true, force: true }); } }); test("a channel on a public site, or a recording with no watch page: no links written, hard cuts as before", async () => { const meta = { webpage_url: "https://www.youtube.com/watch?v=react001", channel: "Synth Reacts Channel" }; const f = await fixture({ meta }); const g = await fixture(); try { await mkdir(path.join(f.sitesDir, "synthsite"), { recursive: true }); await writeFile(path.join(f.sitesDir, "synthsite", "site.json"), JSON.stringify({ siteId: "synthsite", siteUrl: "https://synth.example", channels: [{ slug: "synth-reacts" }] })); // A private site (no siteUrl) does not count. await mkdir(path.join(g.sitesDir, "private"), { recursive: true }); await writeFile(path.join(g.sitesDir, "private", "site.json"), JSON.stringify({ siteId: "private", channels: [{ slug: "synth-reacts" }] })); const { channelOnPublicSite } = await import("./reactions.mjs"); assert.equal(await channelOnPublicSite("synth-reacts", f.sitesDir), true); assert.equal(await channelOnPublicSite("synth-reacts", g.sitesDir), false); for (const [x, slug] of [[f, "onsite"], [g, "nopage"]]) { const r = await scaffoldReportVideo({ root: x.reportsRoot, slug, from: "synth-reacts/react001", seed: "reactions", channelsDir: x.channelsDir, target: 120, sitesDir: x.sitesDir }); const m = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8")); assert.equal(m.render.transition, 0, slug); assert.equal(m.render.headerHeight, 56, slug); assert.ok(m.timeline.every((c) => !("citeUrl" in c)), slug); } // The site's channel still gets its name from the metadata. assert.equal(JSON.parse(await readFile(path.join(f.reportsRoot, "onsite", "video.manifest.json"), "utf8")).provenance.channel, "Synth Reacts Channel"); } finally { await rm(f.root, { recursive: true, force: true }); await rm(g.root, { recursive: true, force: true }); } }); test("--keep-cut: a pass that lists without touching the cut — no clip moved, removed or added; the editor's re-analysis uses it", async () => { const f = await fixture({ chat: true }); try { const r = await scaffoldReportVideo({ root: f.reportsRoot, slug: "kept", from: "synth-reacts/react001", seed: "reactions", channelsDir: f.channelsDir, segment: "s1", target: 60, sitesDir: f.sitesDir }); await pointAt(r.dir, f.channelsDir); const mf = path.join(r.dir, "video.manifest.json"); const before = await readFile(mf, "utf8"); const q = quiet(); assert.equal(await clipsCommand(["propose", "kept", "--keep-cut", "--target", "900"], { reportsRoot: f.reportsRoot, ...q }), 0, q.lines.join("\n")); assert.deepEqual(JSON.parse(await readFile(mf, "utf8")).timeline, JSON.parse(before).timeline); const doc = await readReactions(r.dir); const clipIds = JSON.parse(before).timeline.map((c) => c.id).sort(); assert.deepEqual(doc.proposals.filter((p) => p.used).map((p) => p.clipId).sort(), clipIds); assert.ok(doc.proposals.some((p) => !p.used), "the rest listed, unused"); assert.match(q.lines.join("\n"), /clips \+0 ~0 -0/); // Without it, the larger target adds clips. assert.equal(await clipsCommand(["propose", "kept", "--target", "900"], { reportsRoot: f.reportsRoot, ...quiet() }), 0); assert.ok(JSON.parse(await readFile(mf, "utf8")).timeline.length > clipIds.length); // The job step carries it; the editor's re-analysis of an existing project asks for it. assert.ok(clipsSteps({ id: "kept" }, { mode: "analyze", keepCut: true }).steps[0].argv.includes("--keep-cut")); const { planClipsNew } = await import("./clipsNew.mjs"); const again = await planClipsNew({ mode: "new", slug: "kept-2", from: "synth-reacts/react001", segment: "s1" }, { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir }); assert.equal(again.created, false); assert.ok(again.plan.steps[0].argv.includes("--keep-cut")); } finally { await rm(f.root, { recursive: true, force: true }); } });