"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { caseStageApi } from "@/lib/research/case-stage-hrefs"; import type { AudioAnswer, CaptionsView, VerifyRow, VerifyView } from "@/lib/research/case-verify"; import type { VerifyStatus } from "yt-dlp-transcript-common/lib/research/caseTypes"; import type { WordOp } from "yt-dlp-transcript-common/lib/research/wordDiff"; // STAGE 7, VERIFY (release 38 lane C): the findings on the left; on the right // one finding's window in every caption track side by side with the quote's // words lit, the audio check (the window transcribed through the editor and // diffed with the quote), its status, and a correction by hand that keeps the // reader's words. Nothing here needs a model. const STATUS_LABEL: Record = { unverified: "Unverified", verified: "Verified", corrected: "Corrected", disputed: "Disputed", quarantined: "Quarantined", }; const STATUS_BADGE: Record = { unverified: "info", verified: "neutral", corrected: "neutral", disputed: "blocking", quarantined: "open", }; const clock = (t: number) => { const s = Math.max(0, Math.floor(t)); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const ss = String(s % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; }; async function call(url: string, init?: { method?: string; body?: unknown }): Promise { const res = await fetch(url, { method: init?.method ?? "GET", headers: init?.body !== undefined ? { "content-type": "application/json" } : undefined, body: init?.body !== undefined ? JSON.stringify(init.body) : undefined, cache: "no-store", }); const body = await res.json().catch(() => ({})); if (!res.ok) throw new Error(body?.error ?? `HTTP ${res.status}`); return body as T; } function Diff({ ops }: { ops: WordOp[] }) { return (

{ops.map((o, i) => ( {i > 0 && " "} {o.op === "same" ? ( {o.word} ) : o.op === "missing" ? ( {o.word} ) : ( [{o.word}] )} ))}

); } export default function VerifyPanel({ caseId, initial }: { caseId: string; initial: VerifyView }) { const [view, setView] = useState(initial); const [sel, setSel] = useState(initial.rows[0]?.row ?? null); const [filter, setFilter] = useState("all"); const [caps, setCaps] = useState(null); const [capsError, setCapsError] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [status, setStatus] = useState("unverified"); const [note, setNote] = useState(""); const [quote, setQuote] = useState(""); const [speaker, setSpeaker] = useState(""); const [whilePaused, setWhilePaused] = useState(false); const [audio, setAudio] = useState<{ state: string; message?: string; ops?: WordOp[] } | null>(null); const poll = useRef | null>(null); const row: VerifyRow | null = view.rows.find((r) => r.row === sel) ?? null; useEffect(() => { if (!row) return; setStatus(row.status); setNote(row.verify?.note ?? ""); setQuote(row.quote); setSpeaker(row.speaker); setAudio(null); setError(null); if (poll.current) clearTimeout(poll.current); // Only when the selection moves: a save keeps what is on screen. // eslint-disable-next-line react-hooks/exhaustive-deps }, [sel]); useEffect(() => { if (!sel) return; let live = true; setCaps(null); setCapsError(null); call(`${caseStageApi(caseId, "verify/captions")}?row=${encodeURIComponent(sel)}`) .then((c) => live && setCaps(c)) .catch((e) => live && setCapsError((e as Error).message)); return () => { live = false; }; }, [caseId, sel, view.rows.find((r) => r.row === sel)?.quote]); useEffect(() => () => { if (poll.current) clearTimeout(poll.current); }, []); const save = useCallback( async (patch: { status: VerifyStatus; quote?: string; speaker?: string; how?: string }) => { if (!row) return; setBusy(true); setError(null); try { const r = await call<{ view: VerifyView }>(caseStageApi(caseId, "verify"), { method: "POST", body: { row: row.row, note, ...patch } }); setView(r.view); // The status buttons show what was saved (a correction by hand is "corrected"). setStatus(patch.status); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } }, [caseId, note, row], ); const step = useCallback( async (body: Record) => { if (!row) return; try { const a = await call(caseStageApi(caseId, "verify/audio"), { method: "POST", body: { row: row.row, whilePaused, ...body } }); if (a.state === "done") { setAudio({ state: "done", ops: a.ops }); setView(await call(caseStageApi(caseId, "verify"))); return; } if (a.state === "failed") { setAudio({ state: "failed", message: a.message }); return; } setAudio({ state: a.state, message: a.message }); poll.current = setTimeout(() => step(a.state === "fetching" ? { fetchJob: a.fetchJob } : { job: a.job }), 1000); } catch (e) { setAudio({ state: "failed", message: (e as Error).message }); } }, [caseId, row, whilePaused], ); const shown = view.rows.filter((r) => filter === "all" || r.status === filter); const changed = row ? quote.trim() !== row.quote || speaker.trim() !== row.speaker : false; const lastAudio = row?.verify?.audio; return (
{row ? (
{row.row} · {row.category} · relevance {row.relevance} · by {row.by}
“{row.quote}”
{row.speaker} ·{" "} {row.title} at {clock(row.t)}
{row.verify?.original && (

The reader wrote: “{row.verify.original.quote}”{row.verify.original.speaker ? ` (${row.verify.original.speaker})` : ""}

)} {row.forum && row.status !== "quarantined" && (

First seen on a forum: quarantine it until an independent source agrees, and look at any attachment before describing it.

)} {row.evidenceLabels.length > 0 && (
    {row.evidenceLabels.map((l, i) => (
  • {l}
  • ))}
)}

Captions, side by side

{capsError &&

{capsError}

} {caps?.note &&

{caps.note}

} {!caps && !capsError &&

Reading the window…

} {caps && caps.tracks.length > 0 && (
1 ? "md:grid-cols-2" : "")}> {caps.tracks.map((tr) => (
{tr.label} {tr.track} {tr.holds ? "holds the quote" : `${tr.matched} of ${tr.words} words`}
    {tr.cues.map((c, i) => (
  1. {tr.kind !== "post" && {clock(c.start)}} {c.parts.map((p, j) => p.hit ? ( {p.text} ) : ( {p.text} ), )}
  2. ))}
))}
)}

Audio check

{audio && audio.state !== "done" && ( {audio.message} )}
{lastAudio && (
Heard {lastAudio.matched} of {lastAudio.words} words {" "} · {lastAudio.worker ?? "a local worker"} · {new Date(lastAudio.at).toLocaleString()}
{audio?.ops && }

What the worker heard: {lastAudio.text}

)}

Status

{view.statuses.map((s) => ( ))}

Correct by hand