commit 35313baec6513a4df0859e2a5d33fe95a8f052bd
parent 80ee64bd70befb4f5598a8c5750f79c01fae36c3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 17 Oct 2026 16:45:03 -0400
Merge r33/phrase-seed: umtool --seed phrase (a montage from every time a phrase was said; the preferred channel's copies)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 723 insertions(+), 9 deletions(-)
diff --git a/common/lib/montage/phraseScan.d.mts b/common/lib/montage/phraseScan.d.mts
@@ -0,0 +1,50 @@
+export const REPEAT_WINDOW_S: number;
+export const TWIN_DAYS: number[];
+export const TWIN_DURATION_RATIO: number;
+export const PLACE_MIN_SCORE: number;
+export const PLACE_MIN_WORDS: number;
+export const TWIN_CLOSE_RATIO: number;
+export const SAME_HIT_MIN_SCORE: number;
+export const FOLD_DAYS: number;
+export const FOLD_MIN_OVERLAP: number;
+
+export type Cue = { start: number; end?: number; text?: string };
+export type CueHit = { start: number; end: number; cueFirst: number; cueLast: number; match: string; context: string };
+export type PhraseInstance = CueHit & {
+ slug: string;
+ videoId: string;
+ platform: string | null;
+ source: string | null;
+ date: string | null;
+ title: string | null;
+ duration: number | null;
+ speakerCheck?: boolean;
+ availability?: string | null;
+ via?: { slug: string; videoId: string; start: number; score: number };
+ alsoIn?: { slug: string; videoId: string; start: number }[];
+};
+export type PhraseScanResult = {
+ instances: PhraseInstance[];
+ hits: PhraseInstance[];
+ dropped: (PhraseInstance & { why: string })[];
+ scanned: number;
+};
+
+export function words(t: unknown): string[];
+export function dayNumber(s: unknown): number | null;
+export function phraseRegExp(phrase: string | RegExp): RegExp;
+export function hitsInCues(cues: Cue[], re: RegExp): CueHit[];
+export function locateInCues(cues: Cue[], contextWords: string[]): { score: number; index: number | null };
+export function phraseScan(opts: {
+ channelsDir: string;
+ channels: string[];
+ phrase: string | RegExp;
+ prefer?: string | null;
+ exclude?: string | RegExp | null;
+ onProgress?: (done: number, total: number) => void;
+}): Promise<PhraseScanResult>;
+export function niceDate(s: unknown): string;
+export function instancesAsClips(
+ instances: PhraseInstance[],
+ opts?: { pad?: number; idPrefix?: string },
+): Record<string, unknown>[];
diff --git a/common/lib/montage/phraseScan.mjs b/common/lib/montage/phraseScan.mjs
@@ -0,0 +1,334 @@
+// Every time a phrase was said, across channels: the instances a montage is cut from.
+//
+// Reads each video's transcript.cues.json under the channels named (read-only),
+// matches the phrase over the JOINED cue text — so a phrase a caption line
+// split in two is still found — and folds what is the same moment twice:
+//
+// - a rolling caption repeats its line in the next cue: hits under 8 s apart
+// in one video are one hit;
+// - a stream on the PREFERRED channel (a Rumble copy, say) is the one to cut
+// from: another channel's hit whose video has a twin there (an upload date
+// −1..+2 days, a duration within 10 %, and a title word in common or a
+// duration within 1 %) is found in the twin's transcript by its surrounding
+// content words (at least 6 of them, 60 % found) and cut from the twin instead; one that cannot
+// be placed stays on its own channel;
+// - the same words twice within 3 days (a stream and its clip upload) are one
+// instance, the first kept, the rest listed as `alsoIn`.
+//
+// Nothing is guessed about WHO said it: a context that matches `exclude` (a
+// chat line read out, a co-host) is dropped into `dropped` with the reason, and
+// a context with a caption speaker change (`>>`) is marked `speakerCheck` for
+// the ear. Plain ESM so `umtool new` runs it from a terminal with no server.
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+
+export const REPEAT_WINDOW_S = 8;
+export const TWIN_DAYS = [-1, 0, 1, 2];
+export const TWIN_DURATION_RATIO = 0.1;
+export const PLACE_MIN_SCORE = 0.6;
+// A context this short matches too much: it is never placed in a twin by its words.
+export const PLACE_MIN_WORDS = 6;
+// A twin by date and duration alone is often another upload of the same day: it
+// must also share a title word, unless the durations agree this closely.
+export const TWIN_CLOSE_RATIO = 0.01;
+export const SAME_HIT_MIN_SCORE = 0.35;
+export const FOLD_DAYS = 3;
+export const FOLD_MIN_OVERLAP = 0.6;
+
+const squash = (t) => String(t ?? "").replace(/\s+/g, " ").trim();
+export const words = (t) => String(t ?? "").toLowerCase().match(/[a-z0-9']+/g) ?? [];
+const bag = (t) => new Set(words(t).filter((w) => w.length > 2));
+// What placing a hit by its words counts: no function words, which every
+// stretch of speech shares.
+const STOP = new Set("the and for are but not you all any can had her was one our out day get has him his how man new now old see two way who boy did its let put say she too use that with have this will your from they know want been good much some time very when come here just like long make many over such take than them well were what into it's don't i'm that's there their about would could should really because going think yeah okay right also these those then thing things people mean even".split(" "));
+const content = (ws) => ws.filter((w) => w.length > 2 && !STOP.has(w));
+const TITLE_STOP = new Set(["the", "and", "for", "with", "this", "that", "quartering", "live", "stream", "from", "just", "about", "over", "into", "they", "what", "your", "their", "more", "most"]);
+const titleWords = (t) => new Set(words(t).filter((w) => w.length > 3 && !TITLE_STOP.has(w)));
+
+/** `YYYYMMDD` → days since the epoch, or null. */
+export function dayNumber(s) {
+ const m = /^(\d{4})(\d{2})(\d{2})/.exec(String(s ?? ""));
+ if (!m) return null;
+ const t = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
+ return Number.isFinite(t) ? Math.round(t / 86_400_000) : null;
+}
+
+/**
+ * The phrase as a global, case-insensitive RegExp. A string is a regular
+ * expression's source; a RegExp keeps its source and gets `gi`.
+ */
+export function phraseRegExp(phrase) {
+ const src = phrase instanceof RegExp ? phrase.source : String(phrase ?? "");
+ if (!src.trim()) throw new Error("a phrase is required");
+ return new RegExp(src, "gi");
+}
+
+/**
+ * The hits of one transcript (`{cues: [{start, end, text}]}`), in order: each
+ * `{start, end, cueFirst, cueLast, match, context}` — start of the cue the
+ * match begins in, end of the cue it ends in, the cue before through the cue
+ * after as context.
+ */
+export function hitsInCues(cues, re) {
+ if (!Array.isArray(cues) || !cues.length) return [];
+ const texts = cues.map((c) => squash(c?.text));
+ const starts = [];
+ let pos = 0;
+ for (const t of texts) {
+ starts.push(pos);
+ pos += t.length + 1;
+ }
+ const joined = texts.join(" ");
+ const cueAt = (ch) => {
+ let lo = 0;
+ let hi = starts.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (starts[mid] <= ch) lo = mid;
+ else hi = mid - 1;
+ }
+ return lo;
+ };
+ const out = [];
+ const g = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`);
+ for (const m of joined.matchAll(g)) {
+ if (!m[0]) continue;
+ const a = cueAt(m.index);
+ const b = cueAt(m.index + m[0].length - 1);
+ const start = Number(cues[a].start);
+ const end = Number(cues[b].end ?? cues[b].start);
+ if (out.length && start - out[out.length - 1].start < REPEAT_WINDOW_S) continue;
+ const context = squash(texts.slice(Math.max(0, a - 1), Math.min(texts.length, b + 2)).join(" "));
+ out.push({ start, end, cueFirst: a, cueLast: b, match: m[0], context });
+ }
+ return out;
+}
+
+/** The cue whose 5-cue window best covers `contextWords`: `{score, index}`. */
+export function locateInCues(cues, contextWords) {
+ const want = new Set(content(contextWords));
+ let best = { score: 0, index: null };
+ if (!want.size || !Array.isArray(cues)) return best;
+ const cueBags = cues.map((c) => new Set(content(words(c?.text))));
+ for (let i = 0; i < cues.length; i++) {
+ const win = new Set();
+ for (let j = i; j < Math.min(cues.length, i + 5); j++) for (const w of cueBags[j]) win.add(w);
+ if (!win.size) continue;
+ let n = 0;
+ for (const w of want) if (win.has(w)) n++;
+ const score = n / want.size;
+ if (score > best.score) best = { score, index: i };
+ }
+ return best;
+}
+
+function overlap(a, b) {
+ const A = bag(a);
+ const B = bag(b);
+ if (!A.size || !B.size) return 0;
+ let n = 0;
+ for (const w of A) if (B.has(w)) n++;
+ return n / Math.min(A.size, B.size);
+}
+
+async function readCues(channelsDir, slug, id) {
+ try {
+ return JSON.parse(await readFile(path.join(channelsDir, slug, "data", id, "transcript.cues.json"), "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+async function availabilityOf(channelsDir, slug, id) {
+ try {
+ const a = JSON.parse(await readFile(path.join(channelsDir, slug, "data", id, "availability.json"), "utf8"));
+ return a?.state ?? a?.availability ?? null;
+ } catch {
+ return null;
+ }
+}
+
+async function videoIds(channelsDir, slug) {
+ try {
+ return (await readdir(path.join(channelsDir, slug, "data"), { withFileTypes: true }))
+ .filter((d) => d.isDirectory() || d.isSymbolicLink())
+ .map((d) => d.name)
+ .sort();
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Scan the channels. `prefer` (a slug, optional) is the channel to cut from
+ * where a twin exists; it is scanned too. `exclude` (a regex source or RegExp,
+ * optional) drops a hit whose context matches it. `onProgress(done, total)` is
+ * called per channel.
+ *
+ * Returns `{ instances, hits, dropped, scanned }`: `instances` chronological
+ * (upload date, then time in the video), each `{slug, videoId, platform, date,
+ * title, duration, start, end, match, context, speakerCheck, availability,
+ * via?, alsoIn?}` — `via` names the hit a preferred-channel instance was placed
+ * from.
+ *
+ * @param {{channelsDir: string, channels: string[], phrase: string | RegExp, prefer?: string | null, exclude?: string | RegExp | null, onProgress?: (done: number, total: number) => void}} opts
+ */
+export async function phraseScan({ channelsDir, channels, phrase, prefer = null, exclude = null, onProgress }) {
+ const re = phraseRegExp(phrase);
+ const ex = exclude ? new RegExp(exclude instanceof RegExp ? exclude.source : String(exclude), "i") : null;
+ const slugs = [...new Set([...(prefer ? [prefer] : []), ...channels])];
+ const hits = [];
+ const preferred = new Map(); // id -> {day, duration, record}
+ let scanned = 0;
+ for (const [k, slug] of slugs.entries()) {
+ for (const id of await videoIds(channelsDir, slug)) {
+ const d = await readCues(channelsDir, slug, id);
+ if (!d) continue;
+ scanned++;
+ if (slug === prefer) preferred.set(id, { day: dayNumber(d.uploadDate), duration: Number(d.duration) || 0, title: titleWords(d.title), record: d });
+ for (const h of hitsInCues(d.cues, re)) {
+ hits.push({
+ slug,
+ videoId: id,
+ platform: d.platform ?? null,
+ source: d.source ?? null,
+ date: d.uploadDate ?? null,
+ title: d.title ?? null,
+ duration: Number(d.duration) || null,
+ ...h,
+ });
+ }
+ }
+ onProgress?.(k + 1, slugs.length);
+ }
+
+ const byDay = new Map();
+ for (const [id, v] of preferred) {
+ if (v.day == null) continue;
+ if (!byDay.has(v.day)) byDay.set(v.day, []);
+ byDay.get(v.day).push(id);
+ }
+ const preferredHits = new Map();
+ for (const h of hits) {
+ if (h.slug !== prefer) continue;
+ if (!preferredHits.has(h.videoId)) preferredHits.set(h.videoId, []);
+ preferredHits.get(h.videoId).push(h);
+ }
+
+ const placed = hits.filter((h) => h.slug === prefer).map((h) => ({ ...h }));
+ for (const h of hits) {
+ if (h.slug === prefer) continue;
+ const day = dayNumber(h.date);
+ const twins = [];
+ if (prefer && day != null && h.duration) {
+ for (const off of TWIN_DAYS) {
+ for (const id of byDay.get(day + off) ?? []) {
+ const p = preferred.get(id);
+ const diff = Math.abs(p.duration - h.duration);
+ if (!p.duration || diff > TWIN_DURATION_RATIO * Math.max(p.duration, h.duration)) continue;
+ const titled = [...titleWords(h.title)].some((w) => p.title.has(w));
+ if (titled || diff <= TWIN_CLOSE_RATIO * Math.max(p.duration, h.duration)) twins.push(id);
+ }
+ }
+ }
+ const ctx = words(h.context);
+ // Its twin already has the hit: nothing to add.
+ const covered = twins.some((id) =>
+ (preferredHits.get(id) ?? []).some((p) => locateInCues([{ text: p.context }], ctx).score >= SAME_HIT_MIN_SCORE),
+ );
+ if (covered) continue;
+ // Its twin's transcript says it in other words (a different track): place it there.
+ let moved = null;
+ const placeable = new Set(content(ctx)).size >= PLACE_MIN_WORDS;
+ for (const id of placeable ? twins : []) {
+ const cues = preferred.get(id).record.cues ?? [];
+ const at = locateInCues(cues, ctx);
+ if (at.index != null && at.score >= PLACE_MIN_SCORE) {
+ const rec = preferred.get(id).record;
+ const last = cues[Math.min(at.index + 1, cues.length - 1)];
+ moved = {
+ ...h,
+ slug: prefer,
+ videoId: id,
+ platform: rec.platform ?? null,
+ source: rec.source ?? null,
+ title: rec.title ?? null,
+ duration: Number(rec.duration) || null,
+ start: Number(cues[at.index].start),
+ end: Number(last.end ?? last.start),
+ via: { slug: h.slug, videoId: h.videoId, start: h.start, score: Math.round(at.score * 100) / 100 },
+ };
+ break;
+ }
+ }
+ placed.push(moved ?? { ...h });
+ }
+
+ placed.sort((a, b) => String(a.date ?? "").localeCompare(String(b.date ?? "")) || (a.slug === prefer ? 0 : 1) - (b.slug === prefer ? 0 : 1) || a.start - b.start);
+ const instances = [];
+ const dropped = [];
+ for (const i of placed) {
+ const di = dayNumber(i.date);
+ const twin = instances.find((k) => {
+ const dk = dayNumber(k.date);
+ return dk != null && di != null && Math.abs(dk - di) <= FOLD_DAYS && overlap(k.context, i.context) >= FOLD_MIN_OVERLAP;
+ });
+ if (twin) {
+ (twin.alsoIn ??= []).push({ slug: i.slug, videoId: i.videoId, start: i.start });
+ continue;
+ }
+ if (ex?.test(i.context)) {
+ dropped.push({ ...i, why: "matches the exclude pattern" });
+ continue;
+ }
+ instances.push({ ...i, speakerCheck: i.context.includes(">>") });
+ }
+ for (const i of instances) {
+ i.availability = i.slug === prefer ? null : await availabilityOf(channelsDir, i.slug, i.videoId);
+ }
+ return { instances, hits, dropped, scanned };
+}
+
+/** `20190502` → `2 May 2019`. */
+export function niceDate(s) {
+ const n = dayNumber(s);
+ if (n == null) return String(s ?? "");
+ const d = new Date(n * 86_400_000);
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
+}
+
+/**
+ * Instances → manifest clips, chronological: the extent is the phrase's cues
+ * widened by `pad` each side (room for the renderer's snap and for tighter
+ * montage styles), the cut is the phrase's cues. `onscreen.title` is the phrase
+ * as said, `subtitle` the date; `montage` carries `{n, date, platform, match,
+ * speakerCheck}` for the montage renderer.
+ */
+export function instancesAsClips(instances, { pad = 2.5, idPrefix = "s" } = {}) {
+ const width = String(instances.length).length < 2 ? 2 : String(instances.length).length;
+ const r2 = (x) => Math.round(x * 100) / 100;
+ return instances.map((i, k) => {
+ const n = k + 1;
+ const notes = [];
+ if (i.speakerCheck) notes.push("voice check: a speaker change in the captions");
+ if (i.via) notes.push(`placed from ${i.via.slug}/${i.via.videoId} @ ${Math.round(i.via.start)}s`);
+ if (i.alsoIn?.length) notes.push(`also in ${i.alsoIn.map((a) => `${a.slug}/${a.videoId}`).join(", ")}`);
+ if (i.availability && i.availability !== "public") notes.push(`source availability: ${i.availability}`);
+ return {
+ type: "clip",
+ id: `${idPrefix}${String(n).padStart(width, "0")}`,
+ channel: i.slug,
+ video: i.videoId,
+ start: r2(Math.max(0, i.start - pad)),
+ end: r2(i.end + pad),
+ cutStart: r2(i.start),
+ cutEnd: r2(i.end),
+ cite: r2(i.start),
+ quote: i.context.slice(0, 240),
+ onscreen: { title: squash(i.match).toLowerCase(), subtitle: niceDate(i.date) },
+ ...(notes.length ? { note: notes.join("; ") } : {}),
+ montage: { n, date: i.date ?? null, platform: i.platform ?? null, match: i.match, speakerCheck: Boolean(i.speakerCheck) },
+ };
+ });
+}
diff --git a/common/lib/montage/phraseScan.test.ts b/common/lib/montage/phraseScan.test.ts
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { dayNumber, hitsInCues, instancesAsClips, niceDate, phraseRegExp, phraseScan } from "./phraseScan.mjs";
+
+const PHRASE = String.raw`\bslow[\s,.\-]+news\b(?:[\s,.\-]+(?:day|week|cycle))?`;
+
+type C = { start: number; end: number; text: string };
+function corpus(videos: Record<string, Record<string, { uploadDate: string; duration: number; cues: C[]; platform?: string; availability?: string }>>) {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "phrase-scan-"));
+ for (const [slug, vids] of Object.entries(videos)) {
+ for (const [id, v] of Object.entries(vids)) {
+ const d = path.join(dir, slug, "data", id);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ id, title: `t ${id}`, platform: v.platform ?? "youtube", ...v }));
+ if (v.availability) writeFileSync(path.join(d, "availability.json"), JSON.stringify({ state: v.availability }));
+ }
+ }
+ return dir;
+}
+
+test("hitsInCues: a phrase split over two cues is found; a rolling repeat is one hit", () => {
+ const cues = [
+ { start: 0, end: 2, text: "well it must be a slow" },
+ { start: 2, end: 4, text: "news day for them" },
+ { start: 4, end: 6, text: "slow news day for them" }, // the rolling caption repeating its line
+ { start: 30, end: 33, text: "another slow news week" },
+ ];
+ const hits = hitsInCues(cues, phraseRegExp(PHRASE));
+ assert.equal(hits.length, 2);
+ assert.deepEqual([hits[0].start, hits[0].end, hits[0].cueFirst, hits[0].cueLast], [0, 4, 0, 1]);
+ assert.equal(hits[0].match, "slow news day");
+ assert.match(hits[0].context, /must be a slow news day for them/);
+ assert.equal(hits[1].match, "slow news week");
+});
+
+test("phraseScan: a twin on the preferred channel wins; a hit it lacks is placed by its words; a clip upload folds; exclude drops", async () => {
+ const dir = corpus({
+ rumble: {
+ // the same stream as yt1, and it has the hit itself
+ r1: { uploadDate: "20230102", duration: 1000, platform: "rumble", cues: [{ start: 100, end: 103, text: "kind of a slow news day today folks" }] },
+ // the same stream as yt2, transcribed differently: no hit, but the words are there
+ r2: { uploadDate: "20230301", duration: 2000, platform: "rumble", cues: [
+ { start: 500, end: 503, text: "so the admin tweeted a statement" },
+ { start: 503, end: 506, text: "must be a really slow new state" },
+ ] },
+ // a clip upload of r1's moment, two days on
+ r3: { uploadDate: "20230104", duration: 60, platform: "rumble", cues: [{ start: 5, end: 8, text: "kind of a slow news day today folks" }] },
+ // another upload of yt4's day, near its length: not a twin (no title word in common, 4 % apart)
+ r5: { uploadDate: "20260507", duration: 843, platform: "rumble", cues: [{ start: 40, end: 44, text: "restored upon complaining on X which is the only way you can get attention" }] },
+ // a read-out chat line
+ r4: { uploadDate: "20240101", duration: 900, platform: "rumble", cues: [{ start: 9, end: 12, text: "slow news week Jeremy says chat" }] },
+ },
+ yt: {
+ yt1: { uploadDate: "20230101", duration: 1010, cues: [{ start: 110, end: 113, text: "kind of a slow news day today folks" }] },
+ yt2: { uploadDate: "20230301", duration: 2010, cues: [
+ { start: 520, end: 523, text: "so the admin tweeted a statement" },
+ { start: 523, end: 526, text: "must be a really slow news day" },
+ ] },
+ yt4: { uploadDate: "20260507", duration: 810, cues: [{ start: 769, end: 772, text: "don't get sucked into this it's uh slow news cycle panic" }] },
+ // no twin: kept on its own channel, with its availability
+ yt3: { uploadDate: "20190502", duration: 900, availability: "public", cues: [{ start: 2, end: 5, text: ">> it must be a slow news week" }] },
+ },
+ });
+ try {
+ const r = await phraseScan({ channelsDir: dir, channels: ["yt"], prefer: "rumble", phrase: PHRASE, exclude: String.raw`slow news \w+,? jeremy` });
+ assert.equal(r.scanned, 9);
+ assert.deepEqual(
+ r.instances.map((i) => [i.date, i.slug, i.videoId, i.start]),
+ [
+ ["20190502", "yt", "yt3", 2],
+ ["20230102", "rumble", "r1", 100],
+ ["20230301", "rumble", "r2", 500],
+ ["20260507", "yt", "yt4", 769],
+ ],
+ );
+ assert.deepEqual(r.instances[1].alsoIn, [{ slug: "rumble", videoId: "r3", start: 5 }]);
+ assert.equal(r.instances[2].via?.videoId, "yt2", "placed in the twin from the other channel's hit");
+ assert.equal(r.instances[0].speakerCheck, true);
+ assert.equal(r.instances[0].availability, "public");
+ assert.deepEqual(r.dropped.map((d) => d.videoId), ["r4"]);
+
+ const clips = instancesAsClips(r.instances);
+ assert.deepEqual(clips[0], {
+ type: "clip",
+ id: "s01",
+ channel: "yt",
+ video: "yt3",
+ start: 0,
+ end: 7.5,
+ cutStart: 2,
+ cutEnd: 5,
+ cite: 2,
+ quote: ">> it must be a slow news week",
+ onscreen: { title: "slow news week", subtitle: "2 May 2019" },
+ note: "voice check: a speaker change in the captions",
+ montage: { n: 1, date: "20190502", platform: "youtube", match: "slow news week", speakerCheck: true },
+ });
+ assert.match(String(clips[2].note), /placed from yt\/yt2/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("dates and the phrase", () => {
+ assert.equal(niceDate("20260727"), "27 Jul 2026");
+ assert.equal(dayNumber("20230102")! - dayNumber("20221231")!, 2);
+ assert.equal(dayNumber("nope"), null);
+ assert.throws(() => phraseRegExp(" "), /phrase is required/);
+});
diff --git a/common/package.json b/common/package.json
@@ -35,6 +35,7 @@
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
+ "./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
"./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A montage from a phrase.** umtool's new project can be seeded from a phrase said across channels: `umtool new <slug> --seed phrase --phrase '<regex>' --channels a,b --prefer <channel>`, or the new-project form's seed "a phrase across channels" when no source is given. Every place the transcripts say it becomes a clip, in date order, found even where a caption line split the phrase in two; a stream that the preferred channel also holds (a Rumble copy, say) is cut from that copy; a stream and its clip upload are one clip; `--exclude` leaves out lines that match (a chat line read out), and a caption speaker change is noted for a voice check. The scan is kept beside the manifest as `phrase-scan.json`.
- **`pnpm heavy` caps what it runs.** A command admitted to the heavy slot through `pnpm heavy -- <cmd>` (or `scripts/queue-lock.mjs --heavy`) now runs in a memory-capped systemd user scope of its own — 8 GB, 2 GB of swap — so a runaway render or build is stopped in its scope instead of taking the desktop session down. A command that sets its own `MemoryMax=`, or one started from inside a capped unit or scope (the live editor and umtool, a publish stage's build), is run as before. `HEAVY_CAP=0` turns it off; `HEAVY_CAP_MB` and `HEAVY_CAP_SWAP_MB` size it.
- **A media move says how far its copy got again with the newer rsync.** rsync 3.5.1 as packaged since mid-October writes its progress with a unit on the byte count and an unscaled rate, which the move did not read: the job showed no progress bar and no "Copying… · N % ·" lines, and the log filled with rsync's raw redraws. Both forms are read now, and the rate reads as before (for example 1.16GB/s). Needs a restart of the editor.
- **A full download from Odysee's stored media URL survives a dropped connection.** When the connection to the file's server drops mid-file (`fetch failed`, a reset, a timeout, a body cut short), the same download now checks what came down, pauses 45 seconds, opens the video's page again and goes on from the last clean byte — it no longer ends the job. Each one is in the job log as "Connection dropped at <bytes> — reopening the page and resuming (k of 6)". After six drops in a row with no progress the download stops and keeps what it has for the next run, as before. A refusal that follows bytes the server served is handled the same way; a refusal straight after the page was opened still stops at once. A continuation is not a new file: it does not wait the 20-minute rest between files, and the whole run is still one attempt on the video's record (one of the two full-audio attempts before a salvage). The attempt records how many continuations it took. Needs a restart of the editor.
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -695,6 +695,10 @@ function usage() {
" --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — the events",
" ranked (scoops, milestones, swings, pots, level-ups) into --target <seconds> (default 240), the",
" deck on with the stats region drawing frameScan.overlay over each clip",
+ " --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]: every time",
+ " the phrase was said in those channels' transcripts, chronological, cut from the --prefer",
+ " 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",
" [--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",
@@ -1090,7 +1094,8 @@ async function cmdNew() {
die(
"usage: umtool new <slug> [--kind report-video] [--title T]\n" +
" [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" +
- " [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]",
+ " [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" +
+ " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]]",
);
}
const kind = val("--kind") ?? "report-video";
@@ -1107,6 +1112,14 @@ async function cmdNew() {
seed: val("--seed") ?? null,
brand: val("--brand") ?? null,
...(val("--target") != null ? { target: Number(val("--target")) } : {}),
+ ...(val("--seed") === "phrase" || val("--phrase") != null
+ ? {
+ phrase: val("--phrase") ?? null,
+ channels: String(val("--channels") ?? "").split(",").map((c) => c.trim()).filter(Boolean),
+ prefer: val("--prefer") ?? null,
+ exclude: val("--exclude") ?? null,
+ }
+ : {}),
});
} catch (e) {
die(e?.message ?? String(e));
@@ -1116,7 +1129,7 @@ async function cmdNew() {
console.log(`${r.dir}`);
if (r.seeded) {
- console.log(` video.manifest.json ${r.seeded} clip(s) SEEDED from ${val("--seed") === "frames" ? "the frame scan's events" : "digest chapters"} — review each`);
+ console.log(` video.manifest.json ${r.seeded} clip(s) SEEDED from ${val("--seed") === "frames" ? "the frame scan's events" : val("--seed") === "phrase" ? "a phrase scan (phrase-scan.json)" : "digest chapters"} — review each`);
} else {
console.log(` video.manifest.json an EMPTY timeline — see README.md`);
}
diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx
@@ -30,6 +30,8 @@ import { useHydrated } from "@/components/ui/use-hydrated";
// Release 32 R2: [data-new-seed] is a select (none, the digest's chapters, the
// frame scan), each offered when the video has it (GET /api/projects/new?from=);
// the frames seed's length budget is [data-new-target], seconds.
+// Release 33: with no source, [data-new-seed] offers "a phrase across channels"
+// ([data-new-phrase], [data-new-channels], [data-new-prefer], [data-new-exclude]).
type Brand = { id: string; label: string };
type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null };
@@ -40,6 +42,10 @@ const FIELD_HINT: Record<string, string> = {
siteOrigin: "the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)",
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)",
+ 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)",
+ exclude: "leave out a hit whose surrounding words match this regular expression (optional)",
brand: "a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card",
};
@@ -81,7 +87,11 @@ export default function NewProjectMenu({
const [src, setSrc] = useState(from ?? reports?.[0]?.path ?? "");
const [byHand, setByHand] = useState(!reports?.length);
const [origin, setOrigin] = useState("");
- const [seed, setSeed] = useState<"" | "chapters" | "frames">("");
+ const [seed, setSeed] = useState<"" | "chapters" | "frames" | "phrase">("");
+ const [phrase, setPhrase] = useState("");
+ const [channels, setChannels] = useState("");
+ const [prefer, setPrefer] = useState("");
+ const [exclude, setExclude] = useState("");
const [target, setTarget] = useState("240");
// What the video can be seeded from (null: not asked yet, or not a video).
const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean } | null>(null);
@@ -95,6 +105,8 @@ export default function NewProjectMenu({
// otherwise -- so the box is offered only when the source looks like one.
const looksLikeVideo = /[?&]v=/.test(src) || /^[\w.-]+\/[\w.-]+$/.test(src.trim());
const asksSeed = fields.includes("seed") && looksLikeVideo;
+ // No source at all: the one seed that needs none, a phrase across channels.
+ const asksPhrase = fields.includes("seed") && !src.trim();
useEffect(() => {
if (!asksSeed) return setSeeds(null);
let gone = false;
@@ -122,7 +134,9 @@ export default function NewProjectMenu({
const body: Record<string, unknown> = { kind, slug, title };
if (fields.includes("from") && src.trim()) body.from = src.trim();
if (fields.includes("siteOrigin") && origin.trim()) body.siteOrigin = origin.trim();
- if (fields.includes("seed") && seed && looksLikeVideo) {
+ if (asksPhrase && seed === "phrase") {
+ Object.assign(body, { seed, phrase, channels, prefer, exclude });
+ } else if (fields.includes("seed") && seed && seed !== "phrase" && looksLikeVideo) {
body.seed = seed;
if (seed === "frames") body.target = Number(target);
}
@@ -276,6 +290,30 @@ export default function NewProjectMenu({
</Select>
</Field>
)}
+ {asksPhrase && (
+ <Field label="Seed">
+ <Select value={seed === "phrase" ? "phrase" : ""} onChange={(e) => setSeed(e.target.value as typeof seed)} aria-label="seed — or a phrase across channels" data-new-seed>
+ <option value="">an empty timeline</option>
+ <option value="phrase">a phrase across channels</option>
+ </Select>
+ </Field>
+ )}
+ {asksPhrase && seed === "phrase" && (
+ <>
+ <Field label="Phrase">
+ <Input value={phrase} onChange={(e) => setPhrase(e.target.value)} placeholder="slow[ ,]+news" aria-label={`phrase — ${FIELD_HINT.phrase}`} title={FIELD_HINT.phrase} data-new-phrase className="w-56" />
+ </Field>
+ <Field label="Channels">
+ <Input value={channels} onChange={(e) => setChannels(e.target.value)} placeholder="slug, slug" aria-label={`channels — ${FIELD_HINT.channels}`} title={FIELD_HINT.channels} data-new-channels className="w-56" />
+ </Field>
+ <Field label="Prefer">
+ <Input value={prefer} onChange={(e) => setPrefer(e.target.value)} placeholder="optional" aria-label={`prefer — ${FIELD_HINT.prefer}`} title={FIELD_HINT.prefer} data-new-prefer className="w-44" />
+ </Field>
+ <Field label="Exclude">
+ <Input value={exclude} onChange={(e) => setExclude(e.target.value)} placeholder="optional" aria-label={`exclude — ${FIELD_HINT.exclude}`} title={FIELD_HINT.exclude} data-new-exclude className="w-44" />
+ </Field>
+ </>
+ )}
{asksSeed && seed === "frames" && (
<Field label="Target s">
<Input
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]]` | 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>]` | 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 |
@@ -176,3 +176,28 @@ and taken while the merged, sentence-widened windows fit `--target` seconds
`frameScan.overlay` over each clip (its QR off without `--site-origin`), and
each subtitle is the event's own words. It refuses an existing directory: a
re-seed is a new slug.
+
+**`--seed phrase`** (release 33) needs no `--from`: it reads every
+`transcript.cues.json` of `--channels` (and `--prefer`) and finds `--phrase`, a
+regular expression in any case, over the JOINED cue text — so a phrase a caption
+line split in two is found — through `common/lib/montage/phraseScan.mjs`.
+A rolling caption's repeat is one hit; a hit on another channel whose stream
+the `--prefer` channel also holds (an upload −1..+2 days away, a duration within
+10 %, and a title word in common or a duration within 1 %) is cut from that copy,
+placed by its surrounding words (at least six content words, 60 % found) or, if
+its copy says it too, left to that copy's own hit; the same words twice within
+three days (a stream and its clip upload) are one clip, the others named in its
+note. A context matching `--exclude` is left out, and a caption speaker change
+(`>>`) is noted for a voice check. The clips are chronological, `s01…`, the cut
+on the phrase's cues and the window 2.5 s wider each side; `onscreen.title` is
+the phrase as said, `subtitle` the date, and `montage: {n, date, platform,
+match, speakerCheck}` feeds the montage styles. The scan's whole answer is
+`phrase-scan.json` beside the manifest. The new-project form offers it as the
+seed "a phrase across channels" when no source is given. Example:
+
+```sh
+umtool new quartering-slow-news --seed phrase \
+ --phrase 'slow[ ,]+news[ ,]+(day|week|cycle)' \
+ --channels the-quartering,jeremy-hambly,quartering-live,cornbreadman \
+ --prefer the-quartering-rumble --exclude 'slow news \w+,? jeremy'
+```
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -7,9 +7,11 @@ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
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 { instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs";
import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs";
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
+export const SEEDS = ["chapters", "frames", "phrase"];
/**
* A manifest skeleton, and deliberately an EMPTY timeline.
@@ -215,9 +217,16 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po
* start, end, cite, quote, … }`, in board order), written as they are and
* unlocked; `timelineFrom` names the board in the README.
*
- * @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 }} args
+ *
+ * `seed: "phrase"` (release 33) needs no `--from`: every time `phrase` (a
+ * regular expression, case-insensitive) was said in `channels`, cut from the
+ * `prefer` channel's copy where one exists (common/lib/montage/phraseScan.mjs),
+ * chronological; a context matching `exclude` is left out. The scan's whole
+ * answer is written beside the manifest as `phrase-scan.json`.
+ *
+ * @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 }} 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 }) {
+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 }) {
if (!SLUG_RE.test(String(slug ?? ""))) {
throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
}
@@ -233,8 +242,23 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
`could not tell what --from is: "${from}" is neither a .md report, a viewer share URL (…/?v=<channel>%2F<id>&t=<s>), nor a <channel>/<videoId> ref`,
);
}
- if (seed && seed !== "chapters" && seed !== "frames") throw new Error(`--seed must be "chapters" or "frames", not "${seed}"`);
- if (seed && src?.kind !== "video") throw new Error(`--seed ${seed} needs --from to be a video ref`);
+ if (seed && !SEEDS.includes(seed)) throw new Error(`--seed must be one of ${SEEDS.join(", ")}, not "${seed}"`);
+ if (seed && seed !== "phrase" && src?.kind !== "video") throw new Error(`--seed ${seed} needs --from to be a video ref`);
+ if (seed === "phrase") {
+ if (src) throw new Error("--seed phrase scans channels: give it without --from");
+ if (!String(phrase ?? "").trim()) throw new Error("--seed phrase needs --phrase (a regular expression)");
+ try {
+ new RegExp(String(phrase), "i");
+ if (exclude) new RegExp(String(exclude), "i");
+ } catch (e) {
+ throw new Error(`not a regular expression: ${e?.message ?? e}`);
+ }
+ const list = [...(channels ?? []), ...(prefer ? [prefer] : [])].map((c) => String(c).trim()).filter(Boolean);
+ if (!list.length) throw new Error("--seed phrase needs --channels (and optionally --prefer)");
+ for (const c of list) if (!SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`);
+ } else if (phrase || channels?.length || prefer || exclude) {
+ throw new Error("--phrase, --channels, --prefer and --exclude go with --seed phrase");
+ }
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") throw new Error("--target is the frames seed's length budget: give it with --seed frames");
if (target !== undefined && !(Number.isFinite(target) && target >= 10 && target <= 3600)) {
@@ -296,6 +320,25 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
if (!cut.timeline.length) notes.push("the frame scan found no events worth a clip, so the timeline is empty");
}
+ let phraseSeeded = null;
+ if (seed === "phrase") {
+ const chans = (channels ?? []).map((c) => String(c).trim()).filter(Boolean);
+ const scan = await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null });
+ doc.timeline = instancesAsClips(scan.instances);
+ doc.render.transition = 0;
+ if (prefer) doc.provenance.channelSlug = String(prefer).trim();
+ else if (chans.length === 1) doc.provenance.channelSlug = chans[0];
+ seeded = doc.timeline.length;
+ phraseSeeded = scan;
+ notes.push(`${scan.scanned} transcript(s) read, ${scan.hits.length} hit(s), ${scan.instances.length} instance(s)`);
+ const placed = scan.instances.filter((i) => i.via).length;
+ if (placed) notes.push(`${placed} hit(s) from another channel placed in the ${prefer} copy by their words — check the cut lands on the phrase`);
+ if (scan.dropped.length) notes.push(`${scan.dropped.length} left out by --exclude (phrase-scan.json, "dropped")`);
+ const checks = scan.instances.filter((i) => i.speakerCheck).length;
+ if (checks) notes.push(`${checks} with a speaker change in the captions: check who says it`);
+ if (!scan.instances.length) notes.push("the phrase was not found, so the timeline is empty");
+ }
+
if (timeline) {
doc.timeline = timeline.map((c) => ({ ...c }));
seeded = doc.timeline.length;
@@ -306,6 +349,11 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
await mkdir(dir, { recursive: true });
await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n", "utf8");
if (reportText !== null) await writeFile(path.join(dir, "sweep-report.md"), reportText, "utf8");
+ if (phraseSeeded) {
+ const { instances, dropped, hits, scanned } = phraseSeeded;
+ const scanDoc = { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, scanned, hits: hits.length, instances, dropped };
+ await writeFile(path.join(dir, "phrase-scan.json"), JSON.stringify(scanDoc, null, 1) + "\n", "utf8");
+ }
const lines = [
`# ${finalTitle}`,
@@ -325,6 +373,16 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
"",
...doc.timeline.map((c) => `- [ ] ${c.id} ${c.channel}/${c.video} ${c.start}–${c.end} ${String(c.quote ?? "").slice(0, 80)}`),
);
+ } else if (seeded && phraseSeeded) {
+ lines.push(
+ "## Clips seeded from a phrase scan — review each",
+ "",
+ "Every window below is a place the transcripts say the phrase: the cues it was",
+ "said in, chronological. A transcript can mishear and a line can be someone",
+ "else's (a co-host, chat read out): listen to each in the bench before you keep it.",
+ "",
+ ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.onscreen?.subtitle ?? ""} ${c.channel}/${c.video} ${c.cutStart}–${c.cutEnd} "${c.onscreen?.title ?? ""}"${c.note ? ` (${c.note})` : ""}`),
+ );
} else if (seeded && framesSeeded) {
lines.push(
"## Clips seeded from the frame scan — review each",
diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts
@@ -17,6 +17,13 @@ export type NewProjectBody = {
// The frames seed's length budget, seconds (release 32: the form's "target").
target?: number | string | null;
brand?: string | null;
+ // The phrase seed (release 33): a regular expression, the channels to scan
+ // (a list or a comma-separated string), the channel to cut from where it
+ // has a copy, and a pattern whose context is left out.
+ phrase?: string | null;
+ channels?: string[] | string | null;
+ prefer?: string | null;
+ exclude?: string | null;
};
/**
@@ -43,6 +50,16 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
siteOrigin: body.siteOrigin || null,
seed: body.seed || null,
brand: body.brand || null,
+ ...(body.seed === "phrase"
+ ? {
+ phrase: body.phrase ?? null,
+ channels: (Array.isArray(body.channels) ? body.channels : String(body.channels ?? "").split(","))
+ .map((c) => String(c).trim())
+ .filter(Boolean),
+ prefer: body.prefer || null,
+ exclude: body.exclude || null,
+ }
+ : {}),
...(body.seed === "frames" && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}),
});
result = { ...r, href: `/projects/${r.id}` };
diff --git a/umtool/lib/scaffold-phrase.test.mjs b/umtool/lib/scaffold-phrase.test.mjs
@@ -0,0 +1,65 @@
+// `umtool new <slug> --seed phrase --phrase … --channels … --prefer …` (release
+// 33): every time a phrase was said, from a synthetic corpus in a temp tree.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { scaffoldReportVideo } from "./projects/scaffold.mjs";
+
+async function video(channelsDir, slug, id, doc) {
+ const dir = path.join(channelsDir, slug, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "transcript.cues.json"), JSON.stringify({ id, title: `t ${id}`, ...doc }));
+}
+
+test("--seed phrase: chronological clips cut from the preferred copy, the scan beside the manifest, a checklist", async () => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-phrase-seed-"));
+ try {
+ const channelsDir = path.join(tmp, "channels");
+ await video(channelsDir, "synth-rumble", "r1", { uploadDate: "20230102", duration: 1000, platform: "rumble", cues: [{ start: 100, end: 103, text: "kind of a slow news day today" }] });
+ await video(channelsDir, "synth-yt", "y1", { uploadDate: "20230101", duration: 1005, platform: "youtube", cues: [{ start: 110, end: 113, text: "kind of a slow news day today" }] });
+ await video(channelsDir, "synth-yt", "y0", { uploadDate: "20190502", duration: 600, platform: "youtube", cues: [{ start: 4, end: 6, text: "a slow" }, { start: 6, end: 8, text: "news week indeed" }] });
+ const r = await scaffoldReportVideo({
+ root: path.join(tmp, "reports"),
+ slug: "slow-news",
+ seed: "phrase",
+ phrase: String.raw`slow[\s,]+news`,
+ channels: ["synth-yt"],
+ prefer: "synth-rumble",
+ channelsDir,
+ });
+ assert.equal(r.seeded, 2);
+ const doc = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8"));
+ assert.deepEqual(doc.timeline.map((c) => [c.id, c.channel, c.video, c.cutStart, c.cutEnd, c.onscreen.subtitle]), [
+ ["s01", "synth-yt", "y0", 4, 8, "2 May 2019"],
+ ["s02", "synth-rumble", "r1", 100, 103, "2 Jan 2023"],
+ ]);
+ assert.equal(doc.provenance.channelSlug, "synth-rumble");
+ assert.equal(doc.render.transition, 0);
+ const scan = JSON.parse(await readFile(path.join(r.dir, "phrase-scan.json"), "utf8"));
+ assert.equal(scan.instances.length, 2);
+ assert.equal(scan.hits, 3);
+ const readme = await readFile(path.join(r.dir, "README.md"), "utf8");
+ assert.match(readme, /Clips seeded from a phrase scan/);
+ assert.match(readme, /- \[ \] s02 {2}2 Jan 2023 {2}synth-rumble\/r1 100–103 {2}"slow news"/);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+});
+
+test("--seed phrase refuses what it cannot scan", async () => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-phrase-seed-"));
+ const base = { root: path.join(tmp, "reports"), slug: "x", seed: "phrase", channelsDir: tmp };
+ try {
+ await assert.rejects(scaffoldReportVideo({ ...base, channels: ["a"] }), /needs --phrase/);
+ await assert.rejects(scaffoldReportVideo({ ...base, phrase: "slow news" }), /needs --channels/);
+ await assert.rejects(scaffoldReportVideo({ ...base, phrase: "slow (news", channels: ["a"] }), /not a regular expression/);
+ await assert.rejects(scaffoldReportVideo({ ...base, phrase: "x", channels: ["A B"] }), /not a channel slug/);
+ await assert.rejects(scaffoldReportVideo({ ...base, phrase: "x", channels: ["a"], from: "a/b" }), /without --from/);
+ await assert.rejects(scaffoldReportVideo({ ...base, seed: null, phrase: "x" }), /go with --seed phrase/);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+});