// Every time a phrase was said, across channels: the instances a montage is cut from. // // Reads each video's transcript.cues.json under the channels named (read-only), // matches the phrase over the JOINED cue text — so a phrase a caption line // split in two is still found — and folds what is the same moment twice: // // - a rolling caption repeats its line in the next cue: hits under 8 s apart // in one video are one hit; // - a stream on the PREFERRED channel (a Rumble copy, say) is the one to cut // from: another channel's hit whose video has a twin there (an upload date // −1..+2 days, a duration within 10 %, and a title word in common or a // duration within 1 %) is found in the twin's transcript by its surrounding // content words (at least 6 of them, 60 % found) and cut from the twin instead; one that cannot // be placed stays on its own channel; // - the same words twice within 3 days (a stream and its clip upload) are one // instance, the first kept, the rest listed as `alsoIn`. // // Nothing is guessed about WHO said it: a context that matches `exclude` (a // chat line read out, a co-host) is dropped into `dropped` with the reason, and // a context with a caption speaker change (`>>`) is marked `speakerCheck` for // the ear. Plain ESM so `umtool new` runs it from a terminal with no server. import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; 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]; export const TWIN_DURATION_RATIO = 0.1; export const PLACE_MIN_SCORE = 0.6; // A context this short matches too much: it is never placed in a twin by its words. export const PLACE_MIN_WORDS = 6; // A twin by date and duration alone is often another upload of the same day: it // must also share a title word, unless the durations agree this closely. export const TWIN_CLOSE_RATIO = 0.01; export const SAME_HIT_MIN_SCORE = 0.35; export const FOLD_DAYS = 3; export const FOLD_MIN_OVERLAP = 0.6; const squash = (t) => String(t ?? "").replace(/\s+/g, " ").trim(); export const words = (t) => String(t ?? "").toLowerCase().match(/[a-z0-9']+/g) ?? []; const bag = (t) => new Set(words(t).filter((w) => w.length > 2)); // What placing a hit by its words counts: no function words, which every // stretch of speech shares. const STOP = new Set("the and for are but not you all any can had her was one our out day get has him his how man new now old see two way who boy did its let put say she too use that with have this will your from they know want been good much some time very when come here just like long make many over such take than them well were what into it's don't i'm that's there their about would could should really because going think yeah okay right also these those then thing things people mean even".split(" ")); const content = (ws) => ws.filter((w) => w.length > 2 && !STOP.has(w)); const TITLE_STOP = new Set(["the", "and", "for", "with", "this", "that", "quartering", "live", "stream", "from", "just", "about", "over", "into", "they", "what", "your", "their", "more", "most"]); const titleWords = (t) => new Set(words(t).filter((w) => w.length > 3 && !TITLE_STOP.has(w))); /** `YYYYMMDD` → days since the epoch, or null. */ export function dayNumber(s) { const m = /^(\d{4})(\d{2})(\d{2})/.exec(String(s ?? "")); if (!m) return null; const t = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])); return Number.isFinite(t) ? Math.round(t / 86_400_000) : null; } /** * The phrase as a global, case-insensitive RegExp. A string is a regular * expression's source; a RegExp keeps its source and gets `gi`. */ export function phraseRegExp(phrase) { const src = phrase instanceof RegExp ? phrase.source : String(phrase ?? ""); if (!src.trim()) throw new Error("a phrase is required"); return new RegExp(src, "gi"); } /** * The hits of one transcript (`{cues: [{start, end, text}]}`), in order: each * `{start, end, cueFirst, cueLast, match, context}` — start of the cue the * match begins in, end of the cue it ends in, the cue before through the cue * after as context. */ export function hitsInCues(cues, re) { if (!Array.isArray(cues) || !cues.length) return []; 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; for (const t of texts) { starts.push(pos); pos += t.length + 1; } 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; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= ch) lo = mid; else hi = mid - 1; } return lo; }; const out = []; const g = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`); for (const m of joined.matchAll(g)) { if (!m[0]) continue; const a = cueAt(m.index); const b = cueAt(m.index + m[0].length - 1); const start = Number(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 }); } return out; } /** The cue whose 5-cue window best covers `contextWords`: `{score, index}`. */ export function locateInCues(cues, contextWords) { const want = new Set(content(contextWords)); let best = { score: 0, index: null }; if (!want.size || !Array.isArray(cues)) return best; const cueBags = cues.map((c) => new Set(content(words(c?.text)))); for (let i = 0; i < cues.length; i++) { const win = new Set(); for (let j = i; j < Math.min(cues.length, i + 5); j++) for (const w of cueBags[j]) win.add(w); if (!win.size) continue; let n = 0; for (const w of want) if (win.has(w)) n++; const score = n / want.size; if (score > best.score) best = { score, index: i }; } return best; } function overlap(a, b) { const A = bag(a); const B = bag(b); if (!A.size || !B.size) return 0; let n = 0; for (const w of A) if (B.has(w)) n++; return n / Math.min(A.size, B.size); } async function readCues(channelsDir, slug, id) { try { return JSON.parse(await readFile(path.join(channelsDir, slug, "data", id, "transcript.cues.json"), "utf8")); } catch { return null; } } async function availabilityOf(channelsDir, slug, id) { try { const a = JSON.parse(await readFile(path.join(channelsDir, slug, "data", id, "availability.json"), "utf8")); return a?.state ?? a?.availability ?? null; } catch { return null; } } async function videoIds(channelsDir, slug) { try { return (await readdir(path.join(channelsDir, slug, "data"), { withFileTypes: true })) .filter((d) => d.isDirectory() || d.isSymbolicLink()) .map((d) => d.name) .sort(); } catch { return []; } } /** * Scan the channels. `prefer` (a slug, optional) is the channel to cut from * where a twin exists; it is scanned too. `exclude` (a regex source or RegExp, * optional) drops a hit whose context matches it. `onProgress(done, total)` is * called per channel. * * Returns `{ instances, hits, dropped, scanned }`: `instances` chronological * (upload date, then time in the video), each `{slug, videoId, platform, date, * title, duration, start, end, match, context, speakerCheck, availability, * via?, alsoIn?}` — `via` names the hit a preferred-channel instance was placed * from. * * @param {{channelsDir: string, channels: string[], phrase: string | RegExp, prefer?: string | null, exclude?: string | RegExp | null, onProgress?: (done: number, total: number) => void}} opts */ export async function phraseScan({ channelsDir, channels, phrase, prefer = null, exclude = null, onProgress }) { const re = phraseRegExp(phrase); const ex = excludeRegExp(exclude); const slugs = [...new Set([...(prefer ? [prefer] : []), ...channels])]; const hits = []; 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)) { const d = await readCues(channelsDir, slug, id); if (!d) continue; scanned++; if (slug === prefer) preferred.set(id, { day: dayNumber(d.uploadDate), duration: Number(d.duration) || 0, title: titleWords(d.title), record: d }); for (const h of hitsInCues(d.cues, re)) hits.push(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; if (!byDay.has(v.day)) byDay.set(v.day, []); byDay.get(v.day).push(id); } const preferredHits = new Map(); for (const h of hits) { if (h.slug !== prefer) continue; if (!preferredHits.has(h.videoId)) preferredHits.set(h.videoId, []); preferredHits.get(h.videoId).push(h); } // The other-channel hits each instance stands for (release 35): a twin's hit // its preferred copy already has, the hit a placed instance came from, and // every hit folded into it — the copies a stand-in can be cut from. const altsOf = new Map(); // placed entry -> its alternates const placedOf = new Map(); // a preferred hit -> its placed copy const placed = hits .filter((h) => h.slug === prefer) .map((h) => { const c = { ...h }; placedOf.set(h, c); altsOf.set(c, []); return c; }); for (const h of hits) { if (h.slug === prefer) continue; const day = dayNumber(h.date); const twins = []; if (prefer && day != null && h.duration) { for (const off of TWIN_DAYS) { for (const id of byDay.get(day + off) ?? []) { const p = preferred.get(id); const diff = Math.abs(p.duration - h.duration); if (!p.duration || diff > TWIN_DURATION_RATIO * Math.max(p.duration, h.duration)) continue; const titled = [...titleWords(h.title)].some((w) => p.title.has(w)); if (titled || diff <= TWIN_CLOSE_RATIO * Math.max(p.duration, h.duration)) twins.push(id); } } } const ctx = words(h.context); // Its twin already has the hit: nothing to add. // Covered when any twin's hit says it (as release 34 decided); the // alternate goes to the twin hit that says it BEST, since the phrase's // own words alone clear the bar for every twin of the day. let covered = null; let coveredScore = -1; for (const id of twins) { for (const p of preferredHits.get(id) ?? []) { const score = locateInCues([{ text: p.context }], ctx).score; if (score >= SAME_HIT_MIN_SCORE && score > coveredScore) { covered = p; coveredScore = score; } } } if (covered) { altsOf.get(placedOf.get(covered))?.push(alternateOf(h)); continue; } // Its twin's transcript says it in other words (a different track): place it there. let moved = null; const placeable = new Set(content(ctx)).size >= PLACE_MIN_WORDS; for (const id of placeable ? twins : []) { const rec = await recordOf(id); const cues = rec.cues ?? []; const at = locateInCues(cues, ctx); if (at.index != null && at.score >= PLACE_MIN_SCORE) { const last = cues[Math.min(at.index + 1, cues.length - 1)]; moved = { ...h, slug: prefer, videoId: id, platform: rec.platform ?? null, source: rec.source ?? null, title: rec.title ?? null, duration: Number(rec.duration) || null, start: Number(cues[at.index].start), end: Number(last.end ?? last.start), via: { slug: h.slug, videoId: h.videoId, start: h.start, score: Math.round(at.score * 100) / 100 }, }; break; } } const entry = moved ?? { ...h }; altsOf.set(entry, moved ? [alternateOf(h)] : []); placed.push(entry); } placed.sort((a, b) => String(a.date ?? "").localeCompare(String(b.date ?? "")) || (a.slug === prefer ? 0 : 1) - (b.slug === prefer ? 0 : 1) || a.start - b.start); const instances = []; const dropped = []; for (const i of placed) { const di = dayNumber(i.date); const twin = instances.find((k) => { const dk = dayNumber(k.date); return dk != null && di != null && Math.abs(dk - di) <= FOLD_DAYS && overlap(k.context, i.context) >= FOLD_MIN_OVERLAP; }); if (twin) { (twin.alsoIn ??= []).push({ slug: i.slug, videoId: i.videoId, start: i.start }); altsOf.get(twin.ref).push(alternateOf(i), ...altsOf.get(i)); continue; } if (ex?.test(i.context)) { dropped.push({ ...i, why: "matches the exclude pattern" }); continue; } const inst = { ...i, speakerCheck: i.context.includes(">>") }; // Non-enumerable: never copied into the answer. Object.defineProperty(inst, "ref", { value: i, enumerable: false }); instances.push(inst); } const availabilityFor = (slug, id) => (slug === prefer ? null : availability(slug, id)); for (const i of instances) { i.availability = await availabilityFor(i.slug, i.videoId); const seen = new Set(); const alternates = []; for (const a of altsOf.get(i.ref) ?? []) { const k = `${a.slug}/${a.videoId}`; if ((a.slug === i.slug && a.videoId === i.videoId) || seen.has(k)) continue; seen.add(k); alternates.push({ ...a, availability: await availabilityFor(a.slug, a.videoId) }); } i.alternates = alternates; } return { instances, dropped }; } /** An other-channel hit as an instance's alternate: its own moment on its own recording. */ function alternateOf(h) { return { slug: h.slug, videoId: h.videoId, start: h.start, end: h.end, platform: h.platform ?? null }; } /** * The cap (release 35, `max`): N of the instances, spread across the years in * proportion to each year's count — at least one for every year that has any * (largest-remainder rounding), or, when N is fewer than the years, one each * for N years spread across them. Within a year the instances without a * `speakerCheck` come first, picked evenly through the year (not its first * few). `kept` and `skipped` are both chronological (the order given); an * instance with no date is its own year, last. `max` absent, not a positive * whole number, or ≥ the count → everything kept. * * @template T * @param {T[]} instances chronological * @param {number | null | undefined} max * @returns {{ kept: T[], skipped: T[] }} */ export function capInstances(instances, max) { const list = Array.isArray(instances) ? instances : []; if (!(Number.isInteger(max) && max > 0) || max >= list.length) return { kept: [...list], skipped: [] }; const yearOf = (i) => /^(\d{4})/.exec(String(i?.date ?? ""))?.[1] ?? "~"; const byYear = new Map(); list.forEach((inst, k) => { const y = yearOf(inst); if (!byYear.has(y)) byYear.set(y, []); byYear.get(y).push(k); }); const years = [...byYear.keys()].sort(); const alloc = new Map(years.map((y) => [y, 0])); if (max < years.length) { for (const k of spreadIndices(years.length, max)) alloc.set(years[k], 1); } else { const quota = new Map(years.map((y) => [y, (max * byYear.get(y).length) / list.length])); for (const y of years) alloc.set(y, Math.min(byYear.get(y).length, Math.max(1, Math.floor(quota.get(y))))); let sum = years.reduce((n, y) => n + alloc.get(y), 0); // How far a year is under its quota: at its floor, the remainder. const under = (y) => quota.get(y) - alloc.get(y); while (sum < max) { // The largest remainder first (ties: the bigger year, then the earlier). const y = years .filter((y) => alloc.get(y) < byYear.get(y).length) .sort((a, b) => under(b) - under(a) || byYear.get(b).length - byYear.get(a).length || a.localeCompare(b))[0]; alloc.set(y, alloc.get(y) + 1); sum++; } while (sum > max) { // The ≥ 1 floor overshot: take back from the most over-allotted year that keeps one. const y = years .filter((y) => alloc.get(y) > 1) .sort((a, b) => under(a) - under(b) || byYear.get(b).length - byYear.get(a).length || b.localeCompare(a))[0]; alloc.set(y, alloc.get(y) - 1); sum--; } } const keep = new Set(); for (const y of years) { const n = alloc.get(y); if (!n) continue; const ks = byYear.get(y); const clean = ks.filter((k) => !list[k]?.speakerCheck); const checked = ks.filter((k) => list[k]?.speakerCheck); if (n <= clean.length) for (const j of spreadIndices(clean.length, n)) keep.add(clean[j]); else { for (const k of clean) keep.add(k); for (const j of spreadIndices(checked.length, n - clean.length)) keep.add(checked[j]); } } const kept = []; const skipped = []; list.forEach((inst, k) => (keep.has(k) ? kept : skipped).push(inst)); return { kept, skipped }; } /** `n` of `0..len-1`, evenly spread (the middle of each of n equal stretches). */ function spreadIndices(len, n) { const out = []; for (let j = 0; j < n; j++) out.push(Math.min(len - 1, Math.floor(((j + 0.5) * len) / n))); return out; } /** * 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); } } /** `20190502` → `2 May 2019`. */ export function niceDate(s) { const n = dayNumber(s); if (n == null) return String(s ?? ""); const d = new Date(n * 86_400_000); const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`; } /** * Instances → manifest clips, chronological: the extent is the phrase's cues * widened by `pad` each side (room for the renderer's snap and for tighter * montage styles), the cut is the phrase's cues. `onscreen.title` is the phrase * as said, `subtitle` the date; `montage` carries `{n, date, platform, match, * speakerCheck}` for the montage renderer. */ export function instancesAsClips(instances, { pad = 2.5, idPrefix = "s" } = {}) { const width = String(instances.length).length < 2 ? 2 : String(instances.length).length; const r2 = (x) => Math.round(x * 100) / 100; return instances.map((i, k) => { const n = k + 1; const notes = []; if (i.speakerCheck) notes.push("voice check: a speaker change in the captions"); if (i.via) notes.push(`placed from ${i.via.slug}/${i.via.videoId} @ ${Math.round(i.via.start)}s`); if (i.alsoIn?.length) notes.push(`also in ${i.alsoIn.map((a) => `${a.slug}/${a.videoId}`).join(", ")}`); if (i.availability && i.availability !== "public") notes.push(`source availability: ${i.availability}`); return { type: "clip", id: `${idPrefix}${String(n).padStart(width, "0")}`, channel: i.slug, video: i.videoId, start: r2(Math.max(0, i.start - pad)), end: r2(i.end + pad), cutStart: r2(i.start), cutEnd: r2(i.end), cite: r2(i.start), quote: i.context.slice(0, 240), onscreen: { title: squash(i.match).toLowerCase(), subtitle: niceDate(i.date) }, ...(notes.length ? { note: notes.join("; ") } : {}), montage: { n, of: instances.length, date: i.date ?? null, platform: i.platform ?? null, match: i.match, speakerCheck: Boolean(i.speakerCheck) }, }; }); }