commit 3464e10968c528fbd36221089596d1b42e91b4ed
parent e95542d23879ea9346d38f7444b2a0cb8aea6945
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 16:57:30 -0400
common: phraseScanMany — many phrases in one pass over the transcripts, each answered as phraseScan answers it alone; plain words as a tolerant pattern (phraseSource.mjs); the cue-text cache (cueTextCache.mjs: one streamed file per channel, keyed by each cue file's mtime and size)
Over the real corpus (5 channels, 23,312 transcripts): phraseScan 27.5 s / 560 MB for one phrase;
phraseScanMany 17.3 s / 192 MB for one, 29.0 s / 424 MB for 25; with the cache warm 6.4 s / 168 MB
for one, 20.8 s / 278 MB for 25 (building it: 36.3 s / 336 MB). Equal to phraseScan on the real
corpus for 7 phrases. hitsInCues is joinCues + hitsInJoined; phraseScan's fold is shared, unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 701 insertions(+), 21 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",