Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit ff9f7bb54de47cb3f1dbdbc54a9115158400e39b
parent 7566939b4a024c28f0e48a50bc3532f4c4a76bc6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 17:49:22 -0400

Merge r32/ops-buttons: every operation has a button in the editor — find copies of gone videos (channel and site, preview then run), audit audio with its tally and the video's verdict, frame scan re-derive with no model and hand corrections of readings, media tools on the video page, attach video on an article, more ways in, keep videos matching, the Odysee audio-check default shown

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/components/StreamActionLog.tsx | 16+++++++++++++---
Mcommon/controller/audioAudit.test.ts | 6++++++
Mcommon/controller/channelSnapshot.ts | 47++++++++++++++++++++++++++++++++++++++++++++---
Acommon/controller/frameCorrections.test.ts | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/frameCorrections.ts | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/frameScan.ts | 12++++++++----
Mcommon/jobs/jobKinds.test.ts | 2++
Mcommon/jobs/jobKinds.ts | 15+++++++++++++++
Mcommon/lib/frameScan-server.ts | 10+++++++++-
Acommon/lib/frames/corrections.test.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/frames/corrections.ts | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/frames/scan.ts | 25++++++++++++++++++++-----
Meditor/CHANGELOG.md | 6++++++
Aeditor/app/channels/[slug]/audioAuditActions.ts | 30++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/components/ChannelImportTools.tsx | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/components/KeepMatchingControl.tsx | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 3+++
Aeditor/app/channels/[slug]/components/SocialPostTools.tsx | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/CleanupStage.tsx | 2++
Meditor/app/channels/[slug]/components/stages/DownloadStage.tsx | 88++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/channels/[slug]/page.tsx | 4++++
Aeditor/app/channels/[slug]/videos/[id]/components/FrameReadingEditor.tsx | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/components/FrameRederiveControl.tsx | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/components/FrameScanPanel.tsx | 34++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/frameScanActions.ts | 51++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts | 20++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts | 30++++++++++++++++++++++++++++--
Aeditor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 22++++++++++++++++++++--
Meditor/app/channels/components/channelConfigToForm.ts | 9+++++++++
Meditor/app/channels/components/parseChannelForm.test.ts | 33+++++++++++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 10++++++++++
Aeditor/app/components/FindCopiesControl.tsx | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/lib/resultMarker.test.ts | 18++++++++++++++++++
Aeditor/app/lib/resultMarker.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/sites/[siteId]/page.tsx | 4++++
Meditor/app/sites/articles/page.tsx | 2++
Aeditor/app/sites/components/ArticleVideoControl.tsx | 47+++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/sites/lib/articlesServer.ts | 7+++++--
Aeditor/app/sites/lib/attachVideoAction.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/e2e/ops-buttons.spec.ts | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/FACTS.md | 44++++++++++++++++++++++++++++++++++++++++++--
Aplans/release-32/ops-buttons.md | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
45 files changed, 2729 insertions(+), 26 deletions(-)

diff --git a/common/components/StreamActionLog.tsx b/common/components/StreamActionLog.tsx @@ -36,7 +36,11 @@ type Props = { * flag there lets an operator press Preview and then Evict before a single * count has appeared — which is the whole thing the gate exists to stop. */ - onSettled?: (started: boolean) => void; + // + // `out` (release 32) is what the run left: its whole log and its job id — so + // a caller can read a result marker off the log's last line (a dry run's + // candidate list) and link the job. + onSettled?: (started: boolean, out: { log: string; jobId: string | null }) => void; }; type StatusPoll = { @@ -147,6 +151,8 @@ export function StreamActionLog({ stickToBottomRef.current = true; setRunning(true); let started = false; + let full = ""; + let startedJob: string | null = null; try { const result = await trigger(); if (!result.ok) { @@ -155,18 +161,22 @@ export function StreamActionLog({ return; } started = true; + startedJob = result.jobId; setJobId(result.jobId); const reader = result.stream.getReader(); while (true) { const { value, done } = await reader.read(); if (done) break; - if (value) setLog((prev) => prev + value); + if (value) { + full += value; + setLog((prev) => prev + value); + } } } catch (e) { setError((e as Error).message); } finally { setRunning(false); - onSettled?.(started); + onSettled?.(started, { log: full, jobId: startedJob }); // A run that actually started (success, mid-stream error, or cancel) // may have mutated server-derived data: a saved shard config, channel // counts, bucket lists, failed-transcription lists. Re-fetch the server diff --git a/common/controller/audioAudit.test.ts b/common/controller/audioAudit.test.ts @@ -240,6 +240,10 @@ test("the report: damaged untranscribed held audio is corruptHeldAudio, out of d assert.deepEqual(snap.buckets.corruptHeldAudio, ["bbbb0000002"]); assert.deepEqual(snap.buckets.downloadedNoTranscript, ["aaaa0000001"]); assert.deepEqual(snap.buckets.corruptFullSource, ["dddd0000004"]); + // The channel's tally of the audit's verdicts (release 32): the page's counts. + const { lastCheckedAt, ...tally } = snap.audioIntegrity!; + assert.deepEqual(tally, { clean: 1, damaged: 2, undecodable: 0, stale: 0 }); + assert.ok(lastCheckedAt && !Number.isNaN(Date.parse(lastCheckedAt))); // A transcribed damaged file is not in the bucket (its transcript stands)… assert.ok(!snap.buckets.corruptHeldAudio.includes("cccc0000003")); // …unless its transcript is a salvage. @@ -259,6 +263,8 @@ test("the report: damaged untranscribed held audio is corruptHeldAudio, out of d const snap3 = await generateChannelSnapshot(f.paths, SLUG); assert.deepEqual(snap3.buckets.corruptHeldAudio, ["cccc0000003"]); assert.ok(snap3.buckets.downloadedNoTranscript.includes("bbbb0000002")); + assert.equal(snap3.audioIntegrity?.stale, 1); + assert.equal(snap3.audioIntegrity?.damaged, 1); await rm(f.root, { recursive: true, force: true }); }); diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -59,7 +59,9 @@ import { loadAudioIntegrity } from "../lib/audioIntegrity-server"; import { AUDIO_INTEGRITY_FILENAME, integrityMatches, + integrityVerdict, isDamagedIntegrity, + type AudioIntegrityVerdict, } from "../lib/audioIntegrity"; import { chatOnlyIdsFrom, @@ -106,6 +108,19 @@ export type ExcludedFromDownload = { private: string[]; }; +// The audio audit's verdicts over a channel's video dirs (release 32, lane +// R3): one count per audio-integrity.json — clean, damaged or undecodable by +// the rule in force (integrityVerdict), or stale when the record no longer +// speaks for the file (gone, or a different size). `lastCheckedAt` is the +// newest record's checkedAt. +export type AudioIntegrityTally = { + clean: number; + damaged: number; + undecodable: number; + stale: number; + lastCheckedAt?: string; +}; + export type ChannelSnapshot = { generatedAt: string; totals: { @@ -435,6 +450,9 @@ export type ChannelSnapshot = { // fifth gate: the real gate needs a live probe, and folding a guess into the // hero figure would move the sidebar badge and /cleanup's Est. reclaim too. reclaimableAtRiskBytes?: number; + // The audio audit's verdicts over the channel (release 32). Optional: older + // snapshots lack it; readers show nothing until the next regen. + audioIntegrity?: AudioIntegrityTally; }; // The four holds, in sweep order. Same shape for bytes and for counts. @@ -1037,13 +1055,22 @@ export async function generateChannelSnapshot( // file is gone or its size changed (the size is the lstat above; no // extra stat — an unknown size, a drive not answering, counts the name). let heldAudioDamaged = false; + // The record's standing for the channel's audit tally (release 32): + // its verdict by the rule in force, or stale when it no longer speaks + // for the file. + let integrityState: AudioIntegrityVerdict | "stale" | null = null; + let integrityCheckedAt: string | null = null; if (files.entries.includes(AUDIO_INTEGRITY_FILENAME)) { const integrity = await loadAudioIntegrity(dir); - heldAudioDamaged = + const current = integrity !== null && files.audioFiles.includes(integrity.file) && - integrityMatches(integrity, { name: integrity.file, size: audioSizes[integrity.file] }) && - isDamagedIntegrity(integrity); + integrityMatches(integrity, { name: integrity.file, size: audioSizes[integrity.file] }); + heldAudioDamaged = current && isDamagedIntegrity(integrity); + if (integrity) { + integrityState = current ? integrityVerdict(integrity) : "stale"; + integrityCheckedAt = integrity.checkedAt; + } } // Only transcribed (non-untranscribable) dirs can have a truncated // transcript; skip the cues.json read for everything else. @@ -1105,6 +1132,8 @@ export async function generateChannelSnapshot( outcome, salvaged, heldAudioDamaged, + integrityState, + integrityCheckedAt, coverage, vttProvenance, digest, @@ -1222,6 +1251,9 @@ export async function generateChannelSnapshot( const incompleteTranscript: string[] = []; const salvagedTranscript: string[] = []; const corruptHeldAudio: string[] = []; + // The audio audit's verdicts over the channel (release 32): every + // audio-integrity.json, by the rule in force. + const audioIntegrity: AudioIntegrityTally = { clean: 0, damaged: 0, undecodable: 0, stale: 0 }; const shortAudio: string[] = []; const autoSubsOnly: string[] = []; const downloadedAutoSubsOnly: string[] = []; @@ -1268,11 +1300,19 @@ export async function generateChannelSnapshot( outcome, salvaged, heldAudioDamaged, + integrityState, + integrityCheckedAt, coverage, vttProvenance, digest, } of perVideo) { if (isVideoTranscribed(files)) transcribed++; + if (integrityState) { + audioIntegrity[integrityState]++; + if (integrityCheckedAt && (!audioIntegrity.lastCheckedAt || integrityCheckedAt > audioIntegrity.lastCheckedAt)) { + audioIntegrity.lastCheckedAt = integrityCheckedAt; + } + } if (isVideoDownloaded(files)) downloaded++; totalMediaBytes += mediaBytes; totalTextBytes += textBytes; @@ -1810,6 +1850,7 @@ export async function generateChannelSnapshot( heldAudioBytes, heldAudioCounts, reclaimableAtRiskBytes, + audioIntegrity, }; await writeChannelSnapshot(paths, slug, snapshot); diff --git a/common/controller/frameCorrections.test.ts b/common/controller/frameCorrections.test.ts @@ -0,0 +1,115 @@ +// The video page's reading correction (release 32, lane R3), over a temp +// channel: the reading nearest a second (a duplicate shown as its copy), a +// save that keeps only what differs from the model's reading, a misread, a +// clear — each re-deriving at once, with no model and no frame. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { syntheticPokerHighlights } from "../testing/frames/pokerReadings.mjs"; +import { frameScanSidecar, loadFrameScan, type FrameScanRecord } from "../lib/frameScan-server"; +import type { Paths } from "../lib/paths"; +import { correctFrameReading, frameReadingAt } from "./frameCorrections"; + +const SLUG = "synth-channel"; +const ID = "vid1"; +const fx = syntheticPokerHighlights(); +const NOW = () => new Date("2026-10-16T12:00:00Z"); + +async function setup(): Promise<{ paths: Paths; videoDir: string; done: () => Promise<void> }> { + const root = await mkdtemp(path.join(os.tmpdir(), "frame-corrections-")); + const channelsDir = path.join(root, "channels"); + const videoDir = path.join(channelsDir, SLUG, "data", ID); + await mkdir(videoDir, { recursive: true }); + // 2905 is a duplicate of the read frame at 2900. + const rec = { + format: "archilyzer-frame-scan", + version: 1, + profile: "poker", + source: { savedVideo: "source-media.mp4", durationSeconds: 3000 }, + sampling: { everySeconds: 10, from: 0, to: 3000, width: 1280, keyframesOnly: true, frames: 300, kept: 299, skippedDuplicates: 1 }, + model: { route: "api", model: "claude-haiku-4-5", promptVersion: 3 }, + hints: { hero: fx.hero }, + costUsd: 0.5, + runs: [], + readings: fx.readings, + duplicates: [[2905, 2900]], + spoken: fx.spoken, + derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] }, + updatedAt: "2026-10-15T00:00:00Z", + } as unknown as FrameScanRecord; + await frameScanSidecar("poker").write(videoDir, rec); + return { paths: { channelsDir } as Paths, videoDir, done: () => rm(root, { recursive: true, force: true }) }; +} + +test("frameReadingAt: the nearest reading, its fields as read and as used, the seconds either side; refusals", async () => { + const { paths, done } = await setup(); + try { + const r = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 1003 }); + assert.ok(r.ok, JSON.stringify(r)); + assert.equal(r.view.t, 1000); + assert.equal(r.view.prev, 990); + assert.equal(r.view.next, 1010); + assert.equal(r.view.copyOf, null); + const stack = r.view.fields.find((f) => f.path === "hero.stack")!; + assert.equal(stack.read, 0); + assert.equal(stack.value, 0); + assert.equal(stack.corrected, false); + const dup = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 2906 }); + assert.ok(dup.ok); + assert.equal(dup.view.t, 2905); + assert.equal(dup.view.copyOf, 2900); + assert.equal(dup.view.prev, 2900); + assert.match(((await frameReadingAt(paths, { slug: SLUG, id: "nope", t: 1 })) as { error: string }).error, /has no frame-scan\.poker\.json/); + assert.match(((await frameReadingAt(paths, { slug: "../x", id: ID, t: 1 })) as { error: string }).error, /channel slug/); + } finally { + await done(); + } +}); + +test("correctFrameReading: only what differs is kept; the derivation uses it at once; a misread; a clear; the model's reading untouched", async () => { + const { paths, videoDir, done } = await setup(); + try { + const before = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 1500 }); + assert.ok(before.ok); + // The form sends every field; only the stack differs. + const set = Object.fromEntries(before.view.fields.map((f) => [f.path, f.value])); + set["hero.stack"] = "133,333"; + const saved = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set }, { now: NOW }); + assert.ok(saved.ok, JSON.stringify(saved)); + assert.deepEqual(saved.correction, { t: 1500, at: "2026-10-16T12:00:00.000Z", by: "person", set: { "hero.stack": 133333 } }); + assert.equal(saved.view.fields.find((f) => f.path === "hero.stack")!.corrected, true); + let rec = (await loadFrameScan(videoDir, "poker"))!; + assert.deepEqual(rec.corrections, [saved.correction]); + assert.equal((rec.readings.find((r) => r.t === 1500)!.hero as { stack: number }).stack, 120000, "the model's reading stays as read"); + assert.equal(rec.rederivedAt, "2026-10-16T12:00:00.000Z"); + assert.ok(rec.derived.tournaments.length >= 1, "derived again"); + + // The reading at 2900 set aside (its duplicate at 2905 with it). + const mis = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 2900, misread: true, note: "not the hero's seat" }, { now: NOW }); + assert.ok(mis.ok); + assert.equal(mis.view.misread, true); + const dup = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 2905 }); + assert.ok(dup.ok && dup.view.misread, "a duplicate of a misread is set aside too"); + rec = (await loadFrameScan(videoDir, "poker"))!; + assert.deepEqual(rec.corrections!.map((c) => c.t), [1500, 2900]); + assert.ok(rec.derived.events.every((e) => e.t !== 2900), JSON.stringify(rec.derived.events.filter((e) => e.t >= 2890))); + + // A save that differs in nothing removes the correction; a clear does too. + const same = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set: { "hero.stack": 120000 } }, { now: NOW }); + assert.ok(same.ok && same.correction === null); + const cleared = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 2900, clear: true }, { now: NOW }); + assert.ok(cleared.ok); + rec = (await loadFrameScan(videoDir, "poker"))!; + assert.equal(rec.corrections, undefined); + + // Refusals. + assert.match(((await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1234, misread: true })) as { error: string }).error, /no frame was read at 1234 s/); + assert.match(((await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set: { "hero.stack": -5 } })) as { error: string }).error, /Hero stack/); + assert.match(((await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set: { bogus: 1 } })) as { error: string }).error, /"bogus" is not a field/); + } finally { + await done(); + } +}); diff --git a/common/controller/frameCorrections.ts b/common/controller/frameCorrections.ts @@ -0,0 +1,198 @@ +// A PERSON CORRECTS A FRAME READING, with no model (release 32, lane R3): the +// video page's Frame scan panel opens the reading at a second, shows what the +// model read beside what the derivation now uses, and saves the person's +// values (or "misread") into the sidecar's `corrections` +// (lib/frames/corrections.ts) — then works `derived` out again at once, as +// `frame-scan {rederive: true}` does. Never while a scan of the video is +// queued or running (it writes the same sidecar). +// +// Only what differs from the model's reading is stored, so a form may send +// every field it shows; a save that differs in nothing (and is not a misread) +// removes the correction. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { frameScanSidecar, type FrameScanRecord } from "../lib/frameScan-server"; +import { isFrameProfile } from "../lib/frames/profiles"; +import { rederiveRecord } from "../lib/frames/scan"; +import { + CorrectionInputError, + checkCorrectionSet, + correctableFields, + correctedReading, + readField, + upsertCorrection, + type CorrectableField, + type CorrectionValue, + type ReadingCorrection, +} from "../lib/frames/corrections"; +import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; +import { frameScanBusy, loadCues, rederivedSummary, type FrameScanRederived } from "./frameScan"; + +type Reading = FrameScanRecord["readings"][number]; + +export type FrameReadingField = CorrectableField & { + // What the model read (undefined: not shown), and what the derivation uses. + read: CorrectionValue; + value: CorrectionValue; + corrected: boolean; +}; + +export type FrameReadingView = { + profile: string; + t: number; + // A duplicate frame: the read frame it copies. + copyOf: number | null; + correction: ReadingCorrection | null; + misread: boolean; + fields: FrameReadingField[]; + // The grid seconds before and after, for stepping. + prev: number | null; + next: number | null; +}; + +const norm = (v: unknown): CorrectionValue => (v === undefined || v === "" ? null : (v as CorrectionValue)); +const same = (a: unknown, b: unknown) => JSON.stringify(norm(a)) === JSON.stringify(norm(b)); + +function gridOf(rec: FrameScanRecord): number[] { + const ts = new Set<number>(rec.readings.map((r) => r.t)); + for (const [t] of rec.duplicates ?? []) ts.add(t); + return [...ts].sort((a, b) => a - b); +} + +// The model's reading at `t` (a duplicate's is its source's, at `t`). +function modelReadingAt(rec: FrameScanRecord, t: number): { reading: Reading; copyOf: number | null } | null { + const byT = new Map(rec.readings.map((r) => [r.t, r])); + const own = byT.get(t); + if (own) return { reading: own, copyOf: null }; + const dup = (rec.duplicates ?? []).find(([d]) => d === t); + const src = dup ? byT.get(dup[1]) : undefined; + return src ? { reading: { ...src, t }, copyOf: dup![1] } : null; +} + +function videoDirOf(paths: Paths, slug: string, id: string): string { + return path.join(paths.channelsDir, slug, "data", id); +} + +function checkRef(o: { slug: unknown; id: unknown; profile?: unknown }): { slug: string; id: string; profile: string } { + if (typeof o.slug !== "string" || !isSafeChannelSegment(o.slug)) throw new CorrectionInputError(`"slug" must be a channel slug`); + if (typeof o.id !== "string" || !isSafeIdSegment(o.id)) throw new CorrectionInputError(`"id" must be a video id`); + const profile = o.profile ?? "poker"; + if (!isFrameProfile(profile)) throw new CorrectionInputError(`"${String(profile)}" is not a frame-scan profile`); + return { slug: o.slug, id: o.id, profile }; +} + +function viewOf(rec: FrameScanRecord, t: number): FrameReadingView | null { + const model = modelReadingAt(rec, t); + if (!model) return null; + // The derivation lays a correction made at a copy's second, or at its + // source's, over the copy (deriveOf); the panel shows the same. + const corrections = rec.corrections ?? []; + const own = corrections.find((c) => c.t === t) ?? null; + const fromSource = model.copyOf !== null ? (corrections.find((c) => c.t === model.copyOf) ?? null) : null; + let effective: Reading | null = model.reading; + if (fromSource) effective = effective && correctedReading(effective, fromSource); + if (own) effective = effective && correctedReading(effective, own); + const grid = gridOf(rec); + const i = grid.indexOf(t); + return { + profile: rec.profile, + t, + copyOf: model.copyOf, + correction: own, + misread: effective === null, + fields: correctableFields(rec.profile).map((f) => { + const read = norm(readField(model.reading, f.path)); + const value = effective ? norm(readField(effective, f.path)) : read; + return { ...f, read, value, corrected: !same(read, value) }; + }), + prev: i > 0 ? grid[i - 1]! : null, + next: i >= 0 && i < grid.length - 1 ? grid[i + 1]! : null, + }; +} + +/** The reading nearest `t` (a read frame or a duplicate), as the panel shows it. */ +export async function frameReadingAt( + paths: Paths, + raw: { slug: unknown; id: unknown; profile?: unknown; t: unknown }, +): Promise<{ ok: true; view: FrameReadingView } | { ok: false; error: string }> { + let ref; + try { + ref = checkRef(raw); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const t = typeof raw.t === "number" ? raw.t : Number(raw.t); + if (!Number.isFinite(t) || t < 0) return { ok: false, error: "give a time, in seconds or h:mm:ss" }; + const sidecar = frameScanSidecar(ref.profile); + const rec = await sidecar.load(videoDirOf(paths, ref.slug, ref.id)); + if (!rec) return { ok: false, error: `${ref.slug}/${ref.id} has no ${sidecar.filename}` }; + const grid = gridOf(rec); + if (grid.length === 0) return { ok: false, error: "the scan holds no readings" }; + const nearest = grid.reduce((best, x) => (Math.abs(x - t) < Math.abs(best - t) ? x : best), grid[0]!); + return { ok: true, view: viewOf(rec, nearest)! }; +} + +export type CorrectFrameReadingResult = + | { ok: true; correction: ReadingCorrection | null; view: FrameReadingView; rederived: FrameScanRederived } + | { ok: false; error: string }; + +/** + * Save a person's correction of the reading at `t` and re-derive. + * set field → value (every field a form shows may be sent; only the + * ones that differ from the model's reading are kept) + * misread the whole reading set aside + * clear the correction at `t` removed + */ +export async function correctFrameReading( + paths: Paths, + raw: { slug: unknown; id: unknown; profile?: unknown; t: unknown; set?: unknown; misread?: unknown; clear?: unknown; note?: unknown }, + o: { now?: () => Date } = {}, +): Promise<CorrectFrameReadingResult> { + let ref; + let set: Record<string, CorrectionValue> | undefined; + try { + ref = checkRef(raw); + set = checkCorrectionSet(ref.profile, raw.set); + if (raw.misread !== undefined && typeof raw.misread !== "boolean") throw new CorrectionInputError(`"misread" is true or false`); + if (raw.clear !== undefined && typeof raw.clear !== "boolean") throw new CorrectionInputError(`"clear" is true or false`); + if (raw.note !== undefined && typeof raw.note !== "string") throw new CorrectionInputError(`"note" is text`); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const t = typeof raw.t === "number" ? raw.t : NaN; + if (!Number.isFinite(t)) return { ok: false, error: `"t" is the reading's second` }; + if (frameScanBusy(ref.slug, ref.id)) { + return { ok: false, error: `a frame scan of ${ref.slug}/${ref.id} is queued or running — correct it when the scan is done (it writes the sidecar)` }; + } + const videoDir = videoDirOf(paths, ref.slug, ref.id); + const sidecar = frameScanSidecar(ref.profile); + const rec = await sidecar.load(videoDir); + if (!rec) return { ok: false, error: `${ref.slug}/${ref.id} has no ${sidecar.filename} — scan it first` }; + const model = modelReadingAt(rec, t); + if (!model) return { ok: false, error: `no frame was read at ${t} s` }; + + let correction: ReadingCorrection | null = null; + if (raw.clear !== true) { + const diff: Record<string, CorrectionValue> = {}; + for (const [p, v] of Object.entries(set ?? {})) if (!same(readField(model.reading, p), v)) diff[p] = v; + const note = typeof raw.note === "string" ? raw.note.replace(/\s+/g, " ").trim().slice(0, 300) : ""; + if (raw.misread === true || Object.keys(diff).length > 0) { + correction = { + t, + at: (o.now ?? (() => new Date()))().toISOString(), + by: "person", + ...(raw.misread === true ? { misread: true as const } : {}), + ...(Object.keys(diff).length ? { set: diff } : {}), + ...(note ? { note } : {}), + }; + } + } + const corrections = upsertCorrection(rec.corrections, t, correction); + const withCorrections: FrameScanRecord = { ...rec, corrections }; + if (!corrections.length) delete withCorrections.corrections; + const cues = await loadCues(videoDir); + const out = rederiveRecord(withCorrections, { ...(cues ? { cues } : {}), ...(o.now ? { now: o.now } : {}) }); + await sidecar.write(videoDir, out); + return { ok: true, correction, view: viewOf(out, t)!, rederived: rederivedSummary(rec, out, sidecar.filename) }; +} diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -196,6 +196,13 @@ export function rederivedSummary(before: FrameScanRecord, after: FrameScanRecord }; } +/** Is a frame scan of this video queued or running? (It writes the sidecar.) */ +export function frameScanBusy(slug: string, id: string): boolean { + return getRegistry() + .list() + .some((j) => j.kind === FRAME_SCAN_JOB_KIND && j.channelSlug === slug && j.videoId === id && (j.status === "queued" || j.status === "running")); +} + /** A video's cues (`transcript.cues.json`), sorted, or undefined. */ export async function loadCues(videoDir: string): Promise<Cue[] | undefined> { try { @@ -225,10 +232,7 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame return { evicted: { dir: cacheDir, removed: await removeFrameCache(cacheDir), bytes } }; } if (body.rederive) { - const busy = getRegistry() - .list() - .some((j) => j.kind === FRAME_SCAN_JOB_KIND && j.channelSlug === body.slug && j.videoId === body.id && (j.status === "queued" || j.status === "running")); - if (busy) return refuse(`a frame scan of ${body.slug}/${body.id} is queued or running — re-derive when it is done (it writes the sidecar)`); + if (frameScanBusy(body.slug, body.id)) return refuse(`a frame scan of ${body.slug}/${body.id} is queued or running — re-derive when it is done (it writes the sidecar)`); const sidecar = frameScanSidecar(body.profile); const rec = await sidecar.load(videoDir); if (!rec) return refuse(`${body.slug}/${body.id} has no ${sidecar.filename} to re-derive — scan it first`); diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -105,6 +105,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "find-copy": { label: "Find copies", drainable: false }, // fetch-copies (release 31): gone videos' whole audio from their copies. "fetch-copies": { label: "Fetch copies", drainable: true }, + // An article's own video (release 32): one remux or encode. + "attach-report-video": { label: "Attach article video", drainable: false }, }; test("added kinds carry their pinned label and drainability", () => { diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -885,6 +885,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = { needsMedia: false, needsText: true, }, + // AN ARTICLE'S OWN VIDEO (release 32, the Articles tab's "Attach video"; + // `archilyzer reports attach-video --article` before it): a file the + // operator names, remuxed or encoded to fit the publish limit, written + // beside the article's report.json as video.mp4 with a poster, and `video` + // set through the article registry. Reads a file outside any channel, so no + // media guard. Its own queue (`report-video`): one encode at a time. Not + // replayable: the file is a path on some drive. + "attach-report-video": { + kind: "attach-report-video", + label: "Attach article video", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + needsMedia: false, + }, // THE PER-VIDEO WRITERS THAT WERE NOT IN THIS TABLE (release 16 slice RM). // Each runs with a channelSlug and writes under `data/<id>/` — a single // video's transcription (the video page's two Transcribe buttons, and its diff --git a/common/lib/frameScan-server.ts b/common/lib/frameScan-server.ts @@ -18,6 +18,7 @@ import { lstat } from "node:fs/promises"; import { sidecar, sidecarField, type Sidecar } from "./sidecar-server"; import { FRAME_PROFILE_IDS } from "./frames/profiles"; import { FRAME_SCAN_FORMAT, type Derived, type SpokenReading } from "./frames/types"; +import { coerceCorrections, type ReadingCorrection } from "./frames/corrections"; export const frameScanFilename = (profile: string) => `frame-scan.${profile}.json`; @@ -52,6 +53,9 @@ export type FrameScanRecord = { updatedAt: string; // When `derived` was last worked out again from the readings (no model). rederivedAt?: string; + // A person's corrections of readings (release 32, lib/frames/corrections.ts): + // kept beside the model's readings, laid over them by the derivation. + corrections?: ReadingCorrection[]; }; const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v); @@ -61,8 +65,12 @@ export function coerceFrameScan(v: unknown): FrameScanRecord | null { if (!Array.isArray(v.readings) || !isObj(v.derived) || !isObj(v.sampling) || !isObj(v.source)) return null; const d = v.derived as Record<string, unknown>; if (!Array.isArray(d.tournaments) || !Array.isArray(d.events) || !Array.isArray(d.segments)) return null; + const corrections = coerceCorrections(v.corrections); + const { corrections: _raw, ...rest } = v as Record<string, unknown>; + void _raw; return { - ...(v as unknown as FrameScanRecord), + ...(rest as unknown as FrameScanRecord), + ...(corrections.length ? { corrections } : {}), runs: Array.isArray(v.runs) ? (v.runs as FrameScanRun[]) : [], spoken: Array.isArray(v.spoken) ? (v.spoken as SpokenReading[]) : [], duplicates: Array.isArray(v.duplicates) ? (v.duplicates as [number, number][]).filter((p) => Array.isArray(p) && p.length === 2) : [], diff --git a/common/lib/frames/corrections.test.ts b/common/lib/frames/corrections.test.ts @@ -0,0 +1,126 @@ +// A person's corrections of frame readings (release 32, lane R3): checked by +// field kind, laid over the readings by the derivation (the person's value +// wins; a misread is set aside, and its duplicates with it), kept across a +// re-derive, and never written over the model's readings. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { syntheticPokerHighlights } from "../../testing/frames/pokerReadings.mjs"; +import { derivePoker, type PokerReading } from "./poker"; +import { deriveOf, rederiveRecord } from "./scan"; +import { + CorrectionInputError, + applyCorrections, + checkCorrectionSet, + coerceCorrections, + upsertCorrection, + type ReadingCorrection, +} from "./corrections"; +import { coerceFrameScan, type FrameScanRecord } from "../frameScan-server"; + +type R = PokerReading & { t: number }; +const fx = syntheticPokerHighlights(); +const AT = "2026-10-16T00:00:00.000Z"; +const person = (t: number, more: Partial<ReadingCorrection>): ReadingCorrection => ({ t, at: AT, by: "person", ...more }); + +test("checkCorrectionSet: each field by its kind; unknown fields and bad values refused with the field's name", () => { + assert.deepEqual(checkCorrectionSet("poker", { "hero.stack": "12,400", "tournament.playersLeft": 85, phase: "table", "hero.cards": "as kd", log: "a\n\n b " }), { + "hero.stack": 12400, + "tournament.playersLeft": 85, + phase: "table", + "hero.cards": ["As", "Kd"], + log: ["a", "b"], + }); + assert.deepEqual(checkCorrectionSet("poker", { "hand.pot": "", "tournament.name": " Synth Cup " }), { "hand.pot": null, "tournament.name": "Synth Cup" }); + assert.equal(checkCorrectionSet("poker", {}), undefined); + assert.throws(() => checkCorrectionSet("poker", { "hero.name": "x" }), CorrectionInputError); + assert.throws(() => checkCorrectionSet("poker", { "hero.stack": -1 }), /Hero stack: a number/); + assert.throws(() => checkCorrectionSet("poker", { "tournament.playersLeft": 8.5 }), /Players left: a whole number/); + assert.throws(() => checkCorrectionSet("poker", { phase: null }), /Phase: is required/); + assert.throws(() => checkCorrectionSet("poker", { phase: "dealing" }), /Phase: one of/); + assert.throws(() => checkCorrectionSet("poker", { "hero.cards": "Ax" }), /"Ax" is not a card/); +}); + +test("applyCorrections: a set field takes the person's value, null removes it, a misread is dropped; idempotent", () => { + const rs: R[] = [ + { t: 0, phase: "table", hero: { stack: 100 }, tournament: { playersLeft: 9 } }, + { t: 10, phase: "table", hero: { stack: 999999 } }, + { t: 20, phase: "lobby" }, + ]; + const cs = [person(0, { set: { "tournament.playersLeft": null, "tournament.blinds.bb": 200 } }), person(10, { misread: true }), person(20, { set: { phase: "break" } })]; + const once = applyCorrections(rs, cs); + assert.deepEqual(once, [ + { t: 0, phase: "table", hero: { stack: 100 }, tournament: { blinds: { bb: 200 } } }, + { t: 20, phase: "break" }, + ]); + assert.deepEqual(applyCorrections(once, cs), once); + // The model's readings are untouched. + assert.deepEqual(rs[0].tournament, { playersLeft: 9 }); + // A cleared field that leaves its object empty takes the object with it. + assert.deepEqual(applyCorrections([{ t: 5, phase: "table", hero: { stack: 1 } }], [person(5, { set: { "hero.stack": null } })]), [{ t: 5, phase: "table" }]); +}); + +test("deriveOf: the derivation over the corrected readings is the derivation of the readings as the person says they are", () => { + const readings = fx.readings as R[]; + const cs: ReadingCorrection[] = []; + for (let t = 1500; t < 1600; t += 10) cs.push(person(t, { set: { "hero.stack": 133333 } })); + cs.push(person(2900, { misread: true })); + const byHand = readings + .filter((r) => r.t !== 2900) + .map((r) => (r.t >= 1500 && r.t < 1600 ? { ...r, hero: { ...(r.hero ?? {}), stack: 133333 } } : r)); + const o = { everySeconds: 10, hero: fx.hero }; + const got = deriveOf("poker", readings, [], fx.spoken, { ...o, corrections: cs }); + assert.deepEqual(got, derivePoker(byHand, fx.spoken, o)); + assert.notDeepEqual(got, deriveOf("poker", readings, [], fx.spoken, o)); + assert.ok(got.tournaments[0].series.stack.some(([t, v]) => t === 1500 && v === 133333), "the person's stack is in the series"); +}); + +test("deriveOf: a duplicate copies the corrected reading; a misread is copied nowhere; a correction at the duplicate's own second applies to it", () => { + const rs: R[] = [ + { t: 0, phase: "table", hero: { stack: 100 } }, + { t: 10, phase: "table", hero: { stack: 200 } }, + ]; + const dups: [number, number][] = [[20, 10], [30, 0]]; + const seen: R[][] = []; + const spy = (cs: ReadingCorrection[]) => { + const corrected = applyCorrections(rs, cs); + const byT = new Map(corrected.map((r) => [r.t, r])); + const copies = dups.flatMap(([t, s]) => (byT.get(s) ? [{ ...byT.get(s)!, t }] : [])); + seen.push(applyCorrections([...corrected, ...copies], cs).sort((a, b) => a.t - b.t)); + return deriveOf("poker", rs, dups, [], { everySeconds: 10, corrections: cs }); + }; + const a = spy([person(10, { set: { "hero.stack": 250 } }), person(0, { misread: true }), person(20, { set: { "hero.stack": 260 } })]); + assert.deepEqual(seen[0], [ + { t: 10, phase: "table", hero: { stack: 250 } }, + { t: 20, phase: "table", hero: { stack: 260 } }, + ]); + assert.deepEqual(a, derivePoker(seen[0], [], { everySeconds: 10 })); +}); + +test("the sidecar keeps the corrections (one per second, the newest) and a re-derive applies them", () => { + const rec = { + format: "archilyzer-frame-scan", + version: 1, + profile: "poker", + source: { savedVideo: "source-media.mp4", durationSeconds: 3000 }, + sampling: { everySeconds: 10, from: 0, to: 3000, width: 1280, keyframesOnly: true, frames: 300, kept: 300, skippedDuplicates: 0 }, + model: { route: "api", model: "claude-haiku-4-5", promptVersion: 3 }, + hints: { hero: fx.hero }, + costUsd: 0, + runs: [], + readings: fx.readings, + duplicates: [], + spoken: fx.spoken, + derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] }, + updatedAt: AT, + corrections: [person(2900, { set: { "hero.stack": 5 } }), person(2900, { misread: true }), { t: "x" }, { t: 5, at: AT, by: "person" }], + }; + const coerced = coerceFrameScan(rec) as FrameScanRecord; + assert.deepEqual(coerced.corrections, [person(2900, { misread: true })]); + const out = rederiveRecord(coerced); + assert.deepEqual(out.corrections, coerced.corrections); + assert.deepEqual(out.derived, derivePoker((fx.readings as R[]).filter((r) => r.t !== 2900), fx.spoken, { everySeconds: 10, durationSeconds: 3000, hero: fx.hero })); + assert.equal(out.readings.length, fx.readings.length, "the model's readings are kept as read"); + assert.deepEqual(coerceCorrections(undefined), []); + assert.deepEqual(upsertCorrection([person(1, { misread: true }), person(3, { misread: true })], 1, null), [person(3, { misread: true })]); +}); diff --git a/common/lib/frames/corrections.ts b/common/lib/frames/corrections.ts @@ -0,0 +1,228 @@ +// A PERSON'S CORRECTION OF A FRAME READING (release 32, lane R3): a scan can +// be fixed with no model. A vision model read each kept frame into a reading; +// where it read a field wrong (a stack off by a digit, the wrong players-left +// number, a blinds line misread), a person sets the field to what the frame +// shows, or sets the whole reading aside as a misread. The correction is kept +// BESIDE the model's readings in the sidecar (`corrections`), never written +// over them, and the derivation reads the readings with the corrections laid +// over them — the person's value wins. The derivation's own rules are +// unchanged (P2's guarantees: a flagged reading makes no event, one +// tournament until a confirmed bust), so a corrected value goes through the +// same smoothing a read one does. +// +// Pure: types, the per-profile field table, the check and the overlay. + +import { POKER_FRAME_EVENTS, POKER_PHASES } from "./poker"; + +export type CorrectionValue = number | string | string[] | null; + +export type ReadingCorrection = { + // The grid second of the reading (a read frame's, or a duplicate's). + t: number; + // When the person saved it (ISO). + at: string; + by: "person"; + // The whole reading set aside: the derivation never sees it (nor a + // duplicate that copies it). + misread?: true; + // Field path → the value the frame shows; null: the frame does not show it. + set?: Record<string, CorrectionValue>; + note?: string; +}; + +export type CorrectableField = { + path: string; + label: string; + kind: "whole" | "number" | "text" | "lines" | "cards" | "enum"; + options?: readonly string[]; + // phase is the one a reading must have. + required?: boolean; +}; + +// The fields a person may correct, per profile, in the order a form shows them. +export const CORRECTABLE_FIELDS: Readonly<Record<string, readonly CorrectableField[]>> = { + poker: [ + { path: "phase", label: "Phase", kind: "enum", options: POKER_PHASES, required: true }, + { path: "tournament.name", label: "Tournament", kind: "text" }, + { path: "tournament.level", label: "Level", kind: "whole" }, + { path: "tournament.blinds.sb", label: "Small blind", kind: "number" }, + { path: "tournament.blinds.bb", label: "Big blind", kind: "number" }, + { path: "tournament.blinds.ante", label: "Ante", kind: "number" }, + { path: "tournament.playersLeft", label: "Players left", kind: "whole" }, + { path: "tournament.totalPlayers", label: "Field", kind: "whole" }, + { path: "tournament.position", label: "Position", kind: "whole" }, + { path: "tournament.averageStack", label: "Average stack", kind: "whole" }, + { path: "tournament.prizePool", label: "Prize pool", kind: "number" }, + { path: "tournament.payout", label: "Payout", kind: "number" }, + { path: "hero.stack", label: "Hero stack", kind: "whole" }, + { path: "hero.bb", label: "Hero stack (big blinds)", kind: "number" }, + { path: "hero.bounty", label: "Hero bounty", kind: "number" }, + { path: "hero.cards", label: "Hero cards", kind: "cards" }, + { path: "hand.pot", label: "Pot", kind: "whole" }, + { path: "hand.action", label: "Action", kind: "text" }, + { path: "event", label: "Event", kind: "enum", options: POKER_FRAME_EVENTS }, + { path: "log", label: "Log lines", kind: "lines" }, + ], +}; + +export function correctableFields(profile: string): readonly CorrectableField[] { + return CORRECTABLE_FIELDS[profile] ?? []; +} + +export class CorrectionInputError extends Error { + constructor(message: string) { + super(message); + this.name = "CorrectionInputError"; + } +} + +const CARD = /^(?:[2-9TJQKA])[shdc]$/; +const MAX_NUMBER = 1e12; + +// One field's value, checked against its kind. null clears the field (not shown). +export function checkCorrectionValue(field: CorrectableField, v: unknown): CorrectionValue { + const fail = (m: string): never => { + throw new CorrectionInputError(`${field.label}: ${m}`); + }; + if (v === null || v === undefined || v === "") { + if (field.required) fail("is required"); + return null; + } + switch (field.kind) { + case "whole": + case "number": { + const n = typeof v === "number" ? v : typeof v === "string" ? Number(v.replace(/[,\s]/g, "")) : NaN; + if (!Number.isFinite(n) || n < 0 || n > MAX_NUMBER) fail("a number, 0 or more"); + if (field.kind === "whole" && !Number.isInteger(n)) fail("a whole number"); + return n; + } + case "text": { + if (typeof v !== "string") fail("text"); + const s = (v as string).replace(/\s+/g, " ").trim().slice(0, 200); + return s || null; + } + case "enum": { + if (typeof v !== "string" || !(field.options ?? []).includes(v)) fail(`one of ${(field.options ?? []).join(", ")}`); + return v as string; + } + case "lines": { + const list = Array.isArray(v) ? v : typeof v === "string" ? v.split("\n") : null; + if (!list || list.some((l) => typeof l !== "string")) fail("lines of text"); + const out = (list as string[]).map((l) => l.replace(/\s+/g, " ").trim().slice(0, 300)).filter(Boolean); + if (out.length > 40) fail("at most 40 lines"); + return out.length ? out : null; + } + case "cards": { + const list = Array.isArray(v) ? v : typeof v === "string" ? v.split(/[\s,]+/) : null; + if (!list || list.some((c) => typeof c !== "string")) fail("cards like As Kd"); + const out = (list as string[]).filter(Boolean).map((c) => (c.length === 2 ? c[0].toUpperCase() + c[1].toLowerCase() : c)); + const bad = out.find((c) => !CARD.test(c)); + if (bad) fail(`"${bad}" is not a card (rank then suit: As, Td, 9c)`); + if (new Set(out).size !== out.length) fail("a card twice"); + if (out.length > 6) fail("at most 6 cards"); + return out.length ? out : null; + } + } +} + +// The `set` of a correction, checked: only the profile's fields, each value by +// its kind. Empty → undefined. +export function checkCorrectionSet(profile: string, raw: unknown): Record<string, CorrectionValue> | undefined { + if (raw === undefined || raw === null) return undefined; + if (typeof raw !== "object" || Array.isArray(raw)) throw new CorrectionInputError(`"set" is an object of field → value`); + const fields = new Map(correctableFields(profile).map((f) => [f.path, f])); + const out: Record<string, CorrectionValue> = {}; + for (const [k, v] of Object.entries(raw as Record<string, unknown>)) { + const f = fields.get(k); + if (!f) throw new CorrectionInputError(`"${k}" is not a field a ${profile} reading has (${[...fields.keys()].join(", ")})`); + out[k] = checkCorrectionValue(f, v); + } + return Object.keys(out).length ? out : undefined; +} + +/** A reading's value at a dotted path (undefined when absent). */ +export function readField(reading: Record<string, unknown>, p: string): unknown { + let cur: unknown = reading; + for (const k of p.split(".")) { + if (!cur || typeof cur !== "object" || Array.isArray(cur)) return undefined; + cur = (cur as Record<string, unknown>)[k]; + } + return cur; +} + +// A copy of `reading` with `p` set (or, for null, removed — and an object left +// empty removed with it). +function writeField<T extends Record<string, unknown>>(reading: T, p: string, v: CorrectionValue): T { + const keys = p.split("."); + const root: Record<string, unknown> = { ...reading }; + const chain: Record<string, unknown>[] = [root]; + let cur = root; + for (const k of keys.slice(0, -1)) { + const next = cur[k]; + const copy = next && typeof next === "object" && !Array.isArray(next) ? { ...(next as Record<string, unknown>) } : {}; + cur[k] = copy; + cur = copy; + chain.push(cur); + } + const last = keys[keys.length - 1]!; + if (v === null) delete cur[last]; + else cur[last] = Array.isArray(v) ? [...v] : v; + // Prune objects the clear left empty, innermost first. + for (let i = chain.length - 1; i > 0; i--) { + if (Object.keys(chain[i]!).length === 0) delete chain[i - 1]![keys[i - 1]!]; + } + return root as T; +} + +/** One reading with a correction laid over it; null when it is set aside. */ +export function correctedReading<T extends { t: number; phase: string }>(reading: T, c: ReadingCorrection | undefined): T | null { + if (!c) return reading; + if (c.misread) return null; + let out = reading; + for (const [p, v] of Object.entries(c.set ?? {})) out = writeField(out, p, v); + return out; +} + +/** + * Readings with the person's corrections laid over them (by `t`): a misread is + * dropped, a set field takes the person's value. Idempotent — applying the + * same corrections again changes nothing — so a scan can apply them before + * and after it expands its duplicates. + */ +export function applyCorrections<T extends { t: number; phase: string }>(readings: readonly T[], corrections: readonly ReadingCorrection[] | undefined): T[] { + if (!corrections?.length) return [...readings]; + const byT = new Map(corrections.map((c) => [c.t, c])); + const out: T[] = []; + for (const r of readings) { + const c = correctedReading(r, byT.get(r.t)); + if (c) out.push(c); + } + return out; +} + +/** Corrections as stored: well-formed ones only, one per t (the newest), sorted. */ +export function coerceCorrections(v: unknown): ReadingCorrection[] { + if (!Array.isArray(v)) return []; + const byT = new Map<number, ReadingCorrection>(); + for (const c of v) { + if (!c || typeof c !== "object" || typeof (c as ReadingCorrection).t !== "number" || !Number.isFinite((c as ReadingCorrection).t)) continue; + const x = c as ReadingCorrection; + const set = x.set && typeof x.set === "object" && !Array.isArray(x.set) ? x.set : undefined; + if (!x.misread && !set) continue; + byT.set(x.t, { + t: x.t, + at: typeof x.at === "string" ? x.at : "", + by: "person", + ...(x.misread ? { misread: true as const } : {}), + ...(set ? { set } : {}), + ...(typeof x.note === "string" && x.note ? { note: x.note } : {}), + }); + } + return [...byT.values()].sort((a, b) => a.t - b.t); +} + +/** The corrections with `c` in place of any at its t (or, for `null` at t, without it). */ +export function upsertCorrection(list: readonly ReadingCorrection[] | undefined, t: number, c: ReadingCorrection | null): ReadingCorrection[] { + const rest = (list ?? []).filter((x) => x.t !== t); + return (c ? [...rest, c] : rest).sort((a, b) => a.t - b.t); +} diff --git a/common/lib/frames/scan.ts b/common/lib/frames/scan.ts @@ -22,6 +22,7 @@ import { frameProfile } from "./profiles"; import { probeDuration, sampleFrames, type Crop, type FrameIndex } from "./sample-server"; import { FRAME_SCAN_FORMAT, type Cue, type Derived, type FrameRef, type SpokenReading } from "./types"; import type { FrameScanRecord, FrameScanRun } from "../frameScan-server"; +import { applyCorrections, type ReadingCorrection } from "./corrections"; export const DEFAULT_EVERY_SECONDS = 10; export const DEFAULT_MAX_FRAMES = 5000; @@ -120,15 +121,20 @@ export function deriveOf( readings: FrameScanRecord["readings"], duplicates: readonly [number, number][], spoken: SpokenReading[], - o: { everySeconds: number; durationSeconds?: number | null; hero?: string }, + o: { everySeconds: number; durationSeconds?: number | null; hero?: string; corrections?: readonly ReadingCorrection[] }, ): Derived { const profile = frameProfile(profileId); - const byT = new Map(readings.map((r) => [r.t, r])); + // A person's corrections (release 32) first, so a duplicate copies the + // corrected reading (and a reading set aside is copied nowhere); then again + // over the copies, for a correction made at a duplicate's own second. + const corrected = applyCorrections(readings, o.corrections); + const byT = new Map(corrected.map((r) => [r.t, r])); + const read = new Set(readings.map((r) => r.t)); const copies = duplicates.flatMap(([t, src]) => { const r = byT.get(src); - return r && !byT.has(t) ? [{ ...r, t }] : []; + return r && !read.has(t) ? [{ ...r, t }] : []; }); - const expanded = [...readings, ...copies].sort((a, b) => a.t - b.t); + const expanded = applyCorrections([...corrected, ...copies], o.corrections).sort((a, b) => a.t - b.t); return profile.derive(expanded as never, spoken, { everySeconds: o.everySeconds, ...(o.durationSeconds !== null && o.durationSeconds !== undefined ? { durationSeconds: o.durationSeconds } : {}), @@ -155,6 +161,7 @@ export function rederiveRecord(rec: FrameScanRecord, o: { cues?: Cue[]; hero?: s everySeconds: rec.sampling.everySeconds, durationSeconds: rec.source.durationSeconds, hero: hints?.hero, + ...(rec.corrections?.length ? { corrections: rec.corrections } : {}), }), rederivedAt: at, updatedAt: at, @@ -253,7 +260,15 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr readings: all, duplicates, spoken, - derived: deriveOf(profile.id, all, duplicates, spoken, { everySeconds: every, durationSeconds: duration, hero: hints.hero }), + derived: deriveOf(profile.id, all, duplicates, spoken, { + everySeconds: every, + durationSeconds: duration, + hero: hints.hero, + ...(prev?.corrections?.length ? { corrections: prev.corrections } : {}), + }), + // A person's corrections outlive every run, a fresh one included: they + // say what a frame at that second shows. + ...(prev?.corrections?.length ? { corrections: prev.corrections } : {}), updatedAt: now().toISOString(), }; }; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,12 @@ # Changelog ## [Unreleased] +- **A frame scan can be re-derived and corrected from its panel, with no model.** The video page's **Frame scan** panel has **Re-derive (no model)** beside the hero's screen name (what `archilyzer frames rederive` did), and **Correct a reading**: open the reading at a time, or from the **Correct** beside any event, and set a field to what the frame shows — the stack, players left, the blinds, the tournament's name, the log lines… — or **Mark misread** to set the whole reading aside. The correction is kept beside what the model read (each corrected field says what it read), the timeline is worked out again at once with your values, and every later scan and re-derive keeps them; **Clear correction** takes one back. The corrections are listed under the flags. Needs a restart of the editor. +- **Find copies of gone videos from the channel page and the site page.** The channel's Download stage (and a site's page, for all its channels) has **Find copies of gone videos**: which gone videos (no transcript, or every one with no media), at most how many lookups, and whether to try failed copies again. **Preview** looks without recording or fetching anything and lists each video with the copy it would use (the Wayback capture or the archive.org file); **Find and fetch copies**, armed by a preview of the same settings, runs it and links the find-copy job and the fetch-copies job it started. Needs a restart of the editor. +- **Audit audio from the channel page, and see the verdicts.** The Download stage has **Audit audio** (videos with no transcript, or every video holding audio; at most how many files; decode again files already audited) and a line with the channel's verdicts — clean, damaged, undecodable, and out of date where the file changed since — and when it last checked. The video page shows its audio's verdict: how much decodes and where the gaps are. The counts appear once the channel's report is regenerated. Needs a restart of the editor. +- **A video's media operations are buttons on its page.** Under **Media tools**: attach the video's file from a local archive (a folder, a .zip or a .7z; preview, then attach), make a playable copy of its saved video, and for a Wayback or archive.org record bring the channel's records up to their rules (preview, then refresh; a Wayback record's title and date can be given with it). Needs a restart of the editor. +- **More ops-only operations have buttons.** Each article on the Articles tab has **Attach video** (a video file, a poster and a caption: what `archilyzer reports attach-video --article` did). The Download stage's **More ways in** imports an archive.org item, completes a podcast channel's records from its feed, and reads an Odysee or BitChute channel's remote listing; a posts channel imports one post by its URL and captures posts by id; the Cleanup stage has **Keep videos matching** (preview the matches, then keep them). Needs a restart of the editor. +- **An Odysee channel's Configure form shows the audio check on.** The check is on by default for Odysee, but the box showed unticked; it now shows ticked with "on by default for Odysee", and unticking it turns the check off for the channel (`pnpm ops channel-config` with `"audioCheckEnabled": false` too). Needs a restart of the editor. - **Odysee downloads always get the audio check, clip windows included.** A video from Odysee — which intermittently serves corrupt audio — is downloaded with the audio check on unless its channel turns it off (`audioCheck: {"enabled": false}`); before, a channel had to opt in. A clip window from such a source now gets the check's final probe too: a malformed window is deleted and fetched once more, and if it is malformed again the fetch fails and nothing is kept, so a clip is never cut from corrupt audio. The verdict is recorded in the window's provenance. - **An article can correct what the transcripts mishear in its quotes.** `archilyzer reports respell <article> --heard "cake cup,cakeup" --reads K-Cup` previews every change — the article's quotes and citations, its report's own words, and its video's burned-in quotes and flip cards — as before → after, and writes nothing; `--apply` writes it, each file backed up first. `--bracket` shows the correction as an altered quote, `[K-Cup]`. The article records the respelling, and every quote check applies it to the transcript before comparing, so a corrected quote still verifies exactly; the transcript itself is untouched. A video shows the new words once it is rebuilt. - **`pnpm ops audio-audit` checks the audio already on disk, file by file.** `pnpm ops audio-audit --json '{"platform":"odysee"}'` (or `{"slug":"<channel>"}`; `"scope":"all"` for transcribed videos too, `"max"` to cap the files) decodes each audio file a channel holds with error tolerance — one file at a time, at the lowest CPU and disk priority — and writes what it found beside the file in `audio-integrity.json`: clean, damaged (part of it will not decode) or undecodable, with how much decodes and where the gaps are. Audio downloaded before the audio check existed, or on a channel without it, was never checked. The same command again skips the files already checked. A drive that stops answering ends that channel's run with a sentence that says so instead of hanging. diff --git a/editor/app/channels/[slug]/audioAuditActions.ts b/editor/app/channels/[slug]/audioAuditActions.ts @@ -0,0 +1,30 @@ +"use server"; + +// "Audit audio" on the channel's Download stage (release 32): the +// `audio-audit` job for this channel, through the same door as +// `pnpm ops audio-audit` (controller/audioAudit.ts). Its refusals — a bad +// body, the channel's media unreachable — come back as the button's error. +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { enqueueAudioAudit } from "yt-dlp-transcript-common/controller/audioAudit"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; + +export async function audioAuditAction( + slug: string, + opts: { scope: "untranscribed" | "all"; max?: number; force?: boolean }, +): Promise<StreamActionResult> { + let out; + try { + out = await enqueueAudioAudit( + { slug, scope: opts.scope, ...(opts.max !== undefined ? { max: opts.max } : {}), ...(opts.force ? { force: true } : {}) }, + { paths: getPaths() }, + ); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const started = out.started[0]; + if (started) return started.result; + return { ok: false, error: out.refused.map((r) => r.error).join("; ") || "No audit started" }; +} diff --git a/editor/app/channels/[slug]/components/ChannelImportTools.tsx b/editor/app/channels/[slug]/components/ChannelImportTools.tsx @@ -0,0 +1,99 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { feedMetadataBackfillAction, importArchiveOrgAction, remoteListingAction } from "../pipelineActions"; + +// Channel operations that were ops-only (release 32), on the Download stage: +// an archive.org item imported (`import-archive-org`), the records completed +// from the channel's RSS feed (`feed-metadata`), and an Odysee or BitChute +// channel's remote listing read against what it holds (`remote-listing`). +// Each that writes previews first. + +export function ChannelImportTools({ slug, remoteListing }: { slug: string; remoteListing: boolean }) { + const [item, setItem] = useState(""); + const [match, setMatch] = useState(""); + const itemKey = `${item}\u0000${match}`; + const [itemPreviewed, setItemPreviewed] = useState<string | null>(null); + const [feedPreviewed, setFeedPreviewed] = useState(false); + const itemOpts = { item: item.trim(), ...(match.trim() ? { match: match.trim() } : {}) }; + return ( + <details aria-label="more ways in" className="rounded border border-border p-3"> + <summary className="cursor-pointer text-sm font-semibold">More ways in</summary> + <div className="mt-3 flex flex-col gap-5"> + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Import from archive.org</h4> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Item identifier</span> + <input + value={item} + onChange={(e) => setItem(e.target.value)} + aria-label="archive.org item" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-72 max-w-full" + /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Files matching (optional regex)</span> + <input + value={match} + onChange={(e) => setMatch(e.target.value)} + aria-label="archive.org files matching" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-56 max-w-full" + /> + </label> + </div> + <StreamActionLog + trigger={() => importArchiveOrgAction(slug, { ...itemOpts, dryRun: true })} + cancelAction={cancelJobAction} + buttonLabel="Preview import" + runningLabel="Reading the item…" + label={`Preview archive.org import into ${slug}`} + disabled={!item.trim()} + onSettled={(started) => setItemPreviewed(started ? itemKey : null)} + /> + <StreamActionLog + trigger={() => importArchiveOrgAction(slug, itemOpts)} + cancelAction={cancelJobAction} + buttonLabel="Import" + runningLabel="Importing…" + label={`Import from archive.org into ${slug}`} + disabled={itemPreviewed !== itemKey} + /> + </div> + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Complete records from the feed</h4> + <StreamActionLog + trigger={() => feedMetadataBackfillAction(slug, true)} + cancelAction={cancelJobAction} + buttonLabel="Preview feed backfill" + runningLabel="Reading the feed…" + label={`Preview feed backfill of ${slug}`} + onSettled={(started) => setFeedPreviewed(started)} + /> + <StreamActionLog + trigger={() => feedMetadataBackfillAction(slug)} + cancelAction={cancelJobAction} + buttonLabel="Complete from the feed" + runningLabel="Completing…" + label={`Feed backfill of ${slug}`} + disabled={!feedPreviewed} + /> + </div> + {remoteListing && ( + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Remote listing</h4> + <StreamActionLog + trigger={() => remoteListingAction(slug)} + cancelAction={cancelJobAction} + buttonLabel="Read the remote listing" + runningLabel="Reading…" + label={`Remote listing of ${slug}`} + /> + </div> + )} + </div> + </details> + ); +} diff --git a/editor/app/channels/[slug]/components/KeepMatchingControl.tsx b/editor/app/channels/[slug]/components/KeepMatchingControl.tsx @@ -0,0 +1,102 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useState, useTransition } from "react"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import type { KeepVideosResult } from "yt-dlp-transcript-common/controller/keepVideosMatching"; +import { keepVideosAction } from "../videos/[id]/videoActions"; + +// "Keep videos matching" (release 32; `pnpm ops keep-videos` before it): the +// do-not-clean marker on every video of the channel whose title (or +// description) matches a pattern — the cleanup sweeps then never delete their +// audio. Preview lists the matches; Keep is armed by a preview of the same +// pattern. +export function KeepMatchingControl({ slug }: { slug: string }) { + const [hydrated, setHydrated] = useState(false); + useEffect(() => setHydrated(true), []); + const [pattern, setPattern] = useState(""); + const [description, setDescription] = useState(false); + const [note, setNote] = useState(""); + const key = `${pattern}\u0000${description}`; + const [previewed, setPreviewed] = useState<string | null>(null); + const [result, setResult] = useState<KeepVideosResult | null>(null); + const [error, setError] = useState<string | null>(null); + const [pending, start] = useTransition(); + const go = (dryRun: boolean) => + start(async () => { + setError(null); + const res = await keepVideosAction({ + slug, + pattern, + fields: description ? ["title", "description"] : ["title"], + ...(note.trim() ? { note: note.trim() } : {}), + dryRun, + }); + if (!res.ok) { + setError(res.error); + setResult(null); + return; + } + setResult(res.result); + if (dryRun) setPreviewed(key); + }); + return ( + <div aria-label="keep videos matching" className="flex flex-col gap-2 rounded border border-border p-3"> + <h4 className="text-sm font-semibold">Keep videos matching</h4> + <div className="flex flex-wrap items-center gap-3 text-sm"> + <input + value={pattern} + onChange={(e) => setPattern(e.target.value)} + aria-label="keep pattern" + placeholder="pattern, e.g. interview|debate" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-72 max-w-full" + /> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={description} onChange={(e) => setDescription(e.target.checked)} /> + Descriptions too + </label> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + aria-label="keep note" + placeholder="note (optional)" + className="rounded border border-border bg-card px-2 py-1 text-sm w-56 max-w-full" + /> + </div> + <div className="flex gap-2"> + <Button type="button" size="sm" variant="outline" disabled={!hydrated || pending || !pattern.trim()} onClick={() => go(true)}> + Preview matches + </Button> + <Button type="button" size="sm" disabled={!hydrated || pending || previewed !== key} onClick={() => go(false)}> + Keep them + </Button> + </div> + {error && ( + <p role="alert" className="text-xs text-destructive"> + {error} + </p> + )} + {result && ( + <div className="flex flex-col gap-1 text-xs" aria-label="keep matches"> + <p role="status"> + {result.matched.length} match{result.matched.length === 1 ? "" : "es"} of {result.considered} + {result.dryRun ? "" : `; ${result.marked} kept now`}, {result.alreadyKept} already kept + {result.notDownloaded.length > 0 && `, ${result.notDownloaded.length} not downloaded`} + {result.unscanned > 0 && `, ${result.unscanned} never scanned (not tested)`} + </p> + <ul className="max-h-48 overflow-auto"> + {result.matched.slice(0, 200).map((m) => ( + <li key={m.id}> + <Link href={`/channels/${slug}/videos/${m.id}`} className="font-mono underline"> + {m.id} + </Link>{" "} + {m.title} + {m.alreadyKept ? " (kept)" : m.marked ? " (kept now)" : ""} + </li> + ))} + </ul> + </div> + )} + </div> + ); +} diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -15,6 +15,7 @@ import { setPostFetcherAction, } from "../socialActions"; import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession"; +import { SocialPostTools } from "./SocialPostTools"; export type SocialChannelState = { postCount: number; @@ -387,6 +388,8 @@ export function SocialChannelPanel({ </section> )} + <SocialPostTools slug={slug} /> + <p className="text-xs text-muted-foreground"> Posts are indexed into the search corpus by the normal build — there is no per-post download or transcription stage. diff --git a/editor/app/channels/[slug]/components/SocialPostTools.tsx b/editor/app/channels/[slug]/components/SocialPostTools.tsx @@ -0,0 +1,62 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { capturePostsAction } from "../socialActions"; +import { importPostAction } from "../importPostAction"; + +// A posts channel's ops-only operations as buttons (release 32): one post +// imported by its URL (`import-post`), and specific posts captured — a +// screenshot and their media (`capture-posts`). +export function SocialPostTools({ slug }: { slug: string }) { + const [url, setUrl] = useState(""); + const [ids, setIds] = useState(""); + const [shots, setShots] = useState(true); + const [media, setMedia] = useState(true); + const [force, setForce] = useState(false); + const idList = ids.split(/[\s,]+/).filter(Boolean); + const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; + return ( + <section aria-label="post tools" className="flex flex-col gap-4 rounded-lg border border-border p-3"> + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Import one post</h4> + <input value={url} onChange={(e) => setUrl(e.target.value)} aria-label="post URL" placeholder="https://…" className={`${input} w-[32rem] max-w-full`} /> + <StreamActionLog + trigger={() => importPostAction(slug, url.trim())} + cancelAction={cancelJobAction} + buttonLabel="Import post" + runningLabel="Importing…" + label={`Import post into ${slug}`} + disabled={!url.trim()} + /> + </div> + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Capture posts</h4> + <input value={ids} onChange={(e) => setIds(e.target.value)} aria-label="post ids to capture" placeholder="post ids, comma or space separated" className={`${input} w-[32rem] max-w-full`} /> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={shots} onChange={(e) => setShots(e.target.checked)} /> + Screenshot + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={media} onChange={(e) => setMedia(e.target.checked)} /> + Attached media + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} /> + Again, if captured + </label> + </div> + <StreamActionLog + trigger={() => capturePostsAction(slug, idList, undefined, shots, media, force)} + cancelAction={cancelJobAction} + buttonLabel={`Capture ${idList.length || ""} post${idList.length === 1 ? "" : "s"}`.replace(" ", " ")} + runningLabel="Capturing…" + label={`Capture posts of ${slug}`} + disabled={idList.length === 0} + /> + </div> + </section> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx @@ -1,6 +1,7 @@ "use client"; import { useState } from "react"; +import { KeepMatchingControl } from "../KeepMatchingControl"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { QueueControl } from "../../../../components/QueueControl"; @@ -68,6 +69,7 @@ export function CleanupStage({ const [cleanQueue, setCleanQueue] = useState(defaultQueueKey); return ( <div className="flex flex-col gap-6"> + <KeepMatchingControl slug={slug} /> {(keepLatest > 0 || savedCount > 0) && ( <RetentionSection slug={slug} diff --git a/editor/app/channels/[slug]/components/stages/DownloadStage.tsx b/editor/app/channels/[slug]/components/stages/DownloadStage.tsx @@ -2,7 +2,10 @@ import { useState } from "react"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; -import type { ExcludedFromDownload } from "yt-dlp-transcript-common/controller/channelSnapshot"; +import type { AudioIntegrityTally, ExcludedFromDownload } from "yt-dlp-transcript-common/controller/channelSnapshot"; +import { FindCopiesControl } from "../../../../components/FindCopiesControl"; +import { audioAuditAction } from "../../audioAuditActions"; +import { ChannelImportTools } from "../ChannelImportTools"; import { QueueControl } from "../../../../components/QueueControl"; import { ShardControl, @@ -33,6 +36,11 @@ type Props = { corruptFullSourceIds: string[]; // Release 31 lane A: held audio the audio audit found damaged. corruptHeldAudioIds: string[]; + // Release 32: the audio audit's verdicts over the channel (the snapshot's + // tally), or null when the report predates it. + audioIntegrity: AudioIntegrityTally | null; + // An Odysee or BitChute channel: its remote listing can be read. + remoteListing?: boolean; missingShard: ShardConfigSummary | null; }; @@ -48,6 +56,8 @@ export function DownloadStage({ needsCookiesIds, corruptFullSourceIds, corruptHeldAudioIds, + audioIntegrity, + remoteListing = false, missingShard, }: Props) { const [downloadQueue, setDownloadQueue] = useState(defaultQueueKey); @@ -78,6 +88,7 @@ export function DownloadStage({ slug={slug} excluded={excludedFromDownload} /> + <FindCopiesControl slug={slug} /> <div className="flex flex-col gap-2"> <Heading title="Download from playlist" @@ -247,6 +258,81 @@ export function DownloadStage({ defaultQueueKey={defaultQueueKey} existingQueues={existingQueues} /> + <AudioAuditControl slug={slug} tally={audioIntegrity} /> + <ChannelImportTools slug={slug} remoteListing={remoteListing} /> + </div> + ); +} + +// "Audit audio" (release 32; the audit is release 31 lane A's): decode the +// audio the channel holds and write each file's verdict beside it in +// audio-integrity.json; damaged files land in "Damaged held audio" above. +// The line is the report's tally of those verdicts. +function AudioAuditControl({ + slug, + tally, +}: { + slug: string; + tally: AudioIntegrityTally | null; +}) { + const [scope, setScope] = useState<"untranscribed" | "all">("untranscribed"); + const [maxText, setMaxText] = useState(""); + const [force, setForce] = useState(false); + const max = Number.parseInt(maxText, 10); + const audited = tally ? tally.clean + tally.damaged + tally.undecodable + tally.stale : 0; + return ( + <div aria-label="audit audio" className="flex flex-col gap-2 rounded border border-border p-3"> + <h4 className="text-sm font-semibold">Audit audio</h4> + <p aria-label="audio audit tally" className="text-xs text-muted-foreground"> + {audited === 0 || !tally + ? "Not audited." + : `${tally.clean} clean, ${tally.damaged} damaged, ${tally.undecodable} undecodable` + + (tally.stale ? `, ${tally.stale} out of date (the file changed)` : "") + + (tally.lastCheckedAt ? ` · last checked ${tally.lastCheckedAt.slice(0, 16).replace("T", " ")}` : "")} + </p> + <div className="flex flex-wrap items-center gap-3 text-sm"> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">Files</span> + <select + value={scope} + onChange={(e) => setScope(e.target.value as "untranscribed" | "all")} + aria-label="audit scope" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="untranscribed">videos with no transcript</option> + <option value="all">every video holding audio</option> + </select> + </label> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">At most</span> + <input + type="number" + min={1} + value={maxText} + onChange={(e) => setMaxText(e.target.value)} + placeholder="all" + aria-label="audit at most files" + className="rounded border border-border bg-card px-2 py-1 text-sm w-20" + /> + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} aria-label="decode again files already audited" /> + Decode again files already audited + </label> + </div> + <StreamActionLog + trigger={() => + audioAuditAction(slug, { + scope, + ...(Number.isInteger(max) && max > 0 ? { max } : {}), + ...(force ? { force: true } : {}), + }) + } + cancelAction={cancelJobAction} + buttonLabel="Audit audio" + runningLabel="Auditing…" + label={`Audit audio of ${slug}`} + /> </div> ); } diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -81,6 +81,8 @@ import { liveJobRows } from "../../jobs/active/buildActiveJobs"; import { CleanupStage } from "./components/stages/CleanupStage"; import { DiagnosticsStage } from "./components/stages/DiagnosticsStage"; import { DownloadStage } from "./components/stages/DownloadStage"; +import { isRemoteListingPlatform } from "yt-dlp-transcript-common/controller/remoteListing"; +import { detectPlatform as detectUrlPlatform } from "yt-dlp-transcript-common/lib/platform"; import { PlaylistStage } from "./components/stages/PlaylistStage"; import { MATCHED_PREVIEW_LIMIT, @@ -514,6 +516,8 @@ export default async function ChannelDetailPage({ needsCookiesIds={buckets.needsCookies} corruptFullSourceIds={buckets.corruptFullSource} corruptHeldAudioIds={buckets.corruptHeldAudio} + audioIntegrity={snapshot.audioIntegrity ?? null} + remoteListing={isRemoteListingPlatform(config!.url ? detectUrlPlatform(config!.url) : null)} missingShard={await shard("download-missing")} /> ); diff --git a/editor/app/channels/[slug]/videos/[id]/components/FrameReadingEditor.tsx b/editor/app/channels/[slug]/videos/[id]/components/FrameReadingEditor.tsx @@ -0,0 +1,230 @@ +"use client"; + +import { useCallback, useEffect, useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import type { FrameReadingView } from "yt-dlp-transcript-common/controller/frameCorrections"; +import { correctFrameReadingAction, frameReadingAction } from "../frameScanActions"; + +// A person corrects one frame reading (release 32): open the reading at a +// time (or from an event's "Correct"), set a field to what the frame shows — +// or set the whole reading aside as a misread — and the scan is derived again +// at once with the person's values. The model's reading is kept as it was and +// shown beside each field that differs. + +type Values = Record<string, string>; + +function toText(v: unknown, kind: string): string { + if (v === null || v === undefined) return ""; + if (Array.isArray(v)) return v.join(kind === "lines" ? "\n" : " "); + return String(v); +} + +/** "1:02:03", "4:05" or "125" → seconds; null when it is none of them. */ +export function parseClock(s: string): number | null { + const parts = s.trim().split(":"); + if (!parts.length || parts.length > 3 || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null; + return parts.reduce((acc, p) => acc * 60 + Number(p), 0); +} + +function clock(t: number): string { + const s = Math.max(0, Math.round(t)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`; +} + +export function FrameReadingEditor({ + slug, + videoId, + profile, + initialT, +}: { + slug: string; + videoId: string; + profile: string; + initialT: number | null; +}) { + const router = useRouter(); + const [hydrated, setHydrated] = useState(false); + const [at, setAt] = useState(initialT !== null ? clock(initialT) : ""); + const [view, setView] = useState<FrameReadingView | null>(null); + const [values, setValues] = useState<Values>({}); + const [note, setNote] = useState(""); + const [status, setStatus] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const [pending, start] = useTransition(); + + const show = useCallback((v: FrameReadingView) => { + setView(v); + setAt(clock(v.t)); + setValues(Object.fromEntries(v.fields.map((f) => [f.path, toText(f.value, f.kind)]))); + setNote(v.correction?.note ?? ""); + }, []); + + const open = useCallback( + (t: number) => { + setError(null); + setStatus(null); + start(async () => { + const res = await frameReadingAction(slug, videoId, profile, t); + if (!res.ok) setError(res.error); + else show(res.view); + }); + }, + [slug, videoId, profile, show], + ); + + useEffect(() => { + setHydrated(true); + if (initialT !== null) open(initialT); + }, [initialT, open]); + + const save = (req: { misread?: boolean; clear?: boolean }) => { + if (!view) return; + setError(null); + setStatus(null); + start(async () => { + const set = req.clear || req.misread ? undefined : values; + const res = await correctFrameReadingAction(slug, videoId, profile, { + t: view.t, + ...(set ? { set } : {}), + ...(req.misread ? { misread: true } : {}), + ...(req.clear ? { clear: true } : {}), + ...(note.trim() ? { note } : {}), + }); + if (!res.ok) { + setError(res.error); + return; + } + show(res.view); + const { before: b, after: a } = res.rederived; + setStatus( + `${res.correction ? (res.correction.misread ? "Set aside as a misread" : "Correction saved") : "No correction kept"}; ` + + `derived again: events ${b.events} → ${a.events}, tournaments ${b.tournaments} → ${a.tournaments}`, + ); + router.refresh(); + }); + }; + + const disabled = !hydrated || pending; + return ( + <section id="frame-reading" aria-label="frame reading" className="flex flex-col gap-2 border-t border-border pt-3"> + <h4 className="text-sm font-semibold">Correct a reading</h4> + <form + className="flex flex-wrap items-center gap-2 text-sm" + onSubmit={(e) => { + e.preventDefault(); + const t = parseClock(at); + if (t === null) setError("give a time: 1:02:03, 4:05 or seconds"); + else open(t); + }} + > + <input + value={at} + onChange={(e) => setAt(e.target.value)} + aria-label="reading time" + placeholder="h:mm:ss" + className="rounded border border-border bg-card px-2 py-1 text-sm w-28 font-mono" + /> + <Button type="submit" size="sm" variant="outline" disabled={disabled}> + Open reading + </Button> + {view && ( + <> + <Button type="button" size="sm" variant="ghost" disabled={disabled || view.prev === null} onClick={() => view.prev !== null && open(view.prev)}> + Earlier + </Button> + <Button type="button" size="sm" variant="ghost" disabled={disabled || view.next === null} onClick={() => view.next !== null && open(view.next)}> + Later + </Button> + </> + )} + </form> + {view && ( + <div className="flex flex-col gap-2" data-testid="frame-reading-form"> + <p className="text-xs text-muted-foreground" aria-label="frame reading heading"> + Reading at {clock(view.t)} + {view.copyOf !== null && ` (a duplicate of the frame at ${clock(view.copyOf)})`} + {view.misread && " · set aside as a misread"} + {view.correction && !view.misread && " · corrected by a person"} + </p> + <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2"> + {view.fields.map((f) => ( + <label key={f.path} className="flex flex-col gap-0.5 text-sm"> + <span className="text-xs text-muted-foreground"> + {f.label} + {f.corrected && <span className="text-warning"> · read {toText(f.read, f.kind) || "nothing"}</span>} + </span> + {f.kind === "enum" ? ( + <select + value={values[f.path] ?? ""} + onChange={(e) => setValues((v) => ({ ...v, [f.path]: e.target.value }))} + aria-label={f.label} + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + {!f.required && <option value="">—</option>} + {(f.options ?? []).map((o) => ( + <option key={o} value={o}> + {o} + </option> + ))} + </select> + ) : f.kind === "lines" ? ( + <textarea + value={values[f.path] ?? ""} + onChange={(e) => setValues((v) => ({ ...v, [f.path]: e.target.value }))} + aria-label={f.label} + rows={3} + className="rounded border border-border bg-card px-2 py-1 text-xs font-mono" + /> + ) : ( + <input + value={values[f.path] ?? ""} + onChange={(e) => setValues((v) => ({ ...v, [f.path]: e.target.value }))} + aria-label={f.label} + inputMode={f.kind === "whole" || f.kind === "number" ? "decimal" : undefined} + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + )} + </label> + ))} + </div> + <label className="flex flex-col gap-0.5 text-sm"> + <span className="text-xs text-muted-foreground">Note</span> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + aria-label="correction note" + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <div className="flex flex-wrap gap-2"> + <Button type="button" size="sm" disabled={disabled} onClick={() => save({})}> + Save correction + </Button> + <Button type="button" size="sm" variant="outline" disabled={disabled || view.misread} onClick={() => save({ misread: true })}> + Mark misread + </Button> + {view.correction && ( + <Button type="button" size="sm" variant="ghost" disabled={disabled} onClick={() => save({ clear: true })}> + Clear correction + </Button> + )} + </div> + </div> + )} + {status && ( + <p role="status" aria-label="frame reading status" className="text-xs text-muted-foreground"> + {status} + </p> + )} + {error && ( + <p role="alert" aria-label="frame reading error" className="text-xs text-destructive"> + {error} + </p> + )} + </section> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/components/FrameRederiveControl.tsx b/editor/app/channels/[slug]/videos/[id]/components/FrameRederiveControl.tsx @@ -0,0 +1,80 @@ +"use client"; + +import { useEffect, useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import { frameRederiveAction } from "../frameScanActions"; + +// "Re-derive (no model)": the scan's timeline worked out again from the +// readings it holds — no model, no frame — as `archilyzer frames rederive` +// does. The hero's screen name may be changed with it (the derivation reads +// the hero's pots, all-ins and bust by name). +export function FrameRederiveControl({ + slug, + videoId, + profile, + hero, +}: { + slug: string; + videoId: string; + profile: string; + hero: string | null; +}) { + const router = useRouter(); + const [hydrated, setHydrated] = useState(false); + useEffect(() => setHydrated(true), []); + const [name, setName] = useState(hero ?? ""); + const [pending, start] = useTransition(); + const [done, setDone] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const run = () => { + setError(null); + setDone(null); + start(async () => { + const res = await frameRederiveAction(slug, videoId, profile, name); + if (!res.ok) { + setError(res.error); + return; + } + const { before: b, after: a, eventsByKind } = res.rederived; + const kinds = Object.entries(eventsByKind) + .map(([k, n]) => `${k} ${n}`) + .join(", "); + setDone( + `Re-derived from ${res.rederived.readings} readings: tournaments ${b.tournaments} → ${a.tournaments}, ` + + `events ${b.events} → ${a.events}, flags ${b.flags} → ${a.flags}, misreads ${b.misreads} → ${a.misreads}` + + (kinds ? ` (${kinds})` : ""), + ); + router.refresh(); + }); + }; + return ( + <div className="flex flex-col gap-2"> + <div className="flex flex-wrap items-center gap-2 text-sm"> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">Hero</span> + <input + value={name} + onChange={(e) => setName(e.target.value)} + aria-label="hero screen name" + placeholder="screen name" + className="rounded border border-border bg-card px-2 py-1 text-sm w-44" + /> + </label> + <Button type="button" size="sm" variant="outline" disabled={!hydrated || pending} onClick={run}> + {pending ? "Re-deriving…" : "Re-derive (no model)"} + </Button> + </div> + {done && ( + <p role="status" aria-label="re-derive result" className="text-xs text-muted-foreground"> + {done} + </p> + )} + {error && ( + <p role="alert" aria-label="re-derive error" className="text-xs text-destructive"> + {error} + </p> + )} + </div> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/components/FrameScanPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/FrameScanPanel.tsx @@ -2,14 +2,19 @@ // the phase strip, a small chart per tournament, the events (each a link to // the moment on the video's platform), the flags where something said and // something read disagree — and the Scan button when the video is saved. +// With no model (release 32): Re-derive, and a person's correction of any +// reading (each event has a "Correct" beside it). // // Not a registry operation (those are corpus-wide lanes, one panel each // below): a scan is asked for one stream at a time. Drawn when the sidecar // exists or the video's container is saved; otherwise there is nothing to // show and nothing to scan. +import Link from "next/link"; import type { FrameScanView } from "../lib/frameScanView"; import { FrameScanControl } from "./FrameScanControl"; +import { FrameRederiveControl } from "./FrameRederiveControl"; +import { FrameReadingEditor } from "./FrameReadingEditor"; const PHASE_CLASS: Record<string, string> = { table: "bg-success", @@ -23,11 +28,14 @@ export function FrameScanPanel({ videoId, views, canScan, + readingT = null, }: { slug: string; videoId: string; views: FrameScanView[]; canScan: boolean; + // The reading to open in the correction form (`?reading=<s>` on the page). + readingT?: number | null; }) { if (!views.length && !canScan) return null; return ( @@ -96,6 +104,14 @@ export function FrameScanPanel({ )} <span className="font-medium">{e.kind}</span> <span className="text-muted-foreground">{e.detail}</span> + <Link + href={`?reading=${Math.round(e.t)}#frame-reading`} + scroll={false} + aria-label={`Correct the reading at ${e.at}`} + className="text-xs text-muted-foreground underline hover:text-foreground" + > + Correct + </Link> </li> ))} </ul> @@ -107,6 +123,24 @@ export function FrameScanPanel({ ))} </ul> )} + {v.corrections.length > 0 && ( + <div className="flex flex-col gap-0.5 text-xs"> + <span className="font-medium">Corrected by a person ({v.corrections.length})</span> + <ul className="flex flex-col gap-0.5 text-muted-foreground" aria-label="frame scan corrections"> + {v.corrections.map((c) => ( + <li key={c.t} className="flex gap-2"> + <Link href={`?reading=${Math.round(c.t)}#frame-reading`} scroll={false} className="font-mono underline hover:text-foreground"> + {c.at} + </Link> + <span>{c.what}</span> + {c.note && <span className="italic">{c.note}</span>} + </li> + ))} + </ul> + </div> + )} + <FrameRederiveControl slug={slug} videoId={videoId} profile={v.profile} hero={v.hero} /> + <FrameReadingEditor slug={slug} videoId={videoId} profile={v.profile} initialT={readingT} /> </div> ))} {canScan && <FrameScanControl slug={slug} videoId={videoId} profile="poker" scanned={views.some((v) => v.profile === "poker")} />} diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx @@ -0,0 +1,207 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useState, useTransition } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import { cancelJobAction } from "../../../../../jobs/actions"; +import { + archiveOrgRefreshAction, + attachVideoMediaAction, + playableVideoAction, + waybackRefreshAction, + type RecordsRefreshResult, +} from "../mediaToolsActions"; + +// "Media tools" (release 32): the video-level operations that were CLI- or +// ops-only — attach this video's file from a local archive, make a playable +// copy of its saved container, and bring the channel's Wayback or archive.org +// records up to their rules. Every one previews first where it writes. + +const input = "rounded border border-border bg-card px-2 py-1 text-sm"; + +export function VideoMediaTools({ + slug, + videoId, + saved, + wayback, + archiveOrg, +}: { + slug: string; + videoId: string; + // A source container is in the saved-video store. + saved: boolean; + // A Wayback Machine copy (wayback.json, or a web.archive.org page URL). + wayback: boolean; + // An archive.org file record. + archiveOrg: boolean; +}) { + return ( + <details aria-label="media tools" className="rounded-lg border border-border bg-card p-3"> + <summary className="cursor-pointer text-sm font-semibold">Media tools</summary> + <div className="mt-3 flex flex-col gap-4"> + <AttachFromArchive slug={slug} videoId={videoId} saved={saved} /> + {saved && ( + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Playable copy</h4> + <StreamActionLog + trigger={() => playableVideoAction(slug, videoId)} + cancelAction={cancelJobAction} + buttonLabel="Make playable copy" + runningLabel="Remuxing…" + label={`Make playable copy of ${videoId}`} + /> + </div> + )} + {wayback && ( + <RecordsRefresh + title="Wayback records" + what="Wayback" + slug={slug} + videoId={videoId} + withTitle + run={(dryRun, title) => waybackRefreshAction(slug, { dryRun, ...(title ? { title } : {}) })} + /> + )} + {archiveOrg && ( + <RecordsRefresh + title="archive.org records" + what="archive.org" + slug={slug} + videoId={videoId} + run={(dryRun) => archiveOrgRefreshAction(slug, { dryRun })} + /> + )} + </div> + </details> + ); +} + +function AttachFromArchive({ slug, videoId, saved }: { slug: string; videoId: string; saved: boolean }) { + const [source, setSource] = useState(""); + const [file, setFile] = useState(""); + const [replace, setReplace] = useState(false); + const key = `${source}\u0000${file}\u0000${replace}`; + const [previewed, setPreviewed] = useState<string | null>(null); + const opts = { source, ...(file.trim() ? { file } : {}), ...(replace ? { replace: true } : {}) }; + return ( + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">Attach from a local archive</h4> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Archive (a directory, .zip or .7z, absolute path)</span> + <input value={source} onChange={(e) => setSource(e.target.value)} aria-label="archive path" className={`${input} w-96 max-w-full font-mono`} /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">File inside it (optional: else found by the id)</span> + <input value={file} onChange={(e) => setFile(e.target.value)} aria-label="file inside the archive" className={`${input} w-72 max-w-full font-mono`} /> + </label> + {saved && ( + <label className="flex items-center gap-2 self-end"> + <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} aria-label="replace the saved container" /> + Replace the saved container + </label> + )} + </div> + <StreamActionLog + trigger={() => attachVideoMediaAction(slug, videoId, { ...opts, dryRun: true })} + cancelAction={cancelJobAction} + buttonLabel="Preview attach" + runningLabel="Reading the archive…" + label={`Preview attach of ${videoId}`} + disabled={!source.trim()} + onSettled={(started) => setPreviewed(started ? key : null)} + /> + <StreamActionLog + trigger={() => attachVideoMediaAction(slug, videoId, opts)} + cancelAction={cancelJobAction} + buttonLabel="Attach" + runningLabel="Attaching…" + label={`Attach media to ${videoId}`} + disabled={previewed !== key} + /> + </div> + ); +} + +function RecordsRefresh({ + title, + what, + slug, + videoId, + withTitle = false, + run, +}: { + title: string; + what: string; + slug: string; + videoId: string; + withTitle?: boolean; + run: (dryRun: boolean, title?: { id: string; title?: string; upload_date?: string }) => Promise<RecordsRefreshResult>; +}) { + const [hydrated, setHydrated] = useState(false); + useEffect(() => setHydrated(true), []); + const [recTitle, setRecTitle] = useState(""); + const [recDate, setRecDate] = useState(""); + const key = `${recTitle}\u0000${recDate}`; + const [previewed, setPreviewed] = useState<string | null>(null); + const [result, setResult] = useState<RecordsRefreshResult | null>(null); + const [pending, start] = useTransition(); + const go = (dryRun: boolean) => + start(async () => { + const t = withTitle && (recTitle.trim() || recDate.trim()) ? { id: videoId, title: recTitle, upload_date: recDate } : undefined; + const res = await run(dryRun, t); + setResult(res); + if (dryRun && res.ok) setPreviewed(key); + }); + const label = `${what} refresh`; + return ( + <div className="flex flex-col gap-2"> + <h4 className="text-sm font-semibold">{title}</h4> + {withTitle && ( + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">This record&apos;s title (optional)</span> + <input value={recTitle} onChange={(e) => setRecTitle(e.target.value)} aria-label="record title" className={`${input} w-72 max-w-full`} /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Its date (optional)</span> + <input type="date" value={recDate} onChange={(e) => setRecDate(e.target.value)} aria-label="record date" className={input} /> + </label> + </div> + )} + <div className="flex flex-wrap gap-2"> + <Button type="button" size="sm" variant="outline" disabled={!hydrated || pending} onClick={() => go(true)}> + Preview {what} refresh + </Button> + <Button type="button" size="sm" disabled={!hydrated || pending || previewed !== key} onClick={() => go(false)}> + Refresh {what} records + </Button> + </div> + {result && !result.ok && ( + <p role="alert" aria-label={`${label} error`} className="text-xs text-destructive"> + {result.error} + </p> + )} + {result?.ok && ( + <div className="flex flex-col gap-1" aria-label={`${label} result`}> + <p role="status" className="text-sm"> + {result.summary} + </p> + {result.renamed.length > 0 && ( + <ul className="text-xs"> + {result.renamed.map((r) => ( + <li key={r.from}> + {r.from} → {result.dryRun ? r.to : <Link href={`/channels/${slug}/videos/${r.to}`} className="underline font-mono">{r.to}</Link>} + </li> + ))} + </ul> + )} + {result.log.length > 0 && ( + <pre className="text-xs font-mono bg-muted border border-border rounded-md p-2 max-h-60 overflow-auto whitespace-pre-wrap">{result.log.join("\n")}</pre> + )} + </div> + )} + </div> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/frameScanActions.ts b/editor/app/channels/[slug]/videos/[id]/frameScanActions.ts @@ -5,11 +5,24 @@ // `pnpm ops frame-scan`. Its refusals (no saved video, the route, the day's // cap) come back as the button's error. // +// And (release 32, lane R3) the panel's model-free half: Re-derive — the +// sidecar's `derived` worked out again from its stored readings, as +// `frame-scan {rederive: true}` and `archilyzer frames rederive` do — and a +// person's correction of one reading (controller/frameCorrections.ts), which +// re-derives at once. Neither is a job: each answers in the request. +// // NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file; see // operationActions.ts). +import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { enqueueFrameScan } from "yt-dlp-transcript-common/controller/frameScan"; +import { enqueueFrameScan, type FrameScanRederived } from "yt-dlp-transcript-common/controller/frameScan"; +import { + correctFrameReading, + frameReadingAt, + type CorrectFrameReadingResult, + type FrameReadingView, +} from "yt-dlp-transcript-common/controller/frameCorrections"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; export async function frameScanAction(slug: string, videoId: string, profile: string): Promise<StreamActionResult> { @@ -17,3 +30,39 @@ export async function frameScanAction(slug: string, videoId: string, profile: st if ("evicted" in out || "rederived" in out) return { ok: false, error: "nothing to scan" }; return out.result; } + +export async function frameRederiveAction( + slug: string, + videoId: string, + profile: string, + hero?: string, +): Promise<{ ok: true; rederived: FrameScanRederived } | { ok: false; error: string }> { + const name = hero?.trim(); + const out = await enqueueFrameScan({ slug, id: videoId, profile, rederive: true, ...(name ? { hero: name } : {}) }, { paths: getPaths() }); + if ("rederived" in out) { + revalidatePath(`/channels/${slug}/videos/${videoId}`); + return { ok: true, rederived: out.rederived }; + } + if ("result" in out && !out.result.ok) return { ok: false, error: out.result.error }; + return { ok: false, error: "not re-derived" }; +} + +export async function frameReadingAction( + slug: string, + videoId: string, + profile: string, + t: number, +): Promise<{ ok: true; view: FrameReadingView } | { ok: false; error: string }> { + return frameReadingAt(getPaths(), { slug, id: videoId, profile, t }); +} + +export async function correctFrameReadingAction( + slug: string, + videoId: string, + profile: string, + req: { t: number; set?: Record<string, unknown>; misread?: boolean; clear?: boolean; note?: string }, +): Promise<CorrectFrameReadingResult> { + const out = await correctFrameReading(getPaths(), { slug, id: videoId, profile, ...req }); + if (out.ok) revalidatePath(`/channels/${slug}/videos/${videoId}`); + return out; +} diff --git a/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts b/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts @@ -49,3 +49,23 @@ test("frameScanView: strip, charts, events with links, flags, summary", () => { assert.equal(v.summary, "20 frames every 10 s, 12 read (8 duplicates skipped) on claude-haiku-4-5 · $0.04 · 1 misread set aside · 1 smaller pot won"); assert.equal(v.stopped, "cap"); }); + +test("frameScanView: the hero, a person's corrections (release 32), and when it was re-derived", () => { + const r = { + ...record(), + hints: { hero: "SynthHero" }, + rederivedAt: "2026-10-16T09:30:00.000Z", + corrections: [ + { t: 40, at: "2026-10-16T09:29:00Z", by: "person" as const, misread: true as const, note: "the webcam" }, + { t: 90, at: "2026-10-16T09:29:30Z", by: "person" as const, set: { "hero.stack": 41000, "tournament.name": null } }, + ], + }; + const v = frameScanView(r, null); + assert.equal(v.hero, "SynthHero"); + assert.deepEqual(v.corrections, [ + { t: 40, at: "0:40", what: "misread, set aside", note: "the webcam" }, + { t: 90, at: "1:30", what: "hero.stack 41,000, tournament.name not shown", note: null }, + ]); + assert.match(v.summary, / · re-derived 2026-10-16 09:30$/); + assert.equal(frameScanView(record(), null).hero, null); +}); diff --git a/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts b/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts @@ -10,9 +10,14 @@ export type StripPart = { phase: string; leftPct: number; widthPct: number; labe export type Spark = { label: string; points: string; min: number; max: number; last: number }; export type TournamentView = { key: string; name: string; span: string; sparks: Spark[]; facts: string[] }; export type EventView = { t: number; at: string; kind: string; detail: string; href: string | null; source: string }; +export type CorrectionView = { t: number; at: string; what: string; note: string | null }; export type FrameScanView = { profile: string; summary: string; + // The hero's screen name the scan was told (a re-derive may change it). + hero: string | null; + // A person's corrections of readings (release 32), by second. + corrections: CorrectionView[]; strip: StripPart[]; tournaments: TournamentView[]; events: EventView[]; @@ -102,6 +107,27 @@ export function frameScanView(r: FrameScanRecord, webpageUrl: string | null): Fr `${fmtNum(r.sampling.frames)} frames every ${r.sampling.everySeconds} s, ${fmtNum(r.readings.length)} read` + ` (${fmtNum(r.sampling.skippedDuplicates)} duplicates skipped) on ${r.model.model} · $${r.costUsd.toFixed(2)}` + (r.derived.misreads.length ? ` · ${r.derived.misreads.length} misread${r.derived.misreads.length === 1 ? "" : "s"} set aside` : "") + - (pots ? ` · ${pots} smaller pot${pots === 1 ? "" : "s"} won` : ""); - return { profile: r.profile, summary, strip, tournaments, events, flags, stopped: last?.stopped ?? null }; + (pots ? ` · ${pots} smaller pot${pots === 1 ? "" : "s"} won` : "") + + (r.rederivedAt ? ` · re-derived ${r.rederivedAt.slice(0, 16).replace("T", " ")}` : ""); + const corrections = (r.corrections ?? []).map((c) => ({ + t: c.t, + at: clock(c.t), + what: c.misread + ? "misread, set aside" + : Object.entries(c.set ?? {}) + .map(([k, v]) => `${k} ${v === null ? "not shown" : Array.isArray(v) ? v.join(" ") : typeof v === "number" ? fmtNum(v) : v}`) + .join(", "), + note: c.note ?? null, + })); + return { + profile: r.profile, + summary, + hero: r.hints?.hero ?? null, + corrections, + strip, + tournaments, + events, + flags, + stopped: last?.stopped ?? null, + }; } diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts @@ -0,0 +1,117 @@ +"use server"; + +// The video page's "Media tools" (release 32, lane R3): operations that were +// CLI- or ops-only, each a button where its object lives. +// +// attach `archilyzer media attach` / `pnpm ops attach-media` for THIS +// video: its file out of a local archive (a directory, a .zip, +// a .7z) into the saved-video store — the `attach-media` job, +// narrowed to the file named, else to the id +// playable `archilyzer media playable` / `prepare-playable` for this +// video's saved container — the `prepare-playable` job +// wayback `archilyzer wayback refresh <slug>` — the channel's Wayback +// copies brought up to the rules (offline), a title and date for +// this record with it; answered in the request +// archiveOrg `archilyzer archive-org refresh <slug>` — the channel's +// archive.org file records (offline); answered in the request +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +import path from "node:path"; +import { revalidatePath } from "next/cache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { refreshWaybackRecords } from "yt-dlp-transcript-common/controller/waybackRefresh"; +import { refreshArchiveOrgRecords } from "yt-dlp-transcript-common/controller/archiveOrgRefresh"; +import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { attachMediaAction } from "../../attachMediaActions"; +import { preparePlayableAction } from "../../playableActions"; + +const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +export async function attachVideoMediaAction( + slug: string, + videoId: string, + opts: { source: string; file?: string; replace?: boolean; dryRun?: boolean }, +): Promise<StreamActionResult> { + const file = opts.file?.trim(); + if (file && (path.isAbsolute(file) || file.split(/[\\/]/).includes(".."))) { + return { ok: false, error: "The file is a path INSIDE the archive (relative, no ..)" }; + } + return attachMediaAction(slug, { + source: opts.source, + ...(file ? { items: [{ id: videoId, path: file }] } : { match: escapeRegex(videoId) }), + ...(opts.replace ? { replace: true } : {}), + ...(opts.dryRun ? { dryRun: true } : {}), + }); +} + +export async function playableVideoAction(slug: string, videoId: string, dryRun = false): Promise<StreamActionResult> { + return preparePlayableAction(slug, { ids: [videoId], ...(dryRun ? { dryRun: true } : {}) }); +} + +export type RecordsRefreshResult = + | { ok: true; dryRun: boolean; summary: string; log: string[]; renamed: { from: string; to: string }[] } + | { ok: false; error: string }; + +export async function waybackRefreshAction( + slug: string, + opts: { dryRun: boolean; title?: { id: string; title?: string; upload_date?: string } }, +): Promise<RecordsRefreshResult> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + const t = opts.title; + const title = t?.title?.trim(); + const date = t?.upload_date?.trim().replace(/-/g, ""); + if (date && !/^\d{8}$/.test(date)) return { ok: false, error: "The date is YYYY-MM-DD" }; + const titles = t && (title || date) ? { [t.id]: { ...(title ? { title } : {}), ...(date ? { upload_date: date } : {}) } } : undefined; + const log: string[] = []; + try { + const r = await refreshWaybackRecords({ + slug, + paths: getPaths(), + dryRun: opts.dryRun, + ...(titles ? { titles } : {}), + onLog: (line) => log.push(line.replace(/\n$/, "")), + }); + const would = opts.dryRun ? "would be " : ""; + const renamed = r.records.filter((x) => x.rename === "renamed" || x.rename === "merged"); + const held = r.records.filter((x) => x.rename === "held" || x.rename === "conflict").length; + for (const id of r.unmatchedTitles) log.push(`title: no Wayback record "${id}"`); + for (const f of r.failed) log.push(`${f.id}: failed — ${f.error}`); + const summary = + `${opts.dryRun ? "Preview: " : ""}${r.records.length} Wayback record(s), ${renamed.length} ${would}renamed, ` + + `${r.records.filter((x) => x.sidecar).length} wayback.json ${would}written, ` + + `${r.records.filter((x) => Object.keys(x.changes).length > 0).length} ${would}retitled` + + (held ? `, ${held} not renamed` : "") + + (r.failed.length ? `, ${r.failed.length} failed` : "") + + "."; + if (!opts.dryRun) revalidatePath(`/channels/${slug}`, "layout"); + return { ok: true, dryRun: opts.dryRun, summary, log, renamed: renamed.map((x) => ({ from: x.from, to: x.to })) }; + } catch (e) { + return { ok: false, error: (e as Error).message }; + } +} + +export async function archiveOrgRefreshAction(slug: string, opts: { dryRun: boolean }): Promise<RecordsRefreshResult> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + const log: string[] = []; + try { + const r = await refreshArchiveOrgRecords({ + slug, + paths: getPaths(), + dryRun: opts.dryRun, + onLog: (line) => log.push(line.replace(/\n$/, "")), + }); + const would = opts.dryRun ? "would be " : ""; + for (const f of r.failed) log.push(`${f.id}: failed — ${f.error}`); + const summary = + `${opts.dryRun ? "Preview: " : ""}${r.fileRecords} archive.org file record(s), ${r.changed.length} ${would}refreshed, ` + + `${r.sidecars} provenance sidecar(s) ${would}updated` + + (r.failed.length ? `, ${r.failed.length} failed` : "") + + "."; + if (!opts.dryRun) revalidatePath(`/channels/${slug}`, "layout"); + return { ok: true, dryRun: opts.dryRun, summary, log, renamed: [] }; + } catch (e) { + return { ok: false, error: (e as Error).message }; + } +} diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -48,6 +48,14 @@ import { FrameScanPanel } from "./components/FrameScanPanel"; import { frameScanView } from "./lib/frameScanView"; import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server"; import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails"; +import { VideoMediaTools } from "./components/VideoMediaTools"; +import { loadAudioIntegrity } from "yt-dlp-transcript-common/lib/audioIntegrity-server"; +import { + describeIntegrity, + integrityMatches, + integrityVerdict, + type AudioIntegrityRecord, +} from "yt-dlp-transcript-common/lib/audioIntegrity"; import { RefreshMetadataControl } from "./components/RefreshMetadataControl"; import { loadVideoTags } from "./lib/videoTags"; import { loadVideoOperationPanels } from "./lib/videoOperationPanels"; @@ -105,10 +113,16 @@ export async function generateMetadata({ export default async function VideoDetailPage({ params, + searchParams, }: { params: Promise<{ slug: string; id: string }>; + searchParams: Promise<Record<string, string | string[] | undefined>>; }) { const { slug, id } = await params; + // `?reading=<s>`: the frame reading the Frame scan panel's correction form opens. + const readingRaw = (await searchParams).reading; + const readingT = + typeof readingRaw === "string" && /^\d+(\.\d+)?$/.test(readingRaw) ? Number(readingRaw) : null; const config = await readChannelConfig(getPaths(), slug); if (!config) notFound(); // Everything below reads the video's TEXT, which is on the corpus disk @@ -154,6 +168,9 @@ export default async function VideoDetailPage({ // A gone video whose audio came from a copy (release 31, find-copy's // scope mode): the newest `fetched` attempt in copy-attempts.json. const audioCopy = latestFetchedCopy(await loadCopyAttempts(videoDir)); + // The audio audit's verdict on this video's held audio (release 31 lane + // A's audio-integrity.json; shown since release 32). + const audioIntegrity = await loadAudioIntegrity(videoDir); // The windows another tool asked this editor to fetch. One readdir of // data/<id>/clips/ plus a stat per file — and no per-CHANNEL count anywhere, // because that would be a walk of every video dir to draw one number. @@ -213,6 +230,7 @@ export default async function VideoDetailPage({ archiveOrg, wayback, audioCopy, + audioIntegrity, clipWindows, vttProvenance, coverage, @@ -245,6 +263,7 @@ export default async function VideoDetailPage({ archiveOrg, wayback, audioCopy, + audioIntegrity, clipWindows, vttProvenance, coverage, @@ -321,6 +340,7 @@ export default async function VideoDetailPage({ {wayback && <WaybackProvenanceLine prov={wayback} />} </> )} + {audioIntegrity && <AudioIntegrityLine record={audioIntegrity} files={dirData.files} />} {meta.description && ( <details className="text-sm"> <summary className="cursor-pointer text-muted-foreground hover:text-foreground"> @@ -385,6 +405,15 @@ export default async function VideoDetailPage({ <TagsPanel view={tagsView} /> + {/* CLI-only operations on this video's media, as buttons (release 32). */} + <VideoMediaTools + slug={slug} + videoId={id} + saved={!!savedVideo} + wayback={!!wayback || hostOf(meta.webpageUrl) === "web.archive.org"} + archiveOrg={!!archiveOrg || hostOf(meta.webpageUrl) === "archive.org"} + /> + {/* A frame scan's timeline, and its Scan button when the source container is saved (the scan reads the saved video). */} <FrameScanPanel @@ -392,6 +421,7 @@ export default async function VideoDetailPage({ videoId={id} views={frameScans.map((r) => frameScanView(r, meta.webpageUrl ?? null))} canScan={!!savedVideo} + readingT={readingT} /> {/* The external operations' per-video surface is the pipeline stage @@ -488,6 +518,34 @@ function AudioCopyLine({ copy }: { copy: CopyAttempt }) { ); } +// "Audio check: damaged: 38:55 of 1:40:00 decodes (38.9%), 3 gaps" and the +// gaps — the audit's record for the held file, or that it is out of date. +function AudioIntegrityLine({ record, files }: { record: AudioIntegrityRecord; files: { name: string; size: number | null }[] }) { + const file = files.find((f) => f.name === record.file); + const current = !!file && integrityMatches(record, { name: record.file, ...(file.size !== null ? { size: file.size } : {}) }); + const verdict = integrityVerdict(record); + const gaps = record.gaps.slice(0, 6).map(([a, b]) => `${formatDuration(a)}–${formatDuration(b)}`); + return ( + <div aria-label="audio integrity" className="text-sm text-muted-foreground"> + Audio check ({record.file}):{" "} + <span className={verdict === "clean" ? "" : "text-warning"}>{describeIntegrity({ ...record, verdict })}</span> + {gaps.length > 0 && ` — gaps ${gaps.join(", ")}${record.gaps.length > gaps.length ? ", …" : ""}`} + {" · "} + {record.checkedAt.slice(0, 10)} + {!current && " · out of date: the file changed or is gone"} + </div> + ); +} + +function hostOf(url: string | null | undefined): string | null { + if (!url) return null; + try { + return new URL(url).hostname.replace(/^www\./, ""); + } catch { + return null; + } +} + function formatUploadDate(s: string): string { // yt-dlp emits YYYYMMDD. Render as YYYY-MM-DD; pass through anything else. if (/^\d{8}$/.test(s)) { diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from "react"; import slugify from "@sindresorhus/slugify"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; +import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPolicy"; import { detectPlatform, isSocialPlatform, @@ -711,7 +712,11 @@ export function ChannelForm({ </span> </span> </label> - <AudioCheckFields config={c} state={state} /> + <AudioCheckFields + config={c} + state={state} + defaultOn={AUDIO_CHECK_PLATFORMS.includes(platform || detectPlatform(url) || "")} + /> </Section> <Section title="Retention & persistence"> <label className="flex flex-col gap-1 text-sm"> @@ -1069,16 +1074,23 @@ function SyncIntervalField({ function AudioCheckFields({ config, state, + defaultOn, }: { config?: ChannelConfig; state?: SeedSource; + // The channel's platform has the check on unless it says otherwise + // (lib/audioCheckPolicy.ts: Odysee). Unticking then writes {enabled: false}. + defaultOn: boolean; }) { const ac = config?.audioCheck; - const enabled = ac?.enabled === true; + const enabled = ac?.enabled === true || (defaultOn && ac?.enabled !== false); return ( <div className="flex flex-col gap-3 mt-1"> <label className="flex items-start gap-2 text-sm"> <input + // Remounted when the platform's default changes (create mode follows + // the URL), so the box shows the default it would save. + key={defaultOn ? "default-on" : "opt-in"} type="checkbox" name="audioCheckEnabled" defaultChecked={seedChecked(state, "audioCheckEnabled", enabled)} @@ -1091,6 +1103,12 @@ function AudioCheckFields({ <span className="text-muted-foreground font-normal"> (transcribe only, slow) </span> + {defaultOn && ( + <span className="text-muted-foreground font-normal" aria-label="audio check default"> + {" "} + · on by default for Odysee + </span> + )} </span> <span className="text-xs text-muted-foreground"> For sources that intermittently serve corrupt audio (e.g. Odysee diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -1,4 +1,6 @@ import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; +import { detectPlatform } from "yt-dlp-transcript-common/lib/platform"; +import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPolicy"; // THE INVERSE OF parseChannelForm, and it exists for exactly one caller: // /api/ops/channel-config. @@ -118,6 +120,13 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { ); put(fd, "recordedDateTitlePattern", config.recordedDate?.titlePattern); put(fd, "mirrorOf", config.mirror?.of.join(", ")); + // Ticked when the check is on: said so, or the platform's default (an + // Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch + // that does not name it keeps what the channel has. + const platform = config.platform ?? (config.url ? detectPlatform(config.url) : null); + if (config.audioCheck?.enabled === undefined && platform && AUDIO_CHECK_PLATFORMS.includes(platform)) { + fd.set("audioCheckEnabled", "on"); + } if (config.audioCheck?.enabled) { fd.set("audioCheckEnabled", "on"); putNum(fd, "audioCheckIntervalSeconds", config.audioCheck.intervalSeconds); diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -85,3 +85,36 @@ test("the ops patch sets and clears mirrorOf over the channel's current form", ( applyChannelFormPatch(back, { mirrorOf: "" }); assert.equal("mirror" in parseChannelForm(back).config, false); }); + +// The audio check on an Odysee channel (release 32): on by default +// (lib/audioCheckPolicy.ts), so the box shows ticked with nothing stored; a +// save that leaves it ticked writes nothing, unticking writes the opt-out, and +// the ops patch keeps either through the round trip. + +const ODYSEE = "https://odysee.com/@synth:0"; + +test("an Odysee channel: ticked with nothing else is the default (nothing written), unticked writes enabled: false", () => { + assert.equal("audioCheck" in parseChannelForm(form({ url: ODYSEE, audioCheckEnabled: "on" })).config, false); + assert.deepEqual(parseChannelForm(form({ url: ODYSEE })).config.audioCheck, { enabled: false }); + assert.deepEqual(parseChannelForm(form({ url: ODYSEE, audioCheckEnabled: "on", audioCheckIntervalSeconds: "60" })).config.audioCheck, { + enabled: true, + intervalSeconds: 60, + }); + // Elsewhere the check stays an opt-in. + assert.equal("audioCheck" in parseChannelForm(form({ url: "https://www.youtube.com/@synth" })).config, false); + assert.deepEqual(parseChannelForm(form({ url: "https://www.youtube.com/@synth", audioCheckEnabled: "on" })).config.audioCheck, { enabled: true }); +}); + +test("the ops patch keeps an Odysee channel's default, and turns it off with audioCheckEnabled: false", () => { + const base = { handling: "transcribe" as const, name: "Synth", url: ODYSEE }; + const fd = channelConfigToFormData(base); + assert.equal(fd.get("audioCheckEnabled"), "on"); + applyChannelFormPatch(fd, { mirrorOf: "creator-yt" }); + assert.equal("audioCheck" in parseChannelForm(fd).config, false, "an unrelated patch writes no audioCheck"); + applyChannelFormPatch(fd, { audioCheckEnabled: false }); + const off = parseChannelForm(fd).config; + assert.deepEqual(off.audioCheck, { enabled: false }); + const back = channelConfigToFormData(off); + assert.equal(back.get("audioCheckEnabled"), null, "the opt-out round-trips unticked"); + assert.deepEqual(parseChannelForm(back).config.audioCheck, { enabled: false }); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -28,6 +28,7 @@ import { downloadFilterPatternProblem } from "yt-dlp-transcript-common/lib/downl import { recordedDatePatternProblem } from "yt-dlp-transcript-common/lib/recordedDate"; import { mirrorSlugs } from "yt-dlp-transcript-common/lib/mirrors/config"; import { isRejectedLivestreamMode } from "yt-dlp-transcript-common/lib/channelConfig"; +import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPolicy"; export type ParsedChannelForm = { name: string; @@ -361,6 +362,15 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { audioCheck.resumeDuringProbe = true; } } + // ON BY DEFAULT ON A PLATFORM KNOWN FOR CORRUPT AUDIO (release 31's + // lib/audioCheckPolicy.ts; the form says so since release 32): the box + // shows ticked there with no `audioCheck` stored. Ticked with nothing else + // set is that default — nothing is written; unticked writes the opt-out. + const audioCheckDefaultOn = platform !== undefined && AUDIO_CHECK_PLATFORMS.includes(platform); + if (audioCheckDefaultOn) { + if (!audioCheck) audioCheck = { enabled: false }; + else if (Object.keys(audioCheck).length === 1) audioCheck = undefined; + } const config: ChannelConfig = { handling: handlingRaw, diff --git a/editor/app/components/FindCopiesControl.tsx b/editor/app/components/FindCopiesControl.tsx @@ -0,0 +1,168 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../jobs/actions"; +import { findWholeCopiesAction } from "../channels/[slug]/videos/findCopyAction"; +import { + FIND_COPY_MARKER, + FIND_COPY_OUTCOME_TEXT, + readResultMarker, + type FindCopiesResultView, +} from "../lib/resultMarker"; + +// "Find copies of gone videos" (release 32; find-copy's scope mode, release +// 31 lane C): for a channel — or every channel of a site — the gone videos +// holding no media are looked up on the Wayback Machine and archive.org. +// Preview is a dry run (the same paced lookups, nothing recorded or fetched) +// listing each candidate and the copy it would use; Run is armed by a preview +// of the same settings, looks again, records what has no copy and sends every +// copy found to ONE fetch-copies job, linked here. + +type Gone = "no-transcript" | "all"; +type Params = { gone: Gone; max: number; retryFailed: boolean }; + +const sameParams = (a: Params, b: Params) => a.gone === b.gone && a.max === b.max && a.retryFailed === b.retryFailed; + +export function FindCopiesControl(scope: { slug: string } | { siteId: string }) { + const name = "slug" in scope ? scope.slug : scope.siteId; + const [gone, setGone] = useState<Gone>("no-transcript"); + const [maxText, setMaxText] = useState("10"); + const [retryFailed, setRetryFailed] = useState(false); + const max = Math.min(200, Math.max(1, Math.floor(Number(maxText) || 10))); + const params: Params = { gone, max, retryFailed }; + const [preview, setPreview] = useState<{ params: Params; result: FindCopiesResultView | null } | null>(null); + const [run, setRun] = useState<{ jobId: string | null; result: FindCopiesResultView | null } | null>(null); + const armed = preview !== null && preview.result !== null && sameParams(preview.params, params); + const body = (dryRun: boolean) => ({ ...("slug" in scope ? { slug: scope.slug } : { siteId: scope.siteId }), gone, max, retryFailed, dryRun }); + + return ( + <section aria-label="find copies of gone videos" className="flex flex-col gap-2 rounded border border-border p-3"> + <h4 className="text-sm font-semibold">Find copies of gone videos</h4> + <div className="flex flex-wrap items-center gap-3 text-sm"> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">Videos</span> + <select + value={gone} + onChange={(e) => setGone(e.target.value as Gone)} + aria-label="gone videos to look for" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="no-transcript">gone, no transcript</option> + <option value="all">every gone video with no media</option> + </select> + </label> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">At most</span> + <input + type="number" + min={1} + max={200} + value={maxText} + onChange={(e) => setMaxText(e.target.value)} + aria-label="lookups at most" + className="rounded border border-border bg-card px-2 py-1 text-sm w-20" + /> + <span className="text-xs text-muted-foreground">lookups</span> + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={retryFailed} onChange={(e) => setRetryFailed(e.target.checked)} aria-label="try failed copies again" /> + Try failed copies again + </label> + </div> + <StreamActionLog + trigger={() => findWholeCopiesAction(body(true))} + cancelAction={cancelJobAction} + buttonLabel="Preview" + runningLabel="Looking…" + label={`Preview copies for ${name}`} + onSettled={(started, out) => { + if (!started) return; + setPreview({ params, result: readResultMarker<FindCopiesResultView>(out.log, FIND_COPY_MARKER) }); + }} + /> + {preview?.result && <FindCopiesResult result={preview.result} label="find copies preview" />} + <StreamActionLog + trigger={() => findWholeCopiesAction(body(false))} + cancelAction={cancelJobAction} + buttonLabel="Find and fetch copies" + runningLabel="Finding copies…" + label={`Find copies for ${name}`} + disabled={!armed} + onSettled={(started, out) => { + if (!started) return; + setRun({ jobId: out.jobId, result: readResultMarker<FindCopiesResultView>(out.log, FIND_COPY_MARKER) }); + }} + /> + {!armed && <p className="text-xs text-muted-foreground">Preview these settings first.</p>} + {run && ( + <p role="status" aria-label="find copies run" className="text-sm"> + {run.jobId && ( + <> + <Link href={`/jobs/${run.jobId}`} className="underline font-mono"> + find-copy job {run.jobId} + </Link> + {": "} + </> + )} + {run.result + ? `${run.result.looked.filter((l) => l.outcome === "fetch").length} cop${run.result.looked.filter((l) => l.outcome === "fetch").length === 1 ? "y" : "ies"} found` + : "finished"} + {run.result?.fetchJobId && ( + <> + {" · "} + <Link href={`/jobs/${run.result.fetchJobId}`} className="underline font-mono"> + fetch-copies job {run.result.fetchJobId} + </Link> + </> + )} + {run.result?.refused && <span className="text-destructive"> · fetch refused: {run.result.refused}</span>} + </p> + )} + </section> + ); +} + +function FindCopiesResult({ result, label }: { result: FindCopiesResultView; label: string }) { + const s = result.skipped; + return ( + <div className="flex flex-col gap-1 text-sm" aria-label={label}> + <p className="text-xs text-muted-foreground" aria-label={`${label} counts`}> + {result.eligible} gone video{result.eligible === 1 ? "" : "s"} with no media in {result.channels.length} channel + {result.channels.length === 1 ? "" : "s"}; {result.looked.length} looked up + {result.left > 0 && `, ${result.left} left for a later run`} + {s.recent.length > 0 && `; ${s.recent.length} left out (a recent attempt found none)`} + {s.unreadable.length > 0 && `; ${s.unreadable.length} channel(s) unreadable`} + {result.stopped && ` · stopped: ${result.stopped}`} + </p> + {result.looked.length > 0 && ( + <table className="text-xs"> + <thead className="text-left text-muted-foreground"> + <tr> + <th className="pr-3 font-medium">Video</th> + <th className="pr-3 font-medium">Gone</th> + <th className="pr-3 font-medium">Outcome</th> + <th className="font-medium">Copy</th> + </tr> + </thead> + <tbody> + {result.looked.map((l) => ( + <tr key={`${l.slug}/${l.id}`} data-testid="find-copy-candidate"> + <td className="pr-3 font-mono"> + <Link href={`/channels/${l.slug}/videos/${l.id}`} className="underline"> + {l.slug}/{l.id} + </Link> + {!l.noTranscript && <span className="text-muted-foreground"> (transcribed)</span>} + </td> + <td className="pr-3">{l.gone}</td> + <td className="pr-3">{FIND_COPY_OUTCOME_TEXT[l.outcome] ?? l.outcome}</td> + <td className="break-all">{l.via ?? "—"}</td> + </tr> + ))} + </tbody> + </table> + )} + </div> + ); +} diff --git a/editor/app/lib/resultMarker.test.ts b/editor/app/lib/resultMarker.test.ts @@ -0,0 +1,18 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { FIND_COPY_RESULT_MARKER } from "yt-dlp-transcript-common/publish/findCopy"; +import { AUDIO_AUDIT_RESULT_MARKER } from "yt-dlp-transcript-common/controller/audioAudit"; +import { AUDIO_AUDIT_MARKER, FIND_COPY_MARKER, readResultMarker } from "./resultMarker"; + +test("the client's marker strings are the controllers'", () => { + assert.equal(FIND_COPY_MARKER, FIND_COPY_RESULT_MARKER); + assert.equal(AUDIO_AUDIT_MARKER, AUDIO_AUDIT_RESULT_MARKER); +}); + +test("readResultMarker: the last marker line's JSON; null for none or for a line that is not JSON", () => { + const log = `find-copy channel x: 2 gone video(s)\n@@find-copy {"eligible":1}\n x/a: …\n@@find-copy {"eligible":2,"looked":[]}\n`; + assert.deepEqual(readResultMarker(log, FIND_COPY_MARKER), { eligible: 2, looked: [] }); + assert.equal(readResultMarker("nothing here", FIND_COPY_MARKER), null); + assert.equal(readResultMarker("@@find-copy {broken", FIND_COPY_MARKER), null); + assert.deepEqual(readResultMarker('@@audio-audit {"clean":3}', AUDIO_AUDIT_MARKER), { clean: 3 }); +}); diff --git a/editor/app/lib/resultMarker.ts b/editor/app/lib/resultMarker.ts @@ -0,0 +1,61 @@ +// A job's RESULT MARKER read off its log (release 32): several jobs end their +// log with one `@@<kind> {json}` line (find-copy, audio-audit, frame-scan…). +// A button that ran one — a dry run whose answer is a candidate list — reads +// the LAST such line. Client-safe: no server module is imported, so the +// marker strings are written here and pinned to the controllers' constants by +// resultMarker.test.ts. + +export const FIND_COPY_MARKER = "@@find-copy "; +export const AUDIO_AUDIT_MARKER = "@@audio-audit "; + +/** The JSON after the last line starting with `marker`, or null (none, or not JSON). */ +export function readResultMarker<T = unknown>(log: string, marker: string): T | null { + const lines = log.split("\n"); + for (let i = lines.length - 1; i >= 0; i--) { + const line = lines[i]!.trim(); + if (!line.startsWith(marker.trim())) continue; + try { + return JSON.parse(line.slice(marker.trim().length).trim()) as T; + } catch { + return null; + } + } + return null; +} + +// What the find-copy scope mode's log ends with (publish/findCopy.ts +// FindWholeCopiesResult, plus the job's fetchJobId / refused). +export type FindCopiesResultView = { + gone: "no-transcript" | "all"; + dryRun: boolean; + max: number; + channels: string[]; + eligible: number; + skipped: { + media: number; + transcript: number; + recent: { slug: string; id: string; at: string; outcome: string }[]; + unreadable: { slug: string; error: string }[]; + }; + looked: { + slug: string; + id: string; + gone: string; + noTranscript: boolean; + watchUrl: string | null; + outcome: "fetch" | "none-found" | "not-youtube" | "error"; + via?: string; + }[]; + left: number; + items: unknown[]; + stopped?: string; + fetchJobId?: string; + refused?: string; +}; + +export const FIND_COPY_OUTCOME_TEXT: Record<FindCopiesResultView["looked"][number]["outcome"], string> = { + fetch: "copy found", + "none-found": "no copy found", + "not-youtube": "not looked for (not YouTube)", + error: "lookup failed, try later", +}; diff --git a/editor/app/sites/[siteId]/page.tsx b/editor/app/sites/[siteId]/page.tsx @@ -8,6 +8,7 @@ import { type SiteOption, } from "../components/SiteForm"; import { getSiteCached } from "./lib/siteCache"; +import { FindCopiesControl } from "../../components/FindCopiesControl"; export const dynamic = "force-dynamic"; @@ -35,6 +36,9 @@ export default async function EditSitePage({ allSites={allSites} isNew={false} /> + {/* Every channel of the site at once (release 32): find-copy's scope + mode, as each channel's Download stage offers it for one. */} + <FindCopiesControl siteId={siteId} /> </div> ); } diff --git a/editor/app/sites/articles/page.tsx b/editor/app/sites/articles/page.tsx @@ -7,6 +7,7 @@ import { REPORT_EXPORT_FORMATS, } from "yt-dlp-transcript-common/lib/report/views"; import { ArticleRowActions } from "../components/ArticleRowActions"; +import { ArticleVideoControl } from "../components/ArticleVideoControl"; import { ExportArticlesButton, PrepareArticlesMediaButton } from "../components/ArticlesJobButtons"; import { FetchMissingEvidenceButton } from "../components/FetchMissingEvidenceButton"; import { publishRefusal, reportMediaSummary, type ReportMediaSummary } from "../lib/reportList"; @@ -189,6 +190,7 @@ function ArticleListItem({ row, publishedCount }: { row: ArticleRow; publishedCo {row.claims === 1 ? "" : "s"} · {row.citations} citation{row.citations === 1 ? "" : "s"} </p> )} + {row.status !== "missing" && <ArticleVideoControl articleId={row.id} video={row.video} />} {row.problems.length === 0 ? ( <span className="text-xs text-muted-foreground">{STATUS_TEXT[row.status]}</span> ) : ( diff --git a/editor/app/sites/components/ArticleVideoControl.tsx b/editor/app/sites/components/ArticleVideoControl.tsx @@ -0,0 +1,47 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../jobs/actions"; +import { attachArticleVideoAction } from "../lib/attachVideoAction"; + +// An article's own video (release 32; `archilyzer reports attach-video +// --article` before it): a file on this machine, remuxed or encoded to fit the +// publish limit, beside the article as video.mp4 with a poster. +export function ArticleVideoControl({ articleId, video }: { articleId: string; video: string | null }) { + const [file, setFile] = useState(""); + const [poster, setPoster] = useState(""); + const [caption, setCaption] = useState(""); + const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; + return ( + <details className="text-sm" aria-label={`video of ${articleId}`}> + <summary className="cursor-pointer select-none text-xs text-muted-foreground"> + {video ? `Video: ${video}` : "No video"} · Attach video + </summary> + <div className="mt-2 flex flex-col gap-2"> + <div className="flex flex-wrap gap-3"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Video file (absolute path)</span> + <input value={file} onChange={(e) => setFile(e.target.value)} aria-label={`video file for ${articleId}`} className={`${input} w-96 max-w-full`} /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Poster image (optional)</span> + <input value={poster} onChange={(e) => setPoster(e.target.value)} aria-label={`poster for ${articleId}`} className={`${input} w-72 max-w-full`} /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Caption (optional)</span> + <input value={caption} onChange={(e) => setCaption(e.target.value)} aria-label={`caption for ${articleId}`} className="rounded border border-border bg-card px-2 py-1 text-sm w-72 max-w-full" /> + </label> + </div> + <StreamActionLog + trigger={() => attachArticleVideoAction(articleId, { video: file, ...(poster.trim() ? { poster } : {}), ...(caption.trim() ? { caption } : {}) })} + cancelAction={cancelJobAction} + buttonLabel="Attach video" + runningLabel="Attaching…" + label={`Attach video to ${articleId}`} + disabled={!file.trim()} + /> + </div> + </details> + ); +} diff --git a/editor/app/sites/lib/articlesServer.ts b/editor/app/sites/lib/articlesServer.ts @@ -25,7 +25,8 @@ import type { ReportExportsRow } from "./reportListServer"; // drafts, each read and validated as a site's report is (reportList.ts), with // its audience; the articles' prepared media; their exports; the last jobs. -export type ArticleRow = ReportRow & { audience: ReportAudience }; +// `video`: the article's own video (report.json `video.src`), or null. +export type ArticleRow = ReportRow & { audience: ReportAudience; video: string | null }; // An index.json that cannot be read is the tab's error to show, not an empty // list (lib/report/registry.ts readArticlesIndex). @@ -44,7 +45,9 @@ export async function readArticleRows(paths: Paths): Promise<{ rows: ArticleRow[ ); const rows = reportRows(published, dirIds, reads).map((row) => { const read = reads.get(row.id); - return { ...row, audience: articleAudience(read?.ok ? (read.value as { audience?: unknown }) : null) }; + const value = read?.ok ? (read.value as { audience?: unknown; video?: { src?: unknown } }) : null; + const video = typeof value?.video?.src === "string" ? value.video.src : null; + return { ...row, audience: articleAudience(value), video }; }); return { rows, indexError }; } diff --git a/editor/app/sites/lib/attachVideoAction.ts b/editor/app/sites/lib/attachVideoAction.ts @@ -0,0 +1,63 @@ +"use server"; + +// "Attach video" on the Articles tab (release 32): an article's own video, as +// `archilyzer reports attach-video --article <id> <video>` attaches it — the +// file remuxed (an H.264 mp4 under the limit) or encoded to fit the publish +// limit, written beside report.json as video.mp4 with a poster (given, kept, +// or a frame of the video), and `video` set through the article registry +// (patchArticle: locked, refused if it adds a problem). An `attach-report-video` +// job on its own queue: an encode takes minutes. +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +import path from "node:path"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { articleFile, patchArticle } from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { AttachVideoError, attachReportVideo } from "yt-dlp-transcript-common/publish/reportVideo"; +import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { safeRevalidate } from "../../lib/safeRevalidate"; + +const REPORT_VIDEO_QUEUE = "report-video"; + +export async function attachArticleVideoAction( + articleId: string, + opts: { video: string; poster?: string; caption?: string }, +): Promise<StreamActionResult> { + if (!isReportId(articleId)) return { ok: false, error: `"${articleId}" is not an article id` }; + const video = opts.video.trim(); + const poster = opts.poster?.trim(); + const caption = opts.caption?.trim(); + if (!path.isAbsolute(video)) return { ok: false, error: "The video is an absolute path to a file on this machine" }; + if (poster && !path.isAbsolute(poster)) return { ok: false, error: "The poster is an absolute path to an image on this machine" }; + const paths = getPaths(); + return runManagedFunction({ + kind: "attach-report-video", + queueKey: REPORT_VIDEO_QUEUE, + paths, + fn: async (onLog) => { + try { + const done = await attachReportVideo({ + reportFile: articleFile(paths, articleId), + setVideo: async (v) => { + if (!(await patchArticle(articleId, { video: v }, paths))) throw new AttachVideoError(`no article "${articleId}"`); + }, + video, + ...(poster ? { poster } : {}), + ...(caption ? { caption } : {}), + ffmpegBin: paths.ffmpegBin, + ffprobeBin: paths.ffprobeBin, + onLog: (l) => onLog(`${l}\n`), + }); + onLog( + `Attached to article ${articleId}: ${done.video.src} ` + + `(${done.mode === "remux" ? "remuxed" : `encoded, ${done.attempts} pass(es)`}, ${(done.bytes / (1024 * 1024)).toFixed(2)} MiB)\n`, + ); + safeRevalidate(["/sites/articles"]); + } catch (err) { + const e = err as Error & { stderr?: string }; + throw new Error(err instanceof AttachVideoError ? e.message : (e.stderr || e.message).trim().split("\n").slice(-3).join(" ")); + } + }, + }); +} diff --git a/editor/e2e/ops-buttons.spec.ts b/editor/e2e/ops-buttons.spec.ts @@ -0,0 +1,133 @@ +import { test, expect } from "@playwright/test"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +// By relative path, as frame-scan.spec.ts imports the kit: plain .mjs. +import { syntheticPokerHighlights } from "../../common/testing/frames/pokerReadings.mjs"; +import { channelStage, resetData, testPaths } from "./helpers"; + +// Release 32, lane R3: operations that were CLI- or ops-only, as buttons — +// find-copy's scope mode previewed from the channel's Download stage (a gone +// recording that is not YouTube's: listed, nothing asked of any network), the +// audio audit started from the same stage (the fake ffmpeg's tolerant decode +// reads a marked file as damaged), and a frame scan re-derived and corrected +// on the video page with no model. And the Configure form's audio check on an +// Odysee channel: ticked by default. Synthetic records only. + +const SLUG = "test-transcribe"; // an Odysee channel (one-transcribe-channel) +const GONE = "v7gone01"; +const AUDIO = "v7audio01"; +const FRAMES = "v7frames01"; +const rumble = (id: string) => `https://rumble.com/${id}-synthetic-recording.html`; + +async function video(id: string, files: Record<string, string>) { + const dir = join(testPaths().transcriptsDir, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(join(dir, "metadata.info.json"), JSON.stringify({ id, title: `Synthetic ${id}`, webpage_url: rumble(id), duration: 600 })); + for (const [name, body] of Object.entries(files)) await writeFile(join(dir, name), body); +} + +test.beforeEach(async () => { + await resetData("one-transcribe-channel"); +}); + +test("find copies of gone videos: the preview lists the candidate and arms the run", async ({ page }) => { + await video(GONE, { + "availability.json": JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted", webpageUrl: rumble(GONE), history: [] }), + }); + await page.goto(channelStage(SLUG, "download")); + const box = page.getByRole("region", { name: "find copies of gone videos" }); + await expect(box.getByRole("button", { name: "Find and fetch copies" })).toBeDisabled(); + await box.getByLabel("gone videos to look for").selectOption("all"); + await box.getByRole("button", { name: "Preview", exact: true }).click(); + const preview = box.getByLabel("find copies preview", { exact: true }); + await expect(preview).toBeVisible({ timeout: 30_000 }); + await expect(box.getByLabel("find copies preview counts")).toContainText("1 gone video with no media in 1 channel; 1 looked up"); + const row = box.getByTestId("find-copy-candidate"); + await expect(row).toHaveCount(1); + await expect(row).toContainText(`${SLUG}/${GONE}`); + await expect(row).toContainText("not looked for (not YouTube)"); + await expect(box.getByRole("button", { name: "Find and fetch copies" })).toBeEnabled(); + // Other settings than the preview's disarm it. + await box.getByLabel("gone videos to look for").selectOption("no-transcript"); + await expect(box.getByRole("button", { name: "Find and fetch copies" })).toBeDisabled(); +}); + +test("audit audio: the job decodes the held file, the verdict is beside it and on the video page", async ({ page }) => { + test.setTimeout(90_000); + await video(AUDIO, { "audio.m4a": "__CORRUPT__ __DUR=600__ held audio\n" }); + await page.goto(channelStage(SLUG, "download")); + const box = page.getByLabel("audit audio", { exact: true }); + await expect(box.getByLabel("audio audit tally")).toHaveText("Not audited."); + await box.getByRole("button", { name: "Audit audio" }).click(); + const log = page.getByLabel(`Audit audio of ${SLUG} output`); + await expect(log).toContainText("@@audio-audit", { timeout: 30_000 }); + await expect(log).toContainText('"damaged":1'); + // The report's tally once the job's regen lands. + await expect + .poll( + async () => { + await page.reload(); + return (await page.getByLabel("audio audit tally").textContent()) ?? ""; + }, + { timeout: 45_000, message: "the tally on the Download stage" }, + ) + .toContain("0 clean, 1 damaged, 0 undecodable"); + await page.goto(`/channels/${SLUG}/videos/${AUDIO}`); + await expect(page.getByLabel("audio integrity")).toContainText("damaged: 5:00 of 10:00 decodes (50%)"); +}); + +test("frame scan: Re-derive (no model), then a reading set aside as a misread from its event", async ({ page }) => { + const fx = syntheticPokerHighlights(); + await video(FRAMES, { + "frame-scan.poker.json": JSON.stringify({ + format: "archilyzer-frame-scan", + version: 1, + profile: "poker", + source: { savedVideo: "source-media.mp4", durationSeconds: 3000 }, + sampling: { everySeconds: 10, from: 0, to: 3000, width: 1280, keyframesOnly: true, frames: 300, kept: 300, skippedDuplicates: 0 }, + model: { route: "api", model: "claude-haiku-4-5", promptVersion: 3 }, + hints: { hero: fx.hero }, + costUsd: 0.5, + runs: [], + readings: fx.readings, + duplicates: [], + spoken: fx.spoken, + derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] }, + updatedAt: "2026-10-15T00:00:00.000Z", + }), + }); + await page.goto(`/channels/${SLUG}/videos/${FRAMES}`); + const panel = page.getByTestId("frame-scan-panel"); + await expect(panel.getByLabel("hero screen name")).toHaveValue(fx.hero); + await expect(panel.getByLabel("frame scan events")).toHaveCount(0); + await panel.getByRole("button", { name: "Re-derive (no model)" }).click(); + await expect(panel.getByLabel("re-derive result")).toContainText("tournaments 0 → 1"); + const events = panel.getByLabel("frame scan events"); + await expect(events).toContainText("bust"); + await expect(panel.getByLabel("frame scan summary")).toContainText("re-derived"); + + // The bust's reading at 48:20, opened from its event and set aside. + await events.getByRole("link", { name: "Correct the reading at 48:20" }).first().click(); + const form = panel.getByRole("region", { name: "frame reading" }); + await expect(form.getByLabel("frame reading heading")).toContainText("Reading at 48:20"); + await expect(form.getByLabel("Hero stack", { exact: true })).toHaveValue("0"); + await form.getByRole("button", { name: "Mark misread" }).click(); + await expect(form.getByLabel("frame reading status")).toContainText("Set aside as a misread; derived again"); + await expect(panel.getByLabel("frame scan corrections")).toContainText("48:20"); + await expect(panel.getByLabel("frame scan corrections")).toContainText("misread, set aside"); + // A person's value for a field: saved, shown beside what the model read. + await form.getByLabel("reading time").fill("25:00"); + await form.getByRole("button", { name: "Open reading" }).click(); + await expect(form.getByLabel("frame reading heading")).toContainText("Reading at 25:00"); + await form.getByLabel("Hero stack", { exact: true }).fill("133,333"); + await form.getByRole("button", { name: "Save correction" }).click(); + await expect(form.getByLabel("frame reading status")).toContainText("Correction saved"); + await expect(form).toContainText("read 120000"); + await expect(panel.getByLabel("frame scan corrections")).toContainText("hero.stack 133,333"); +}); + +test("the Configure form: an Odysee channel's audio check shows on by default", async ({ page }) => { + await page.goto(channelStage(SLUG, "configure")); + await expect(page.getByLabel("audio check default")).toContainText("on by default for Odysee"); + await expect(page.getByLabel("audio-check enabled")).toBeChecked(); +}); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9911,6 +9911,46 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri malformed → `FetchWindowError` `per_video` ("the source serves corrupt audio…"), nothing kept. Provenance `audioCheck: {verdict: "clean" | "partial", attempts}` (`ClipAudioCheck`, parsed tolerantly). Cached windows are not re-probed. -- The editor's Configure form writes `audioCheck` only when its box is ticked: an Odysee channel with no `audioCheck` - shows an unticked box though the check is on (owed: show the default). +- The editor's Configure form (since release 32 R3): on an Odysee channel the box shows ticked with no `audioCheck` + stored ("on by default for Odysee"); ticked with no other audio-check field → nothing written; unticked → + `{enabled: false}`. `channelConfigToFormData` ticks it the same way, so an ops patch keeps the default. + +## Release 32 lane R3: every operation has a button (verified 2026-10-16, branch `r32/ops-buttons`) + +- **Reading corrections** (`common/lib/frames/corrections.ts`): `frame-scan.<profile>.json` gains + `corrections?: [{t, at, by: "person", misread?: true, set?: {<field path>: value | null}, note?}]` — one per grid + second (coerce keeps the newest), sorted. Field paths per profile in `CORRECTABLE_FIELDS` (poker: phase, + tournament.{name, level, blinds.sb/bb/ante, playersLeft, totalPlayers, position, averageStack, prizePool, payout}, + hero.{stack, bb, bounty, cards}, hand.{pot, action}, event, log); `checkCorrectionSet` checks each by kind (whole, + number — commas allowed —, text, enum, lines, cards); null clears a field (empty objects pruned). The model's + `readings` are never rewritten. +- **The derivation applies them** (`deriveOf(…, {corrections})`): over the readings first (a duplicate copies the + corrected reading; a reading set aside is copied nowhere; a read second is never filled by a copy), then again over + the expanded list (a correction at a duplicate's own second). Idempotent. `rederiveRecord` passes the record's + corrections; `runFrameScan` carries them across every run, `fresh` included. The poker rules are unchanged: a + corrected value goes through the same smoothing and flags. +- **The controller** (`controller/frameCorrections.ts`): `frameReadingAt(paths, {slug, id, profile?, t})` → the grid + second nearest `t` (readings ∪ duplicates) with each field's `read` (model) and `value` (as derived), `copyOf`, + `prev`/`next`; `correctFrameReading(paths, {slug, id, profile?, t, set?, misread?, clear?, note?})` stores only the + fields that differ from the model's reading (none and not misread → the correction is removed), re-derives with the + cues and writes; refused while a frame-scan job of the video is queued or running (`frameScanBusy`, exported from + controller/frameScan.ts, also the rederive's guard). No ops route: the editor's actions only. +- **Snapshot `audioIntegrity`** (`AudioIntegrityTally {clean, damaged, undecodable, stale, lastCheckedAt?}`): one + count per `audio-integrity.json`, the verdict recomputed by `integrityVerdict`; `stale` when the record's file is not + in the dir's audio files or its size differs (the same name+size test the `corruptHeldAudio` bucket uses). Optional: + absent until a channel's next regen. +- **`StreamActionLog.onSettled(started, {log, jobId})`**: the second argument is new (the run's whole streamed log and + its job id). `editor/app/lib/resultMarker.ts` reads a job's last `@@<kind> {json}` line client-side; its marker + strings are pinned to the controllers' constants by its test. +- **Job kind `attach-report-video`** (queue `report-video`, not drainable, not replayable, no media guard): the + Articles tab's Attach video, `attachReportVideo` + `patchArticle`, as the CLI row. +- **Editor surfaces** (no new routes, no new ops keys): channel Download stage — `FindCopiesControl` + (`app/components/`, also on `/sites/<id>`), Audit audio, "More ways in" (import-archive-org, feed-metadata, + remote-listing for Odysee/BitChute); Cleanup — Keep videos matching (`keepVideosAction`); posts channel — + import-post, capture-posts; video page — the audit's verdict line (`aria-label="audio integrity"`), "Media tools" + (attach-media narrowed to the id — `items` when a file is named, else `match` = the escaped id —, prepare-playable + `ids: [id]`, wayback / archive-org refresh run in the request), Frame scan's Re-derive and Correct a reading + (`?reading=<s>` opens it). Find copies, attach, the archive.org import, the feed backfill, keep-matching and the + records refreshes are armed by a preview of the same settings; the playable copy (lossless, keyed by the source's + sha256) is not. diff --git a/plans/release-32/ops-buttons.md b/plans/release-32/ops-buttons.md @@ -0,0 +1,111 @@ +# Release 32, lane R3 — every operation has a button, in the editor (as shipped) + +Branch `r32/ops-buttons` from `main` `977917c7`. Brief: `r32r3-brief.md` (the plan of record for this lane). FACTS: +"Release 32 lane R3: every operation has a button" (and the Configure-form line of "The audio check's reach"). + +## What and why + +The operator's rule for the release: every step a model or the CLI can do must also be doable by a person in the UI, +and nothing built here calls a model. Each gap the brief named, verified, now has a surface where its object lives. + +- **Frame scan, with no model** (`common/lib/frames/corrections.ts`, `controller/frameCorrections.ts`; the video + page's Frame scan panel): **Re-derive (no model)** beside the hero's screen name (the panel's action refused + `rederive` before), and **Correct a reading** — open the reading at a time, or from an event's **Correct** + (`?reading=<s>`), set fields to what the frame shows or **Mark misread**, **Clear correction**. A correction is kept + in the sidecar's `corrections` beside the model's readings (never over them), only the fields that differ from the + model's reading; the derivation lays the corrections over the readings (duplicates copy the corrected reading, a + misread is copied nowhere) and every scan and re-derive keeps them. Saving re-derives at once. P2's guarantees hold: + the poker rules are untouched, a corrected value goes through the same smoothing and flags. +- **find-copy's scope mode** (`app/components/FindCopiesControl.tsx`, on the channel's Download stage and + `/sites/<id>`): which gone videos, at most N lookups, try failed copies again; **Preview** is the dry-run job, its + `@@find-copy` line read into the candidate list with the copy each would use; **Find and fetch copies** is armed by + a preview of the same settings and links the find-copy and fetch-copies jobs. +- **The audio audit** (Download stage, `audioAuditActions.ts`): scope, at most N files, decode again; the line is the + channel report's new `audioIntegrity` tally (clean, damaged, undecodable, out of date, last checked). The video page + shows the file's verdict (`describeIntegrity`, the gaps, out of date when the file changed). +- **The video's media operations** ("Media tools", `mediaToolsActions.ts`): attach from a local archive (attach-media + narrowed to this id: `items` when a file is named, else `match` = the escaped id; preview then attach), a playable + copy (prepare-playable `ids: [id]`), and for a Wayback or archive.org record the channel's records refreshed + (`refreshWaybackRecords` / `refreshArchiveOrgRecords` in the request; preview then refresh; a Wayback record's title + and date as `titles`). +- **reports attach-video** (Articles tab, `sites/lib/attachVideoAction.ts`): per article, a video file, poster and + caption → an `attach-report-video` job (new kind, queue `report-video`). +- **The rest of COMMANDS.md's channel-level ops-only rows**: the Download stage's "More ways in" (import-archive-org + one item, preview then import; feed-metadata, preview then complete; remote-listing on Odysee/BitChute), a posts + channel's import-post and capture-posts, the Cleanup stage's **Keep videos matching** (keep-videos; preview then + keep). +- **The Configure form's audio check**: an Odysee channel with no `audioCheck` shows ticked, "on by default for + Odysee"; ticked with nothing else writes nothing, unticked writes `{enabled: false}`; `channelConfigToFormData` ticks + it the same way, so `pnpm ops channel-config` keeps the default and `{"audioCheckEnabled": false}` turns it off. +- `StreamActionLog.onSettled` also hands over the run's log and job id (`{log, jobId}`), so a dry run's result marker + can be read (`app/lib/resultMarker.ts`). + +| Commit | What | +| --- | --- | +| `d1575e95` | common: reading corrections (lib + controller), `frameScanBusy`, the snapshot's `audioIntegrity` tally; tests | +| `68fc0cc7` | editor: the Frame scan panel's Re-derive and Correct a reading, the view's hero/corrections, `?reading=` | +| `e7480d7c` | editor: find copies (channel + site), Audit audio, the video page's verdict line and Media tools, `onSettled` out, resultMarker | +| `aa95ddb9` | editor: Attach video on each article; the `attach-report-video` job kind | +| `9aeb1e20` | channels: the Odysee audio-check default on the Configure form and in the ops patch | +| `790a72f5` | channels: archive.org import, feed backfill, remote listing, import-post, capture-posts | +| `1ed526da` | channels: Keep videos matching | +| `d406c560` | editor: `e2e/ops-buttons.spec.ts` | +| (this commit) | this record, FACTS, CHANGELOG | + +## Gates (from the worktree root, every heavy step through the shared lock) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean (editor's tsc before each editor commit, the + full workspace before the spec commit and at the end). +- common: 4448 (4447 + 1 skipped) at the branch's start → 4455 (4454 + 1 skipped), all pass. New: `lib/frames/corrections.test.ts` 5, + `controller/frameCorrections.test.ts` 2; `controller/audioAudit.test.ts` (the tally asserted in the report test); + `jobs/jobKinds.test.ts` pins the new kind. `lib/frames/*` 87/87 with the new files. +- editor unit: 322 → 327/327 (`lib/resultMarker.test.ts` 2, `frameScanView.test.ts` +1, + `parseChannelForm.test.ts` +2). +- `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: clean (no CLI row, ops + key, env or settings key changed; COMMANDS.md not regenerated). +- e2e (editor, one spec, through the lock): `ops-buttons.spec.ts` **4/4 passed** in 20.9 s on its first run (the + start-mode build in the heavy slot first: TypeScript 33 s; the slot waited 1 m 52 s and 3 m 25 s behind another + project's jobs) — find-copy preview (a gone non-YouTube record: listed, no network), Audit audio (the fake + ffmpeg's damaged file: the job's `@@audio-audit`, the tally on the Download stage after the regen, the verdict on + the video page), Re-derive then Mark misread from an event and a field corrected, the Odysee audio-check default. +- test:scripts, mcp, export, homepage, umtool: not run — nothing under `umtool/`, `scripts/`, `mcp/`, `export/` or + `homepage/` changed, and the common changes they import (`deriveOf`, the frame-scan sidecar's coerce) change + nothing for a sidecar without `corrections`. + +## Decisions I made + +- **Corrections live beside the readings, and the derivation reads both** — the model's readings stay as read, so a + correction can be cleared and the record says who said what. Only differing fields are stored, so the form can + send every field it shows. +- **A correction does not bypass the derivation's rules** (P2: "keep the guarantees"): the person's value replaces + the model's in the reading, and smoothing, flags and the one-tournament rule apply as before. To take a reading out + entirely, Mark misread. +- **"Hero name" is the record's hint, not a reading field** (a reading has no hero name): it sits beside Re-derive, + as `frame-scan {rederive, hero}` takes it. +- **No ops key for corrections**: the brief asks UI for what the CLI does, not the reverse; the controller is + callable if an agent needs it later. +- **Corrections re-derive in the request and are no job** (as `rederive` is): pure code over one sidecar. +- **The Wayback / archive.org refreshes run in the request**, not as jobs: offline, over one channel's records, and + the controller already skips a record a live job holds. They are channel-wide (as the CLI) though offered on the + video page of such a record; a rename links the new id. +- **The audit tally is in the snapshot**, read where the `corruptHeldAudio` bucket already reads each sidecar — no new + walk; it shows after the job's regen (the e2e polls for it). +- **Attach video is a job on its own queue `report-video`** (an encode takes minutes), not gated by the heavy slot: + `attachReportVideo` spawns ffmpeg itself and the CLI row never was; a ≤24 MiB output is a short encode. +- **find-copy's Run is armed by a preview of the same settings** (the evict pattern), and runs its lookups again — + the preview is not replayed (a copy may have appeared or gone since). +- **The Odysee default**: ticked with no other audio-check field saves nothing (the default), so saving an Odysee + channel's form never writes `{enabled: true}` it did not have; a stored `{enabled: true}` with no other field is + saved as no key — the same behaviour. + +## Not done, and why + +- Channel-wide `media attach` (a whole archive, `--create-records`) and channel-wide `media playable` + (`--trackers`, `--root`): the buttons are per video; the channel-wide runs stay `pnpm ops attach-media` / + `prepare-playable`. +- `feeds backfill-metadata --feed <url>` (another feed than the channel's URL): the button reads the channel's URL. +- `persist-videos` in bulk: the video page's existing Persist source video covers one video. +- `storage migrate-tier` (runs only with the editor stopped), `reconcile video-dirs` (every report regen runs it), + `verify transcripts` and `diarize backfill` per video (passthrough diagnostics; the Cleanup stage's Diarize speakers + covers a channel): left on the CLI. +- No live run (the orchestrator's).