commit df5fbeb2e322fa478a959cdf17129888f7c5139a
parent faf6823ef5439a7e932d24814a0656d2c470938e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 17:29:43 -0400
Merge r34/phrase-finder: /tools/phrases (counts by year, contexts, source split, compare, Create montage from the finished search), phraseScanMany in one pass, a streamed per-channel cue-text cache, umtool phrases
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
38 files changed, 2607 insertions(+), 41 deletions(-)
diff --git a/common/lib/montage/cueTextCache.d.mts b/common/lib/montage/cueTextCache.d.mts
@@ -0,0 +1,23 @@
+export const CACHE_VERSION: number;
+export type CompactRecord = {
+ uploadDate: unknown;
+ duration: unknown;
+ title: unknown;
+ platform: unknown;
+ source: unknown;
+ j: string | null;
+ a: unknown[] | null;
+ b: unknown[] | null;
+};
+export type ChannelCache = {
+ changed: boolean;
+ read(id: string): Promise<{ r: CompactRecord | null; line: string | null }>;
+ keep(id: string, line: string | null): Promise<void>;
+ close(): Promise<boolean>;
+ abort(): Promise<void>;
+};
+export function compactRecord(d: unknown): CompactRecord;
+export function textsOf(r: CompactRecord | null): string[];
+export function readCompact(channelsDir: string, slug: string, id: string): Promise<CompactRecord | null>;
+export function cacheRoot(cacheDir: string, channelsDir: string): string;
+export function openChannelCache(cacheDir: string, channelsDir: string, slug: string, ids: string[]): Promise<ChannelCache>;
diff --git a/common/lib/montage/cueTextCache.mjs b/common/lib/montage/cueTextCache.mjs
@@ -0,0 +1,207 @@
+// The phrase finder's cue-text cache (release 34): what a phrase scan needs of
+// each video — its cue texts, their times, and five fields of the record —
+// kept per channel in ONE file read front to back, so a second search reads
+// one file per channel instead of thousands of cue files with their
+// descriptions and metadata.
+//
+// <cacheDir>/<hash of the channels dir>/<channel>.ndjson
+// one line per video, in video-id order: {"id": "<videoId>", "r": record | null}
+// <cacheDir>/<hash of the channels dir>/<channel>.index.json
+// { version, videos: { "<videoId>": [mtimeMs, size] } }
+//
+// A video's line is used only while its transcript.cues.json has the same
+// modification time and size as the index says; anything else is read again
+// (an unreadable file is remembered as null, so it is not re-parsed every
+// search). Lines are streamed, one at a time, so a channel of eight thousand
+// videos costs one line's memory, not the channel's. When anything changed the
+// channel's file is written again as the scan goes (a temporary name, renamed at
+// the end); when nothing did, nothing is written.
+//
+// It never writes under the channels directory: the cache dir is the caller's
+// (umtool's CACHE_DIR/phrase-text). Delete it at any time; the next search
+// rebuilds it.
+import { createHash } from "node:crypto";
+import { createReadStream, createWriteStream } from "node:fs";
+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { createInterface } from "node:readline";
+
+export const CACHE_VERSION = 3;
+
+const squash = (t) => String(t ?? "").replace(/\s+/g, " ").trim();
+
+/**
+ * What a scan keeps of a parsed transcript.cues.json: `uploadDate`,
+ * `duration`, `title`, `platform`, `source` as they are, and the cues as three
+ * columns — `j` the squashed texts joined with a newline (a squashed text has
+ * none), `a` the starts, `b` the ends (null where a cue has none) — or all
+ * three null when the record has no cue list.
+ */
+export function compactRecord(d) {
+ const cues = Array.isArray(d?.cues) ? d.cues : null;
+ return {
+ uploadDate: d?.uploadDate ?? null,
+ duration: d?.duration ?? null,
+ title: d?.title ?? null,
+ platform: d?.platform ?? null,
+ source: d?.source ?? null,
+ j: cues ? cues.map((c) => squash(c?.text)).join("\n") : null,
+ a: cues ? cues.map((c) => c?.start ?? null) : null,
+ b: cues ? cues.map((c) => c?.end ?? null) : null,
+ };
+}
+
+/** A compact record's cue texts (its `j`, split again). */
+export const textsOf = (r) => (r?.a?.length ? String(r.j ?? "").split("\n") : []);
+
+const cueFile = (channelsDir, slug, id) => path.join(channelsDir, slug, "data", id, "transcript.cues.json");
+
+async function parseFile(file) {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+/** One video's compact record straight from its cue file, or null when it is missing or parses to nothing. */
+export async function readCompact(channelsDir, slug, id) {
+ const d = await parseFile(cueFile(channelsDir, slug, id));
+ return d ? compactRecord(d) : null;
+}
+
+/** The directory a channels dir's cache files live in. */
+export function cacheRoot(cacheDir, channelsDir) {
+ const h = createHash("sha1").update(path.resolve(channelsDir)).digest("hex").slice(0, 12);
+ return path.join(cacheDir, h);
+}
+
+async function statAll(files, n) {
+ const out = new Array(files.length).fill(null);
+ let next = 0;
+ const worker = async () => {
+ while (next < files.length) {
+ const k = next++;
+ out[k] = await stat(files[k]).catch(() => null);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(n, files.length) }, worker));
+ return out;
+}
+
+/**
+ * A channel's cache, for one pass over `ids` (sorted, as the scan visits
+ * them). `read(id)` → `{r, line}` (call it in id order, as many in flight as
+ * you like): `r` the record (null: not a transcript), `line` what to `keep`;
+ * `keep(id, line)` in id order; `close()` writes the channel's file when
+ * anything changed. `changed` says whether it will.
+ */
+export async function openChannelCache(cacheDir, channelsDir, slug, ids) {
+ const root = cacheRoot(cacheDir, channelsDir);
+ const base = path.join(root, encodeURIComponent(slug));
+ const dataFile = `${base}.ndjson`;
+ const indexFile = `${base}.index.json`;
+ let index = {};
+ try {
+ const doc = JSON.parse(await readFile(indexFile, "utf8"));
+ if (doc?.version === CACHE_VERSION && doc.videos && typeof doc.videos === "object") index = doc.videos;
+ } catch {
+ /* none yet, or unreadable: rebuilt */
+ }
+ const hasData = await stat(dataFile).then((s) => s.isFile(), () => false);
+ if (!hasData) index = {};
+ const stats = await statAll(ids.map((id) => cueFile(channelsDir, slug, id)), 32);
+ const statOf = new Map(ids.map((id, k) => [id, stats[k]]));
+ const fresh = new Set();
+ for (const [k, id] of ids.entries()) {
+ const st = stats[k];
+ const e = index[id];
+ if (st && Array.isArray(e) && e[0] === st.mtimeMs && e[1] === st.size) fresh.add(id);
+ }
+ const changed = fresh.size !== ids.filter((id) => statOf.get(id)).length || fresh.size !== Object.keys(index).length;
+
+ // The old file, a line at a time; a line is taken only in id order.
+ let lines = null;
+ let rl = null;
+ if (fresh.size) {
+ rl = createInterface({ input: createReadStream(dataFile, { encoding: "utf8" }), crlfDelay: Infinity });
+ lines = rl[Symbol.asyncIterator]();
+ }
+ let chain = Promise.resolve();
+ // A line the index promised and the file did not hold: the file is rebuilt next time.
+ let missed = false;
+ const take = async (id) => {
+ for (;;) {
+ const { value, done } = await lines.next();
+ if (done) return null;
+ let doc;
+ try {
+ doc = JSON.parse(value);
+ } catch {
+ continue;
+ }
+ if (doc?.id === id) return { r: doc.r ?? null, line: value };
+ }
+ };
+
+ let out = null;
+ let tmp = null;
+ const nextIndex = {};
+ if (changed) {
+ await mkdir(root, { recursive: true });
+ tmp = `${dataFile}.${process.pid}.${Date.now()}.tmp`;
+ out = createWriteStream(tmp, { encoding: "utf8" });
+ }
+
+ return {
+ changed,
+ read(id) {
+ const st = statOf.get(id);
+ if (!st) return Promise.resolve({ r: null, line: null });
+ if (fresh.has(id)) {
+ const p = chain.then(() => take(id));
+ chain = p.then(
+ () => {},
+ () => {},
+ );
+ return p.then(async (got) => {
+ if (got) return got;
+ missed = true;
+ return this.readFile(id);
+ });
+ }
+ return this.readFile(id);
+ },
+ async readFile(id) {
+ const d = await parseFile(cueFile(channelsDir, slug, id));
+ const r = d ? compactRecord(d) : null;
+ return { r, line: JSON.stringify({ id, r }) };
+ },
+ async keep(id, line) {
+ if (!out || line === null) return;
+ const st = statOf.get(id);
+ nextIndex[id] = [st.mtimeMs, st.size];
+ if (!out.write(line + "\n")) await new Promise((resolve) => out.once("drain", resolve));
+ },
+ async close() {
+ rl?.close();
+ if (!out) {
+ if (missed) await rm(indexFile, { force: true });
+ return false;
+ }
+ await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve())));
+ await rename(tmp, dataFile);
+ const itmp = `${indexFile}.${process.pid}.tmp`;
+ await writeFile(itmp, JSON.stringify({ version: CACHE_VERSION, slug, videos: nextIndex }), "utf8");
+ await rename(itmp, indexFile);
+ return true;
+ },
+ async abort() {
+ rl?.close();
+ if (out) {
+ out.destroy();
+ await rm(tmp, { force: true });
+ }
+ },
+ };
+}
diff --git a/common/lib/montage/phraseScan.d.mts b/common/lib/montage/phraseScan.d.mts
@@ -34,6 +34,9 @@ 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 type JoinedCues = { texts: string[]; starts: number[]; joined: string };
+export function joinCues(cues: Cue[]): JoinedCues;
+export function hitsInJoined(cues: Cue[], joined: JoinedCues, re: RegExp): CueHit[];
export function locateInCues(cues: Cue[], contextWords: string[]): { score: number; index: number | null };
export function phraseScan(opts: {
channelsDir: string;
@@ -43,6 +46,19 @@ export function phraseScan(opts: {
exclude?: string | RegExp | null;
onProgress?: (done: number, total: number) => void;
}): Promise<PhraseScanResult>;
+export type PhraseScanProgress = { done: number; total: number; channel: string; channelsDone: number; channels: number };
+export type PhraseScanManyResult = PhraseScanResult & { id: string; phrase: string };
+export function phraseScanMany(opts: {
+ channelsDir: string;
+ channels: string[];
+ phrases: { id: string; phrase: string | RegExp; exclude?: string | RegExp | null }[];
+ prefer?: string | null;
+ exclude?: string | RegExp | null;
+ cacheDir?: string | null;
+ concurrency?: number;
+ onProgress?: (p: PhraseScanProgress) => void;
+}): Promise<PhraseScanManyResult[]>;
+export { phraseSourceOf, phraseWords, wordsPhraseSource } from "./phraseSource.mjs";
export function niceDate(s: unknown): string;
export function instancesAsClips(
instances: PhraseInstance[],
diff --git a/common/lib/montage/phraseScan.mjs b/common/lib/montage/phraseScan.mjs
@@ -21,6 +21,9 @@
// 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";
+import { openChannelCache, readCompact, textsOf } from "./cueTextCache.mjs";
+
+export { phraseSourceOf, phraseWords, wordsPhraseSource } from "./phraseSource.mjs";
export const REPEAT_WINDOW_S = 8;
export const TWIN_DAYS = [-1, 0, 1, 2];
@@ -71,6 +74,14 @@ export function phraseRegExp(phrase) {
*/
export function hitsInCues(cues, re) {
if (!Array.isArray(cues) || !cues.length) return [];
+ return hitsInJoined(cues, joinCues(cues), re);
+}
+
+/**
+ * A transcript's cue texts joined once, for many phrases: `{texts, starts,
+ * joined}` — each cue's squashed text, where it starts in `joined`.
+ */
+export function joinCues(cues) {
const texts = cues.map((c) => squash(c?.text));
const starts = [];
let pos = 0;
@@ -78,7 +89,17 @@ export function hitsInCues(cues, re) {
starts.push(pos);
pos += t.length + 1;
}
- const joined = texts.join(" ");
+ return { texts, starts, joined: texts.join(" ") };
+}
+
+/** hitsInCues over a transcript already joined (joinCues). */
+export function hitsInJoined(cues, joined, re) {
+ if (!Array.isArray(cues) || !cues.length) return [];
+ return hitsCore(joined, (i) => cues[i].start, (i) => cues[i].end, re);
+}
+
+/** The matcher: `startOf(i)` / `endOf(i)` are cue i's raw start and end. */
+function hitsCore({ texts, starts, joined }, startOf, endOf, re) {
const cueAt = (ch) => {
let lo = 0;
let hi = starts.length - 1;
@@ -95,8 +116,8 @@ export function hitsInCues(cues, re) {
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);
+ const start = Number(startOf(a));
+ const end = Number(endOf(b) ?? startOf(b));
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 });
@@ -175,10 +196,10 @@ async function videoIds(channelsDir, slug) {
*/
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 ex = excludeRegExp(exclude);
const slugs = [...new Set([...(prefer ? [prefer] : []), ...channels])];
const hits = [];
- const preferred = new Map(); // id -> {day, duration, record}
+ const preferred = new Map(); // id -> {day, duration, title, record}
let scanned = 0;
for (const [k, slug] of slugs.entries()) {
for (const id of await videoIds(channelsDir, slug)) {
@@ -186,22 +207,45 @@ export async function phraseScan({ channelsDir, channels, phrase, prefer = null,
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,
- });
- }
+ for (const h of hitsInCues(d.cues, re)) hits.push(hitOf(slug, id, d, h));
}
onProgress?.(k + 1, slugs.length);
}
+ const folded = await foldHits({
+ hits,
+ prefer,
+ preferred,
+ recordOf: async (id) => preferred.get(id).record,
+ ex,
+ availability: (slug, id) => availabilityOf(channelsDir, slug, id),
+ });
+ return { ...folded, hits, scanned };
+}
+
+const excludeRegExp = (exclude) => (exclude ? new RegExp(exclude instanceof RegExp ? exclude.source : String(exclude), "i") : null);
+function hitOf(slug, videoId, d, h) {
+ return {
+ slug,
+ videoId,
+ platform: d.platform ?? null,
+ source: d.source ?? null,
+ date: d.uploadDate ?? null,
+ title: d.title ?? null,
+ duration: Number(d.duration) || null,
+ ...h,
+ };
+}
+
+/**
+ * The hits of one phrase → its instances: placed in the preferred channel's
+ * twin where one has it, folded, the excluded dropped. `preferred` maps each
+ * preferred-channel video to `{day, duration, title}`; `recordOf(id)` gives
+ * its record (`{cues, platform, source, title, duration}`) when a hit is placed
+ * in it. Shared by phraseScan and phraseScanMany, so one phrase scanned either
+ * way folds the same.
+ */
+async function foldHits({ hits, prefer, preferred, recordOf, ex, availability }) {
const byDay = new Map();
for (const [id, v] of preferred) {
if (v.day == null) continue;
@@ -241,10 +285,10 @@ export async function phraseScan({ channelsDir, channels, phrase, prefer = null,
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 rec = await recordOf(id);
+ const cues = rec.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,
@@ -284,9 +328,143 @@ export async function phraseScan({ channelsDir, channels, phrase, prefer = null,
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);
+ i.availability = i.slug === prefer ? null : await availability(i.slug, i.videoId);
+ }
+ return { instances, dropped };
+}
+
+/**
+ * Many phrases in ONE pass over the transcripts (release 34): each cue file is
+ * read and parsed once, its text joined once, and every phrase matched in it.
+ * Each phrase's result is what `phraseScan` returns for it alone — the same
+ * instances, hits, dropped and scanned (tested) — in the order given.
+ *
+ * `phrases`: `[{ id, phrase, exclude? }]` (a phrase's own `exclude` overrides
+ * the scan's). `cacheDir` (optional): where the joined text of every video is
+ * kept, keyed by its cue file's modification time and size, so a second search
+ * streams one file per channel instead of reading every cue file (cueTextCache.mjs);
+ * nothing under `channelsDir` is ever written. `onProgress({done, total,
+ * channel, channelsDone, channels})` is called every few hundred videos and at
+ * each channel's end.
+ *
+ * @param {{channelsDir: string, channels: string[], phrases: {id: string, phrase: string | RegExp, exclude?: string | RegExp | null}[], prefer?: string | null, exclude?: string | RegExp | null, cacheDir?: string | null, concurrency?: number, onProgress?: (p: {done: number, total: number, channel: string, channelsDone: number, channels: number}) => void}} opts
+ */
+export async function phraseScanMany({ channelsDir, channels, phrases, prefer = null, exclude = null, cacheDir = null, concurrency = 16, onProgress }) {
+ if (!Array.isArray(phrases) || !phrases.length) throw new Error("at least one phrase is required");
+ const list = phrases.map((p, k) => ({
+ id: String(p?.id ?? k),
+ phrase: p?.phrase,
+ re: phraseRegExp(p?.phrase),
+ ex: excludeRegExp(p && "exclude" in p && p.exclude !== undefined ? p.exclude : exclude),
+ }));
+ if (new Set(list.map((p) => p.id)).size !== list.length) throw new Error("each phrase needs its own id");
+ const slugs = [...new Set([...(prefer ? [prefer] : []), ...channels])];
+ const plan = [];
+ for (const slug of slugs) plan.push({ slug, ids: await videoIds(channelsDir, slug) });
+ const total = plan.reduce((n, p) => n + p.ids.length, 0);
+
+ const hitsBy = list.map(() => []);
+ const preferred = new Map(); // id -> {day, duration, title}
+ let scanned = 0;
+ let done = 0;
+ for (const [k, { slug, ids }] of plan.entries()) {
+ const cache = cacheDir ? await openChannelCache(cacheDir, channelsDir, slug, ids) : null;
+ try {
+ await forEachInOrder(
+ ids,
+ concurrency,
+ (id) => (cache ? cache.read(id) : readCompact(channelsDir, slug, id).then((r) => ({ r, line: null }))),
+ async (id, v) => {
+ done++;
+ const d = v?.r ?? null;
+ if (cache) await cache.keep(id, v?.line ?? null);
+ if (d) {
+ scanned++;
+ if (slug === prefer) preferred.set(id, { day: dayNumber(d.uploadDate), duration: Number(d.duration) || 0, title: titleWords(d.title) });
+ if (d.a?.length) {
+ const joined = joinTexts(textsOf(d));
+ for (const [j, p] of list.entries()) {
+ for (const h of hitsInTimed(d, joined, p.re)) hitsBy[j].push(hitOf(slug, id, d, h));
+ }
+ }
+ }
+ if (done % 250 === 0) onProgress?.({ done, total, channel: slug, channelsDone: k, channels: plan.length });
+ },
+ );
+ await cache?.close();
+ } catch (e) {
+ await cache?.abort();
+ throw e;
+ }
+ onProgress?.({ done, total, channel: slug, channelsDone: k + 1, channels: plan.length });
+ }
+
+ // A twin's cues, read again only when a hit is placed in it.
+ const records = new Map();
+ const recordOf = (id) => {
+ if (!records.has(id)) {
+ records.set(
+ id,
+ readCompact(channelsDir, prefer, id).then((d) => ({
+ platform: d?.platform,
+ source: d?.source,
+ title: d?.title,
+ duration: d?.duration,
+ cues: d?.a ? textsOf(d).map((text, i) => ({ start: d.a[i], end: d.b[i], text })) : null,
+ })),
+ );
+ }
+ return records.get(id);
+ };
+ const avail = new Map();
+ const availability = (slug, id) => {
+ const key = `${slug}/${id}`;
+ if (!avail.has(key)) avail.set(key, availabilityOf(channelsDir, slug, id));
+ return avail.get(key);
+ };
+ const out = [];
+ for (const [j, p] of list.entries()) {
+ const hits = hitsBy[j];
+ const folded = await foldHits({ hits, prefer, preferred, recordOf, ex: p.ex, availability });
+ out.push({ id: p.id, phrase: p.re.source, ...folded, hits, scanned });
+ }
+ return out;
+}
+
+/** The joined text of a compact record's cue texts (joinCues's shape). */
+function joinTexts(texts) {
+ const starts = [];
+ let pos = 0;
+ for (const t of texts) {
+ starts.push(pos);
+ pos += t.length + 1;
+ }
+ return { texts, starts, joined: texts.join(" ") };
+}
+
+/** hitsCore over a compact record: its cue times are `a` (start) and `b` (end). */
+function hitsInTimed(d, joined, re) {
+ return hitsCore(joined, (i) => d.a[i], (i) => d.b[i], re);
+}
+
+/** Run `read` over `items` with up to `n` in flight, handing each result to `use` in order. */
+async function forEachInOrder(items, n, read, use) {
+ const pending = [];
+ let next = 0;
+ const fill = () => {
+ while (pending.length < n && next < items.length) {
+ const item = items[next++];
+ const p = read(item).then((v) => v, () => null);
+ pending.push({ item, p });
+ }
+ };
+ fill();
+ while (pending.length) {
+ const { item, p } = pending.shift();
+ const v = await p;
+ fill();
+ await use(item, v);
}
- return { instances, hits, dropped, scanned };
}
/** `20190502` → `2 May 2019`. */
diff --git a/common/lib/montage/phraseScanMany.test.ts b/common/lib/montage/phraseScanMany.test.ts
@@ -0,0 +1,181 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { cacheRoot, openChannelCache } from "./cueTextCache.mjs";
+import { hitsInCues, hitsInJoined, joinCues, phraseRegExp, phraseScan, phraseScanMany } from "./phraseScan.mjs";
+import { phraseSourceOf, phraseWords, wordsPhraseSource } from "./phraseSource.mjs";
+
+// Release 34: many phrases in one pass must answer, phrase by phrase, exactly
+// what phraseScan answers for each alone — with and without the cue-text cache.
+
+const SLOW = String.raw`\bslow[\s,.\-]+news\b(?:[\s,.\-]+(?:day|week|cycle))?`;
+
+type C = { start: number; end?: number; text: string };
+type V = { uploadDate: string; duration: number; cues: C[]; platform?: string; availability?: string; title?: string };
+function corpus(videos: Record<string, Record<string, V>>) {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "phrase-many-"));
+ 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: v.title ?? `t ${id}`, platform: v.platform ?? "youtube", description: "x".repeat(50), ...v }));
+ if (v.availability) writeFileSync(path.join(d, "availability.json"), JSON.stringify({ state: v.availability }));
+ }
+ }
+ return dir;
+}
+
+const VIDEOS: Record<string, Record<string, V>> = {
+ rumble: {
+ r1: { uploadDate: "20230102", duration: 1000, platform: "rumble", cues: [{ start: 100, end: 103, text: "kind of a slow news day today folks" }, { start: 103, end: 106, text: "well well well look at this" }] },
+ 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" },
+ { start: 506, end: 509, text: "and nobody asked for it" },
+ ] },
+ r3: { uploadDate: "20230104", duration: 60, platform: "rumble", cues: [{ start: 5, end: 8, text: "kind of a slow news day today folks" }] },
+ r4: { uploadDate: "20240101", duration: 900, platform: "rumble", cues: [{ start: 9, end: 12, text: "slow news week Jeremy says chat" }, { start: 40, text: "well, well, well" }] },
+ r5: { uploadDate: "20260507", duration: 843, platform: "rumble", cues: [{ start: 40, end: 44, text: "restored upon complaining on X which is the only way" }] },
+ // no cue list at all: read, counted, never a hit
+ r6: { uploadDate: "20250101", duration: 10, platform: "rumble", cues: undefined as unknown as C[] },
+ },
+ 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" },
+ { start: 526, end: 529, text: "and no one asked for it" },
+ ] },
+ yt3: { uploadDate: "20190502", duration: 900, availability: "public", cues: [{ start: 2, end: 5, text: ">> it must be a slow news week" }, { start: 30, end: 33, text: "Well well-well, here we go" }] },
+ yt4: { uploadDate: "20260507", duration: 810, cues: [{ start: 769, end: 772, text: "don't get sucked into this it's uh slow news cycle panic" }] },
+ },
+ other: {
+ o1: { uploadDate: "20220303", duration: 300, availability: "unlisted", cues: [{ start: 1, end: 4, text: "nobody asked" }, { start: 4, end: 7, text: "for this slow" }, { start: 7, end: 10, text: "news day" }] },
+ },
+};
+
+const PHRASES = [
+ { id: "slow", phrase: SLOW },
+ { id: "asked", phrase: String.raw`\b(?:no ?one|nobody) (?:asked|was asking)\b` },
+ { id: "well", phrase: wordsPhraseSource("well well well") },
+ { id: "none", phrase: "zebra crossing" },
+];
+
+test("phraseScanMany: each phrase's answer is phraseScan's for it alone (prefer, exclude, no prefer, every cache state)", async () => {
+ const dir = corpus(VIDEOS);
+ const cacheDir = mkdtempSync(path.join(os.tmpdir(), "phrase-many-cache-"));
+ try {
+ for (const opts of [
+ { channels: ["yt", "other"], prefer: "rumble", exclude: String.raw`slow news \w+,? jeremy` },
+ { channels: ["yt", "other", "rumble"], prefer: null, exclude: null },
+ { channels: ["other"], prefer: "rumble", exclude: "today" },
+ ]) {
+ const alone = [];
+ for (const p of PHRASES) alone.push(await phraseScan({ channelsDir: dir, ...opts, phrase: p.phrase }));
+ for (const cache of [null, cacheDir, cacheDir]) {
+ const many = await phraseScanMany({ channelsDir: dir, ...opts, phrases: PHRASES, cacheDir: cache, concurrency: 3 });
+ assert.deepEqual(many.map((m) => m.id), PHRASES.map((p) => p.id));
+ for (const [k, m] of many.entries()) {
+ const { id, phrase, ...rest } = m;
+ assert.equal(phrase, phraseRegExp(PHRASES[k].phrase).source);
+ assert.deepEqual(rest, alone[k], `${id} with ${JSON.stringify(opts)} and cache ${cache ? "on" : "off"}`);
+ }
+ }
+ }
+ // The scans found something worth comparing.
+ const one = await phraseScan({ channelsDir: dir, channels: ["yt", "other"], prefer: "rumble", phrase: SLOW });
+ assert.ok(one.instances.some((i) => i.via), "a hit placed in a twin");
+ assert.ok(one.instances.some((i) => i.alsoIn?.length), "a folded clip upload");
+ assert.ok(one.instances.some((i) => i.availability === "unlisted"));
+ assert.equal(one.scanned, 11);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ rmSync(cacheDir, { recursive: true, force: true });
+ }
+});
+
+test("phraseScanMany: the cache follows a cue file that changed, and drops a video that is gone", async () => {
+ const dir = corpus(VIDEOS);
+ const cacheDir = mkdtempSync(path.join(os.tmpdir(), "phrase-many-cache-"));
+ try {
+ const opts = { channelsDir: dir, channels: ["yt"], prefer: "rumble", phrases: [{ id: "slow", phrase: SLOW }], cacheDir };
+ const first = await phraseScanMany(opts);
+ const root = cacheRoot(cacheDir, dir);
+ assert.deepEqual(readdirSync(root).sort(), ["rumble.index.json", "rumble.ndjson", "yt.index.json", "yt.ndjson"]);
+ // Nothing changed: nothing is written.
+ const before = statSync(path.join(root, "yt.ndjson")).mtimeMs;
+ const again = await phraseScanMany(opts);
+ assert.deepEqual(again, first);
+ assert.equal(statSync(path.join(root, "yt.ndjson")).mtimeMs, before);
+ assert.equal((await openChannelCache(cacheDir, dir, "yt", ["yt1", "yt2", "yt3", "yt4"])).changed, false);
+ // Same size, new words: only the modification time tells.
+ const f = path.join(dir, "yt", "data", "yt4", "transcript.cues.json");
+ writeFileSync(f, JSON.stringify({ id: "yt4", title: "t yt4", platform: "youtube", description: "x".repeat(50), ...VIDEOS.yt.yt4, cues: [{ start: 769, end: 772, text: "don't get sucked into this it's uh slow news CYCLE panic" }] }));
+ utimesSync(f, new Date(), new Date(Date.now() + 5000));
+ rmSync(path.join(dir, "yt", "data", "yt3"), { recursive: true });
+ const second = await phraseScanMany(opts);
+ const alone = await phraseScan({ channelsDir: dir, channels: ["yt"], prefer: "rumble", phrase: SLOW });
+ const { id: _id, phrase: _p, ...rest } = second[0];
+ assert.deepEqual(rest, alone);
+ assert.equal(second[0].scanned, first[0].scanned - 1);
+ assert.ok(second[0].instances.some((i) => i.match === "slow news CYCLE"));
+ // A cache file cut short reads the rest from the cue files.
+ const nd = path.join(root, "rumble.ndjson");
+ writeFileSync(nd, readFileSync(nd, "utf8").split("\n").slice(0, 2).join("\n") + "\n");
+ const third = await phraseScanMany(opts);
+ assert.deepEqual(third, second);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ rmSync(cacheDir, { recursive: true, force: true });
+ }
+});
+
+test("phraseScanMany: progress counts videos; ids must differ; a bad phrase throws", async () => {
+ const dir = corpus(VIDEOS);
+ try {
+ const seen: { done: number; total: number; channelsDone: number }[] = [];
+ await phraseScanMany({ channelsDir: dir, channels: ["yt", "other"], prefer: "rumble", phrases: [{ id: "a", phrase: SLOW }], onProgress: (p) => seen.push(p) });
+ assert.deepEqual(seen.at(-1), { done: 11, total: 11, channel: "other", channelsDone: 3, channels: 3 });
+ await assert.rejects(phraseScanMany({ channelsDir: dir, channels: ["yt"], phrases: [{ id: "a", phrase: "x" }, { id: "a", phrase: "y" }] }), /its own id/);
+ await assert.rejects(phraseScanMany({ channelsDir: dir, channels: ["yt"], phrases: [] }), /at least one/);
+ await assert.rejects(phraseScanMany({ channelsDir: dir, channels: ["yt"], phrases: [{ id: "a", phrase: "slow (news" }] }));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("hitsInJoined is hitsInCues over a transcript joined once", () => {
+ const cues = [
+ { start: 0, end: 2, text: "well it must be a slow" },
+ { start: 2, end: 4, text: "news day for them" },
+ { start: 30, text: "another slow news week" },
+ ];
+ const re = phraseRegExp(SLOW);
+ assert.deepEqual(hitsInJoined(cues, joinCues(cues), re), hitsInCues(cues, re));
+ assert.equal(hitsInCues(cues, re)[1].end, 30, "a cue with no end ends where it starts");
+});
+
+test("plain words become a tolerant whole-word pattern", () => {
+ assert.deepEqual(phraseWords("Slow, news-day!"), ["slow", "news", "day"]);
+ const re = (t: string) => new RegExp(wordsPhraseSource(t), "i");
+ for (const said of ["slow news day", "slow, news day", "Slow-news days", "slow news. day"]) assert.match(said, re("slow news day"));
+ assert.doesNotMatch("slow newsday", re("slow news day"));
+ assert.doesNotMatch("slow news daylight", re("slow news day"));
+ assert.match("those stories", re("story"));
+ assert.match("the boxes", re("box"));
+ assert.match("i dont know", re("don't know"));
+ assert.match("i don’t know", re("don't know"));
+ assert.match("4d chess", re("4D chess"), "a word ending in s takes no plural");
+ assert.doesNotMatch("newsletter", re("news"));
+ assert.match("a (literal) .dot", new RegExp(phraseSourceOf("literal", "words").source));
+
+ assert.deepEqual(phraseSourceOf("slow news day"), { source: wordsPhraseSource("slow news day"), mode: "words" });
+ assert.deepEqual(phraseSourceOf("slow (news|views)"), { source: "slow (news|views)", mode: "regex" });
+ assert.equal(phraseSourceOf("who? me", "words").mode, "words");
+ assert.equal(phraseSourceOf("plain", "regex").source, "plain");
+ assert.throws(() => phraseSourceOf(" "), /phrase is required/);
+ assert.throws(() => phraseSourceOf("slow (news"), /not a regular expression/);
+ assert.throws(() => wordsPhraseSource("!!"), /phrase is required/);
+});
diff --git a/common/lib/montage/phraseSource.d.mts b/common/lib/montage/phraseSource.d.mts
@@ -0,0 +1,4 @@
+export const REGEX_CHARS: RegExp;
+export function phraseWords(text: unknown): string[];
+export function wordsPhraseSource(text: unknown): string;
+export function phraseSourceOf(text: unknown, mode?: "auto" | "words" | "regex"): { source: string; mode: "words" | "regex" };
diff --git a/common/lib/montage/phraseSource.mjs b/common/lib/montage/phraseSource.mjs
@@ -0,0 +1,69 @@
+// What a typed phrase is searched as (release 34): a regular expression as
+// written, or plain words made into a tolerant one.
+//
+// Plain words are what a person types: "slow news day". A caption writes the
+// same words "slow, news day" or "slow-news day", and says "days" as often as
+// "day", so plain words become a pattern that takes any run of spaces, commas,
+// full stops and hyphens between the words, an apostrophe or none inside one
+// ("dont" finds "don't" and "don’t"), and an optional plural on the last word.
+// Whole words only: "news" does not match inside "newsletter".
+//
+// Pure and dependency-free, so the phrase finder's page, its server and the
+// `umtool phrases` CLI all read a phrase the same way.
+
+/** The characters that make a typed phrase a regular expression in `auto` mode. */
+export const REGEX_CHARS = /[\\^$.|?*+()[\]{}]/;
+
+const GAP = String.raw`[\s,.\-]+`;
+const escape = (s) => s.replace(/[\\^$.|?*+()[\]{}]/g, "\\$&");
+
+/** The words of a plain phrase, lower-cased, apostrophes kept. */
+export function phraseWords(text) {
+ return String(text ?? "")
+ .toLowerCase()
+ .replace(/[’‘`]/g, "'")
+ .split(/[\s,.;:!?"“”()\-–—/]+/)
+ .map((w) => w.replace(/^'+|'+$/g, ""))
+ .filter(Boolean);
+}
+
+/**
+ * Plain words → a regular expression's source: `slow news day` →
+ * `\bslow[\s,.\-]+news[\s,.\-]+day(?:s|es)?\b`. Throws on no words.
+ */
+export function wordsPhraseSource(text) {
+ const ws = phraseWords(text);
+ if (!ws.length) throw new Error("a phrase is required");
+ const parts = ws.map((w) => w.split("'").map(escape).join("['’]?"));
+ const last = parts.length - 1;
+ const w = ws[last];
+ // The plural: story → stories, day → days, box → boxes; a word already
+ // ending in s (news, chess) or in a digit is left as it is.
+ if (/[^aeiou]y$/.test(w) && w.length > 2) parts[last] = parts[last].slice(0, -1) + "(?:y|ies)";
+ else if (/[a-z]$/.test(w) && !w.endsWith("s")) parts[last] += "(?:s|es)?";
+ return String.raw`\b` + parts.join(GAP) + String.raw`\b`;
+}
+
+/**
+ * What `text` is searched as. `mode`: `regex` takes it as written, `words`
+ * makes it a tolerant pattern, `auto` (the default) is `regex` when it holds a
+ * regular expression's characters and `words` otherwise. Returns `{ source,
+ * mode }` with the mode used; throws when the text is empty or the expression
+ * does not compile.
+ *
+ * @param {string} text
+ * @param {"auto" | "words" | "regex"} [mode]
+ * @returns {{ source: string, mode: "words" | "regex" }}
+ */
+export function phraseSourceOf(text, mode = "auto") {
+ const t = String(text ?? "").trim();
+ if (!t) throw new Error("a phrase is required");
+ const used = mode === "regex" || (mode !== "words" && REGEX_CHARS.test(t)) ? "regex" : "words";
+ const source = used === "regex" ? t : wordsPhraseSource(t);
+ try {
+ new RegExp(source, "gi");
+ } catch (e) {
+ throw new Error(`not a regular expression: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ return { source, mode: used };
+}
diff --git a/common/package.json b/common/package.json
@@ -35,7 +35,9 @@
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
+ "./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs",
"./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs",
+ "./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.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
@@ -2,6 +2,7 @@
## [Unreleased]
- **Rule a montage's clips by ear, and the render leaves out the ones that aren't him.** A report video made of one phrase said many times has a clip deck (the Cut tab's **Clips — n to rule**, at `/projects/<id>/clips`): one card per instance, its cut playing from the cached window (**Wider** plays the whole clip), the quote with the phrase marked, the date and source, the clip's note, and — when a speaker score is beside the manifest — that score. Swipe or press → **Keep**, ← **Cut**, ↓ **Not him** (a co-host, a guest, a clip played), ↑ **Read aloud** (a post or a quote read out); **e** keeps it with a wider phrase, **s** skips, space replays, **z** undoes; a reason chip or a few words go with the ruling. The deck walks the unruled clips, the doubtful ones first, the ruled ones, or all, and works at phone width with the buttons under the thumb. The rulings are `montage-rulings.json` beside the manifest, kept by the moment in the source rather than the clip's number, so seeding the montage again keeps them. A render, and a take, leaves out every clip ruled cut, not him or read aloud (of the cut and of the wall), cuts a clip to its wider phrase, and numbers the kept clips 1 to N; the build log names each clip left out and why. Without a rulings file a render is exactly as before; `--no-rulings` builds every clip. The end of the deck counts the rulings, shows the next render's clips, and **Re-render the take** makes the picked take (or the one whole-cut take) again. A seed's `edits.json` is offered once as **Import earlier rulings**. From a terminal: `umtool rulings <project>` (show, `import`, `set`, `clear`). Nothing calls a model. Needs a restart of umtool.
+- **Find the next montage phrase in umtool, with no model.** Tools → **Phrases** (`/tools/phrases`) searches several phrases at once across the channels you pick: type plain words (a caption's commas, hyphens and a plural are allowed for) or a regular expression, choose a channel to cut from where it holds the same stream and a pattern to leave out, and press **Search**. It runs as a job with its progress and a Stop. For each phrase you see how many times it was said (a stream and its clip upload counted once), a bar per year, how many are on Rumble and how many elsewhere, how many have a speaker change in the captions, and ten moments spread over the years, each with **Play** and **Transcript** (the lines around it); several phrases are ranked side by side. **Create montage** makes a report-video project from that search, exactly as the new-project form's phrase seed would, and opens it. A catchphrase report's `candidates.json` under the reports folder shows as suggestions. The page remembers your last search. The same search from a terminal: `umtool phrases "<phrase>" … --channels a,b --prefer c`. A second search over the same channels reads a cache and takes seconds instead of most of a minute. Needs a restart of umtool.
- **Report videos cut clips from Rumble windows on the right second.** Some downloaded windows (Rumble's) keep their source's clock, so their picture starts a second or two in, and every cut from one landed that much late — in the slow-news montage, one clip's "slow news week" fell into the pause after it. The build now reads where such a window's picture starts and cuts on its own clock (and says so in the build log). In a montage with even loudness, a clip or wall tile that measures near-silent is taken for a phrase looked for in the wrong place: it is found again by the sound — the speech nearest where it was expected — recorded, said in the log, and never boosted from silence.
- **Montages are level, and their walls don't repeat themselves side by side.** With `render.montage.loudness` (every montage style has it, at −16 LUFS), each clip and each wall tile is measured and brought to the same loudness, with a limiter so a quiet clip raised up cannot clip — an old upload and a recent stream no longer jump in level at the cut. `wall.spread: "stream"` keeps two clips of one stream, or a stream and its mirror on another platform, from touching in the wall's grid, and `wall.distinct` takes one clip per stream when there are enough. `wall.label` puts each tile's year, its number or both in its corner. Build to the wall uses all three. Manifests without them render exactly as before.
- **A montage can build to its wall.** The closing wall can fill in groups of 1, 1, 2, 4, 8 … tiles, each group sliding in on a beat that comes a little sooner than the last; a group says the phrase together, with every tile's first syllable placed on the beat (from whisper's word timings, or from the captions checked against the sound), and at the end every tile says it on the same frame. The wall can take the latest clips instead of a spread (`wall.clips: "tail"`) and take them out of the run before it (`wall.exclusive`), so it condenses the repetition instead of repeating it; the count before it then stops where the wall begins. A ramp can end at the wall's first beat (`ramp.into: "wall"`), so the cuts speed straight into it. A seventh style, **Build to the wall**, puts these together: whip cuts getting shorter, tally marks, then the latest twenty-five in synced groups. Manifests without the new keys render exactly as before.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10526,3 +10526,37 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
<project> [--json] | import [--dry-run] | set <clip|key> <verdict> [--reason] [--match] | clear <clip|key>`.
"Re-render the take" = `POST /api/report/takes/make {project, rebuild}` on the single picked take, else the single
full-window maker take (`baseHash`), else a link to the Takes page.
+
+## Release 34 lane N3: the phrase finder (verified 2026-10-18, branch `r34/phrase-finder`)
+
+- `phraseScanMany({channelsDir, channels, phrases: [{id, phrase, exclude?}], prefer, exclude, cacheDir?, concurrency?,
+ onProgress?})` (common/lib/montage/phraseScan.mjs) → `[{id, phrase, instances, hits, dropped, scanned}]` in the
+ order given; each phrase's `{instances, hits, dropped, scanned}` deep-equals `phraseScan` for that phrase alone (unit
+ tests in every cache state; the real corpus, 7 phrases incl. slow-news, 2026-10-18). `phraseScan` is unchanged in
+ behaviour; both share `foldHits`. `onProgress({done, total, channel, channelsDone, channels})`, every 250 videos and
+ per channel.
+- The cue-text cache (common/lib/montage/cueTextCache.mjs, `CACHE_VERSION` 3):
+ `<cacheDir>/<sha1(resolved channelsDir)[:12]>/<encodeURIComponent(slug)>.ndjson` (one line per video, video-id order:
+ `{"id", "r": {uploadDate, duration, title, platform, source, j: texts joined by "\n", a: starts, b: ends} | null}`)
+ and `.index.json` (`{version, slug, videos: {id: [mtimeMs, size]}}`). Streamed a line at a time; rewritten (temp +
+ rename) only when a cue file's mtime/size changed, one appeared or one went; a line the index promised and the file
+ lacked → the index is deleted (rebuilt next search). umtool's is `<UMTOOL_CACHE_DIR>/phrase-text` (real corpus,
+ 5 Quartering channels: 473 MB).
+- Measured 2026-10-18 over the-quartering-rumble (prefer) + the-quartering, jeremy-hambly, quartering-live,
+ cornbreadman = 23,312 transcripts, page cache warm: `phraseScan` one phrase 27.5 s / 560 MB RSS; `phraseScanMany`
+ one 17.3 s / 192 MB, 25 phrases 29.0 s / 424 MB; cache build 36.3 s / 336 MB; cache warm one 6.4 s / 168 MB, 25
+ 20.8 s / 278 MB (25 phrases are regex-bound).
+- `phraseSourceOf(text, mode)` (common/lib/montage/phraseSource.mjs, no node imports, client-safe): `auto` = regex when
+ the text holds `\ ^ $ . | ? * + ( ) [ ] { }`, else words → `\b` + words joined by `[\s,.\-]+` (apostrophe →
+ `['’]?`) + optional plural on the last word (`(?:s|es)?`; consonant+y → `(?:y|ies)`; none after s or a digit) + `\b`.
+- umtool: `/tools/phrases` (`phraseFinderHref({q, scan})`); a search is a child process `umtool phrases --spec <f>
+ --out <f> --progress` (one at a time; registry on `globalThis.__umtoolPhraseScans`); the store is
+ `<UMTOOL_CACHE_DIR>/phrase-finder/{scans,specs}/ps-<UTC yyyymmddhhmmss>-<6 hex>.json` (last 20) and `last.json`
+ (the page's defaults). API: `GET|POST /api/phrase-finder`, `GET|DELETE /api/phrase-finder/<id>`,
+ `GET /api/phrase-finder/context?channel&video&at`.
+- Create montage posts `/api/projects/new` with the phrase seed's settings plus `scan: {id, row}`; `scaffoldProject`
+ loads that row (`scanRowFor`, refused unless phrase source, channels, prefer and exclude match exactly) and passes it as
+ `scaffoldReportVideo({scan})`, which uses it instead of `phraseScan`. The phrase seed's channel check is now
+ `CHANNEL_SLUG_RE` (`/^[A-Za-z0-9][A-Za-z0-9._-]*$/`): mixed-case channel dirs (HasanAbiVODs3) were refused before.
+- Suggestions: `UMTOOL_PHRASE_CANDIDATES` (`:`-separated paths) else every `<REPORTS_ROOT>/<dir>/candidates.json` with
+ `scanned: [{key, regex, instances?, spark?}]` (the catchphrase report's shape).
diff --git a/plans/release-34/phrase-finder.md b/plans/release-34/phrase-finder.md
@@ -0,0 +1,114 @@
+# Release 34 lane N3 — `r34/phrase-finder`: find the next montage phrase in the UI (as shipped)
+
+The catchphrase ranking of 2026-10-18 was made by a script a model wrote (a patched phraseScan for many phrases in one
+pass, because one phrase took 2.5+ min under load). Operator rule (2026-10-16): what a model can do is doable in the
+UI with no model. This lane makes the search a umtool page and a CLI, and a montage one click from a result. Nothing
+here calls a model.
+
+## What
+
+1. **`phraseScanMany`** (`common/lib/montage/phraseScan.mjs`): every phrase in ONE pass over the transcripts — each cue
+ file read and parsed once, its text joined once (`joinCues`), every phrase matched in it (`hitsInJoined`); up to 16
+ reads in flight, used in order. Each phrase's `{instances, hits, dropped, scanned}` is what `phraseScan` returns for
+ it alone: `phraseScan` keeps its code path, and the placing/folding is one shared `foldHits`. A phrase may carry its
+ own `exclude`. A twin's cues are re-read only when a hit is placed in it, so the preferred channel is never held in
+ memory (phraseScan holds every record of it).
+2. **The cue-text cache** (`common/lib/montage/cueTextCache.mjs`): per channel one NDJSON file of each video's joined
+ cue text, times and five record fields, in video-id order, plus an index of each cue file's mtime and size. Streamed
+ a line at a time; rewritten only when something changed; a missing line falls back to the cue file and drops the
+ index. Never under the channels dir (umtool's is `<UMTOOL_CACHE_DIR>/phrase-text`).
+3. **Plain words** (`common/lib/montage/phraseSource.mjs`, client-safe): `phraseSourceOf(text, "auto"|"words"|"regex")`
+ — words become `\bw1[\s,.\-]+w2…(?:s|es)?\b` (apostrophes optional, consonant+y → `(?:y|ies)`); `auto` takes a
+ phrase with a regular expression's characters as written.
+4. **`umtool phrases`** (`umtool/lib/phrase-finder/{cli,scan,summary}.mjs`, one dispatch block in `bin/umtool.mjs`):
+ `"<p1>" "<p2>" --channels … --prefer … --exclude … [--words|--regex] [--samples N] [--no-cache] [--json|--full]`, and
+ the page's job form `--spec F --out F --progress` (NDJSON progress lines). `summarisePhrase`: count, by year (gaps as
+ 0), sparkline, Rumble/other (by platform), preferred/other (by channel), placed, speaker changes, excluded, raw hits,
+ per channel, 10 samples spread over the years.
+5. **`/tools/phrases`** (`app/tools/phrases/page.tsx`, `components/tools/PhraseFinder.tsx`, `lib/phrase-finder/server.ts`,
+ `/api/phrase-finder`, `/api/phrase-finder/<id>`, `/api/phrase-finder/context`): phrase rows (Add phrase, ×, the mode,
+ "as words: /…/" under each), suggestions from `candidates.json`, the channel picker (filter, picked chips), prefer,
+ exclude, **Search** (a child process, one at a time, polled progress, Stop), Recent; per phrase the count, year bars,
+ the split, ten samples with **Play** (CitedClip: a window or saved video on disk, else Fetch clip) and **Transcript**
+ (the cues around it, the hit's lit); **Compared** for several phrases; **Create montage** (slug prefilled
+ `<phrase>-montage`). The next visit opens on the last search's settings (`last.json`). Rail: Tools → phrases;
+ `/tools` lists it under Montage; the jump palette has it.
+6. **Create montage → the scaffold's phrase seed, from this search**: `/api/projects/new` with the seed's settings and
+ `scan: {id, row}`; `scaffoldReportVideo` takes `scan` (the finished answer) instead of reading the corpus again,
+ refused unless phrase, channels, prefer and exclude match. Same manifest, `phrase-scan.json` and README as a fresh
+ seed (unit-tested byte for byte). The seed's channel check now allows mixed-case channel dirs (`CHANNEL_SLUG_RE`).
+
+## Files
+
+common: `lib/montage/{phraseScan.mjs, phraseScan.d.mts, phraseSource.mjs, phraseSource.d.mts, cueTextCache.mjs,
+cueTextCache.d.mts, phraseScanMany.test.ts}`, `package.json` (two exports). umtool: `lib/phrase-finder/{cli.mjs,
+scan.mjs, scan.d.mts, summary.mjs, summary.d.mts, server.ts, types.ts}`, `lib/phrase-finder.test.mjs`,
+`app/tools/phrases/page.tsx`, `components/tools/PhraseFinder.tsx`, `app/api/phrase-finder/{route.ts, [id]/route.ts,
+context/route.ts}`, `bin/umtool.mjs` (usage + one dispatch line), `lib/hrefs.ts` (`phraseFinderHref`),
+`lib/hrefs.test.mjs`, `components/AppNav.tsx`, `components/shell/JumpPalette.tsx`, `app/tools/page.tsx`,
+`lib/projects/{scaffold.mjs, scaffold.ts}`, `lib/scaffold-phrase.test.mjs`, `e2e/phrase-finder.spec.ts`,
+`e2e/visual-audit.spec.ts` (one page), `docs/{tools.md, cli.md, README.md}`. `plans/FACTS.md`, `editor/CHANGELOG.md`.
+
+| Commit | What |
+| --- | --- |
+| `f6ad3897` | common: phraseScanMany, phraseSource, the cue-text cache; 5 tests |
+| `f8fa7ced` | umtool: the page, the API, `umtool phrases`, the scaffold's `scan`; 4 tests |
+| `f6bb9374` | umtool: phrase-finder e2e, visual audit page, the answer folder made before writing (found by the e2e) |
+| `e22f1ab3` | docs: tools.md, cli.md, FACTS, CHANGELOG |
+| (this commit) | this record |
+
+## Measured (the real corpus, read-only, 2026-10-18)
+
+Channels the-quartering-rumble (prefer) + the-quartering, jeremy-hambly, quartering-live, cornbreadman: 23,312
+transcripts. Slow-news phrase = the project's `scan.py` regex; 25 phrases = it + the first 24 of the catchphrase
+report's candidates. Page cache warm after the first run; one process per row (`/usr/bin/time`).
+
+| Run | Wall | Max RSS |
+| --- | --- | --- |
+| `phraseScan`, slow-news | 27.5 s | 560 MB |
+| `phraseScanMany`, slow-news, no cache | 17.3 s | 192 MB |
+| `phraseScanMany`, 25 phrases, no cache | 29.0 s | 424 MB |
+| `phraseScanMany`, 25 phrases, building the cache | 36.3 s | 336 MB |
+| `phraseScanMany`, 25 phrases, cache warm | 20.8 s | 278 MB |
+| `phraseScanMany`, slow-news, cache warm | 6.4 s | 168 MB |
+
+The cache is 473 MB on disk for the five channels. Equal to `phraseScan` (deep-equal) on the real corpus for the
+slow-news phrase (76 instances) and six of the report's candidates (61–141 instances each). A first cache design (one JSON per channel, parsed whole) peaked at
+1.5–2.0 GB; the streamed NDJSON replaced it.
+
+## Gates
+
+All through the shared heavy lock, from the worktree root.
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before each commit.
+- common: **4606 → 4611 (4610 pass, 1 skip)**; +5 `phraseScanMany.test.ts` (equivalence in three settings × three
+ cache states, the cache following a changed file and a removed video and a truncated cache file, nothing written
+ when nothing changed, progress, plain words).
+- `pnpm run test:scripts`: **1141 → 1145 (1141 pass, 0 fail, 4 skip)**; +3 `umtool/lib/phrase-finder.test.mjs`
+ (checkSpec, the summary, `umtool phrases` job and terminal forms), +1 `scaffold-phrase.test.mjs` (a given scan makes
+ the same project). `hrefs.test.mjs` gains two assertions.
+- umtool TS (`pnpm --filter umtool test`): 45/45, unchanged.
+- `docs env --check`, `docs cli --check`, `docs files --check`: clean (no common env var, CLI row or file schema).
+- umtool `next build` with the corpus linked (`ln -sT` + 5 GB cap): clean, 14.2 s compile; the phrase-finder routes'
+ `.nft.json` carry 1069 files, the same as `/api/phrases`, none under `transcripts/`.
+- e2e (umtool, single specs, fixture): phrase-finder + phrase-seed: 2 passed, 1 failed (the answer folder, fixed);
+ phrase-finder **1/1** (12.9 s); visual-audit (with `/tools/phrases`) + a scratch screenshot spec (not committed)
+ **67/67** (1.4 min) — no horizontal scroll at 390 and 1366 px in either theme.
+- Not run: editor, mcp, export, homepage (untouched).
+
+## Decisions
+
+- Suggestions come from catchphrase reports' `candidates.json` (`UMTOOL_PHRASE_CANDIDATES`, else every
+ `<REPORTS_ROOT>/<dir>/candidates.json`); no n-gram "Suggest" job (the report's mining is a heavier, separate tool).
+- Create montage seeds from the finished search (`scan: {id, row}`) instead of scanning again in the request: on the
+ real corpus a re-scan would hold the request 17–30 s. The scaffold still scans when no search is given.
+- A search is a child process (`umtool phrases`), not in-process: the memory stays out of the server, and the CLI and
+ the page run the same code. One search at a time (a second gets 409); it is not in the rail's Running list.
+- The cache is on by default for the page and the CLI (`--no-cache` to skip).
+- Rumble/other is by platform (`platform === "rumble"`), as the catchphrase report counted; the preferred channel's
+ share is in `--json` and `bySlug`.
+- Mixed-case channel slugs are allowed by the phrase seed (they were refused, so HasanAbiVODs3 could never be seeded).
+
+## Rulings followed
+
+Nothing calls a model; every step is a page control; plain words in labels; no cards; synthetic fixtures only (the e2e
+writes and removes its candidates file); the real corpus read only; the slow-news project not touched.
diff --git a/umtool/app/api/phrase-finder/[id]/route.ts b/umtool/app/api/phrase-finder/[id]/route.ts
@@ -0,0 +1,17 @@
+import { cancelPhraseScan, phraseScanView } from "@/lib/phrase-finder/server";
+
+export const dynamic = "force-dynamic";
+
+// One search: GET its state, progress and, once done, each phrase's numbers;
+// DELETE stops it while it runs.
+export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
+ const { id } = await ctx.params;
+ const view = await phraseScanView(id);
+ if (!view) return Response.json({ error: "no such search" }, { status: 404 });
+ return Response.json(view, { headers: { "cache-control": "no-store" } });
+}
+
+export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string }> }) {
+ const { id } = await ctx.params;
+ return Response.json({ cancelled: cancelPhraseScan(id) }, { headers: { "cache-control": "no-store" } });
+}
diff --git a/umtool/app/api/phrase-finder/context/route.ts b/umtool/app/api/phrase-finder/context/route.ts
@@ -0,0 +1,18 @@
+import { transcriptAround } from "@/lib/phrase-finder/server";
+
+export const dynamic = "force-dynamic";
+
+// GET ?channel&video&at -> the cues around that second of the video's
+// transcript, the hit's cue lit: where the phrase was said, read in place.
+export async function GET(request: Request) {
+ const sp = new URL(request.url).searchParams;
+ const at = Number(sp.get("at"));
+ if (!Number.isFinite(at)) return Response.json({ error: "at is a second" }, { status: 400 });
+ try {
+ const t = await transcriptAround(String(sp.get("channel") ?? ""), String(sp.get("video") ?? ""), at);
+ if (!t) return Response.json({ error: "no transcript" }, { status: 404 });
+ return Response.json(t, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/phrase-finder/route.ts b/umtool/app/api/phrase-finder/route.ts
@@ -0,0 +1,28 @@
+import { phraseFinderState, startPhraseScan } from "@/lib/phrase-finder/server";
+
+export const dynamic = "force-dynamic";
+
+// The phrase finder (release 34, /tools/phrases). GET: what the page opens
+// with -- the channels, the last search's settings, the suggestions, the
+// running search and the recent ones. POST {rows: [{id, text, mode}],
+// channels, prefer, exclude}: start a search, a job (lib/phrase-finder/server.ts);
+// a bad phrase or channel is refused here with its sentence, a second search
+// while one runs with 409 and the running one's id.
+export async function GET() {
+ return Response.json(await phraseFinderState(), { headers: { "cache-control": "no-store" } });
+}
+
+export async function POST(request: Request) {
+ let body: unknown;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "bad json" }, { status: 400 });
+ }
+ try {
+ return Response.json(await startPhraseScan(body), { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ const err = e as Error & { status?: number; running?: string };
+ return Response.json({ error: err.message, ...(err.running ? { running: err.running } : {}) }, { status: err.status ?? 400 });
+ }
+}
diff --git a/umtool/app/tools/page.tsx b/umtool/app/tools/page.tsx
@@ -1,6 +1,6 @@
import AppShell from "@/components/shell/AppShell";
import ToolList, { PILE_WHAT, type ToolEntry } from "@/components/tools/ToolList";
-import { benchHref, facesHref, findHref, mixHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs";
+import { benchHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs";
import { TRIM_SETS } from "@/lib/trim";
export const dynamic = "force-dynamic";
@@ -24,7 +24,10 @@ export default function ToolsPage() {
const articles: ToolEntry[] = [
{ href: benchHref(), name: "verdict bench", what: "Could a model propose a fact-check verdict well enough to review", testid: "bench" },
];
- const n = song.length + articles.length;
+ const montage: ToolEntry[] = [
+ { href: phraseFinderHref(), name: "phrases", what: "How often phrases were said, by year, and a montage from one", testid: "phrases" },
+ ];
+ const n = song.length + articles.length + montage.length;
return (
<div className="flex h-full flex-col">
<AppShell active="tools" crumbs={[{ label: "Tools" }]} meta={`${n} tools`} />
@@ -32,6 +35,7 @@ export default function ToolsPage() {
<ToolList
groups={[
{ title: "Song", tools: song },
+ { title: "Montage", tools: montage },
{ title: "Articles", tools: articles },
]}
/>
diff --git a/umtool/app/tools/phrases/page.tsx b/umtool/app/tools/phrases/page.tsx
@@ -0,0 +1,33 @@
+import AppShell from "@/components/shell/AppShell";
+import PhraseFinder from "@/components/tools/PhraseFinder";
+import { toolsHref } from "@/lib/hrefs";
+import { phraseFinderState, phraseScanView } from "@/lib/phrase-finder/server";
+
+export const dynamic = "force-dynamic";
+
+// THE PHRASE FINDER (release 34): the next montage phrase, found in the UI
+// with no model. Phrases (plain words or a regular expression) over the
+// channels picked, in one pass, as a job; per phrase the instances once folded
+// (phraseScan's rules), by year, Rumble or another channel, how many have a
+// caption speaker change, ten contexts to read in place and play; and Create
+// montage, the new-project form's phrase seed with these exact settings. The
+// search is in the page's state, not the URL: `?scan=<id>` reopens a finished
+// one and `?q=` prefills a phrase.
+
+type Params = Record<string, string | string[] | undefined>;
+const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v) ?? "";
+
+export default async function PhrasesPage({ searchParams }: { searchParams: Promise<Params> }) {
+ const sp = await searchParams;
+ const state = await phraseFinderState();
+ const scanId = one(sp.scan) || state.running || null;
+ const initialScan = scanId ? await phraseScanView(scanId) : null;
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell active="phrases" crumbs={[{ label: "Tools", href: toolsHref() }, { label: "Phrases" }]} meta={`${state.channels.length} channels`} />
+ <main className="deck-main flex-1 px-4 pb-6 pt-4">
+ <PhraseFinder state={state} initialScan={initialScan} prefill={one(sp.q)} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -52,6 +52,8 @@
// umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]
// umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>]
// the clip deck's montage rulings (release 34)
+// umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex]
+// [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass)
import process from "node:process";
import {
PROJECT_KINDS,
@@ -722,6 +724,8 @@ function usage() {
" umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]",
" umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>",
" the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out",
+ " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]",
+ " how often each phrase was said, by year, in one pass (the phrase finder's search)",
" umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]",
" re-fetch an article's scope, see what changed, update: the plan (the editor's);",
" --yes starts it, one editor job (needs WORKER_TOKEN and the editor)",
@@ -760,6 +764,8 @@ const COMMANDS = {
takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))),
// The clip deck's rulings (release 34): lib/report/rulingsCli.mjs.
rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))),
+ // The phrase finder (release 34): lib/phrase-finder/cli.mjs.
+ phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))),
inbox: cmdInbox,
schedule: () => tsxScript("schedule"),
refresh: () => tsxScript("refresh"),
diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx
@@ -6,6 +6,7 @@ import {
facesHref,
homeHref,
mixHref,
+ phraseFinderHref,
pileHref,
researchHref,
sourcesHref,
@@ -22,7 +23,7 @@ import RailCount from "./shell/RailCount";
// (the lit line, at rest; app/globals.css `.app-places`): "page" on the place's
// own page, "true" on a page under it.
//
-// Tools opens into its tools while you are in one -- find, mix, the song piles
+// Tools opens into its tools while you are in one -- find, mix, phrases, the song piles
// (the `song ▸` group, at /tools/song/<pile>), faces, sources -- so moving
// between tools is one click; /tools lists them all from anywhere.
//
@@ -39,6 +40,7 @@ const SONG_ITEMS = MODES.map((m) => ({ href: pileHref(m), label: m as string }))
const TOOL_ITEMS = [
{ href: findHref(), label: "find" },
{ href: mixHref(), label: "mix" },
+ { href: phraseFinderHref(), label: "phrases" },
{ href: facesHref(), label: "faces" },
{ href: sourcesHref(), label: "sources" },
{ href: benchHref(), label: "bench" },
@@ -92,13 +94,13 @@ export default function AppNav({ active }: { active: string }) {
</Link>
{place === "tools" && (
<div className="app-sub" data-rail-sub="tools">
- {TOOL_ITEMS.slice(0, 2).map((it) => (
+ {TOOL_ITEMS.slice(0, 3).map((it) => (
<Link key={it.href} href={it.href} prefetch={false} aria-current={it.label === active ? "page" : undefined}>
{it.label}
</Link>
))}
<NavGroup label="song" items={SONG_ITEMS} active={active} on={songActive} />
- {TOOL_ITEMS.slice(2).map((it) => (
+ {TOOL_ITEMS.slice(3).map((it) => (
<Link key={it.href} href={it.href} prefetch={false} aria-current={it.label === active ? "page" : undefined}>
{it.label}
</Link>
diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx
@@ -18,6 +18,7 @@ import {
systemHref,
toolsHref,
workHref,
+ phraseFinderHref,
} from "@/lib/hrefs";
import { MODES } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -44,12 +45,13 @@ const FIXED: Item[] = [
{ id: "research", section: "Places", label: "Research", hint: "search the archive", href: researchHref() },
{ id: "work", section: "Places", label: "Work", hint: "every piece", href: workHref() },
{ id: "projects", section: "Places", label: "Projects", hint: "every project, by folder", href: projectsHref() },
- { id: "tools", section: "Places", label: "Tools", hint: "find, mix, song piles, faces, sources", href: toolsHref() },
+ { id: "tools", section: "Places", label: "Tools", hint: "find, mix, phrases, song piles, faces, sources", href: toolsHref() },
{ id: "system", section: "Places", label: "Settings · system", hint: "tools, disk, index, sources, recent jobs", href: systemHref() },
{ id: "create", section: "Places", label: "Create", hint: "what are you making?", href: createHref() },
{ id: "policy", section: "Places", label: "Settings · generation", hint: "routes, models, caps, the key, today's spend", href: generationPolicyHref() },
{ id: "find", section: "Tools", label: "Find", hint: "every occurrence of a word", href: findHref() },
{ id: "mix", section: "Tools", label: "Mix", hint: "the mix bench", href: mixHref() },
+ { id: "phrases", section: "Tools", label: "Phrases", hint: "how often a phrase was said, by year; a montage from it", href: phraseFinderHref() },
{ id: "song", section: "Tools", label: "Song piles", hint: "sort, salvage, verify, keeps", href: songToolsHref() },
...MODES.map((m): Item => ({ id: `pile-${m}`, section: "Tools", label: `Song · ${m}`, hint: "judging pile", href: pileHref(m) })),
{ id: "faces", section: "Tools", label: "Faces", hint: "the face judger", href: facesHref() },
diff --git a/umtool/components/tools/PhraseFinder.tsx b/umtool/components/tools/PhraseFinder.tsx
@@ -0,0 +1,582 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import CitedClip from "@/components/clips/CitedClip";
+import { Button } from "@/components/ui/button";
+import { clock } from "@/components/ui/clock";
+import { Field, Input, Select } from "@/components/ui/field";
+import { JobProgressBar } from "@/components/ui/job-progress";
+import { Panel } from "@/components/ui/panel";
+import { phraseFinderHref } from "@/lib/hrefs";
+import { montageSlug } from "@/lib/phrase-finder/summary.mjs";
+import type { PhraseFinderState, PhraseMode, PhraseSample, PhraseScanRowView, PhraseScanView, TranscriptAround } from "@/lib/phrase-finder/types";
+import { phraseSourceOf } from "yt-dlp-transcript-common/lib/montage/phraseSource.mjs";
+
+// ---------------------------------------------------------------------------
+// THE PHRASE FINDER (release 34), the page's one island.
+//
+// phrases one row each: the words (plain words, or a regular expression
+// -- `auto` tells them apart by its characters), what is searched
+// under it; Add phrase / ×; a suggestion (a catchphrase report's
+// candidates) adds a row
+// channels the ones to scan, filtered by typing; prefer (the copy to cut
+// from where a stream has one) and exclude (a context that
+// matches is left out) -- the phrase seed's own four settings
+// Search one job for every row (POST /api/phrase-finder), its progress
+// polled; Stop ends it
+// results per phrase: the instances once folded, by year, Rumble or
+// another, speaker changes; ten contexts, each with Play (the
+// clip window or saved video on disk, else Fetch clip) and
+// Transcript (the cues around it, read in place); Create montage
+// (the slug prefilled) seeds a project from THIS search
+//
+// The data attributes are the e2e spec's handles (phrase-finder.spec.ts).
+// ---------------------------------------------------------------------------
+
+type Row = { key: number; text: string; mode: PhraseMode; label?: string };
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+function niceDate(s: string | null): string {
+ const m = /^(\d{4})(\d{2})(\d{2})/.exec(String(s ?? ""));
+ return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1] ?? "?"} ${m[1]}` : (s ?? "no date");
+}
+const n0 = (n: number) => n.toLocaleString("en-GB");
+const scanStamp = (id: string) => {
+ const m = /^ps-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(id);
+ return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[4]}:${m[5]}` : id;
+};
+
+/** What a row is searched as, or why it cannot be. */
+function sourceOf(r: Row): { source: string; mode: string } | { error: string } | null {
+ if (!r.text.trim()) return null;
+ try {
+ return phraseSourceOf(r.text, r.mode);
+ } catch (e) {
+ return { error: e instanceof Error ? e.message : String(e) };
+ }
+}
+
+export default function PhraseFinder({ state, initialScan, prefill }: { state: PhraseFinderState; initialScan: PhraseScanView | null; prefill: string }) {
+ const seq = useRef(0);
+ const mk = (r: Omit<Row, "key">): Row => ({ ...r, key: ++seq.current });
+ const [rows, setRows] = useState<Row[]>(() => {
+ if (prefill.trim()) return [mk({ text: prefill.trim(), mode: "auto" })];
+ if (initialScan) return initialScan.spec.rows.map((r) => mk({ text: r.text, mode: r.mode, label: r.label }));
+ if (state.last?.rows.length) return state.last.rows.map((r) => mk({ text: r.text, mode: r.mode, label: r.label }));
+ return [mk({ text: "", mode: "auto" })];
+ });
+ const from = initialScan?.spec ?? state.last;
+ const [chosen, setChosen] = useState<Set<string>>(() => new Set(from?.channels ?? []));
+ const [prefer, setPrefer] = useState(from?.prefer ?? "");
+ const [exclude, setExclude] = useState(from?.exclude ?? "");
+ const [filter, setFilter] = useState("");
+ const [scan, setScan] = useState<PhraseScanView | null>(initialScan);
+ const [error, setError] = useState<string | null>(null);
+ const [starting, setStarting] = useState(false);
+
+ const running = scan?.state === "running";
+ const names = useMemo(() => new Map(state.channels.map((c) => [c.slug, c.name])), [state.channels]);
+
+ // Poll the running search.
+ useEffect(() => {
+ if (!scan || scan.state !== "running") return;
+ let gone = false;
+ const t = setTimeout(async () => {
+ try {
+ const r = await fetch(`/api/phrase-finder/${encodeURIComponent(scan.id)}`, { cache: "no-store" });
+ const j = await r.json();
+ if (!gone && r.ok) setScan(j as PhraseScanView);
+ } catch {
+ /* the next poll */
+ }
+ }, 800);
+ return () => {
+ gone = true;
+ clearTimeout(t);
+ };
+ }, [scan]);
+
+ const setRow = (key: number, patch: Partial<Row>) => setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch, ...(patch.text !== undefined ? { label: undefined } : {}) } : r)));
+ const addRow = (r: Omit<Row, "key"> = { text: "", mode: "auto" }) =>
+ setRows((rs) => (rs.length === 1 && !rs[0].text.trim() ? [mk(r)] : [...rs, mk(r)]));
+ const removeRow = (key: number) => setRows((rs) => (rs.length > 1 ? rs.filter((r) => r.key !== key) : [mk({ text: "", mode: "auto" })]));
+ const toggle = (slug: string) =>
+ setChosen((s) => {
+ const n = new Set(s);
+ if (n.has(slug)) n.delete(slug);
+ else n.add(slug);
+ return n;
+ });
+
+ const filled = rows.filter((r) => r.text.trim());
+ const bad = filled.map(sourceOf).find((s) => s && "error" in s) as { error: string } | undefined;
+ const canSearch = !running && !starting && filled.length > 0 && !bad && (chosen.size > 0 || !!prefer);
+
+ const search = async () => {
+ if (!canSearch) return;
+ setStarting(true);
+ setError(null);
+ try {
+ const body = {
+ rows: filled.map((r, k) => ({ id: `p${k + 1}`, text: r.text.trim(), mode: r.mode, ...(r.label ? { label: r.label } : {}) })),
+ channels: [...chosen],
+ prefer: prefer || null,
+ exclude: exclude.trim() || null,
+ };
+ const r = await fetch("/api/phrase-finder", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), cache: "no-store" });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`);
+ const v = await fetch(`/api/phrase-finder/${encodeURIComponent(j.id)}`, { cache: "no-store" }).then((x) => x.json());
+ setScan(v as PhraseScanView);
+ window.history.replaceState(null, "", phraseFinderHref({ scan: j.id }));
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setStarting(false);
+ }
+ };
+ const stop = async () => {
+ if (!scan) return;
+ await fetch(`/api/phrase-finder/${encodeURIComponent(scan.id)}`, { method: "DELETE", cache: "no-store" }).catch(() => {});
+ setScan({ ...scan, state: "cancelled" });
+ };
+
+ const shown = state.channels.filter((c) => {
+ const f = filter.trim().toLowerCase();
+ return !f || c.slug.toLowerCase().includes(f) || c.name.toLowerCase().includes(f);
+ });
+
+ return (
+ <div className="grid max-w-[1180px] gap-4">
+ <form
+ className="grid gap-4"
+ data-phrase-form=""
+ onSubmit={(e) => {
+ e.preventDefault();
+ void search();
+ }}
+ >
+ <Panel title="Phrases" aside={<span className="text-muted">{filled.length} to search</span>}>
+ <ul className="grid gap-2.5">
+ {rows.map((r, k) => {
+ const s = sourceOf(r);
+ return (
+ <li key={r.key} className="grid gap-1" data-phrase-row={k + 1}>
+ <div className="flex flex-wrap items-center gap-2">
+ <Input
+ value={r.text}
+ onChange={(e) => setRow(r.key, { text: e.target.value })}
+ placeholder={k === 0 ? "slow news day" : "another phrase"}
+ aria-label={`phrase ${k + 1}`}
+ className="min-w-0 flex-1 basis-64"
+ data-phrase-text=""
+ />
+ <Select value={r.mode} onChange={(e) => setRow(r.key, { mode: e.target.value as PhraseMode })} aria-label={`phrase ${k + 1}: read as`} data-phrase-mode="">
+ <option value="auto">words or expression</option>
+ <option value="words">plain words</option>
+ <option value="regex">regular expression</option>
+ </Select>
+ <Button type="button" size="sm" variant="quiet" onClick={() => removeRow(r.key)} aria-label={`remove phrase ${k + 1}`} data-phrase-remove="">
+ ×
+ </Button>
+ </div>
+ {s && (
+ <span className={"error" in s ? "text-[11.5px] text-reject-text" : "font-mono text-[11px] text-muted-2"} data-phrase-source="">
+ {"error" in s ? s.error : `${r.label ? `${r.label} · ` : ""}${s.mode === "words" ? "as words" : "as written"}: /${s.source}/`}
+ </span>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ <div className="mt-2.5 flex flex-wrap items-center gap-2">
+ <Button type="button" size="sm" onClick={() => addRow()} data-phrase-add="">
+ Add phrase
+ </Button>
+ {state.suggestions.length > 0 && (
+ <details className="basis-full text-[12.5px]" data-phrase-suggestions="">
+ <summary className="cursor-pointer text-text-2">Suggestions ({state.suggestions.length})</summary>
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {state.suggestions.map((s) => (
+ <Button
+ key={`${s.from}/${s.key}`}
+ type="button"
+ size="sm"
+ title={`/${s.regex}/ · from ${s.from}`}
+ onClick={() => addRow({ text: s.regex, mode: "regex", label: s.key })}
+ data-phrase-suggestion={s.key}
+ >
+ {s.key}
+ {s.instances != null && <span className="font-mono text-muted-2">{s.instances}</span>}
+ </Button>
+ ))}
+ </div>
+ </details>
+ )}
+ </div>
+ </Panel>
+
+ <Panel title="Channels" aside={<span className="text-muted" data-phrase-chosen={chosen.size}>{chosen.size} picked</span>}>
+ {chosen.size > 0 && (
+ <div className="mb-2 flex flex-wrap gap-1.5">
+ {[...chosen].map((slug) => (
+ <Button key={slug} type="button" size="sm" variant="pressed" onClick={() => toggle(slug)} title="leave it out" data-phrase-picked={slug}>
+ {names.get(slug) ?? slug} ×
+ </Button>
+ ))}
+ </div>
+ )}
+ <Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="filter channels" aria-label="filter channels" className="mb-2 w-64" data-phrase-channel-filter="" />
+ <div className="grid max-h-56 grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-x-4 gap-y-0.5 overflow-auto text-[12.5px]">
+ {shown.map((c) => (
+ <label key={c.slug} className="flex items-baseline gap-2 py-0.5" data-phrase-channel={c.slug}>
+ <input type="checkbox" checked={chosen.has(c.slug)} onChange={() => toggle(c.slug)} />
+ <span className="truncate">{c.name}</span>
+ <span className="ml-auto font-mono text-[10.5px] text-muted-2">{n0(c.videos)}</span>
+ </label>
+ ))}
+ {!shown.length && <span className="text-muted">No channel matches.</span>}
+ </div>
+ <div className="mt-3 flex flex-wrap items-end gap-3">
+ <Field label="Prefer" hint="cut from this channel's copy where it has the same stream">
+ <Select value={prefer} onChange={(e) => setPrefer(e.target.value)} aria-label="prefer" data-phrase-prefer="">
+ <option value="">none</option>
+ {state.channels.map((c) => (
+ <option key={c.slug} value={c.slug}>
+ {c.name}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ <Field label="Exclude" hint="leave out a hit whose words around it match (a regular expression)">
+ <Input value={exclude} onChange={(e) => setExclude(e.target.value)} placeholder="optional" aria-label="exclude" className="w-64" data-phrase-exclude="" />
+ </Field>
+ <Button type="submit" variant="go" disabled={!canSearch} data-phrase-search="">
+ {starting ? "Starting…" : filled.length > 1 ? `Search ${filled.length} phrases` : "Search"}
+ </Button>
+ {state.recent.length > 0 && (
+ <span className="text-[12px] text-muted">
+ Recent:{" "}
+ {state.recent.slice(0, 5).map((id, k) => (
+ <a key={id} href={phraseFinderHref({ scan: id })} className="ink-link" data-phrase-recent={id}>
+ {k ? ", " : ""}
+ {scanStamp(id)}
+ </a>
+ ))}
+ </span>
+ )}
+ </div>
+ {(error || bad) && (
+ <p role="alert" className="mt-2 text-[12.5px] text-reject-text" data-phrase-error="">
+ {error ?? bad?.error}
+ </p>
+ )}
+ </Panel>
+ </form>
+
+ {scan && <ScanResults scan={scan} names={names} onStop={stop} />}
+ </div>
+ );
+}
+
+function ScanResults({ scan, names, onStop }: { scan: PhraseScanView; names: Map<string, string>; onStop: () => void }) {
+ const p = scan.progress;
+ if (scan.state === "running") {
+ const meter = p && p.total ? { fraction: p.done / p.total, text: `${p.done}/${p.total}` } : null;
+ return (
+ <Panel title="Searching" data-phrase-state="running">
+ <div className="grid grid-cols-[1fr_auto] items-center gap-x-3 gap-y-1.5">
+ <span className="text-[12.5px] text-text-2" data-phrase-progress="">
+ {p ? `${n0(p.done)} of ${n0(p.total)} transcripts · ${names.get(p.channel) ?? p.channel}` : "starting…"}
+ </span>
+ <Button type="button" size="sm" onClick={onStop} data-phrase-stop="">
+ Stop
+ </Button>
+ <JobProgressBar meter={meter} />
+ </div>
+ </Panel>
+ );
+ }
+ if (scan.state !== "done" || !scan.rows) {
+ return (
+ <Panel title="Search" data-phrase-state={scan.state}>
+ <p className="text-[12.5px] text-reject-text">{scan.state === "cancelled" ? "Stopped." : (scan.error ?? "The search failed.")}</p>
+ </Panel>
+ );
+ }
+ const rows = scan.rows;
+ return (
+ <div className="grid gap-4" data-phrase-state="done" data-phrase-scan={scan.id}>
+ <p className="text-[12px] text-muted" data-phrase-scanned={scan.scanned ?? 0}>
+ {n0(scan.scanned ?? 0)} transcripts read in {scan.seconds ?? "?"} s · {scan.spec.channels.map((c) => names.get(c) ?? c).join(", ")}
+ {scan.spec.prefer ? ` · cut from ${names.get(scan.spec.prefer) ?? scan.spec.prefer} where it has the stream` : ""}
+ </p>
+ {rows.length > 1 && <Compare rows={rows} />}
+ {rows.map((r) => (
+ <PhraseResult key={r.id} scan={scan} row={r} names={names} />
+ ))}
+ </div>
+ );
+}
+
+function Compare({ rows }: { rows: PhraseScanRowView[] }) {
+ const sorted = [...rows].sort((a, b) => b.summary.instances - a.summary.instances);
+ return (
+ <Panel title="Compared" data-phrase-compare="">
+ <table className="w-full text-[12.5px]">
+ <thead>
+ <tr className="text-left text-[11px] text-muted">
+ <th className="py-1 font-medium">phrase</th>
+ <th className="py-1 text-right font-medium">times</th>
+ <th className="py-1 pl-4 font-medium">by year</th>
+ <th className="py-1 text-right font-medium">Rumble / other</th>
+ <th className="py-1 text-right font-medium">speaker changes</th>
+ </tr>
+ </thead>
+ <tbody>
+ {sorted.map((r) => (
+ <tr key={r.id} className="border-t border-seam" data-phrase-compare-row={r.id}>
+ <td className="py-1">
+ <a href={`#phrase-${r.id}`} className="ink-link">
+ {r.label ?? r.text}
+ </a>
+ </td>
+ <td className="py-1 text-right font-mono">{r.summary.instances}</td>
+ <td className="py-1 pl-4 font-mono text-meter" title={Object.entries(r.summary.years).map(([y, n]) => `${y}: ${n}`).join(", ")}>
+ {r.summary.spark}
+ </td>
+ <td className="py-1 text-right font-mono">
+ {r.summary.rumble} / {r.summary.notRumble}
+ </td>
+ <td className="py-1 text-right font-mono">{r.summary.speakerChecks}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </Panel>
+ );
+}
+
+function YearBars({ years }: { years: Record<string, number> }) {
+ const entries = Object.entries(years);
+ const max = Math.max(1, ...entries.map(([, n]) => n));
+ if (!entries.length) return null;
+ return (
+ <div className="flex items-end gap-1" data-phrase-years="">
+ {entries.map(([y, n]) => (
+ <div key={y} className="flex w-7 flex-col items-center gap-0.5" data-phrase-year={y} data-count={n} title={`${y}: ${n}`}>
+ <span className="font-mono text-[10px] text-text-2">{n || ""}</span>
+ <span className="block w-4 bg-meter" style={{ height: `${n ? Math.max(2, Math.round((n / max) * 32)) : 0}px` }} />
+ <span className="font-mono text-[10px] text-muted-2">'{y.slice(2)}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function PhraseResult({ scan, row, names }: { scan: PhraseScanView; row: PhraseScanRowView; names: Map<string, string> }) {
+ const s = row.summary;
+ const span = s.first ? `${String(s.first).slice(0, 4)}–${String(s.last).slice(0, 4)}` : "";
+ return (
+ <Panel
+ id={`phrase-${row.id}`}
+ title={row.label ?? row.text}
+ aside={<span className="font-mono text-muted-2">/{row.source}/</span>}
+ data-phrase-result={row.id}
+ >
+ <div className="flex flex-wrap items-end gap-x-8 gap-y-3">
+ <div>
+ <div className="font-mono text-[28px] leading-none text-text" data-phrase-count={s.instances}>
+ {s.instances}
+ </div>
+ <div className="mt-1 text-[11.5px] text-muted">
+ {s.instances === 1 ? "time" : "times"}
+ {span ? `, ${span}` : ""}
+ </div>
+ </div>
+ <YearBars years={s.years} />
+ <dl className="grid grid-cols-[auto_auto] gap-x-3 gap-y-0.5 text-[12px]">
+ <dt className="text-muted">Rumble</dt>
+ <dd className="font-mono" data-phrase-rumble={s.rumble}>
+ {s.rumble}
+ </dd>
+ <dt className="text-muted">other</dt>
+ <dd className="font-mono" data-phrase-other={s.notRumble}>
+ {s.notRumble}
+ </dd>
+ <dt className="text-muted">speaker changes</dt>
+ <dd className="font-mono" data-phrase-speaker={s.speakerChecks}>
+ {s.speakerChecks}
+ </dd>
+ {s.placed > 0 && (
+ <>
+ <dt className="text-muted">placed by words</dt>
+ <dd className="font-mono">{s.placed}</dd>
+ </>
+ )}
+ {s.dropped > 0 && (
+ <>
+ <dt className="text-muted">excluded</dt>
+ <dd className="font-mono">{s.dropped}</dd>
+ </>
+ )}
+ <dt className="text-muted">raw hits</dt>
+ <dd className="font-mono">{s.hits}</dd>
+ </dl>
+ </div>
+ {Object.keys(s.bySlug).length > 1 && (
+ <p className="mt-2 text-[11.5px] text-muted">
+ {Object.entries(s.bySlug)
+ .sort((a, b) => b[1] - a[1])
+ .map(([slug, n]) => `${names.get(slug) ?? slug} ${n}`)
+ .join(" · ")}
+ </p>
+ )}
+ {s.samples.length > 0 && (
+ <ol className="mt-3 grid gap-2" data-phrase-samples="">
+ {s.samples.map((x) => (
+ <Sample key={`${x.slug}/${x.videoId}@${x.start}`} s={x} names={names} />
+ ))}
+ </ol>
+ )}
+ <CreateMontage scan={scan} row={row} />
+ </Panel>
+ );
+}
+
+function Lit({ context, match }: { context: string; match: string }) {
+ const at = context.toLowerCase().indexOf(match.toLowerCase());
+ if (!match || at < 0) return <>{context}</>;
+ return (
+ <>
+ {context.slice(0, at)}
+ <b className="font-semibold text-signal-text">{context.slice(at, at + match.length)}</b>
+ {context.slice(at + match.length)}
+ </>
+ );
+}
+
+function Sample({ s, names }: { s: PhraseSample; names: Map<string, string> }) {
+ const [open, setOpen] = useState<"play" | "text" | null>(null);
+ const [ctx, setCtx] = useState<TranscriptAround | { error: string } | null>(null);
+ const readTranscript = useCallback(async () => {
+ if (open === "text") return setOpen(null);
+ setOpen("text");
+ if (ctx && !("error" in ctx)) return;
+ try {
+ const q = new URLSearchParams({ channel: s.slug, video: s.videoId, at: String(s.start) });
+ const r = await fetch(`/api/phrase-finder/context?${q}`, { cache: "no-store" });
+ const j = await r.json();
+ setCtx(r.ok ? (j as TranscriptAround) : { error: j.error ?? `HTTP ${r.status}` });
+ } catch (e) {
+ setCtx({ error: e instanceof Error ? e.message : String(e) });
+ }
+ }, [open, ctx, s.slug, s.videoId, s.start]);
+ return (
+ <li className="rounded-[3px] border border-seam px-3 py-2" data-phrase-sample={`${s.slug}/${s.videoId}`}>
+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1 text-[11.5px] text-muted">
+ <span className="font-mono text-text-2">{niceDate(s.date)}</span>
+ <span>{names.get(s.slug) ?? s.slug}</span>
+ <span className="font-mono">
+ {s.videoId} @ {clock(s.start)}
+ </span>
+ {s.speakerCheck && <span className="text-doubt-text">speaker change</span>}
+ {s.via && <span>placed from {names.get(s.via.slug) ?? s.via.slug}</span>}
+ <span className="ml-auto flex gap-1.5">
+ <Button type="button" size="sm" variant={open === "play" ? "pressed" : "outline"} onClick={() => setOpen(open === "play" ? null : "play")} data-phrase-play="">
+ Play
+ </Button>
+ <Button type="button" size="sm" variant={open === "text" ? "pressed" : "outline"} onClick={() => void readTranscript()} data-phrase-transcript="">
+ Transcript
+ </Button>
+ </span>
+ </div>
+ {s.title && <div className="mt-0.5 truncate text-[11.5px] text-muted-2">{s.title}</div>}
+ <p className="mt-1 text-[13px] leading-snug text-text">
+ <Lit context={s.context} match={s.match} />
+ </p>
+ {open === "play" && (
+ <div className="mt-2">
+ <CitedClip target={{ channel: s.slug, video: s.videoId, from: s.start, to: Math.max(s.end, s.start + 1) }} reason="phrase finder" />
+ </div>
+ )}
+ {open === "text" && (
+ <div className="mt-2" data-phrase-cues="">
+ {!ctx ? (
+ <span className="text-[12px] text-muted">reading…</span>
+ ) : "error" in ctx ? (
+ <span className="text-[12px] text-reject-text">{ctx.error}</span>
+ ) : (
+ <ol className="grid gap-0.5 text-[12.5px]">
+ {ctx.cues.map((c) => (
+ <li key={c.start} className={c.lit ? "text-text" : "text-muted"} data-phrase-cue={c.lit ? "lit" : ""}>
+ <span className="mr-2 font-mono text-[10.5px] text-muted-2">{clock(c.start)}</span>
+ {c.text}
+ </li>
+ ))}
+ </ol>
+ )}
+ </div>
+ )}
+ </li>
+ );
+}
+
+function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRowView }) {
+ const router = useRouter();
+ const [slug, setSlug] = useState(() => montageSlug(row.label ?? row.text));
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const empty = row.summary.instances === 0;
+ const create = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/projects/new", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ cache: "no-store",
+ body: JSON.stringify({
+ kind: "report-video",
+ slug: slug.trim(),
+ title: row.label ?? row.text,
+ seed: "phrase",
+ phrase: row.source,
+ channels: scan.spec.channels,
+ prefer: scan.spec.prefer,
+ exclude: scan.spec.exclude,
+ scan: { id: scan.id, row: row.id },
+ }),
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`);
+ router.push(j.href);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ setBusy(false);
+ }
+ };
+ return (
+ <form
+ className="mt-3 flex flex-wrap items-end gap-2 border-t border-seam pt-3"
+ data-phrase-montage={row.id}
+ onSubmit={(e) => {
+ e.preventDefault();
+ void create();
+ }}
+ >
+ <Field label="Montage project">
+ <Input value={slug} onChange={(e) => setSlug(e.target.value)} aria-label="montage project slug" className="w-72" data-phrase-slug="" />
+ </Field>
+ <Button type="submit" disabled={busy || empty || !slug.trim()} title={empty ? "nothing to cut" : `${row.summary.instances} clips, chronological`} data-phrase-create="">
+ {busy ? "Creating…" : "Create montage"}
+ </Button>
+ {error && (
+ <span role="alert" className="text-[12px] text-reject-text" data-phrase-create-error="">
+ {error}
+ </span>
+ )}
+ </form>
+ );
+}
diff --git a/umtool/docs/README.md b/umtool/docs/README.md
@@ -15,7 +15,7 @@ anywhere), Pinned, the **Running** list with today's API spend, and the theme (*
| A series or watch | `/series/<id>`, a triage run `/series/<id>/triage/<k>` | [recurring.md](recurring.md), [triage.md](triage.md) |
| The benches | `/projects/<path>/clip/<id>`, `…/claim/<id>`, `…/narration`, `…/takes`, `…/review`; a song's cut `/projects/<path>/<cut>` | [piece.md](piece.md#the-benches) |
| Create | `/create` (`?make=`, `?from=`, `?case=`, `?article=`) | below |
-| Tools | `/tools`, `/tools/{find,mix,faces,sources,bench}`, `/tools/song[/<mode>]`, `/tools/trim/<set>` | [tools.md](tools.md) |
+| Tools | `/tools`, `/tools/{find,mix,phrases,faces,sources,bench}`, `/tools/song[/<mode>]`, `/tools/trim/<set>` | [tools.md](tools.md) |
| Settings | `/settings`, `/settings/generation`, `/settings/system` | [settings.md](settings.md) |
**Create** is one list, "What are you making?" — j/k move the lit line, Enter opens its form, Escape closes it; the
@@ -123,7 +123,7 @@ root. See [report-video.md](report-video.md#one-manifest-two-cuts).
| [refresh.md](refresh.md) | Refresh: fetch what is new, check it, update; the daily check |
| [recurring.md](recurring.md) | Recurring reports: living reports, series and watches, the schedule, the series page |
| [triage.md](triage.md) | Triage first: the cheap pass, its tiers, flags and marks, Worth researching |
-| [tools.md](tools.md) | The song piles, find, mix, faces, sources, trims, the verdict bench |
+| [tools.md](tools.md) | The song piles, find, mix, the phrase finder, faces, sources, trims, the verdict bench |
| [settings.md](settings.md) | The generation policy and spend; the system page; `umtool doctor` |
| [report-video.md](report-video.md) | The manifest as an EDL, the three-stage window model, `lock` |
| [clip-bench.md](clip-bench.md) | Editing a clip's window against the waveform and the cues |
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -43,6 +43,7 @@ Inbox cannot disagree about what is wrong with one.
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
+| `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase |
A project argument is an exact id, a directory, or a **unique** basename. Two
projects answering to one name is reported, never resolved by picking one.
@@ -50,7 +51,7 @@ projects answering to one name is reported, never resolved by picking one.
## Environment
`REPORTS_DIR`, `SONG_REPORTS_DIR`, `SONG_DIR`, `CHANNELS_DIR`, `UMTOOL_INDEX_DIR`,
-`UMTOOL_CACHE_DIR`, `UMTOOL_MEDIA_DIR`
+`UMTOOL_CACHE_DIR`, `UMTOOL_MEDIA_DIR`, `UMTOOL_PHRASE_CANDIDATES` (the phrase finder's suggestion files)
— which is how it is tested against the e2e fixture (which also sets
`E2E_UMTOOL_MONTAGE_STYLES`, the montage styles module `take`/`takes` read in place of
`report-to-video/montage-styles.mjs`). The path defaults
diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md
@@ -2,13 +2,15 @@
## `/tools`
-Two lists. **Song**: song piles, find, mix, faces, sources, a trim set. **Articles**: the verdict bench. While you are in
-a tool the rail opens Tools into its tools: find · mix · **song ▸** (the four piles) · faces · sources · bench.
+Three lists. **Song**: song piles, find, mix, faces, sources, a trim set. **Montage**: the phrase finder. **Articles**:
+the verdict bench. While you are in a tool the rail opens Tools into its tools: find · mix · phrases · **song ▸** (the
+four piles) · faces · sources · bench.
| Tool | Address | What it is |
|---|---|---|
| Song piles | `/tools/song`, `/tools/song/<mode>` | the clip-judging deck, one pile at a time: `sort` (candidate clips never judged), `salvage` (clips parked as unclean, offered again), `verify` (accepted clips the risk check flagged, riskiest first), `keeps` (clips kept on purpose for a stray word, to side). `?limit=`, `?only=<ids>` |
| Find | `/tools/find` | every occurrence of a word across the song corpus: a GET form (`?q=`, `?page=`, `?list=<shortlist>`), filters as links, so a view is one pasteable URL |
+| Phrases | `/tools/phrases` | how often phrases were said, by year, across the channels picked, and a montage from one ([the phrase finder](#the-phrase-finder-toolsphrases)). `?q=` prefills a phrase, `?scan=<id>` reopens a search |
| Mix | `/tools/mix` | the mix bench: set the handover and the end point, hear it, render it. A clip deep-links in with `?body=&start=&end=&from=&clip=` ([mix-from-a-project.md](mix-from-a-project.md)) |
| Faces | `/tools/faces` | every cover corner on record, deduped by episode and moment, the ones that ship first: judge the crop (`face-verdicts.json`, which `make-thumb.mjs` reads; the page never touches the thumb manifests). The dashed box is what `facecrop.py` would cut, the solid one yours. `?cover=` / `?key=` open one |
| Sources | `/tools/sources` | where the song palette comes from: placements (the finished runtime an episode supplies) and clips (the palette) per episode — different units, both shown, never summed — the top episode, the top five, how many cover half |
@@ -19,6 +21,45 @@ A song's own page links its piles, find, mix and sources (its Overview's Song to
The old addresses (`/sort`, `/salvage`, `/verify`, `/keeps`, `/mix`, `/bench`, `/browse/find`, `/browse/faces`,
`/browse/sources`, `/browse/trim/<set>`) redirect here.
+## The phrase finder (`/tools/phrases`)
+
+Finding the next montage phrase, with no model. Type phrases — one row each, **Add phrase** for another — pick the
+channels, and **Search**: every phrase in one pass over the transcripts.
+
+- **A phrase** is plain words or a regular expression, and the row says which it was read as. Plain words become a
+ tolerant pattern: any run of spaces, commas, full stops or hyphens between the words, an apostrophe or none inside
+ one (`dont` finds `don't`), an optional plural on the last word (`day` → `days`, `story` → `stories`), whole words
+ only. A phrase with a regular expression's characters (`\ ^ $ . | ? * + ( ) [ ] { }`) is taken as written; the row's
+ select forces either. Case never matters.
+- **Channels**: the ones with transcripts, filtered by typing. **Prefer** is the channel to cut from where it holds a
+ copy of the same stream (a Rumble upload of a YouTube stream); **Exclude** leaves out a hit whose words around it
+ match (a chat line read out). These are the new-project form's phrase seed's own settings, and they fold the same:
+ a rolling caption's repeat is one hit, a stream and its clip upload are one instance, a hit on another channel is
+ cut from the preferred copy when its words are found there ([report-video.md](report-video.md)).
+- **The search** runs as a job (`umtool phrases --spec … --out …`), with its progress (transcripts read, the channel)
+ and **Stop**. Its answer is kept under the cache (`<UMTOOL_CACHE_DIR>/phrase-finder/`, the last 20); **Recent**
+ reopens one. The next visit opens on the last search's phrases and settings.
+- **Per phrase**: the times it was said once folded and the years they span, a bar per year, how many are on Rumble
+ and how many elsewhere, how many have a caption speaker change (`>>` — listen for who says it), how many were placed
+ in the preferred copy by their words, how many the exclude left out, the raw hits; each channel's count. Then ten
+ contexts spread over the years, each with **Play** (the clip window or saved video on disk; else **Fetch clip**, the
+ editor's managed fetch) and **Transcript** (the cues around it, read where it was said). With several phrases,
+ **Compared** ranks them side by side.
+- **Create montage** (the slug prefilled from the phrase) makes a report-video project seeded from THIS search — the
+ phrase seed with these exact settings, its `phrase-scan.json` the search's answer, nothing read again — and opens it.
+ A search whose settings no longer match is refused ("search again").
+- **Suggestions**: the phrases of a catchphrase report's `candidates.json` (`{scanned: [{key, regex, instances}]}`):
+ every `<REPORTS_DIR>/<dir>/candidates.json`, or the files `UMTOOL_PHRASE_CANDIDATES` names (`:`-separated). One
+ click adds the phrase as a row. None found, none shown.
+
+A second search reads a cache of each channel's cue text (`<UMTOOL_CACHE_DIR>/phrase-text/`, one file per channel,
+streamed; a video's entry is used while its `transcript.cues.json` keeps its modification time and size). Measured
+over five channels (23,312 transcripts): one phrase 17 s cold, 6 s from the cache; 25 phrases 29 s cold, 21 s from
+the cache. Delete it at any time.
+
+From a terminal: `umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE]`
+([cli.md](cli.md)).
+
## The deck (`/tools/song/<mode>`)
A clip at a time, its verdict and reason codes by key. Some of the keys: space play, `[` / `]` +1 s left / right, `,`
diff --git a/umtool/e2e/phrase-finder.spec.ts b/umtool/e2e/phrase-finder.spec.ts
@@ -0,0 +1,105 @@
+import { test, expect } from "@playwright/test";
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// Release 34: the phrase finder (/tools/phrases). Two phrases over the fixture
+// corpus (testchan's cue files say "The sweep fixture opens.", "The deliver
+// fixture opens.", "The editor fetch fixture speaks.", "The reuse fixture
+// begins here." …) in one search, run as a job: counts, the year bars, the
+// contexts with their transcript read in place, the comparison, the last
+// search's settings on the next visit, a suggestion from a candidates file,
+// and Create montage landing on a new project seeded from that search.
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+
+test("the phrase finder searches two phrases in one pass, shows the numbers and contexts, and makes a montage", async ({ page }) => {
+ const slug = "phrase-finder-probe";
+ const dir = path.join(FIXTURE, slug);
+ // A catchphrase report's candidates, as the report writes them (REPORTS_ROOT/<dir>/candidates.json).
+ const cand = path.join(FIXTURE, "phrase-finder-candidates");
+ rmSync(dir, { recursive: true, force: true });
+ mkdirSync(cand, { recursive: true });
+ writeFileSync(path.join(cand, "candidates.json"), JSON.stringify({ scanned: [{ key: "whole sentence", regex: String.raw`\bwhole sentence\b`, instances: 1 }] }));
+ try {
+ await page.goto(urls.phraseFinderHref());
+ await expect(page.locator("[data-rail-sub=tools] a[aria-current=page]")).toHaveText("phrases");
+
+ // Plain words, and an expression.
+ await page.locator("[data-phrase-text]").first().fill("fixture opens");
+ await expect(page.locator("[data-phrase-source]").first()).toContainText("as words");
+ await page.locator("[data-phrase-add]").click();
+ await page.locator("[data-phrase-text]").nth(1).fill("fixture (speaks|begins)");
+ await expect(page.locator("[data-phrase-source]").nth(1)).toContainText("as written: /fixture (speaks|begins)/");
+ // A bad expression says so and cannot be searched.
+ await page.locator("[data-phrase-add]").click();
+ await page.locator("[data-phrase-text]").nth(2).fill("fixture (opens");
+ await expect(page.locator("[data-phrase-error]")).toContainText("not a regular expression");
+ await page.locator("[data-phrase-remove]").nth(2).click();
+ // A suggestion adds a row.
+ await page.locator("[data-phrase-suggestions] summary").click();
+ await page.locator("[data-phrase-suggestion='whole sentence']").click();
+ await expect(page.locator("[data-phrase-text]")).toHaveCount(3);
+ await expect(page.locator("[data-phrase-source]").nth(2)).toContainText("whole sentence · as written");
+
+ await expect(page.locator("[data-phrase-search]")).toBeDisabled();
+ await page.locator("[data-phrase-channel-filter]").fill("testch");
+ await page.locator("[data-phrase-channel=testchan] input").check();
+ await expect(page.locator("[data-phrase-picked=testchan]")).toBeVisible();
+ await page.locator("[data-phrase-search]").click();
+
+ const done = page.locator("[data-phrase-state=done]");
+ await expect(done).toBeVisible({ timeout: 60_000 });
+ expect(page.url()).toContain("/tools/phrases?scan=ps-");
+ await expect(page.locator("[data-phrase-compare-row]")).toHaveCount(3);
+
+ const opens = page.locator("[data-phrase-result=p1]");
+ const n = Number(await opens.locator("[data-phrase-count]").getAttribute("data-phrase-count"));
+ expect(n).toBeGreaterThanOrEqual(2);
+ await expect(opens.locator("[data-phrase-year='2025']")).toHaveAttribute("data-count", String(n));
+ await expect(opens.locator("[data-phrase-other]")).toHaveAttribute("data-phrase-other", String(n));
+ await expect(opens.locator("[data-phrase-sample]")).toHaveCount(Math.min(n, 10));
+ await expect(opens.locator("[data-phrase-sample]").first()).toContainText(/fixture opens/i);
+ await expect(opens.locator("[data-phrase-sample]").first()).toContainText("1 Jan 2025");
+ // The transcript where it was said, its cue lit.
+ await opens.locator("[data-phrase-transcript]").first().click();
+ await expect(opens.locator("[data-phrase-cue=lit]").first()).toContainText(/fixture opens/i);
+ // Play mounts the cited clip (a window on disk, or Fetch clip).
+ await opens.locator("[data-phrase-play]").first().click();
+ await expect(opens.locator("[data-cited-clip]").first()).toBeVisible();
+ const speaks = page.locator("[data-phrase-result=p2]");
+ expect(Number(await speaks.locator("[data-phrase-count]").getAttribute("data-phrase-count"))).toBeGreaterThanOrEqual(2);
+
+ // The next visit opens on this search's settings.
+ await page.goto(urls.phraseFinderHref());
+ await expect(page.locator("[data-phrase-text]").first()).toHaveValue("fixture opens");
+ await expect(page.locator("[data-phrase-picked=testchan]")).toBeVisible();
+ await expect(page.locator("[data-phrase-recent]").first()).toBeVisible();
+ await page.locator("[data-phrase-recent]").first().click();
+ await expect(done).toBeVisible();
+
+ // Create montage: the slug prefilled, a project seeded from this search.
+ const form = page.locator("[data-phrase-montage=p1]");
+ await expect(form.locator("[data-phrase-slug]")).toHaveValue("fixture-opens-montage");
+ await form.locator("[data-phrase-slug]").fill(slug);
+ await form.locator("[data-phrase-create]").click();
+ await page.waitForURL(`**/projects/${slug}`);
+ const doc = JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8"));
+ const clips = doc.timeline as Array<{ id: string; channel: string; montage: { n: number; of: number; match: string } }>;
+ expect(clips).toHaveLength(n);
+ clips.forEach((c, k) => {
+ expect(c.id).toBe(`s${String(k + 1).padStart(2, "0")}`);
+ expect(c.channel).toBe("testchan");
+ expect(c.montage.match).toMatch(/fixture opens/i);
+ });
+ const scan = JSON.parse(readFileSync(path.join(dir, "phrase-scan.json"), "utf8"));
+ expect(scan.channels).toEqual(["testchan"]);
+ expect(scan.instances).toHaveLength(n);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ rmSync(cand, { recursive: true, force: true });
+ }
+ expect(existsSync(dir)).toBe(false);
+});
diff --git a/umtool/e2e/visual-audit.spec.ts b/umtool/e2e/visual-audit.spec.ts
@@ -60,6 +60,7 @@ const PAGES: [string, string][] = [
),
["tools", urls.toolsHref()],
["tools-find", urls.findHref()],
+ ["tools-phrases", urls.phraseFinderHref()],
["tools-mix", urls.mixHref()],
["tools-song", urls.songToolsHref()],
...["sort", "salvage", "verify", "keeps"].map((m) => [`tools-song-${m}`, urls.pileHref(m)] as [string, string]),
diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs
@@ -89,6 +89,8 @@ test("site pages, tools and piles", () => {
assert.equal(H.siteHref("jeralyzer", { ws: "w", rel: "a/b.md" }), "/sites/jeralyzer?ws=w&rel=a%2Fb.md#files");
assert.equal(H.sitesHref({ status: "draft" }), "/work?by=site&status=draft");
assert.equal(H.findHref({ q: "um" }), "/tools/find?q=um");
+ assert.equal(H.phraseFinderHref(), "/tools/phrases");
+ assert.equal(H.phraseFinderHref({ q: "slow news day" }), "/tools/phrases?q=slow+news+day");
assert.equal(H.facesHref({ cover: "c 1" }), "/tools/faces?cover=c+1");
assert.equal(H.sourcesHref(), "/tools/sources");
assert.equal(H.trimHref("hooks"), "/tools/trim/hooks");
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -309,6 +309,14 @@ export function findHref(q: Query = {}): string {
return withQuery("/tools/find", q);
}
+/**
+ * The phrase finder (release 34): how often phrases were said, by year, and a
+ * montage from one. `q` prefills the first phrase.
+ */
+export function phraseFinderHref(q: { q?: string; scan?: string } = {}): string {
+ return withQuery("/tools/phrases", q);
+}
+
/** The face judger; `cover` opens on one cover's corners. */
export function facesHref(q: { cover?: string } = {}): string {
return withQuery("/tools/faces", q);
diff --git a/umtool/lib/phrase-finder.test.mjs b/umtool/lib/phrase-finder.test.mjs
@@ -0,0 +1,111 @@
+// The phrase finder's own parts (release 34): the spec check, the summary,
+// the slug, and `umtool phrases` over a synthetic corpus — its job form
+// (--spec/--out/--progress) and its terminal form.
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+import { phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs";
+import { wordsPhraseSource } from "yt-dlp-transcript-common/lib/montage/phraseSource.mjs";
+import { checkSpec } from "./phrase-finder/scan.mjs";
+import { byYear, montageSlug, sparkline, spread, summarisePhrase } from "./phrase-finder/summary.mjs";
+
+const run = promisify(execFile);
+const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "bin", "umtool.mjs");
+
+function corpus() {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "phrase-finder-"));
+ const put = (slug, id, rec) => {
+ 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}`, ...rec }));
+ };
+ put("rum", "r1", { uploadDate: "20200105", duration: 600, platform: "rumble", cues: [{ start: 10, end: 13, text: "what a slow news day" }, { start: 50, end: 53, text: "nobody asked for this" }] });
+ put("rum", "r2", { uploadDate: "20220310", duration: 900, platform: "rumble", cues: [{ start: 5, end: 8, text: ">> slow, news days again" }] });
+ put("yt", "y1", { uploadDate: "20180101", duration: 300, platform: "youtube", cues: [{ start: 1, end: 4, text: "a slow news week this is" }, { start: 90, end: 93, text: "and nobody asked" }] });
+ put("yt", "y2", { uploadDate: "20220601", duration: 400, platform: "youtube", cues: [{ start: 7, end: 9, text: "no one asked" }] });
+ return dir;
+}
+
+test("checkSpec: phrases become what is searched; a bad one is refused with its sentence", () => {
+ const s = checkSpec({ rows: [{ id: "a", text: " slow news day ", mode: "auto" }, { text: "" }, { text: "no ?one asked", label: "nobody asked" }], channels: "yt, rum", prefer: "rum", exclude: "" });
+ assert.deepEqual(s.rows, [
+ { id: "a", text: "slow news day", mode: "auto", source: wordsPhraseSource("slow news day"), used: "words" },
+ { id: "p3", text: "no ?one asked", label: "nobody asked", mode: "auto", source: "no ?one asked", used: "regex" },
+ ]);
+ assert.deepEqual(s.channels, ["yt", "rum"]);
+ assert.equal(s.prefer, "rum");
+ assert.equal(s.exclude, null);
+ assert.equal(checkSpec({ rows: [{ text: "x" }], channels: ["HasanAbiVODs3"] }).channels[0], "HasanAbiVODs3");
+ assert.throws(() => checkSpec({ rows: [], channels: ["yt"] }), /type a phrase/);
+ assert.throws(() => checkSpec({ rows: [{ text: "slow (news" }], channels: ["yt"] }), /"slow \(news": not a regular expression/);
+ assert.throws(() => checkSpec({ rows: [{ text: "x" }], channels: [] }), /pick at least one channel/);
+ assert.throws(() => checkSpec({ rows: [{ text: "x" }], channels: ["../etc"] }), /is not a channel/);
+ assert.throws(() => checkSpec({ rows: [{ text: "x" }], channels: ["yt"], exclude: "(" }), /exclude is not a regular expression/);
+ assert.throws(() => checkSpec({ rows: Array.from({ length: 31 }, (_, k) => ({ text: `w${k}` })), channels: ["yt"] }), /at most 30/);
+});
+
+test("the summary: by year with the gaps, the split, the spread of samples", async () => {
+ assert.deepEqual(byYear([{ date: "20180101" }, { date: "20200105" }, { date: "20200301" }, { date: null }]), { 2018: 1, 2019: 0, 2020: 2 });
+ assert.equal(sparkline({ 2018: 1, 2019: 0, 2020: 2 }), "▄ █");
+ assert.deepEqual(spread([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 3), [1, 6, 11]);
+ assert.deepEqual(spread([1, 2], 10), [1, 2]);
+ assert.equal(montageSlug("slow news day"), "slow-news-day-montage");
+ assert.equal(montageSlug(String.raw`\b(?:no ?one|nobody) asked\b`), "no-one-nobody-asked-montage");
+ assert.equal(montageSlug("!!!"), "phrase-montage");
+
+ const dir = corpus();
+ try {
+ const r = await phraseScan({ channelsDir: dir, channels: ["yt"], prefer: "rum", phrase: wordsPhraseSource("slow news day") });
+ const s = summarisePhrase(r, { prefer: "rum", samples: 2 });
+ assert.equal(s.instances, 2);
+ assert.deepEqual(s.years, { 2020: 1, 2021: 0, 2022: 1 });
+ assert.equal(s.rumble, 2);
+ assert.equal(s.notRumble, 0);
+ assert.equal(s.preferred, 2);
+ assert.equal(s.speakerChecks, 1);
+ assert.deepEqual(s.samples.map((x) => x.videoId), ["r1", "r2"]);
+ assert.equal(s.samples[1].match, "slow, news days");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("umtool phrases: the job form writes the whole answer and its progress; the terminal form prints the numbers", async () => {
+ const dir = corpus();
+ const cache = mkdtempSync(path.join(os.tmpdir(), "phrase-finder-cache-"));
+ const env = { ...process.env, CHANNELS_DIR: dir, UMTOOL_CACHE_DIR: cache };
+ try {
+ const spec = path.join(cache, "spec.json");
+ const out = path.join(cache, "out.json");
+ writeFileSync(spec, JSON.stringify({ rows: [{ id: "slow", text: "slow news day" }, { id: "asked", text: String.raw`\b(?:no ?one|nobody) asked\b` }], channels: ["yt", "rum"], prefer: null }));
+ const { stdout } = await run(process.execPath, [CLI, "phrases", "--spec", spec, "--out", out, "--progress"], { env });
+ const lines = stdout.trim().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(lines.at(-2).progress, { done: 4, total: 4, channel: "rum", channelsDone: 2, channels: 2 });
+ assert.equal(lines.at(-1).done, true);
+ const answer = JSON.parse(readFileSync(out, "utf8"));
+ assert.equal(answer.scanned, 4);
+ assert.deepEqual(answer.rows.map((r) => [r.id, r.used, r.result.instances.length]), [["slow", "words", 2], ["asked", "regex", 3]]);
+ // Each phrase's answer is phraseScan's for it alone.
+ const alone = await phraseScan({ channelsDir: dir, channels: ["yt", "rum"], prefer: null, phrase: answer.rows[1].source });
+ assert.deepEqual(answer.rows[1].result, JSON.parse(JSON.stringify(alone)));
+
+ const text = await run(process.execPath, [CLI, "phrases", "slow news day", "nobody asked", "--channels", "yt,rum", "--samples", "1"], { env });
+ assert.match(text.stdout, /4 transcripts read/);
+ assert.match(text.stdout, /slow news day {2}2 time\(s\) {2}2020–2022/);
+ assert.match(text.stdout, /searched as \/\\bnobody\[\\s,\.\\-\]\+asked\(\?:s\|es\)\?\\b\/ \(words\)/);
+ const json = JSON.parse((await run(process.execPath, [CLI, "phrases", "slow news", "--channels", "yt", "--prefer", "rum", "--json"], { env })).stdout);
+ assert.equal(json.rows[0].instances, 3);
+ assert.equal(json.rows[0].preferred, 2);
+ const bad = await run(process.execPath, [CLI, "phrases", "slow (news", "--channels", "yt", "--regex"], { env }).catch((e) => e);
+ assert.equal(bad.code, 1);
+ assert.match(bad.stderr, /not a regular expression/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ rmSync(cache, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/phrase-finder/cli.mjs b/umtool/lib/phrase-finder/cli.mjs
@@ -0,0 +1,103 @@
+// `umtool phrases` (release 34): the phrase finder from a terminal, and the
+// page's job. Prints, per phrase, how many times it was said once folded, by
+// year, from the preferred channel or another, and how many need an ear.
+//
+// umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE]
+// [--words | --regex] [--samples N] [--no-cache] [--json | --full]
+// umtool phrases --spec FILE --out FILE [--progress]
+//
+// A phrase is plain words (a tolerant pattern: any spaces, commas or hyphens
+// between the words, an optional plural) unless it holds a regular
+// expression's characters; --words or --regex says which for all of them.
+// --json prints the summaries, --full every instance. The second form is what
+// the page's job runs: the settings in a JSON file, the whole answer written to
+// --out, and with --progress one JSON line of progress per few hundred videos.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { runPhraseScan } from "./scan.mjs";
+import { summarisePhrase } from "./summary.mjs";
+
+function parse(args) {
+ const o = { phrases: [], channels: [], prefer: null, exclude: null, mode: "auto", samples: 10, cache: true, json: false, full: false, spec: null, out: null, progress: false };
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ const v = () => {
+ const x = args[++i];
+ if (x === undefined) throw new Error(`${a} needs a value`);
+ return x;
+ };
+ if (a === "--channels") o.channels.push(...v().split(","));
+ else if (a === "--prefer") o.prefer = v();
+ else if (a === "--exclude") o.exclude = v();
+ else if (a === "--words") o.mode = "words";
+ else if (a === "--regex") o.mode = "regex";
+ else if (a === "--samples") o.samples = Math.max(0, Number(v()) || 0);
+ else if (a === "--no-cache") o.cache = false;
+ else if (a === "--json") o.json = true;
+ else if (a === "--full") o.full = true;
+ else if (a === "--spec") o.spec = v();
+ else if (a === "--out") o.out = v();
+ else if (a === "--progress") o.progress = true;
+ else if (a === "--help" || a === "-h") o.help = true;
+ else if (a.startsWith("--")) throw new Error(`unknown option ${a}`);
+ else o.phrases.push(a);
+ }
+ return o;
+}
+
+const USAGE = `umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE]
+ [--words | --regex] [--samples N] [--no-cache] [--json | --full]
+umtool phrases --spec FILE --out FILE [--progress]`;
+
+/** @param {string[]} args @returns {Promise<number>} the exit code */
+export async function phrasesCommand(args) {
+ let o;
+ try {
+ o = parse(args);
+ } catch (e) {
+ console.error(`${e.message}\n\n${USAGE}`);
+ return 2;
+ }
+ if (o.help) {
+ console.log(USAGE);
+ return 0;
+ }
+ try {
+ const spec = o.spec
+ ? JSON.parse(await readFile(o.spec, "utf8"))
+ : { rows: o.phrases.map((text, k) => ({ id: `p${k + 1}`, text, mode: o.mode })), channels: o.channels, prefer: o.prefer, exclude: o.exclude };
+ const onProgress = o.progress ? (p) => console.log(JSON.stringify({ progress: p })) : undefined;
+ const answer = await runPhraseScan(spec, { ...(o.cache ? {} : { cacheDir: null }), onProgress });
+ if (o.out) {
+ await mkdir(path.dirname(o.out), { recursive: true });
+ const tmp = `${o.out}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify(answer), "utf8");
+ await rename(tmp, o.out);
+ if (o.progress) console.log(JSON.stringify({ done: true, out: o.out, seconds: answer.seconds }));
+ return 0;
+ }
+ if (o.full) {
+ console.log(JSON.stringify(answer, null, 1));
+ return 0;
+ }
+ const rows = answer.rows.map((r) => ({ id: r.id, text: r.text, searched: r.source, as: r.used, ...summarisePhrase(r.result, { prefer: answer.spec.prefer, samples: o.samples }) }));
+ if (o.json) {
+ console.log(JSON.stringify({ scanned: answer.scanned, seconds: answer.seconds, spec: answer.spec, rows }, null, 2));
+ return 0;
+ }
+ console.log(`${answer.scanned} transcripts read in ${answer.seconds} s`);
+ for (const r of rows) {
+ const span = r.first ? `${String(r.first).slice(0, 4)}–${String(r.last).slice(0, 4)}` : "";
+ const split = answer.spec.prefer ? `${answer.spec.prefer} ${r.preferred} · other ${r.other}` : `rumble ${r.rumble} · other ${r.notRumble}`;
+ console.log("");
+ console.log(`${r.text} ${r.instances} time(s) ${span} ${r.spark}`);
+ console.log(` ${split} · speaker changes ${r.speakerChecks}${r.dropped ? ` · excluded ${r.dropped}` : ""}`);
+ console.log(` searched as /${r.searched}/ (${r.as})`);
+ for (const s of r.samples) console.log(` ${s.date ?? "?"} ${s.slug}/${s.videoId} @ ${Math.round(s.start)}s ${s.context.slice(0, 100)}`);
+ }
+ return 0;
+ } catch (e) {
+ console.error(e instanceof Error ? e.message : String(e));
+ return 1;
+ }
+}
diff --git a/umtool/lib/phrase-finder/scan.d.mts b/umtool/lib/phrase-finder/scan.d.mts
@@ -0,0 +1,10 @@
+import type { PhraseScanSpec } from "./types";
+export const MAX_PHRASES: number;
+export const CHANNEL_RE: RegExp;
+export const MODES: string[];
+export function phraseTextCacheDir(): string;
+export function checkSpec(spec: unknown): PhraseScanSpec;
+export function runPhraseScan(
+ spec: unknown,
+ opts?: { channelsDir?: string; cacheDir?: string | null; onProgress?: (p: unknown) => void },
+): Promise<{ version: number; spec: PhraseScanSpec; startedAt: string; seconds: number; scanned: number; rows: (PhraseScanSpec["rows"][number] & { result: unknown })[] }>;
diff --git a/umtool/lib/phrase-finder/scan.mjs b/umtool/lib/phrase-finder/scan.mjs
@@ -0,0 +1,95 @@
+// The phrase finder's scan (release 34): several phrases over a set of
+// channels in ONE pass (phraseScanMany), each typed as plain words or a
+// regular expression (phraseSource.mjs), through the cue-text cache under
+// umtool's CACHE_DIR. The page runs it as a job (`umtool phrases --spec … --out
+// …`, lib/phrase-finder/jobs.ts) and `umtool phrases` runs it in a terminal;
+// both get this.
+//
+// Read-only over the channels directory. Plain ESM, no server.
+import { phraseScanMany, phraseSourceOf } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs";
+import { CHANNELS_DIR, cacheFile } from "../paths.mjs";
+
+/** The most phrases one scan compares. */
+export const MAX_PHRASES = 30;
+/** A channel directory's name: no separators, no dot first. */
+export const CHANNEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+export const MODES = ["auto", "words", "regex"];
+
+/** Where the joined cue text is cached (cueTextCache.mjs), under CACHE_DIR. */
+export const phraseTextCacheDir = () => cacheFile("phrase-text");
+
+/**
+ * A scan's settings, checked: `{rows: [{id, text, mode, label?}], channels,
+ * prefer, exclude}` → the same with each row's `source` (what is searched)
+ * and `used` (`words` | `regex`); `label` names a phrase given as an
+ * expression (a suggestion's "nobody asked"). Throws a sentence naming what is wrong.
+ */
+export function checkSpec(spec) {
+ const rowsIn = Array.isArray(spec?.rows) ? spec.rows : [];
+ const rows = [];
+ const seen = new Set();
+ for (const [k, r] of rowsIn.entries()) {
+ const text = String(r?.text ?? "").trim();
+ if (!text) continue;
+ const mode = MODES.includes(r?.mode) ? r.mode : "auto";
+ let id = String(r?.id ?? `p${k + 1}`).trim() || `p${k + 1}`;
+ if (!/^[A-Za-z0-9_-]{1,40}$/.test(id) || seen.has(id)) id = `p${k + 1}`;
+ if (seen.has(id)) throw new Error(`two phrases share the id "${id}"`);
+ seen.add(id);
+ let src;
+ try {
+ src = phraseSourceOf(text, mode);
+ } catch (e) {
+ throw new Error(`"${text}": ${e instanceof Error ? e.message : String(e)}`);
+ }
+ const label = String(r?.label ?? "").trim().slice(0, 80);
+ rows.push({ id, text, ...(label ? { label } : {}), mode, source: src.source, used: src.mode });
+ }
+ if (!rows.length) throw new Error("type a phrase to search for");
+ if (rows.length > MAX_PHRASES) throw new Error(`at most ${MAX_PHRASES} phrases in one search`);
+ const list = (v) => (Array.isArray(v) ? v : String(v ?? "").split(",")).map((c) => String(c).trim()).filter(Boolean);
+ const channels = [...new Set(list(spec?.channels))];
+ const prefer = String(spec?.prefer ?? "").trim() || null;
+ for (const c of [...channels, ...(prefer ? [prefer] : [])]) if (!CHANNEL_RE.test(c)) throw new Error(`"${c}" is not a channel`);
+ if (!channels.length && !prefer) throw new Error("pick at least one channel");
+ const exclude = String(spec?.exclude ?? "").trim() || null;
+ if (exclude) {
+ try {
+ new RegExp(exclude, "i");
+ } catch (e) {
+ throw new Error(`exclude is not a regular expression: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ }
+ return { rows, channels, prefer, exclude };
+}
+
+/**
+ * Run a checked spec: `{version, spec, startedAt, seconds, scanned, rows:
+ * [{id, text, mode, used, source, result}]}`, `result` being phraseScan's
+ * answer for that phrase alone. `cacheDir: null` reads every cue file.
+ */
+export async function runPhraseScan(spec, { channelsDir = CHANNELS_DIR, cacheDir = phraseTextCacheDir(), onProgress } = {}) {
+ const s = checkSpec(spec);
+ const t0 = Date.now();
+ const results = await phraseScanMany({
+ channelsDir,
+ channels: s.channels,
+ prefer: s.prefer,
+ exclude: s.exclude,
+ phrases: s.rows.map((r) => ({ id: r.id, phrase: r.source })),
+ cacheDir,
+ onProgress,
+ });
+ const byId = new Map(results.map((r) => [r.id, r]));
+ return {
+ version: 1,
+ spec: s,
+ startedAt: new Date(t0).toISOString(),
+ seconds: Math.round((Date.now() - t0) / 100) / 10,
+ scanned: results[0]?.scanned ?? 0,
+ rows: s.rows.map((r) => {
+ const { id: _id, phrase: _phrase, ...result } = byId.get(r.id);
+ return { ...r, result };
+ }),
+ };
+}
diff --git a/umtool/lib/phrase-finder/server.ts b/umtool/lib/phrase-finder/server.ts
@@ -0,0 +1,337 @@
+import { spawn } from "node:child_process";
+import { randomBytes } from "node:crypto";
+import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { CHANNELS_DIR, REPORTS_ROOT, cacheFile } from "@/lib/paths";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { CHANNEL_RE, checkSpec } from "./scan.mjs";
+import { summarisePhrase } from "./summary.mjs";
+import type { PhraseChannel, PhraseFinderState, PhraseScanRowView, PhraseScanSpec, PhraseScanView, PhraseSuggestion } from "./types";
+
+// ---------------------------------------------------------------------------
+// THE PHRASE FINDER's server half (release 34; the page is /tools/phrases).
+//
+// a scan runs as a CHILD PROCESS, `umtool phrases --spec … --out …
+// --progress` (lib/phrase-finder/cli.mjs), never inside a request:
+// over a big corpus it reads tens of thousands of cue files, and
+// a request that waited would time out, and a server that read
+// them itself would hold their memory. Its progress lines are
+// read off its stdout; its answer is a file. One scan at a time.
+// the store CACHE_DIR/phrase-finder/: scans/<id>.json (the whole answer,
+// what Create montage seeds a project from), specs/<id>.json, and
+// last.json (the channels, prefer, exclude and phrases of the last
+// search, the page's defaults). A cache: delete it at any time.
+// suggestions candidates.json files of a catchphrase report: the paths in
+// UMTOOL_PHRASE_CANDIDATES (":"-separated), else every
+// <REPORTS_ROOT>/<dir>/candidates.json with the report's shape
+// (`{scanned: [{key, regex, instances, …}]}`).
+//
+// SERVER ONLY. Every path here carries the Turbopack opt-out (lib/paths.mjs,
+// findRepoRoot): CHANNELS_DIR and the cache are the user's, not the app's.
+// ---------------------------------------------------------------------------
+
+const STORE = () => cacheFile("phrase-finder");
+// A video directory's name: a YouTube id may start with a dash or an underscore; never a dot.
+const VIDEO_RE = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
+const SCAN_ID_RE = /^ps-\d{14}-[0-9a-f]{6}$/;
+const scanFile = (id: string) => path.join(/* turbopackIgnore: true */ STORE(), "scans", `${id}.json`);
+const specFile = (id: string) => path.join(/* turbopackIgnore: true */ STORE(), "specs", `${id}.json`);
+const LAST = () => path.join(/* turbopackIgnore: true */ STORE(), "last.json");
+/** Finished scans kept on disk; older ones are removed when a scan starts. */
+const KEEP_SCANS = 20;
+
+export const isScanId = (id: unknown): id is string => typeof id === "string" && SCAN_ID_RE.test(id);
+
+type Job = {
+ id: string;
+ state: "running" | "done" | "failed" | "cancelled";
+ startedAt: number;
+ endedAt: number | null;
+ spec: PhraseScanSpec;
+ progress: PhraseScanView["progress"];
+ error: string | null;
+ pid: number | null;
+ log: string[];
+};
+type Registry = { jobs: Map<string, Job> };
+const g = globalThis as typeof globalThis & { __umtoolPhraseScans?: Registry };
+const reg: Registry = (g.__umtoolPhraseScans ??= { jobs: new Map() });
+
+const runningScan = () => [...reg.jobs.values()].find((j) => j.state === "running") ?? null;
+
+async function writeAtomic(file: string, text: string) {
+ await mkdir(path.dirname(/* turbopackIgnore: true */ file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, text, "utf8");
+ await rename(/* turbopackIgnore: true */ tmp, file);
+}
+
+async function readJsonFile<T>(file: string): Promise<T | null> {
+ try {
+ return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")) as T;
+ } catch {
+ return null;
+ }
+}
+
+function newScanId(): string {
+ const d = new Date();
+ const p = (n: number, w = 2) => String(n).padStart(w, "0");
+ const stamp = `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`;
+ return `ps-${stamp}-${randomBytes(3).toString("hex")}`;
+}
+
+async function pruneScans() {
+ const dir = path.join(/* turbopackIgnore: true */ STORE(), "scans");
+ const names = (await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[])).filter((n) => /^ps-.*\.json$/.test(n)).sort();
+ for (const n of names.slice(0, Math.max(0, names.length - KEEP_SCANS))) {
+ await rm(path.join(/* turbopackIgnore: true */ dir, n), { force: true });
+ await rm(path.join(/* turbopackIgnore: true */ STORE(), "specs", n), { force: true });
+ }
+}
+
+/**
+ * Start a scan of `spec` (checked first: a bad phrase is refused here, in the
+ * request, with its sentence). Refuses while another scan runs.
+ */
+export async function startPhraseScan(raw: unknown): Promise<{ id: string }> {
+ const spec = checkSpec(raw) as PhraseScanSpec;
+ const running = runningScan();
+ if (running) throw Object.assign(new Error("a search is already running"), { status: 409, running: running.id });
+ await pruneScans();
+ const id = newScanId();
+ await writeAtomic(specFile(id), JSON.stringify(spec));
+ await mkdir(path.dirname(/* turbopackIgnore: true */ scanFile(id)), { recursive: true });
+ await writeAtomic(LAST(), JSON.stringify({ channels: spec.channels, prefer: spec.prefer, exclude: spec.exclude, rows: spec.rows.map((r) => ({ text: r.text, mode: r.mode, ...(r.label ? { label: r.label } : {}) })) }));
+ const job: Job = { id, state: "running", startedAt: Date.now(), endedAt: null, spec, progress: null, error: null, pid: null, log: [] };
+ reg.jobs.set(id, job);
+
+ const cli = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+ const child = spawn(process.execPath, [cli, "phrases", "--spec", specFile(id), "--out", scanFile(id), "--progress"], {
+ cwd: UMTOOL_DIR,
+ env: process.env,
+ stdio: ["ignore", "pipe", "pipe"],
+ detached: true,
+ });
+ job.pid = child.pid ?? null;
+ let buf = "";
+ child.stdout.on("data", (b: Buffer) => {
+ buf += b.toString();
+ let nl;
+ while ((nl = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, nl).trim();
+ buf = buf.slice(nl + 1);
+ if (!line) continue;
+ try {
+ const m = JSON.parse(line);
+ if (m?.progress) job.progress = m.progress;
+ } catch {
+ job.log.push(line);
+ }
+ }
+ });
+ child.stderr.on("data", (b: Buffer) => {
+ job.log.push(...b.toString().split("\n").filter((l) => l.trim()));
+ if (job.log.length > 50) job.log.splice(0, job.log.length - 50);
+ });
+ const end = (state: Job["state"], error: string | null) => {
+ if (job.state !== "running") return;
+ job.state = state;
+ job.error = error;
+ job.endedAt = Date.now();
+ };
+ child.on("error", (e) => end("failed", e.message));
+ child.on("close", (code) => {
+ if (job.state !== "running") return;
+ if (code === 0) end("done", null);
+ else end("failed", job.log.at(-1) ?? `the search exited ${code}`);
+ });
+ return { id };
+}
+
+/** Stop a running scan (its whole process group). */
+export function cancelPhraseScan(id: string): boolean {
+ const job = reg.jobs.get(id);
+ if (!job || job.state !== "running") return false;
+ job.state = "cancelled";
+ job.endedAt = Date.now();
+ if (job.pid) {
+ try {
+ process.kill(-job.pid, "SIGTERM");
+ } catch {
+ /* gone */
+ }
+ }
+ return true;
+}
+
+type ScanAnswer = {
+ version: number;
+ spec: PhraseScanSpec;
+ startedAt: string;
+ seconds: number;
+ scanned: number;
+ rows: (PhraseScanSpec["rows"][number] & { result: { instances: unknown[]; hits: unknown[]; dropped: unknown[]; scanned: number } })[];
+};
+
+// One answer file is a few MB; the page polls the view, so the last few are kept parsed.
+const answers = new Map<string, { at: number; answer: ScanAnswer }>();
+async function readAnswer(id: string): Promise<ScanAnswer | null> {
+ if (!isScanId(id)) return null;
+ const st = await stat(/* turbopackIgnore: true */ scanFile(id)).catch(() => null);
+ if (!st) return null;
+ const kept = answers.get(id);
+ if (kept && kept.at === st.mtimeMs) return kept.answer;
+ const answer = await readJsonFile<ScanAnswer>(scanFile(id));
+ if (!answer) return null;
+ answers.set(id, { at: st.mtimeMs, answer });
+ while (answers.size > 4) answers.delete(answers.keys().next().value as string);
+ return answer;
+}
+
+/** What the page shows of a scan: its state and progress, and once done each phrase's numbers. */
+export async function phraseScanView(id: string): Promise<PhraseScanView | null> {
+ if (!isScanId(id)) return null;
+ const job = reg.jobs.get(id) ?? null;
+ const spec = job?.spec ?? (await readJsonFile<PhraseScanSpec>(specFile(id)));
+ if (!spec) return null;
+ const answer = !job || job.state === "done" ? await readAnswer(id) : null;
+ const state = job?.state ?? (answer ? "done" : "failed");
+ const rows: PhraseScanRowView[] | null = answer
+ ? answer.rows.map((r) => ({
+ id: r.id,
+ text: r.text,
+ ...(r.label ? { label: r.label } : {}),
+ mode: r.mode,
+ used: r.used,
+ source: r.source,
+ summary: summarisePhrase(r.result, { prefer: answer.spec.prefer }) as PhraseScanRowView["summary"],
+ }))
+ : null;
+ return {
+ id,
+ state,
+ spec,
+ startedAt: job ? new Date(job.startedAt).toISOString() : (answer?.startedAt ?? null),
+ seconds: answer?.seconds ?? (job ? Math.round(((job.endedAt ?? Date.now()) - job.startedAt) / 100) / 10 : null),
+ progress: job?.progress ?? null,
+ error: job?.error ?? (answer ? null : "this search's answer is gone (the cache was cleared): search again"),
+ scanned: answer?.scanned ?? null,
+ rows,
+ };
+}
+
+/**
+ * One phrase of a finished scan, whole — for Create montage. Refuses a scan
+ * whose settings are not the ones given, so a project is seeded only from
+ * the search it says it is.
+ */
+export async function scanRowFor(id: string, row: string, want: { phrase: string; channels: string[]; prefer: string | null; exclude: string | null }) {
+ const answer = await readAnswer(id);
+ if (!answer) throw new Error("that search is gone: search again");
+ const r = answer.rows.find((x) => x.id === row);
+ if (!r) throw new Error(`that search has no phrase "${row}"`);
+ const same = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
+ if (r.source !== want.phrase || !same(answer.spec.channels, want.channels) || (answer.spec.prefer ?? null) !== (want.prefer ?? null) || (answer.spec.exclude ?? null) !== (want.exclude ?? null)) {
+ throw new Error("the search does not match these settings: search again");
+ }
+ return r.result;
+}
+
+// ── the page's defaults ─────────────────────────────────────────────────────
+
+let channelsCache: { at: number; list: PhraseChannel[] } | null = null;
+
+/** The channels with transcripts (a social channel has none), by name. Cached a minute. */
+export async function phraseChannels(): Promise<PhraseChannel[]> {
+ if (channelsCache && Date.now() - channelsCache.at < 60_000) return channelsCache.list;
+ const out: PhraseChannel[] = [];
+ const dirs = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR, { withFileTypes: true }).catch(() => []);
+ for (const d of dirs) {
+ if (!d.isDirectory() || !CHANNEL_RE.test(d.name)) continue;
+ const dir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, d.name);
+ const cfg = await readJsonFile<{ name?: string; platform?: string; sourceKind?: string }>(path.join(/* turbopackIgnore: true */ dir, "config.json"));
+ if (cfg?.sourceKind === "social") continue;
+ const videos = (await readdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "data")).catch(() => [] as string[])).length;
+ if (!videos) continue;
+ out.push({ slug: d.name, name: cfg?.name || d.name, platform: cfg?.platform ?? null, videos });
+ }
+ out.sort((a, b) => a.name.localeCompare(b.name));
+ channelsCache = { at: Date.now(), list: out };
+ return out;
+}
+
+/** The suggestions: each candidates file's phrases, as the report ranked them. */
+export async function phraseSuggestions(): Promise<PhraseSuggestion[]> {
+ const env = (process.env.UMTOOL_PHRASE_CANDIDATES ?? "").split(":").map((s) => s.trim()).filter(Boolean);
+ let files = env;
+ if (!files.length) {
+ const dirs = await readdir(/* turbopackIgnore: true */ REPORTS_ROOT, { withFileTypes: true }).catch(() => []);
+ files = dirs.filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => path.join(/* turbopackIgnore: true */ REPORTS_ROOT, d.name, "candidates.json"));
+ }
+ const out: PhraseSuggestion[] = [];
+ for (const f of files.sort()) {
+ const doc = await readJsonFile<{ scanned?: { key?: string; regex?: string; instances?: number; perYear?: Record<string, number>; spark?: string }[] }>(f);
+ if (!Array.isArray(doc?.scanned)) continue;
+ const from = path.basename(path.dirname(/* turbopackIgnore: true */ f));
+ for (const c of doc.scanned) {
+ if (typeof c?.regex !== "string" || !c.regex.trim()) continue;
+ try {
+ new RegExp(c.regex, "i");
+ } catch {
+ continue;
+ }
+ out.push({ key: String(c.key ?? c.regex), regex: c.regex, instances: Number(c.instances) || null, spark: typeof c.spark === "string" ? c.spark : null, from });
+ }
+ }
+ return out;
+}
+
+/** Everything the page opens with. */
+export async function phraseFinderState(): Promise<PhraseFinderState> {
+ const [channels, suggestions, last] = await Promise.all([phraseChannels(), phraseSuggestions(), readJsonFile<PhraseFinderState["last"]>(LAST())]);
+ const running = runningScan();
+ const dir = path.join(/* turbopackIgnore: true */ STORE(), "scans");
+ const recent = (await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[]))
+ .filter((n) => /^ps-.*\.json$/.test(n))
+ .map((n) => n.replace(/\.json$/, ""))
+ .sort()
+ .reverse()
+ .slice(0, 8);
+ const known = new Set(channels.map((c) => c.slug));
+ return {
+ channels,
+ suggestions,
+ last: last
+ ? {
+ channels: (last.channels ?? []).filter((c) => known.has(c)),
+ prefer: last.prefer && known.has(last.prefer) ? last.prefer : null,
+ exclude: last.exclude ?? null,
+ rows: Array.isArray(last.rows) ? last.rows.slice(0, 30) : [],
+ }
+ : null,
+ running: running?.id ?? null,
+ recent,
+ };
+}
+
+// ── the transcript position ─────────────────────────────────────────────────
+
+/** The cues around a second of a video (`span` either side), for reading a hit where it was said. */
+export async function transcriptAround(channel: string, video: string, at: number, span = 5) {
+ if (!CHANNEL_RE.test(channel) || !VIDEO_RE.test(video)) throw new Error("not a video");
+ const doc = await readJsonFile<{ title?: string; uploadDate?: string; cues?: { start: number; end?: number; text?: string }[] }>(
+ path.join(/* turbopackIgnore: true */ CHANNELS_DIR, channel, "data", video, "transcript.cues.json"),
+ );
+ if (!doc || !Array.isArray(doc.cues)) return null;
+ const cues = doc.cues.filter((c) => c && Number.isFinite(Number(c.start)));
+ let k = cues.findIndex((c) => Number(c.start) >= at - 0.01);
+ if (k < 0) k = cues.length - 1;
+ const lo = Math.max(0, k - span);
+ return {
+ title: doc.title ?? null,
+ date: doc.uploadDate ?? null,
+ at,
+ cues: cues.slice(lo, Math.min(cues.length, k + span + 1)).map((c) => ({ start: Number(c.start), end: Number(c.end ?? c.start), text: String(c.text ?? ""), lit: Number(c.start) === Number(cues[k]?.start) })),
+ };
+}
diff --git a/umtool/lib/phrase-finder/summary.d.mts b/umtool/lib/phrase-finder/summary.d.mts
@@ -0,0 +1,7 @@
+import type { PhraseSummary } from "./types";
+export function yearOf(date: unknown): string | null;
+export function byYear(instances: { date?: string | null }[]): Record<string, number>;
+export function sparkline(years: Record<string, number>): string;
+export function spread<T>(list: T[], n: number): T[];
+export function summarisePhrase(result: unknown, opts?: { prefer?: string | null; samples?: number }): PhraseSummary;
+export function montageSlug(text: string): string;
diff --git a/umtool/lib/phrase-finder/summary.mjs b/umtool/lib/phrase-finder/summary.mjs
@@ -0,0 +1,97 @@
+// The phrase finder's numbers (release 34), from one phrase's scan
+// (common/lib/montage/phraseScan.mjs: phraseScan or phraseScanMany): how many
+// times it was said once folded, by year, from the preferred (Rumble) copy or
+// another channel, how many need an ear for who says it, and a handful of
+// contexts spread over the years to read and play.
+//
+// Pure, so the page, its API and `umtool phrases` print the same numbers.
+
+/** `YYYYMMDD…` → `YYYY`, or null. */
+export const yearOf = (date) => (/^(\d{4})/.exec(String(date ?? ""))?.[1] ?? null);
+
+/** `{year: count}` over the instances, in year order, every year between the first and the last present (0 for a gap). */
+export function byYear(instances) {
+ const n = new Map();
+ for (const i of instances) {
+ const y = yearOf(i.date);
+ if (y) n.set(y, (n.get(y) ?? 0) + 1);
+ }
+ const ys = [...n.keys()].map(Number).sort((a, b) => a - b);
+ const out = {};
+ if (!ys.length) return out;
+ for (let y = ys[0]; y <= ys[ys.length - 1]; y++) out[String(y)] = n.get(String(y)) ?? 0;
+ return out;
+}
+
+const BARS = " ▁▂▃▄▅▆▇█";
+/** A one-line bar row of `byYear`: one character per year. */
+export function sparkline(years) {
+ const vals = Object.values(years);
+ const max = Math.max(0, ...vals);
+ if (!max) return "";
+ return vals.map((v) => (v ? BARS[Math.max(1, Math.round((v / max) * 8))] : BARS[0])).join("");
+}
+
+/** Pick `n` of `list` spread evenly from first to last (all of them when there are fewer). */
+export function spread(list, n) {
+ if (list.length <= n) return list.slice();
+ if (n <= 1) return list.slice(0, Math.max(0, n));
+ const out = [];
+ for (let k = 0; k < n; k++) out.push(list[Math.round((k * (list.length - 1)) / (n - 1))]);
+ return out;
+}
+
+/**
+ * One phrase's summary. `prefer` is the preferred channel (the Rumble copy):
+ * an instance there counts as `preferred`, every other as `other`; `rumble`
+ * counts by platform, whatever the channel. `samples` contexts (10) are spread
+ * over the chronological instances.
+ */
+export function summarisePhrase(result, { prefer = null, samples = 10 } = {}) {
+ const instances = Array.isArray(result?.instances) ? result.instances : [];
+ const bySlug = {};
+ for (const i of instances) bySlug[i.slug] = (bySlug[i.slug] ?? 0) + 1;
+ const years = byYear(instances);
+ return {
+ instances: instances.length,
+ hits: Array.isArray(result?.hits) ? result.hits.length : 0,
+ dropped: Array.isArray(result?.dropped) ? result.dropped.length : 0,
+ scanned: Number(result?.scanned) || 0,
+ years,
+ spark: sparkline(years),
+ rumble: instances.filter((i) => i.platform === "rumble").length,
+ notRumble: instances.filter((i) => i.platform !== "rumble").length,
+ preferred: prefer ? instances.filter((i) => i.slug === prefer).length : 0,
+ other: prefer ? instances.filter((i) => i.slug !== prefer).length : instances.length,
+ placed: instances.filter((i) => i.via).length,
+ speakerChecks: instances.filter((i) => i.speakerCheck).length,
+ bySlug,
+ first: instances[0]?.date ?? null,
+ last: instances[instances.length - 1]?.date ?? null,
+ samples: spread(instances, samples).map((i) => ({
+ slug: i.slug,
+ videoId: i.videoId,
+ date: i.date ?? null,
+ title: i.title ?? null,
+ platform: i.platform ?? null,
+ start: i.start,
+ end: i.end,
+ match: i.match,
+ context: String(i.context ?? "").slice(0, 300),
+ speakerCheck: Boolean(i.speakerCheck),
+ ...(i.via ? { via: { slug: i.via.slug, videoId: i.via.videoId } } : {}),
+ })),
+ };
+}
+
+/** A phrase as a project slug: `slow news day` → `slow-news-day-montage`; a regex keeps its letters. */
+export function montageSlug(text) {
+ const base = String(text ?? "")
+ .toLowerCase()
+ .replace(/\\[bswd]/g, " ")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 48)
+ .replace(/-+$/g, "");
+ return `${base || "phrase"}-montage`;
+}
diff --git a/umtool/lib/phrase-finder/types.ts b/umtool/lib/phrase-finder/types.ts
@@ -0,0 +1,79 @@
+// The phrase finder's shapes (release 34), shared by its server
+// (lib/phrase-finder/server.ts, the /api/phrase-finder routes) and the page
+// (components/tools/PhraseFinder.tsx). Types only.
+
+export type PhraseMode = "auto" | "words" | "regex";
+
+/** A checked search (lib/phrase-finder/scan.mjs checkSpec). */
+export type PhraseScanSpec = {
+ rows: { id: string; text: string; label?: string; mode: PhraseMode; source: string; used: "words" | "regex" }[];
+ channels: string[];
+ prefer: string | null;
+ exclude: string | null;
+};
+
+export type PhraseSample = {
+ slug: string;
+ videoId: string;
+ date: string | null;
+ title: string | null;
+ platform: string | null;
+ start: number;
+ end: number;
+ match: string;
+ context: string;
+ speakerCheck: boolean;
+ via?: { slug: string; videoId: string };
+};
+
+/** One phrase's numbers (lib/phrase-finder/summary.mjs summarisePhrase). */
+export type PhraseSummary = {
+ instances: number;
+ hits: number;
+ dropped: number;
+ scanned: number;
+ years: Record<string, number>;
+ spark: string;
+ rumble: number;
+ notRumble: number;
+ preferred: number;
+ other: number;
+ placed: number;
+ speakerChecks: number;
+ bySlug: Record<string, number>;
+ first: string | null;
+ last: string | null;
+ samples: PhraseSample[];
+};
+
+export type PhraseScanRowView = { id: string; text: string; label?: string; mode: PhraseMode; used: "words" | "regex"; source: string; summary: PhraseSummary };
+
+export type PhraseScanView = {
+ id: string;
+ state: "running" | "done" | "failed" | "cancelled";
+ spec: PhraseScanSpec;
+ startedAt: string | null;
+ seconds: number | null;
+ progress: { done: number; total: number; channel: string; channelsDone: number; channels: number } | null;
+ error: string | null;
+ scanned: number | null;
+ rows: PhraseScanRowView[] | null;
+};
+
+export type PhraseChannel = { slug: string; name: string; platform: string | null; videos: number };
+export type PhraseSuggestion = { key: string; regex: string; instances: number | null; spark: string | null; from: string };
+
+export type PhraseFinderState = {
+ channels: PhraseChannel[];
+ suggestions: PhraseSuggestion[];
+ last: { channels: string[]; prefer: string | null; exclude: string | null; rows: { text: string; mode: PhraseMode; label?: string }[] } | null;
+ running: string | null;
+ recent: string[];
+};
+
+export type TranscriptAround = {
+ title: string | null;
+ date: string | null;
+ at: number;
+ cues: { start: number; end: number; text: string; lit: boolean }[];
+};
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -11,6 +11,8 @@ import { instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/monta
import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs";
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
+// A channel's directory name: mixed case is a channel too (HasanAbiVODs3); no separators, no dot first.
+export const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
export const SEEDS = ["chapters", "frames", "phrase"];
/**
@@ -222,11 +224,14 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po
* 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`.
+ * answer is written beside the manifest as `phrase-scan.json`. `scan` (release
+ * 34) is that answer already made — the phrase finder's search with these
+ * same settings (phraseScanMany answers each phrase as phraseScan does) — so a
+ * project is seeded from what the page showed without reading the corpus again.
*
- * @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
+ * @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 }} 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 }) {
+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 }) {
if (!SLUG_RE.test(String(slug ?? ""))) {
throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
}
@@ -255,8 +260,9 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
}
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) {
+ for (const c of list) if (!CHANNEL_SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`);
+ if (given && !(Array.isArray(given.instances) && Array.isArray(given.hits) && Array.isArray(given.dropped))) throw new Error("a phrase scan is { instances, hits, dropped, scanned }");
+ } else if (phrase || channels?.length || prefer || exclude || given) {
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");
@@ -323,7 +329,7 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
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 });
+ const scan = given ?? (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;
// The window already carries its margin (2.5 s each side), and the editor
diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts
@@ -4,6 +4,7 @@ import { ScaffoldError, scaffoldSong } from "./scaffold-song";
import { scaffoldReportVideo } from "./scaffold.mjs";
import { kindById } from "./kinds.mjs";
import { invalidateProjects } from "../projects";
+import { scanRowFor } from "../phrase-finder/server";
export { ScaffoldError };
@@ -24,6 +25,9 @@ export type NewProjectBody = {
channels?: string[] | string | null;
prefer?: string | null;
exclude?: string | null;
+ // The phrase finder's search these settings came from (release 34): the
+ // project is seeded from its answer, not from a second read of the corpus.
+ scan?: { id?: string; row?: string } | null;
};
/**
@@ -38,6 +42,22 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
const slug = String(body.slug ?? "").trim().toLowerCase();
let result: { href: string; [k: string]: unknown };
+ const channelList = (Array.isArray(body.channels) ? body.channels : String(body.channels ?? "").split(","))
+ .map((c) => String(c).trim())
+ .filter(Boolean);
+ let scan: Awaited<ReturnType<typeof scanRowFor>> | null = null;
+ if (body.seed === "phrase" && body.scan?.id && body.scan.row) {
+ try {
+ scan = await scanRowFor(String(body.scan.id), String(body.scan.row), {
+ phrase: String(body.phrase ?? ""),
+ channels: channelList,
+ prefer: body.prefer || null,
+ exclude: body.exclude || null,
+ });
+ } catch (e) {
+ throw new ScaffoldError(e instanceof Error ? e.message : String(e), 400);
+ }
+ }
if (kind === SONG_KIND) {
result = await scaffoldSong({ slug, title: body.title });
} else {
@@ -53,11 +73,10 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
...(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),
+ channels: channelList,
prefer: body.prefer || null,
exclude: body.exclude || null,
+ ...(scan ? { scan } : {}),
}
: {}),
...(body.seed === "frames" && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}),
diff --git a/umtool/lib/scaffold-phrase.test.mjs b/umtool/lib/scaffold-phrase.test.mjs
@@ -64,3 +64,26 @@ test("--seed phrase refuses what it cannot scan", async () => {
await rm(tmp, { recursive: true, force: true });
}
});
+
+test("--seed phrase with a finished scan (release 34, the phrase finder): the same project, the corpus not read again", 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", "y0", { uploadDate: "20190502", duration: 600, platform: "youtube", cues: [{ start: 4, end: 6, text: "a slow" }, { start: 6, end: 8, text: "news week indeed" }] });
+ const { phraseScanMany } = await import("yt-dlp-transcript-common/lib/montage/phraseScan.mjs");
+ const phrase = String.raw`slow[\s,]+news`;
+ const [{ id: _id, phrase: _p, ...scan }] = await phraseScanMany({ channelsDir, channels: ["Synth-YT"], prefer: "synth-rumble", phrases: [{ id: "a", phrase }] });
+ const args = { root: path.join(tmp, "reports"), seed: "phrase", phrase, channels: ["Synth-YT"], prefer: "synth-rumble" };
+ const fresh = await scaffoldReportVideo({ ...args, slug: "fresh", channelsDir });
+ // An empty channels dir: only the given scan can seed it.
+ const given = await scaffoldReportVideo({ ...args, slug: "given", channelsDir: path.join(tmp, "nothing"), scan });
+ assert.equal(given.seeded, 2);
+ const read = async (dir, f) => (await readFile(path.join(dir, f), "utf8")).replaceAll("given", "fresh");
+ for (const f of ["video.manifest.json", "phrase-scan.json", "README.md"]) assert.equal(await read(given.dir, f), await read(fresh.dir, f), f);
+ await assert.rejects(scaffoldReportVideo({ ...args, slug: "bad", channelsDir, scan: { instances: "no" } }), /a phrase scan is/);
+ await assert.rejects(scaffoldReportVideo({ root: args.root, slug: "bad2", channelsDir, scan }), /go with --seed phrase/);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+});