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>) { 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> = { 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/); }); // Release 35: every instance records its alternates — the other-channel hits // folded into it. Everything else is what release 34 answered: the snapshot // fixtures/phraseScan.r34.json was made by release 34's phraseScan over this // same corpus, and the new answer minus `alternates` equals it. test("alternates: the old answer is the new one minus alternates (every option set, every phrase, both scanners)", async () => { const dir = corpus(VIDEOS); const want = JSON.parse(readFileSync(path.join(import.meta.dirname, "fixtures", "phraseScan.r34.json"), "utf8")); const strip = (r: { instances: Record[]; dropped: unknown[] }) => ({ instances: r.instances.map(({ alternates, ...rest }) => { assert.ok(Array.isArray(alternates), "every instance carries its alternates"); return rest; }), dropped: r.dropped, }); try { let k = 0; 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 many = await phraseScanMany({ channelsDir: dir, ...opts, phrases: PHRASES }); for (const [j, p] of PHRASES.entries()) { const alone = await phraseScan({ channelsDir: dir, ...opts, phrase: p.phrase }); assert.deepEqual(strip(alone), want[k], `${p.id} with ${JSON.stringify(opts)}`); assert.deepEqual(strip(many[j]), want[k], `${p.id} (many) with ${JSON.stringify(opts)}`); k++; } } assert.equal(k, want.length); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("alternates: a twin's covered hit, the hit a placed instance came from, a folded upload — each with its own moment", async () => { const dir = corpus(VIDEOS); try { const r = await phraseScan({ channelsDir: dir, channels: ["yt", "other"], prefer: "rumble", phrase: SLOW }); const by = (id: string) => r.instances.find((i) => i.videoId === id)!; // r1 has the hit itself: yt1 (its twin) is covered, r3 (a clip upload) folds in. assert.deepEqual(by("r1").alternates, [ { slug: "yt", videoId: "yt1", start: 110, end: 113, platform: "youtube", availability: null }, { slug: "rumble", videoId: "r3", start: 5, end: 8, platform: "rumble", availability: null }, ]); // r2 was placed from yt2's hit: yt2 is the alternate, at yt2's own moment. assert.equal(by("r2").via?.videoId, "yt2"); assert.deepEqual(by("r2").alternates, [{ slug: "yt", videoId: "yt2", start: 523, end: 526, platform: "youtube", availability: null }]); // No twin, nothing folded: none. assert.deepEqual(by("yt3").alternates, []); // Availability is read for an alternate as for an instance. const o = await phraseScan({ channelsDir: dir, channels: ["other", "yt"], prefer: null, phrase: String.raw`\b(?:no ?one|nobody) (?:asked|was asking)\b` }); assert.ok(o.instances.every((i) => Array.isArray(i.alternates))); } finally { rmSync(dir, { recursive: true, force: true }); } });