import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { findVideo } from "yt-dlp-transcript-mcp/research"; import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; import { cuesOfTrack, trackKind, trackLabel } from "yt-dlp-transcript-common/lib/captionTracks"; import { holdsWords, wordsOf } from "yt-dlp-transcript-common/lib/report/quoteWords"; import { QUOTE_WORDS_MAX, VERIFY_STATUSES, evidenceLabel, isVerifyStatus, type AudioCheck, type FindingRow, type FindingVerify, type VerifyStatus, } from "yt-dlp-transcript-common/lib/research/caseTypes"; import { withholdPrivateNames } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; import { quoteWordDiff, type WordOp } from "yt-dlp-transcript-common/lib/research/wordDiff"; import { CHANNELS_DIR, REPORTS_ROOT } from "../paths.mjs"; import { readCase } from "./cases.mjs"; import { mutateFindings, readFindings, rowOf } from "./case-findings-store"; import { CaseError, privateHashes } from "./case-stage-files"; import { jobState, resultLine, startJob } from "./case-editor"; import { fetchForReader } from "./fetch"; import { localDir, openSource } from "./sources"; // --------------------------------------------------------------------------- // STAGE 7, VERIFY (release 38 lane C): per finding, the window's captions in // both tracks side by side with the quote's words lit; an AUDIO CHECK -- the // window transcribed through the editor (`transcribe`, a transcribe-file job // on a local worker; never a hand-run whisper) and its words diffed with the // quote; and a status, `verified | corrected | disputed | unverified | // quarantined`. A quote corrected by hand keeps the reader's words in // `verify.original`. Every change is a whole rewrite of findings.jsonl // through lane A's store and privacy gate (case-findings-store.ts): a // hand-written quote or note that names a private name is refused (counts and // the row id, never the name). // --------------------------------------------------------------------------- /** How far before and after a finding's `t` its window reaches (seconds). */ export const WINDOW_BEFORE = 15; export const WINDOW_AFTER = 35; /** The audio check's window: a little before the quote, enough after it for 45 words. */ export const AUDIO_BEFORE = 5; export const AUDIO_AFTER = 30; const MEDIA_EXT = /\.(?:m4a|mp3|opus|ogg|oga|wav|flac|aac|mp4|mkv|webm|mov)$/i; // ── who the finding came from ── async function channelPlatform(slug: string): Promise { if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) return null; try { const c = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(CHANNELS_DIR, slug, "config.json"), "utf8")); return typeof c?.platform === "string" ? c.platform : null; } catch { return null; } } /** First seen on a forum: the row is from a forum channel, or its evidence is a forum attachment. */ export function forumSourced(row: FindingRow, platformOfSlug: string | null): boolean { return platformOfSlug === "xenforo" || (row.evidence ?? []).some((e) => e.kind === "forum-attachment"); } // ── the list ── export type VerifyRow = FindingRow & { status: VerifyStatus; forum: boolean; evidenceLabels: string[] }; export type VerifyView = { rows: VerifyRow[]; counts: Record; bad: { line: number; error: string }[]; statuses: readonly VerifyStatus[]; }; export async function verifyView(caseId: string): Promise { const { rows, bad } = await readFindings(caseId); const platforms = new Map(); for (const r of rows) if (!platforms.has(r.slug)) platforms.set(r.slug, await channelPlatform(r.slug)); const counts = Object.fromEntries(VERIFY_STATUSES.map((s) => [s, 0])) as Record; const out: VerifyRow[] = rows.map((r) => { const status = r.verify?.status ?? "unverified"; counts[status]++; return { ...r, status, forum: forumSourced(r, platforms.get(r.slug) ?? null), evidenceLabels: (r.evidence ?? []).map((e) => evidenceLabel({ kind: e.kind, position: e.position, post: e.post, capturedAt: e.capturedAt })), }; }); return { rows: out, counts, bad, statuses: VERIFY_STATUSES }; } // ── the captions, both tracks ── export type CaptionPart = { text: string; hit: boolean }; export type CaptionCue = { start: number; end: number; parts: CaptionPart[] }; export type CaptionTrack = { track: string; label: string; kind: string; cues: CaptionCue[]; holds: boolean; matched: number; words: number }; export type CaptionsView = { row: string; quote: string; t: number; title: string; tracks: CaptionTrack[]; note?: string }; type Tok = { text: string; cue: number; norm: string[] }; /** * Which of `words` the quote lands on: the stretch (about the quote's length) that holds the most of its words in * order, the nearest to the finding's moment on a tie; its matched words are the hits. */ export function alignQuote(quote: string[], words: string[], nearIndex = 0): { hits: Set; matched: number } { const n = quote.length; if (!n || !words.length) return { hits: new Set(), matched: 0 }; const span = Math.min(words.length, Math.max(n + 4, Math.ceil(n * 1.5))); let best = { start: 0, matched: -1, dist: Infinity }; for (let s = 0; s + span <= words.length || s === 0; s++) { const w = words.slice(s, s + span); const m = lcsLen(quote, w); const dist = Math.abs(s - nearIndex); if (m > best.matched || (m === best.matched && dist < best.dist)) best = { start: s, matched: m, dist }; if (s + span >= words.length) break; } const w = words.slice(best.start, best.start + span); const hits = new Set(); for (const j of lcsPairs(quote, w)) hits.add(best.start + j); return { hits, matched: Math.max(0, best.matched) }; } function lcsTable(a: string[], b: string[]): number[][] { const t: number[][] = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0)); for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) t[i][j] = a[i] === b[j] ? t[i + 1][j + 1] + 1 : Math.max(t[i + 1][j], t[i][j + 1]); return t; } const lcsLen = (a: string[], b: string[]) => lcsTable(a, b)[0][0]; function lcsPairs(a: string[], b: string[]): number[] { const t = lcsTable(a, b); const out: number[] = []; let i = 0; let j = 0; while (i < a.length && j < b.length) { if (a[i] === b[j]) { out.push(j); i++; j++; } else if (t[i + 1][j] >= t[i][j + 1]) i++; else j++; } return out; } /** One track's window, its words lit where the quote lands. */ export function litTrack(cues: { start: number; end?: number; text: string }[], quote: string, t: number): Omit { const win = cues.filter((c) => c.start >= t - WINDOW_BEFORE && c.start <= t + WINDOW_AFTER); const toks: Tok[] = []; win.forEach((c, i) => { for (const piece of c.text.split(/\s+/).filter(Boolean)) toks.push({ text: piece, cue: i, norm: wordsOf(piece).split(" ").filter(Boolean) }); }); const flat: { tok: number; w: string }[] = []; toks.forEach((tk, i) => tk.norm.forEach((w) => flat.push({ tok: i, w }))); const q = wordsOf(quote).split(" ").filter(Boolean); const nearCue = win.findIndex((c) => c.start >= t - 1); const nearIndex = Math.max(0, flat.findIndex((f) => toks[f.tok].cue >= nearCue)); const { hits, matched } = alignQuote(q, flat.map((f) => f.w), nearIndex); const litTok = new Set([...hits].map((h) => flat[h].tok)); const out: CaptionCue[] = win.map((c) => ({ start: c.start, end: c.end ?? c.start, parts: [] })); toks.forEach((tk, i) => { const parts = out[tk.cue].parts; const hit = litTok.has(i); const last = parts[parts.length - 1]; if (last && last.hit === hit) last.text += ` ${tk.text}`; else parts.push({ text: parts.length ? ` ${tk.text}` : tk.text, hit }); }); // A leading space belongs outside a lit run. for (const c of out) { for (let i = 1; i < c.parts.length; i++) { if (c.parts[i].hit && c.parts[i].text.startsWith(" ")) { c.parts[i].text = c.parts[i].text.slice(1); c.parts[i - 1].text += " "; } } } return { cues: out, holds: holdsWords(win.map((c) => c.text).join(" "), quote), matched, words: q.length }; } const trackOrder = (track: string) => ({ original: 0, uploaded: 1, transcription: 2 })[trackKind(track) as "original"] ?? 3; async function sourceOf(caseId: string): Promise { const doc = (await readCase(REPORTS_ROOT, caseId)) as { scope?: { source?: string } }; return doc.scope?.source?.trim() || `local:${localDir()}`; } async function postTrack(f: FindingRow, hashes: string[]): Promise { const platform = await channelPlatform(f.slug); if (!platform || !["xenforo", "twitter", "bluesky", "webpage", "instagram"].includes(platform)) return null; const posts = await readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, f.slug)).catch(() => []); const p = posts.find((x) => x.id === f.id); if (!p) return null; const lit = litTrack([{ start: 0, end: 0, text: withholdPrivateNames(p.text, hashes).text }], f.quote, 0); const author = withholdPrivateNames(p.author, hashes).text; const label = platform === "xenforo" ? `forum post${p.forum?.position ? ` #${p.forum.position}` : ""} by ${author}` : `post by ${author}`; return { track: "post", label, kind: "post", ...lit }; } export async function findingCaptions(caseId: string, row: string): Promise { const { rows } = await readFindings(caseId); const f = rowOf(rows, row); const opened = await openSource(await sourceOf(caseId)); // A post (a forum's, an X account's): its text is the "track", read from the editor's corpus. // Text from the corpus is shown with the case's private names withheld. const hashes = await privateHashes(caseId); const asPost = await postTrack(f, hashes); if (asPost) return { row, quote: f.quote, t: f.t, title: f.title, tracks: [asPost] }; const found = await findVideo(opened.source, f.id, f.slug).catch(() => null); if (!found) return { row, quote: f.quote, t: f.t, title: f.title, tracks: [], note: `${f.slug}/${f.id} is not in ${opened.option.label}` }; const rec = found.record as { track?: string; altTracks?: { track: string }[]; transcriptFormat?: string }; const primary = rec.track ?? (rec.transcriptFormat && rec.transcriptFormat !== "vtt" ? "transcription" : "captions"); const ids = [primary, ...(rec.altTracks ?? []).map((a) => a.track)]; const tracks: CaptionTrack[] = []; for (const id of [...new Set(ids)].sort((a, b) => trackOrder(a) - trackOrder(b)).slice(0, 3)) { const cues = ((cuesOfTrack(found.record, id === primary ? rec.track : id) ?? []) as { start: number; end: number; text: string }[]).filter( (c) => c && typeof c.start === "number", ); if (!cues.length) continue; const shown = hashes.length ? cues.map((c) => ({ ...c, text: withholdPrivateNames(c.text, hashes).text })) : cues; tracks.push({ track: id, label: trackLabel(id), kind: trackKind(id), ...litTrack(shown, f.quote, f.t) }); } return { row, quote: f.quote, t: f.t, title: f.title, tracks }; } // ── a status, and a correction by hand ── export type VerifyPatch = { status: string; note?: string; quote?: string; speaker?: string; how?: string }; export async function setVerify(caseId: string, row: string, patch: VerifyPatch, now = new Date()): Promise { if (!isVerifyStatus(patch.status)) throw new CaseError(`not a status: ${JSON.stringify(patch.status)} (one of ${VERIFY_STATUSES.join(", ")})`, 400); const note = typeof patch.note === "string" ? patch.note.replace(/\s+/g, " ").trim().slice(0, 1000) : undefined; const quote = typeof patch.quote === "string" ? patch.quote.replace(/\s+/g, " ").trim() : undefined; const speaker = typeof patch.speaker === "string" ? patch.speaker.replace(/\s+/g, " ").trim().slice(0, 120) : undefined; if (quote !== undefined && !quote) throw new CaseError("a corrected quote cannot be empty", 400); if (quote && quote.split(" ").length > QUOTE_WORDS_MAX) throw new CaseError(`a quote is at most ${QUOTE_WORDS_MAX} words, verbatim`, 400); // The privacy gate is the findings writer's (case-findings-store.ts): a hand-written quote, speaker or note // that names a private name refuses the whole write (409, counts and the row id, never the name). const r = await mutateFindings(caseId, (rows) => { const f = rowOf(rows, row); const changesWords = (quote !== undefined && quote !== f.quote) || (speaker !== undefined && speaker !== f.speaker); if (changesWords && patch.status !== "corrected") throw new CaseError("a quote or speaker changed by hand is status corrected", 400); const prev = f.verify; const next: FindingVerify = { status: patch.status as VerifyStatus, at: now.toISOString(), how: changesWords ? "hand" : patch.how === "audio" && prev?.audio ? "audio" : "captions", ...(note ? { note } : {}), ...(prev?.original ? { original: prev.original } : {}), ...(prev?.audio ? { audio: prev.audio } : {}), }; if (changesWords) { // The reader's words are kept once: a second correction never loses them. next.original ??= { quote: f.quote, ...(f.speaker ? { speaker: f.speaker } : {}) }; if (quote !== undefined) f.quote = quote; if (speaker !== undefined) f.speaker = speaker; } f.verify = next; return f; }); const platform = await channelPlatform(r.result.slug); return { ...r.result, status: r.result.verify!.status, forum: forumSourced(r.result, platform), evidenceLabels: (r.result.evidence ?? []).map((e) => evidenceLabel(e)), }; } // ── the audio check ── /** The held media to transcribe the window from: the video's own file, else a fetched clip window covering it. */ export async function heldMedia(slug: string, id: string, from: number, to: number): Promise<{ file: string; offset: number } | null> { if (!/^[A-Za-z0-9_.@-]+$/.test(slug) || !/^[A-Za-z0-9_.@-]+$/.test(id)) return null; const dir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "data", id); const names = await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[]); const media = names.filter((n) => MEDIA_EXT.test(n) && !n.startsWith(".")).sort((a, b) => Number(b.startsWith("audio.")) - Number(a.startsWith("audio."))); if (media.length) return { file: path.join(dir, media[0]), offset: 0 }; const clips = await readdir(/* turbopackIgnore: true */ path.join(dir, "clips")).catch(() => [] as string[]); let best: { file: string; offset: number; len: number } | null = null; for (const n of clips) { const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\.(?:mp4|m4a|webm|mkv)$/.exec(n); if (!m) continue; const a = Number(m[1]); const b = Number(m[2]); if (a <= from && b >= to && (!best || b - a < best.len)) best = { file: path.join(dir, "clips", n), offset: a, len: b - a }; } return best ? { file: best.file, offset: best.offset } : null; } export type AudioAnswer = | { state: "fetching"; fetchJob: string; message: string } | { state: "transcribing"; job: string; message: string } | { state: "done"; audio: AudioCheck; ops: WordOp[] } | { state: "failed"; message: string; job?: string }; export const TRANSCRIBE_RESULT_MARKER = "@@transcribe-result "; async function queueTranscribe(file: string, start: number, end: number, whilePaused: boolean): Promise { const job = await startJob("/api/ops/transcribe", { path: file, start: Math.max(0, Math.round(start * 10) / 10), end: Math.round(end * 10) / 10, ...(whilePaused ? { whilePaused: true } : {}), }); return { state: "transcribing", job, message: "the window is queued on a local transcription worker" }; } /** * One step of a finding's audio check. With no job: find the window's media (held, or a clip fetched through the * editor's fetch-window, exactly as the reader's Fetch clip asks) and queue its transcription. With `fetchJob`: once * the clip is in, queue it. With `job`: once the transcription is done, diff it and keep it on the finding. */ export async function audioStep( caseId: string, row: string, opts: { whilePaused?: boolean; fetchJob?: string; job?: string }, now = new Date(), ): Promise { const { rows } = await readFindings(caseId); const f = rowOf(rows, row); const from = Math.max(0, f.t - AUDIO_BEFORE); const to = f.t + AUDIO_AFTER; const whilePaused = opts.whilePaused === true; if (opts.job) { const st = await jobState(opts.job); if (!st.done) return { state: "transcribing", job: opts.job, message: `the transcription is ${st.status}` }; const res = resultLine<{ text?: string; cues?: { text: string }[]; worker?: { name?: string; id?: string } }>(st.tail, TRANSCRIBE_RESULT_MARKER); if (st.status !== "done" || !res) { return { state: "failed", job: opts.job, message: `the transcription ${st.status}${st.tail.length ? `: ${st.tail[st.tail.length - 1]}` : ""}` }; } const heard = res.text ?? (res.cues ?? []).map((c) => c.text).join(" "); const diff = quoteWordDiff(f.quote, heard); const hashes = await privateHashes(caseId); const audio: AudioCheck = { at: now.toISOString(), job: opts.job, text: withholdPrivateNames(heard.replace(/\s+/g, " ").trim(), hashes).text.slice(0, 4000), matched: diff.matched, words: diff.words, ...(res.worker?.name || res.worker?.id ? { worker: String(res.worker?.name ?? res.worker?.id) } : {}), }; await mutateFindings(caseId, (all) => { const r = rowOf(all, row); r.verify = { ...(r.verify ?? { status: "unverified" as const, at: audio.at }), audio }; }); return { state: "done", audio, ops: diff.ops }; } if (opts.fetchJob) { const fetched = await fetchForReader({ job: opts.fetchJob }); if (fetched.state === "queued") return { state: "fetching", fetchJob: opts.fetchJob, message: `the clip is ${fetched.status}` }; if (fetched.state === "failed") return { state: "failed", message: fetched.message }; const offset = fetched.from ?? from; return queueTranscribe(fetched.file, from - offset, to - offset, whilePaused); } const held = await heldMedia(f.slug, f.id, from, to); if (held) return queueTranscribe(held.file, from - held.offset, to - held.offset, whilePaused); const fetched = await fetchForReader({ source: await sourceOf(caseId), channel: f.slug, video: f.id, start: from, end: to, reason: `research case ${caseId}: audio check of ${row}`, }); if (fetched.state === "queued") return { state: "fetching", fetchJob: fetched.job, message: "no media is held; the window is being fetched through the editor" }; if (fetched.state === "failed") return { state: "failed", message: fetched.message }; const offset = fetched.from ?? from; return queueTranscribe(fetched.file, from - offset, to - offset, whilePaused); }