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 { MONTAGE_KIND } from "../projects/create.mjs"; import type { PhraseChannel, PhraseFinderState, PhraseScanRowView, PhraseScanSpec, PhraseScanView, PhraseSuggestion } from "./types"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // --------------------------------------------------------------------------- // 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/.json (the whole answer, // what Create montage seeds a project from), specs/.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 // //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 }; 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 = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, text, "utf8"); await rename(/* turbopackIgnore: true */ tmp, file); } async function readJsonFile(file: string): Promise { 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(); async function readAnswer(id: string): Promise { 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(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 { if (!isScanId(id)) return null; const job = reg.jobs.get(id) ?? null; const spec = job?.spec ?? (await readJsonFile(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 { 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 { 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; 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 { const [channels, suggestions, last] = await Promise.all([phraseChannels(), phraseSuggestions(), readJsonFile(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 { montageKind: MONTAGE_KIND, 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) })), }; }