commit ff2035cdf9ff0a9e3a9a5b2f3ff2701560a68d87 parent 25156ab10ca6c9fd32d7e8a54b00776a7bacd9cb Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 21 Nov 2026 11:04:47 -0500 stored text, slice 4: every caption reader reads a track stored as transcript.<lang>.vtt.zst Every caption track is now a declared stored-text name (isStoredCaptionName: transcript.<lang>.vtt, not a transcriber's transcript.tmp-<pid>.vtt). No production code compresses one yet; this slice makes every reader read either form, so a stored track is never absent, never re-fetched and never read as zstd bytes: - readVideoFiles is LOGICAL (physicalEntries for the byte walk); readEnglishVttCues, the alternate tracks, normalize's freshness (mtimes of either form), its word-timing head and its en/en-orig size test (logical sizes), the index's transcriptMs, buildStats, compose's cited record, report refresh, copies, find-clips, the live pre-clip, duplicate shorts. - Head sniffs decode (readStoredTextHead): the ASR/manual provenance and the word-timing check would otherwise answer wrong, not absent. - The work-triggering skips: destinationExists (a re-fetch of the URL), hasAnyTranscriptOnDisk (an audio download and a transcription), the archive.org twin. The subtitle passes (youtubeHandlingArgs, downloadSubsForUrl) exclude each stored track by code from --sub-langs, so yt-dlp never lands a second plain copy beside it. - Deleters: the superseded-auto-caption purge and the clear-transcript fix list logically and remove both forms; the purge keeps both when they differ or the stored one does not decode (a slice-1 test changed to say so). - Movers: reconcile collides by logical name (already generic); the tier migration's reclaim takes a platter copy whose twin is stored only when it decodes to exactly its bytes. - The remote worker gets the PLAIN bytes under the logical name (readUnitInputFiles). The files route serves a stored caption decoded (by its plain name, or ?decoded=1), the files card previews it; the video page matches tracks over the logical listing. Set as transcript reads either form and keeps a stored en beside the new plain one. - umtool's bare-node readers (cue source, clip words, ingredients) go through lib/storedText-read.mjs, a plain-JS twin held equal by a test. - Two new grep gates: a raw read/stat/delete naming a caption, and a caption rule applied in a file with no logical listing. Tests in temp dirs, red with the sources at HEAD: storedText.captions (13), the purge (2), buildIndex (u) — the real index sees zero mutations after every caption is compressed and re-reads the same cues, alternates and subs — the snapshot, reconcile, reclaim, the files route, the clear fix, umtool's cue source, the .mjs twin, the gates. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
51 files changed, 1418 insertions(+), 134 deletions(-)
diff --git a/common/bin/migrate-media-tier.test.ts b/common/bin/migrate-media-tier.test.ts @@ -410,6 +410,29 @@ test("--reclaim keeps a platter copy whose twin on the corpus disk is gone or di assert.ok(lines.some((l) => /kept 2 entries on the drive with no same-size copy/.test(l))); }); +test("--reclaim takes a platter caption whose twin was since COMPRESSED — only when the stored form holds its very bytes", async () => { + // Lane text-compress-captions: a caption brought home and then compressed + // is `transcript.en.vtt.zst` on the corpus disk. Its platter copy is taken + // when the stored form decodes to exactly its bytes; a stored form of OTHER + // content (or one that does not decode) keeps the copy, reported. + resetCorpus(); + seedLegacy(); + writeFileSync(path.join(oldTree(SLUG), "v3", "transcript.en.vtt"), VTT); + await run(); + const { storeFixture } = await import("../testing/storedTextFixture"); + const data = (id: string) => path.join(channelDir(), "data", id); + await storeFixture(data("v1"), "transcript.en.vtt"); + // v3: since the migration, the track was re-written with other words of + // the same size, then compressed — the stored form is not the platter copy. + writeFileSync(path.join(data("v3"), "transcript.en.vtt"), VTT.replace(/[a-z]/, "Z")); + await storeFixture(data("v3"), "transcript.en.vtt"); + const res = await run({ reclaim: true }); + assert.equal(res.exitCode, 0, res.channels[0].detail); + assert.deepEqual(res.channels[0].reclaimKept?.sort(), ["v3/transcript.en.vtt"]); + assert.throws(() => lstatSync(path.join(mediaTarget(), "v1", "transcript.en.vtt")), "its stored twin holds it: taken"); + assert.ok(lstatSync(path.join(mediaTarget(), "v3", "transcript.en.vtt")).isFile(), "a stored twin of other content: kept"); +}); + test("a reclaim killed after its deletes resumes from its marker and ends clean", async () => { resetCorpus(); seedLegacy(); diff --git a/common/bin/migrate-media-tier.ts b/common/bin/migrate-media-tier.ts @@ -68,6 +68,7 @@ import { lutimes, mkdir, readdir, + readFile, readlink, rename, rm, @@ -83,6 +84,8 @@ import type { SiteSettings } from "../lib/settings"; import { formatBytes } from "../lib/format"; import { getFreeBytes } from "../lib/diskSpace"; import { classifyEntry, CLIPS_DIR, isTierable } from "../lib/mediaTier"; +import { STORED_TEXT_SUFFIX, isStoredTextName } from "../lib/storedText"; +import { decodeStoredBytes } from "../lib/storedText-server"; import { channelMediaLink, relocatedMediaDir, @@ -935,7 +938,12 @@ async function reclaimTree( try { twin = await lstat(path.join(ssd, rel)); } catch { - return false; + // A TWIN IN ITS STORED FORM (lib/storedText.ts): a caption brought home + // and since compressed is `<name>.zst` on the corpus disk. It is the + // twin only when it decodes whole (checksum, length) to exactly the + // platter copy's bytes — never by size alone, so a reclaim run after a + // compress-text run removes no copy the stored form does not hold. + return st.isFile() && isStoredTextName(path.basename(rel)) && (await storedTwinHolds(path.join(ssd, rel), path.join(mediaDir, rel))); } if (st.isDirectory()) return twin.isDirectory(); return !twin.isDirectory() && twin.size === st.size; @@ -979,6 +987,22 @@ async function reclaimTree( return { reclaimedFiles: files, reclaimedBytes: bytes, reclaimKept: kept }; } +// Does `<plain>.zst` beside `plain` (a real file) hold exactly `copy`'s bytes? +async function storedTwinHolds(plain: string, copy: string): Promise<boolean> { + const stored = `${plain}${STORED_TEXT_SUFFIX}`; + try { + const z = await lstat(stored); + if (!z.isFile()) return false; + const [decoded, bytes] = await Promise.all([ + readFile(stored).then((b) => decodeStoredBytes(b, stored)), + readFile(copy), + ]); + return decoded.equals(bytes); + } catch { + return false; + } +} + // --reclaim on a channel already on the media tier: only one this tool // migrated (its reclaim note stands), whose media drive answers and whose // `data/` is a real directory. diff --git a/common/controller/adoptLocalMediaReference.ts b/common/controller/adoptLocalMediaReference.ts @@ -11,6 +11,8 @@ import { openExternalMedia } from "../lib/externalMediaResolver-server"; import { localMediaFingerprint } from "../lib/localMediaScan"; import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference } from "../lib/localMedia"; import { writeExternalMediaReference } from "../lib/externalMedia-server"; +import { storedNameOf } from "../lib/storedText"; +import { decodeStoredBytes } from "../lib/storedText-server"; type Selection = { sourceToken: string; media: string; fingerprint: string }; export type LocalMediaAdoptionResult = { status: "ready" | "attached" | "already-linked" | "conflict"; stagingCleanupFailed?: boolean }; @@ -34,6 +36,17 @@ async function bytes(root: string, name: string, afterRead?: () => Promise<void> } finally { await h.close(); } } +// A caption's exact bytes in either form (lib/storedText.ts): the plain file +// by `bytes`, else its stored `.zst` by `bytes` (the same no-follow, bounded, +// unchanged read), decoded — the frame's checksum and length checked. The +// decoded bytes are the plain file's exactly. +async function captionBytes(root: string, name: string): Promise<Buffer> { + if (await lstat(path.join(root, name)).then(() => true, () => false)) return bytes(root, name); + const stored = storedNameOf(name); + if (!(await lstat(path.join(root, stored)).then(() => true, () => false))) return bytes(root, name); + return decodeStoredBytes(await bytes(root, stored), path.join(root, stored)); +} + // Separate from import: occupied records are NEVER silently merged by scanning. // This explicit operation requires exact existing metadata/transcript matches. // It publishes only a new sidecar and never changes/removes prototype links. @@ -68,7 +81,7 @@ export async function adoptLocalMediaReference(paths: Paths, slug: string, }); const channel=path.join(paths.channelsDir,slug), data=path.join(channel,"data"), record=path.join(data,row.directoryId); for(const dir of [channel,data,record]) { const s=await lstat(dir); if(!s.isDirectory() || s.isSymbolicLink()) throw new Error("Expected real archive directories"); } - const metadata=await bytes(record,"metadata.info.json"), transcript=await bytes(record,"transcript.en.vtt"); + const metadata=await bytes(record,"metadata.info.json"), transcript=await captionBytes(record,"transcript.en.vtt"); if(!metadata.equals(source.metadata) || !transcript.equals(source.transcript)) throw new Error("Existing metadata or transcript differs; manual review required"); // Repeat the configuration/relocation guards after the source reads too. const after=await previewLocalMedia(paths,slug); diff --git a/common/controller/archiveOrgDownload.ts b/common/controller/archiveOrgDownload.ts @@ -48,6 +48,7 @@ import path from "node:path"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { appendFile, mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import { readdirLogical } from "../lib/storedText-server"; import type { ManagedDownloadOpts } from "../ytdlp/downloadOneManaged"; import type { AudioFormat } from "../lib/channelConfig"; import type { @@ -165,8 +166,9 @@ function extOf(name: string): string { return m ? m[1].toLowerCase() : ""; } +// LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript. async function hasTranscriptOnDisk(videoDir: string): Promise<boolean> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const entries = await readdirLogical(videoDir); return entries.some((e) => { if (e === "transcript.json") return true; const m = /^transcript\.([^.]+)\.(?:vtt|json|json3|srv1|srv2|srv3)$/.exec(e); diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts @@ -969,6 +969,64 @@ test("(t) lane text-compress: THE COMPRESSOR itself, over a real and a tiered ch assert.deepEqual(mtimesOf(), before); }); +test("(u) lane text-compress-captions: every caption track compressed — the index sees NO change, and reads the same cues, alternates and subs", async () => { + resetCorpus(); + seedVideo("c1", CHANNEL, { subs: true }); + seedVideo("c2"); + // c1 carries an en-orig whose words differ from en (an alternate track), a + // German sub track, and sub-millisecond times a `Date` would lose. + const ORIG = VTT.replace("First", "Original").replace("Second", "Spoken"); + writeFileSync(path.join(videoDir("c1"), "transcript.en-orig.vtt"), ORIG); + const { utimesSync } = await import("node:fs"); + for (const [n, t] of [["transcript.en.vtt", 1763700000.123457], ["transcript.en-orig.vtt", 1763700002.000003], ["transcript.de.vtt", 1763700003.5]] as const) { + utimesSync(path.join(videoDir("c1"), n), t, t + 0.000001); + } + const all = () => + withIndex((db) => ({ + mtimes: [...db("mtimes").getRange()].map(({ key, value }) => [key, value]), + cues: [...db("cues").getRange()].map(({ key, value }) => [key, value]), + subs: [...db("subs").getRange()].map(({ key, value }) => [key, value]), + alts: [...db("alts").getRange()].map(({ key, value }) => [key, value]), + })); + await runIndex(); + const before = all(); + assert.ok(before.alts.length > 0, "the fixture has an alternate track"); + assert.ok(before.subs.length > 0, "the fixture has a sub track"); + assert.ok(before.cues.length >= 2); + + // THE COMPRESSOR over every caption of both videos (c2 through the fixture + // helper, the way a run killed after its rename leaves it). + const { compressStoredText } = await import("../lib/storedText-write-server"); + for (const n of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.de.vtt"]) { + const out = await compressStoredText(videoDir("c1"), n, { reserveBytes: 0 }); + assert.equal(out.status, "compressed", `${n}: ${JSON.stringify(out)}`); + } + const { storeFixture } = await import("../testing/storedTextFixture"); + await storeFixture(videoDir("c2"), "transcript.en.vtt"); + assert.deepEqual(readdirSync(videoDir("c1")).filter((n) => n.endsWith(".vtt")), [], "no plain caption is left"); + + const after = await runIndex(); + assert.equal(after.res.changed, 0, after.log.join("\n")); + assert.equal(after.res.added, 0); + assert.equal(after.res.removed, 0); + assert.deepEqual(all(), before, "the same mtimes, cues, subs and alternates"); + + // A change elsewhere re-reads both records: everything comes from the stored forms. + seedVideo("c1", CHANNEL, { title: "Retitled" }); + seedVideo("c2", CHANNEL, { title: "Retitled" }); + // seedVideo wrote a plain en.vtt again (the same bytes): what a re-fetch + // would leave beside the stored one — plain is read, and is the same. + rmSync(path.join(videoDir("c1"), "transcript.en.vtt")); + rmSync(path.join(videoDir("c1"), "transcript.de.vtt"), { force: true }); + rmSync(path.join(videoDir("c2"), "transcript.en.vtt")); + const reread = await runIndex(); + assert.equal(reread.res.changed, 2, reread.log.join("\n")); + const now = all(); + assert.deepEqual(now.cues, before.cues, "the cues are read from the stored captions"); + assert.deepEqual(now.subs, before.subs, "the German track is read from its stored form"); + assert.deepEqual(now.alts, before.alts, "the alternate is read from the stored en-orig"); +}); + test("(z) no write this file caused landed outside its temp root", () => { // LMDB writes natively, past the spy: its file must be under the root too. assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath); diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -575,7 +575,10 @@ async function scanSource( : [picked.filename, ...captionInputs(files.entries)]; for (const name of inputs) { try { - const ms = (await stat(path.join(fullVideoDir, name))).mtimeMs; + // Either form (lib/storedText.ts): a caption stored compressed + // carries the plain file's mtime exactly, so the same + // `transcriptMs` — a compression re-ingests nothing. + const ms = (await statStoredText(fullVideoDir, name)).stats.mtimeMs; if (transcriptMs === null || ms > transcriptMs) transcriptMs = ms; } catch { // ignore diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts @@ -72,6 +72,7 @@ import { heldReason, } from "../lib/channelMediaHold"; import { getSettings } from "../lib/settings"; +import { storedTextMtimeMs } from "../lib/storedText-server"; import type { Paths } from "../lib/paths"; import { channelsOnlyOnUnlistedSites, @@ -271,7 +272,8 @@ async function resolveAcquisitionDates( if (transcribedDate === null) { const picked = pickIndexTranscript(await readVideoFiles(videoDir)); const mtime = - (picked ? await fileMtimeMs(path.join(videoDir, picked.filename)) : null) ?? + // Either form (lib/storedText.ts): a stored caption carries its mtime. + (picked ? await storedTextMtimeMs(videoDir, picked.filename) : null) ?? (await fileMtimeMs(path.join(videoDir, CUES_JSON_FILENAME))); transcribedDate = (mtime != null ? ymdFromMs(mtime) : null) ?? downloadedDate; } diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts @@ -658,6 +658,40 @@ test("a chat-only livestream whose chat is STORED compressed is still a corpus m } }); +test("videos whose captions are STORED compressed read exactly as before: downloaded, transcribed, ASR-only (lane text-compress-captions)", async () => { + // Missed, an ASR-only video would leave the replace lane's bucket, and a + // captioned one would read undownloaded — the download lane fetching it + // again. The byte walk counts the stored file as text, under its own name. + const ASR = + "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" + + "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" + + "Second<00:01:10.000><c> caption</c>\n"; + const { dir, paths, channelDir } = await filteredChannel({ listed: ["aaaa0000001", "bbbb0000002"] }); + try { + for (const id of ["aaaa0000001", "bbbb0000002"]) { + const videoDir = path.join(channelDir, "data", id); + await mkdir(videoDir, { recursive: true }); + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id, title: `Synthetic ${id}` })); + await writeFile(path.join(videoDir, "transcript.en.vtt"), ASR); + } + const plain = await generateChannelSnapshot(paths, "alpha"); + const { storeFixture } = await import("../testing/storedTextFixture"); + for (const id of ["aaaa0000001", "bbbb0000002"]) { + await storeFixture(path.join(channelDir, "data", id), "transcript.en.vtt"); + } + const stored = await generateChannelSnapshot(paths, "alpha"); + assert.deepEqual(stored.buckets.autoSubsOnly, ["aaaa0000001", "bbbb0000002"]); + assert.deepEqual(stored.buckets.autoSubsOnly, plain.buckets.autoSubsOnly); + assert.deepEqual(stored.undownloadedIds, plain.undownloadedIds); + assert.deepEqual(stored.undownloadedIds, []); + assert.equal(stored.totals.downloaded, plain.totals.downloaded); + assert.equal(stored.totals.transcribed, plain.totals.transcribed); + assert.equal(stored.totals.transcribed, 2); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("before the chat lands it is chatOnlyPending — the download lane's bucket", async () => { const { dir, paths } = await filteredChannel({ filter: { include: "keep", rejectedLivestreams: "chat-only" }, diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -1046,7 +1046,9 @@ export async function generateChannelSnapshot( let textBytes = 0; let clipsBytes = 0; const linked: string[] = []; - for (const name of files.entries) { + // PHYSICAL: a stored `.zst` is a file of its own size (text unless + // its name is tierable — lib/mediaTier.ts). + for (const name of files.physicalEntries) { try { const st = await lstat(path.join(dir, name)); if (st.isSymbolicLink()) { diff --git a/common/controller/copiesLane.ts b/common/controller/copiesLane.ts @@ -30,6 +30,8 @@ import { isGroup, type AutoQueueKind, type AutoQueueNode, type AutoQueuePolicy } import { mapConcurrent } from "../lib/concurrency"; import { isTranscriptVtt, readVideoFiles, resolvePrimaryVtt, WHISPER_FILENAME } from "../lib/videoStatus"; import { parseVtt } from "../lib/vtt"; +import { isStoredTextName, logicalEntries, storedNameOf } from "../lib/storedText"; +import { readStoredText } from "../lib/storedText-server"; import { resolveCaptionsProvenance } from "../lib/subtitleProvenance"; import { operationsForLane } from "../lib/operations"; import { DIARIZATION_FILENAME } from "../lib/videoStatus"; @@ -74,11 +76,15 @@ export type CopiesLaneIo = { readFile: (p: string) => Promise<string>; readdir: (p: string) => Promise<string[]>; stat: (p: string) => Promise<{ mtimeMs: number; size: number }>; + // A caption's text in either form (lib/storedText.ts). A test's seam may + // leave it out: the plain file is read through `readFile` then. + readCaption?: (dir: string, name: string) => Promise<string>; }; const realIo: CopiesLaneIo = { readFile: (p) => readFile(p, "utf8"), readdir: (p) => readdir(p), stat: (p) => stat(p), + readCaption: (dir, name) => readStoredText(dir, name, "utf8"), }; let io: CopiesLaneIo = realIo; let revalidateMs = COPY_DONE_REVALIDATE_MS; @@ -224,7 +230,10 @@ type DoneRules = { // The files that decide a video's done state for the lane, with their sizes // and mtimes: equal signatures, equal answers. async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig: string; entries: string[] }> { - const entries = (await io.readdir(videoDir).catch(() => [] as string[])).sort(); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is listed under + // its plain name, and stamped by the form that is there. + const physical = await io.readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(physical).sort(); const decisive = kind === "transcription" ? entries.filter((e) => e === WHISPER_FILENAME || isTranscriptVtt(e)) @@ -236,7 +245,11 @@ async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig e === ATTRIBUTION_FILENAME || e === AUDIO_INTEGRITY_FILENAME, ); - const stamps = await Promise.all(decisive.map((e) => stampOf(path.join(videoDir, e)))); + const stamps = await Promise.all( + decisive.map((e) => + stampOf(path.join(videoDir, physical.includes(e) || !isStoredTextName(e) ? e : storedNameOf(e))), + ), + ); // The Speakers states also turn on which other files are there (audio, a // container), so the backfill signature carries the whole listing. return { sig: JSON.stringify([kind === "backfill" ? entries : decisive, stamps]), entries }; @@ -268,7 +281,8 @@ async function transcriptDone(videoDir: string, entries: readonly string[], rule if (rules.replaceAutoSubs && (await resolveCaptionsProvenance(videoDir, entries)) === "asr") return false; try { let words = 0; - for (const cue of parseVtt(await io.readFile(path.join(videoDir, vtt)))) words += speechWords(cue.text); + const text = io.readCaption ? await io.readCaption(videoDir, vtt) : await io.readFile(path.join(videoDir, vtt)); + for (const cue of parseVtt(text)) words += speechWords(cue.text); return words >= min; } catch { return false; diff --git a/common/controller/duplicateShorts.ts b/common/controller/duplicateShorts.ts @@ -49,6 +49,7 @@ import { STATS_SCHEMA_VERSION } from "../lib/stats"; import type { Cue } from "../lib/vtt"; import { parseTranscriptJson } from "../lib/whisper"; import { readVideoFiles, pickIndexTranscript } from "../lib/videoStatus"; +import { readStoredText } from "../lib/storedText-server"; import { DEFAULT_ALIGNMENT_TOLERANCE_SECONDS, DEFAULT_CONTAINMENT_THRESHOLD, @@ -966,7 +967,8 @@ async function readRawCues( if (!picked) return null; let raw: string; try { - raw = await readFile(path.join(dir, picked.filename), "utf8"); + // Either form (lib/storedText.ts): a caption stored as `.zst` is read. + raw = await readStoredText(dir, picked.filename, "utf8"); } catch { return null; } diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts @@ -63,6 +63,7 @@ import { getSettings } from "../lib/settings"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { findSourceMedia, isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; import { DIARIZATION_FILENAME, englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus"; +import { logicalEntries } from "../lib/storedText"; import { loadSavedVideo, resolveSavedVideo } from "../lib/savedVideo-server"; import { backfillLaneOperations, DIARIZATION_OPERATION_ID } from "../lib/operations"; import { isGateHeld } from "../lib/pauseGates"; @@ -201,7 +202,10 @@ export async function inspectFindClips( const audio = pickPreferredAudio(entries.filter(isRealAudioFile)); let audioPath: string | null = audio ? path.join(videoDir, audio) : container ? path.join(videoDir, container) : null; if (!audioPath && pointer) audioPath = await resolveSavedVideo(videoDir).catch(() => null); - const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(entries)[0] ?? null); + // LOGICAL for the transcript (lib/storedText.ts): a stored caption counts. + const transcript = entries.includes(WHISPER_FILENAME) + ? WHISPER_FILENAME + : (englishVttsByPreference(logicalEntries(entries))[0] ?? null); const words = await loadWordTimings(videoDir).catch(() => null); return { saved: pointer !== null || container !== null, diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts @@ -39,7 +39,7 @@ // machine. import path from "node:path"; -import { mkdir, readdir, rm } from "node:fs/promises"; +import { mkdir, rm } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { getSettings } from "../lib/settings"; @@ -51,6 +51,7 @@ import { savedVideoDir } from "../lib/savedVideo"; import { loadSavedVideo } from "../lib/savedVideo-server"; import { savedVideoPath } from "../lib/savedVideo"; import { englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus"; +import { readdirLogical } from "../lib/storedText-server"; import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl"; import { getWorkerToken } from "../lib/workerToken"; import { @@ -290,7 +291,8 @@ export function umtoolMiner(umtool: string, token: string, doFetch: typeof fetch } export async function hasCorpusTranscript(videoDir: string): Promise<boolean> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript. + const entries = await readdirLogical(videoDir); return entries.includes(WHISPER_FILENAME) || englishVttsByPreference(entries).length > 0; } diff --git a/common/controller/normalizeTranscript.ts b/common/controller/normalizeTranscript.ts @@ -4,7 +4,13 @@ // shape that buildIndex would emit, plus a `source` marker. import path from "node:path"; -import { open, readdir, readFile, stat } from "node:fs/promises"; +import { open, readFile, stat } from "node:fs/promises"; +import { + readStoredTextHead, + readdirLogical, + storedTextLogicalSize, + storedTextMtimeMs, +} from "../lib/storedText-server"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { hasWordTiming, type Cue } from "../lib/vtt"; import { @@ -300,14 +306,17 @@ export async function isCuesJsonFresh( ): Promise<{ fresh: boolean; reason: CuesFreshReason; cuesPath: string }> { const cuesPath = path.join(videoDir, CUES_JSON_FILENAME); const metaPath = path.join(videoDir, META_FILENAME); - const entries = await readdir(videoDir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is an input under + // its plain name, and its mtime is the plain file's (the stored form carries + // it exactly), so a compression moves no cues.json to stale. + const entries = await readdirLogical(videoDir); const whisperPath = path.join(videoDir, WHISPER_FILENAME); const inputs = captionInputs(entries); const [cuesMs, metaMs, whisperMs, ...inputMs] = await Promise.all([ mtimeMs(cuesPath), mtimeMs(metaPath), mtimeMs(whisperPath), - ...inputs.map((n) => mtimeMs(path.join(videoDir, n))), + ...inputs.map((n) => storedTextMtimeMs(videoDir, n)), ]); const vttMs = inputMs.reduce<number | null>( (max, ms) => (ms !== null && (max === null || ms > max) ? ms : max), @@ -383,18 +392,24 @@ async function followsCaptionTrackRule( const vtts = englishVttsByPreference(entries); if (vtts.length === 0) return true; try { - if (vtts.length === 1 && hasWordTiming(await readHead(path.join(videoDir, vtts[0])))) { + // The DECODED head of a stored track (lib/storedText-server.ts). + if ( + vtts.length === 1 && + hasWordTiming((await readStoredTextHead(videoDir, vtts[0], HEAD_BYTES)).toString("utf8")) + ) { return true; } const m = (await readHead(cuesPath)).match(/"captionTrackRule"\s*:\s*(\d+)/); if (m !== null && Number(m[1]) === CAPTION_TRACK_RULE_VERSION) return true; if (/"cues"\s*:\s*\[\s*\]\s*\}\s*$/.test(await readTail(cuesPath))) return false; if (!entries.includes(VTT_FILENAME) || !entries.includes(ORIG_VTT_FILENAME)) return true; + // LOGICAL sizes: a stored track's is its frame header's content size — + // never the compressed size, which differs between the two forms. const [en, orig] = await Promise.all([ - stat(path.join(videoDir, VTT_FILENAME)), - stat(path.join(videoDir, ORIG_VTT_FILENAME)), + storedTextLogicalSize(videoDir, VTT_FILENAME), + storedTextLogicalSize(videoDir, ORIG_VTT_FILENAME), ]); - return en.size === orig.size; + return en === orig; } catch { return false; } diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts @@ -34,7 +34,7 @@ // share. Nothing new. import path from "node:path"; -import { open, readFile, readdir } from "node:fs/promises"; +import { open, readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { getSettings, type SiteSettings } from "../lib/settings"; import { isGateHeld } from "../lib/pauseGates"; @@ -49,6 +49,17 @@ import { runPool } from "../jobs/concurrentRunner"; import type { TaskTracker } from "../jobs/taskHooks"; import type { JobProgress } from "../jobs/registry"; import { readVideoFiles, CUES_JSON_FILENAME } from "../lib/videoStatus"; +import { readStoredText } from "../lib/storedText-server"; + +// A remote unit's inputs, as the worker receives them: each under its LOGICAL +// name with its PLAIN bytes (lib/storedText.ts) — a caption stored as `.zst` +// is decoded here, so the worker protocol and an older worker see exactly what +// they always did. Exported for its test. +export async function readUnitInputFiles(videoDir: string, names: readonly string[]): Promise<Record<string, Buffer>> { + const files: Record<string, Buffer> = {}; + for (const name of names) files[name] = await readStoredText(videoDir, name); + return files; +} import { DIARIZATION_OPERATION_ID, DIGEST_OPERATION_ID, @@ -1311,9 +1322,7 @@ async function runViaTaggedRemote( checkUntranscribable: true, }); const files: Record<string, Buffer> = {}; - for (const name of unit.op.inputs(listing)) { - files[name] = await readFile(path.join(videoDir, name)); - } + Object.assign(files, await readUnitInputFiles(videoDir, unit.op.inputs(listing))); // The channel context is injected because a scratch corpus has no // digest-context.md to read. Read per channel, memoized by the same map // the targets use. diff --git a/common/controller/purgeSupersededAutoSubs.ts b/common/controller/purgeSupersededAutoSubs.ts @@ -1,4 +1,5 @@ -import { removeStoredText } from "../lib/storedText-write-server"; +import { removeStoredText, verifyStoredText } from "../lib/storedText-write-server"; +import { logicalEntries, storedFormsIn } from "../lib/storedText"; import path from "node:path"; import fs from "fs-extra"; import type { Paths } from "../lib/paths"; @@ -70,7 +71,10 @@ export async function purgeSupersededAutoSubs({ for (const id of dirs) { if (signal?.aborted) break; const videoDir = path.join(dataDir, id); - const entries = await readdir(videoDir).catch(() => [] as string[]); + // PHYSICAL, then LOGICAL (lib/storedText.ts): a track stored as `.zst` is + // a track here under its plain name — and is purged in both forms. + const physical = await readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(physical); // No transcript of our own yet — nothing has been superseded, so the VTT is // still this video's only transcript. Never touch it. if (!entries.includes(WHISPER_FILENAME)) continue; @@ -89,6 +93,17 @@ export async function purgeSupersededAutoSubs({ skipped++; continue; } + // BOTH FORMS WITH DIFFERENT CONTENT: the sniff read the plain one, and + // the stored one is another capture this purge has not looked at (it + // may be the manual one) — kept, both, for a person. + if (storedFormsIn(physical, name) === "both") { + const v = await verifyStoredText(videoDir, name); + if (v.status !== "ok") { + log(`Kept ${id}/${name} (its plain and stored forms differ: ${v.status} — settle it on the files card)`); + skipped++; + continue; + } + } // Both forms (lib/storedText-write-server.ts): a stored copy left behind // would bring the captions back. Each through removeMediaFile. await removeStoredText(videoDir, name); diff --git a/common/controller/reconcileVideoDirs.test.ts b/common/controller/reconcileVideoDirs.test.ts @@ -193,6 +193,21 @@ test("a stored chat and a plain chat collide by their LOGICAL name; the loser is ); }); +test("a stored caption and a plain caption collide by their LOGICAL name too (lane text-compress-captions)", async (t) => { + const channelDir = await makeChannel(); + t.after(() => rm(channelDir, { recursive: true, force: true })); + await writeStrayDir(channelDir, "canonical01", { "transcript.en.vtt.zst": "destination stored caption" }); + await writeStrayDir(channelDir, "v-canonical01", { "transcript.en.vtt": "source plain caption" }); + await reconcileVideoDirs({ channelDir }); + const dst = path.join(channelDir, "data", "canonical01"); + const names = (await readdir(dst)).filter((n) => n.startsWith("transcript.")).sort(); + assert.deepEqual(names, ["transcript.en.vtt", "transcript.en.vtt.zst.dup-v-canonical01"]); + assert.equal( + await readFile(path.join(dst, "transcript.en.vtt.zst.dup-v-canonical01"), "utf8"), + "destination stored caption", + ); +}); + test("both forms on the source side move in together over a destination's stored chat", async (t) => { const channelDir = await makeChannel(); t.after(() => rm(channelDir, { recursive: true, force: true })); diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts @@ -22,7 +22,7 @@ // (current.json), else the newest done iteration that carries a report. import { modelLogged } from "./jobModelLog"; -import { access, readdir, readFile } from "node:fs/promises"; +import { access, readFile } from "node:fs/promises"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; @@ -40,6 +40,7 @@ import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { detectPlatform } from "../lib/detectPlatform.mjs"; import { WHISPER_FILENAME, englishVttsByPreference } from "../lib/videoStatus"; import { parseVtt } from "../lib/vtt"; +import { readStoredText, readdirLogical } from "../lib/storedText-server"; import { parseTranscriptJson } from "../lib/whisper"; import { isCuesJsonFresh, readNormalizedTranscript } from "./normalizeTranscript"; import { diskPostChannelOf } from "../lib/report/convert-server"; @@ -501,7 +502,8 @@ async function runRefreshJob( export async function diskRecordOf(channelsDir: string, slug: string, id: string): Promise<RecordRead | null> { const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null); if (!dir) return null; - const entries = await readdir(dir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a stored caption is a track under its name. + const entries = await readdirLogical(dir); if (!entries.length) return null; const tracks: { name: string; cues: { start: number; end: number; text: string }[] }[] = []; const fresh = await isCuesJsonFresh(dir).catch(() => ({ fresh: false as const })); @@ -514,7 +516,7 @@ export async function diskRecordOf(channelsDir: string, slug: string, id: string if (w.length) tracks.push({ name: WHISPER_FILENAME, cues: w }); } for (const name of englishVttsByPreference(entries)) { - const v = await readFile(path.join(dir, name), "utf8").then((t) => parseVtt(t), () => []); + const v = await readStoredText(dir, name, "utf8").then((t) => parseVtt(t), () => []); if (v.length) tracks.push({ name, cues: v }); } const state = stateFromAvailability(await resolveEffectiveAvailability(dir).catch(() => null)); diff --git a/common/controller/storedText.captions.test.ts b/common/controller/storedText.captions.test.ts @@ -0,0 +1,242 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { ChannelConfig } from "../lib/channelConfig"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.captions.test.ts +// +// THE CAPTIONS ARE STILL FOUND BY EVERY READER AFTER THEY ARE COMPRESSED (lane +// text-compress-captions, slice 4). Each case builds a video dir whose caption +// tracks are `transcript.<lang>.vtt.zst` only and asks a reader of each class +// what it sees: the listing (readVideoFiles), the cue read, the freshness +// stat, the head sniff (provenance, word timing), the logical size, the +// yt-dlp skip-if-exists checks (a miss there is a re-fetch, or an audio +// download and a transcription), the cited record, the remote worker's +// inputs. Before this slice each read a stored track as ABSENT — or, for a +// head sniff, read zstd bytes and answered WRONG. Temp corpus, no network, +// no yt-dlp. Synthetic names only. + +const ROOT = await mkdtemp(path.join(tmpdir(), "stored-captions-")); +const CORPUS = path.join(ROOT, "transcripts"); +process.env.TRANSCRIPTS_DIR = CORPUS; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await mkdir(CORPUS, { recursive: true }); +await writeFile(process.env.SETTINGS_FILE, "{}"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { readVideoFiles, readEnglishVttCues, pickIndexTranscript } = await import("../lib/videoStatus"); +const { normalizeTranscript, isCuesJsonFresh } = await import("./normalizeTranscript"); +const { readVttProvenance, resolveCaptionsProvenance, isAutoSubsOnly } = await import("../lib/subtitleProvenance"); +const { readVideoTracks } = await import("../lib/captionTracks-server"); +const { destinationExists, subLangsForVideo } = await import("../ytdlp/runYtdlp"); +const { youtubeHandlingArgs, __hasAnyTranscriptOnDiskForTest } = await import("../ytdlp/downloadOneManaged"); +const { readCitedRecord } = await import("../publish/composeReports"); +const { diskRecordOf } = await import("./reportRefresh"); +const { hasCorpusTranscript } = await import("./livePreclip"); +const { readUnitInputFiles } = await import("./operationBatch"); +const { storeFixture } = await import("../testing/storedTextFixture"); + +const paths = getPaths(); +const SLUG = "synth-captions"; +const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth/videos", name: "Synth" } as ChannelConfig; +const channelDir = path.join(CORPUS, "channels", SLUG); +const dataDir = path.join(channelDir, "data"); + +// YouTube's rolling ASR shape (align + inline word timing) and a human track. +const ASR = + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + "00:00:00.000 --> 00:00:05.000 align:start position:0%\n" + + "First<00:00:01.000><c> caption</c><00:00:02.000><c> line.</c>\n\n" + + "00:01:00.000 --> 00:01:50.000 align:start position:0%\n" + + "Second<00:01:10.000><c> caption</c><00:01:20.000><c> line.</c>\n"; +const MANUAL = + "WEBVTT\n\n00:00:00.000 --> 00:00:04.000\nA human wrote this line.\n\n" + + "00:00:04.000 --> 00:00:09.000\nAnd this one, with care.\n\n00:00:09.000 --> 00:00:12.000\nThe end.\n"; +const ORIG = ASR.replace("First", "Original").replace("Second", "Spoken"); + +async function video(id: string, tracks: Record<string, string>, extra: Record<string, string> = {}): Promise<string> { + const dir = path.join(dataDir, id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify(CONFIG)); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ + id, + title: `Synth ${id}`, + upload_date: "20260101", + duration: 120, + webpage_url: `https://www.youtube.com/watch?v=${id}`, + extractor_key: "Youtube", + }), + ); + for (const [name, body] of Object.entries({ ...tracks, ...extra })) await writeFile(path.join(dir, name), body); + // Sub-millisecond times: a `Date` round trip would lose them. + for (const name of Object.keys(tracks)) await utimes(path.join(dir, name), 1763700000.123457, 1763700000.987653); + return dir; +} + +async function storeAll(dir: string): Promise<void> { + for (const n of await readdir(dir)) if (/^transcript\.[^.]+\.vtt$/.test(n)) await storeFixture(dir, n); + assert.equal((await readdir(dir)).some((n) => n.endsWith(".vtt")), false, "only stored captions are left"); +} + +test("the listing: readVideoFiles is LOGICAL — a stored track is listed, primary and all", async () => { + const dir = await video("list1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG, "transcript.es.vtt": MANUAL }); + const before = await readVideoFiles(dir); + await storeAll(dir); + const after = await readVideoFiles(dir); + assert.equal(after.hasYtVtt, true); + assert.equal(after.ytVttFile, "transcript.en-orig.vtt"); + assert.equal(after.hasNonCanonicalVtt, before.hasNonCanonicalVtt); + assert.deepEqual([...after.entries].sort(), [...before.entries].sort(), "the same logical names"); + assert.ok(after.physicalEntries.includes("transcript.en.vtt.zst")); + assert.deepEqual(pickIndexTranscript(after), pickIndexTranscript(before)); +}); + +test("the cue read: readEnglishVttCues reads the stored tracks, under their plain names", async () => { + const dir = await video("cues1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + const before = await readEnglishVttCues(dir); + await storeAll(dir); + assert.deepEqual(await readEnglishVttCues(dir), before); + // Given the caller's raw readdir, too. + assert.deepEqual(await readEnglishVttCues(dir, await readdir(dir)), before); + assert.equal(before?.filename, "transcript.en-orig.vtt"); +}); + +test("normalize: a cues.json made before compression stays FRESH, and a forced one writes the same cues", async () => { + const dir = await video("norm1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} })).status, "wrote"); + const made = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8")); + await storeAll(dir); + assert.deepEqual(await isCuesJsonFresh(dir), { fresh: true, reason: "fresh", cuesPath: path.join(dir, "transcript.cues.json") }); + assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} })).status, "fresh"); + assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {}, force: true })).status, "wrote"); + const again = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8")); + assert.deepEqual(again.cues, made.cues); + assert.equal(again.vttFile, "transcript.en-orig.vtt", "the record names the LOGICAL track"); +}); + +test("normalize: the caption-track rule's head and size checks read the stored tracks as the plain ones", async () => { + // An unversioned cues.json (made before the rule had a version) with cues, + // en and en-orig of DIFFERENT content: stale — it was read from en, and + // en-orig is read now. Stored, the sizes compared must be the logical ones. + const dir = await video("rule1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG + "\n" }); + await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} }); + const cuesPath = path.join(dir, "transcript.cues.json"); + const rec = JSON.parse(await readFile(cuesPath, "utf8")); + delete rec.captionTrackRule; + await writeFile(cuesPath, JSON.stringify(rec)); + assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "plain: stale"); + await storeFixture(dir, "transcript.en.vtt"); + assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "en stored, en-orig plain: still stale"); + await storeFixture(dir, "transcript.en-orig.vtt"); + assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "both stored: still stale"); + + // A lone word-timed track with an empty unversioned cues.json: FRESH (its + // parse did not change) — read from the DECODED head. + const lone = await video("rule2", { "transcript.en.vtt": ASR }); + await writeFile(path.join(lone, "transcript.cues.json"), JSON.stringify({ title: "x", cues: [] })); + assert.equal((await isCuesJsonFresh(lone)).fresh, true, "plain"); + await storeFixture(lone, "transcript.en.vtt"); + assert.equal((await isCuesJsonFresh(lone)).fresh, true, "stored: the head is decoded"); +}); + +test("the head sniff: provenance reads the DECODED head — ASR stays ASR, manual stays manual", async () => { + const dir = await video("prov1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ASR, "transcript.es.vtt": MANUAL }); + await storeAll(dir); + assert.equal(await readVttProvenance(dir, "transcript.en.vtt"), "asr"); + assert.equal(await readVttProvenance(dir, "transcript.es.vtt"), "manual"); + assert.equal(await resolveCaptionsProvenance(dir, await readdir(dir)), "asr"); + const files = await readVideoFiles(dir); + assert.equal(await isAutoSubsOnly(dir, files), true, "the replace lane still sees an ASR-only video"); + const human = await video("prov2", { "transcript.en.vtt": MANUAL }); + await storeAll(human); + assert.equal(await resolveCaptionsProvenance(human, await readdir(human)), "manual", "a human track is never scheduled for replacement"); +}); + +test("the alternate tracks: readVideoTracks reads stored tracks", async () => { + const dir = await video("alts1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + const before = await readVideoTracks(dir); + await storeAll(dir); + assert.deepEqual(await readVideoTracks(dir), before); + assert.equal(before?.tracks.length, 2); +}); + +test("destinationExists: a stored transcript.en.vtt is the destination — the URL is NOT fetched again", async () => { + await video("dest1", { "transcript.en.vtt": ASR }); + await storeAll(path.join(dataDir, "dest1")); + assert.equal(await destinationExists(dataDir, "dest1", "youtube"), true); + // The replace-auto-captions run still sees it as ASR (the decoded sniff). + assert.equal(await destinationExists(dataDir, "dest1", "youtube", { replaceAutoSubs: true }), false); + await video("dest2", { "transcript.en.vtt": MANUAL }); + await storeAll(path.join(dataDir, "dest2")); + assert.equal(await destinationExists(dataDir, "dest2", "youtube", { replaceAutoSubs: true }), true, "a human track suppresses it"); +}); + +test("hasAnyTranscriptOnDisk: a stored caption is a transcript — no audio download, no transcription", async () => { + for (const name of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.es.vtt"]) { + const dir = await video(`any-${name.split(".")[1]}`, { [name]: ASR }); + await storeAll(dir); + assert.equal(await __hasAnyTranscriptOnDiskForTest(dir), true, name); + } + // The control: a stored chat alone is not a transcript. + const chat = await video("any-chat", {}, { "transcript.live_chat.json": "{}\n" }); + await storeFixture(chat, "transcript.live_chat.json"); + assert.equal(await __hasAnyTranscriptOnDiskForTest(chat), false); +}); + +test("the subtitle passes leave every stored track out of --sub-langs (yt-dlp's skip sees only the plain name)", async () => { + const dir = await video("subs1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + await storeFixture(dir, "transcript.en.vtt"); + await storeFixture(dir, "transcript.en-orig.vtt"); + const entries = await readdir(dir); + assert.equal(subLangsForVideo(entries, "en.*,live_chat"), "en.*,live_chat,-en,-en-orig"); + // Both forms (the plain is there): yt-dlp's own skip sees it — unchanged. + assert.equal(subLangsForVideo(["transcript.en.vtt", "transcript.en.vtt.zst"], "en.*"), "en.*"); + // A stored chat and a stored caption: the chat left out as for a `later` + // channel, the caption excluded by code. + assert.equal(subLangsForVideo(["transcript.live_chat.json.zst", "transcript.en.vtt.zst"], "en.*,live_chat"), "en.*,-en"); + const langs = (args: string[]) => args[args.indexOf("--sub-langs") + 1]; + assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false, ["en", "en-orig"])), "en.*,live_chat,-en,-en-orig"); + assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true, ["en"])), "en.*,-en"); + assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat", "nothing stored: unchanged"); +}); + +test("the cited record (compose, report refresh) reads stored tracks — cues and every English track", async () => { + const dir = await video("cite1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + const before = await readCitedRecord(path.join(CORPUS, "channels"), SLUG, "cite1"); + const beforeDisk = await diskRecordOf(path.join(CORPUS, "channels"), SLUG, "cite1"); + await storeAll(dir); + const after = await readCitedRecord(path.join(CORPUS, "channels"), SLUG, "cite1"); + assert.deepEqual(after?.cues, before?.cues); + assert.deepEqual(after?.tracks, before?.tracks); + assert.equal(after?.tracks.length, 2); + assert.deepEqual(await diskRecordOf(path.join(CORPUS, "channels"), SLUG, "cite1"), beforeDisk); +}); + +test("the live pre-clip's transcript check sees a stored caption", async () => { + const dir = await video("pre1", { "transcript.en.vtt": ASR }); + await storeAll(dir); + assert.equal(await hasCorpusTranscript(dir), true); +}); + +test("the remote worker's inputs: the PLAIN bytes under the logical name", async () => { + const dir = await video("worker1", { "transcript.en-orig.vtt": ORIG }); + await storeAll(dir); + const files = await readUnitInputFiles(dir, ["metadata.info.json", "transcript.en-orig.vtt"]); + assert.deepEqual(Object.keys(files), ["metadata.info.json", "transcript.en-orig.vtt"]); + assert.equal(files["transcript.en-orig.vtt"].toString("utf8"), ORIG); +}); + +test("with no caption in either form, every check says so (the control)", async () => { + const dir = await video("none1", {}); + assert.equal(await destinationExists(dataDir, "none1", "youtube"), false); + assert.equal(await __hasAnyTranscriptOnDiskForTest(dir), false); + assert.equal((await readVideoFiles(dir)).hasYtVtt, false); + assert.equal(await readEnglishVttCues(dir), null); + assert.equal(paths.channelsDir, path.join(CORPUS, "channels")); +}); diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts @@ -68,8 +68,9 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too", const d = await videoDir("p", "v3"); await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] })); await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT); - // What a later stored-captions slice would leave: an older stored copy. - await writeFile(path.join(d, "transcript.en.vtt.zst"), "older stored copy"); + // Both forms of the same track (a compression that stopped before the + // original went): purged in both. + await storeFixture(d, "transcript.en.vtt", { keepPlain: true }); const r = await purgeSupersededAutoSubs({ channelSlug: "p", paths: { channelsDir: path.join(ROOT, "channels") } as never, @@ -79,6 +80,48 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too", assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]); }); +test("the purge KEEPS both forms when they differ (or the stored one does not decode): it sniffed only the plain one", async () => { + // (Changed in lane text-compress-captions: slice 1 removed a stored sibling + // whatever it held. A stored copy with other content is another capture — + // it may be the manual track — and nothing removes a stored caption + // because a different one arrived.) + for (const [id, stored] of [["v4", "differs"], ["v5", "corrupt"]] as const) { + const d = await videoDir("p", id); + await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] })); + if (stored === "differs") { + await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nA human track.\n"); + await storeFixture(d, "transcript.en.vtt"); + } else { + await writeFile(path.join(d, "transcript.en.vtt.zst"), "not a zstd frame"); + } + await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT); + const r = await purgeSupersededAutoSubs({ + channelSlug: "p", + ids: [id], + paths: { channelsDir: path.join(ROOT, "channels") } as never, + onLog: () => {}, + }); + assert.equal(r.removedFiles, 0, stored); + assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt", "transcript.en.vtt.zst", "transcript.json"], stored); + } +}); + +test("the purge finds a superseded ASR track stored ONLY compressed, and removes it", async () => { + const d = await videoDir("p", "v6"); + await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] })); + await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT); + await storeFixture(d, "transcript.en.vtt"); + assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt.zst", "transcript.json"]); + const r = await purgeSupersededAutoSubs({ + channelSlug: "p", + ids: ["v6"], + paths: { channelsDir: path.join(ROOT, "channels") } as never, + onLog: () => {}, + }); + assert.equal(r.removedFiles, 1, "the decoded head sniffs as ASR"); + assert.deepEqual(await readdir(d), ["transcript.json"]); +}); + // REVIEW-1 F5 / REVIEW-2 R2: THE FILES CARD'S DELETE OF ONE NAMED FORM // (`removeStoredTextForm`, what deleteVideoFileAction and `pnpm ops // delete-file` run). A person asked for ONE file: only that one goes, never the diff --git a/common/lib/captionTracks-server.ts b/common/lib/captionTracks-server.ts @@ -2,7 +2,9 @@ // says what an alternate is). SERVER-ONLY (node:fs). import path from "node:path"; -import { readdir, readFile } from "node:fs/promises"; +import { readFile } from "node:fs/promises"; +import { logicalEntries } from "./storedText"; +import { readStoredText, readdirLogical } from "./storedText-server"; import { parseVtt, type Cue } from "./vtt"; import { parseTranscriptJson } from "./whisper"; import { @@ -47,11 +49,12 @@ export async function readEnglishVttTracks( entries: readonly string[], ): Promise<{ filename: string; cues: Cue[] }[]> { const out: { filename: string; cues: Cue[] }[] = []; - for (const filename of englishVttsByPreference(entries)) { + for (const filename of englishVttsByPreference(logicalEntries(entries))) { try { out.push({ filename, - cues: parseVtt(await readFile(path.join(videoDir, filename), "utf8")), + // Either form (lib/storedText.ts): a track stored as `.zst` is read. + cues: parseVtt(await readStoredText(videoDir, filename, "utf8")), }); } catch { // unreadable: not a track @@ -72,7 +75,8 @@ export async function readTrackFields( primaryCues: readonly Cue[] | undefined, entries?: readonly string[], ): Promise<TrackFields> { - const listing = entries ?? (await readdir(videoDir).catch(() => [] as string[])); + // LOGICAL (lib/storedText.ts): a stored track is listed under its name. + const listing = entries ? logicalEntries(entries) : await readdirLogical(videoDir); if (!mayHaveAltTracks(primaryKind, listing)) return {}; const vtts = await readEnglishVttTracks(videoDir, listing); let primaryTrack: string; @@ -105,7 +109,7 @@ export async function readTrackFields( export async function readVideoTracks( videoDir: string, ): Promise<{ tracks: AltTrack[] } | null> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const entries = await readdirLogical(videoDir); let primary: AltTrack | null = null; let kind: "vtt" | "whisper" = "vtt"; if (entries.includes(WHISPER_FILENAME)) { diff --git a/common/lib/operationUnit.test.ts b/common/lib/operationUnit.test.ts @@ -47,6 +47,7 @@ function files(entries: string[]): VideoFiles { audioFiles: entries.filter((e) => e.startsWith("audio.")), partAudioFiles: [], entries, + physicalEntries: entries, }; } diff --git a/common/lib/storedText-read.d.mts b/common/lib/storedText-read.d.mts @@ -0,0 +1,14 @@ +// Types for ./storedText-read.mjs: the stored-text read path in plain JS. +import type { Stats } from "node:fs"; +export const STORED_TEXT_SUFFIX: ".zst"; +export function isStoredTextName(name: string): boolean; +export function plainNameOf(name: string): string | null; +export function logicalEntries(entries: Iterable<string>): string[]; +export function readdirLogical(dir: string): Promise<string[]>; +export function frameContentSize(head: Uint8Array): number | null; +export function decodeStoredBytes(bytes: Buffer, label?: string): Promise<Buffer>; +export function readStoredText(dir: string, name: string): Promise<Buffer>; +export function readStoredText(dir: string, name: string, encoding: "utf8"): Promise<string>; +export function readStoredTextHead(dir: string, name: string, bytes: number): Promise<Buffer>; +export function statStoredText(dir: string, name: string): Promise<{ form: "plain" | "zst"; stats: Stats }>; +export function storedTextLogicalSize(dir: string, name: string): Promise<number>; diff --git a/common/lib/storedText-read.mjs b/common/lib/storedText-read.mjs @@ -0,0 +1,201 @@ +// STORED TEXT, THE READ PATH IN PLAIN JS — for umtool's bare-node scripts +// (report-to-video's cue source, the clip words, the ingredients rail), which +// cannot import lib/storedText-server.ts. The same rules (lib/storedText.ts): +// a declared file — the raw live chat, or a caption track +// `transcript.<lang>.vtt` — may be on disk as `<name>.zst`, one zstd frame +// whose header carries the content size; THE PLAIN FILE, WHEN PRESENT, IS THE +// TRUTH; a matching listing is LOGICAL (the `.zst` reported under its plain +// name, once). storedText.mjs-twin.test.ts holds this module and the TS one +// equal (names, decode, head, sizes); change one, change the other. +// SERVER-ONLY (node:fs, node:zlib). Read only: nothing here writes. + +import { open, readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import zlib from "node:zlib"; + +export const STORED_TEXT_SUFFIX = ".zst"; +const LIVE_CHAT = "transcript.live_chat.json"; +const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/; + +/** @param {string} name */ +export function isStoredTextName(name) { + return name === LIVE_CHAT || CAPTION_RE.test(name); +} + +/** @param {string} name */ +export function plainNameOf(name) { + if (!name.endsWith(STORED_TEXT_SUFFIX)) return null; + const plain = name.slice(0, -STORED_TEXT_SUFFIX.length); + return isStoredTextName(plain) ? plain : null; +} + +/** @param {Iterable<string>} entries */ +export function logicalEntries(entries) { + const out = []; + const seen = new Set(); + for (const e of entries) { + const n = plainNameOf(e) ?? e; + if (seen.has(n)) continue; + seen.add(n); + out.push(n); + } + return out; +} + +/** @param {string} dir */ +export async function readdirLogical(dir) { + return logicalEntries(await readdir(dir).catch(() => [])); +} + +const ZSTD_MAGIC = 0xfd2fb528; + +/** The content size a zstd frame header declares, or null. @param {Uint8Array} head */ +export function frameContentSize(head) { + if (head.length < 5) return null; + const dv = new DataView(head.buffer, head.byteOffset, head.byteLength); + if (dv.getUint32(0, true) !== ZSTD_MAGIC) return null; + const fhd = head[4]; + const fcsFlag = fhd >> 6; + const singleSegment = (fhd >> 5) & 1; + const dictFlag = fhd & 3; + if (fcsFlag === 0 && !singleSegment) return null; + const off = 5 + (singleSegment ? 0 : 1) + [0, 1, 2, 4][dictFlag]; + const fcsBytes = fcsFlag === 0 ? 1 : [1, 2, 4, 8][fcsFlag]; + if (head.length < off + fcsBytes) return null; + if (fcsBytes === 1) return head[off]; + if (fcsBytes === 2) return dv.getUint16(off, true) + 256; + if (fcsBytes === 4) return dv.getUint32(off, true); + const n = dv.getUint32(off + 4, true) * 2 ** 32 + dv.getUint32(off, true); + return Number.isSafeInteger(n) ? n : null; +} + +function assertZstd() { + if (typeof zlib.zstdDecompress !== "function" || typeof zlib.createZstdDecompress !== "function") { + throw new Error(`stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`); + } +} + +const isEnoent = (err) => err?.code === "ENOENT" || err?.code === "ENOTDIR"; +const enoent = (dir, name) => + Object.assign(new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`), { code: "ENOENT" }); + +/** A stored file's bytes decoded, its checksum and length checked. @param {Buffer} bytes @param {string} label */ +export async function decodeStoredBytes(bytes, label = "stored text") { + assertZstd(); + const want = frameContentSize(bytes.subarray(0, 18)); + if (want === null) throw new Error(`${label}: not a whole stored-text frame (no content size in the frame header)`); + const out = await new Promise((resolve, reject) => + zlib.zstdDecompress(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) => (err ? reject(err) : resolve(res))), + ).catch((err) => { + throw new Error(`${label}: not a whole stored-text frame (${err.message})`); + }); + if (out.length !== want) throw new Error(`${label}: not a whole stored-text frame (decoded ${out.length} bytes, header says ${want})`); + return out; +} + +/** + * The plain file's bytes when it opens; else (a declared name) the stored form + * decoded; ENOENT when neither opens. + * @param {string} dir @param {string} name @param {"utf8"} [encoding] + */ +export async function readStoredText(dir, name, encoding) { + try { + return encoding ? await readFile(path.join(dir, name), encoding) : await readFile(path.join(dir, name)); + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX); + let bytes; + try { + bytes = await readFile(storedPath); + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } + const out = await decodeStoredBytes(bytes, storedPath); + return encoding ? out.toString(encoding) : out; +} + +/** The first `bytes` bytes as the plain file has them (decoded from a stored form). */ +export async function readStoredTextHead(dir, name, bytes) { + try { + const fh = await open(path.join(dir, name), "r"); + try { + const buf = Buffer.alloc(bytes); + const { bytesRead } = await fh.read(buf, 0, bytes, 0); + return buf.subarray(0, bytesRead); + } finally { + await fh.close(); + } + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + assertZstd(); + const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX); + let fh; + try { + fh = await open(storedPath, "r"); + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } + const src = fh.createReadStream(); + const dec = zlib.createZstdDecompress(); + const out = []; + let n = 0; + try { + await new Promise((resolve, reject) => { + dec.on("data", (chunk) => { + if (n >= bytes) return; + out.push(chunk); + n += chunk.length; + if (n >= bytes) { + src.unpipe(dec); + src.destroy(); + dec.destroy(); + resolve(); + } + }); + dec.on("end", resolve); + dec.on("error", (err) => reject(new Error(`${storedPath}: not a whole stored-text frame (${err.message})`))); + src.on("error", reject); + src.pipe(dec); + }); + } finally { + src.destroy(); + await fh.close().catch(() => {}); + } + return Buffer.concat(out).subarray(0, bytes); +} + +/** `stat` of the plain name, else of its stored form (which carries the plain file's times). */ +export async function statStoredText(dir, name) { + try { + return { form: "plain", stats: await stat(path.join(dir, name)) }; + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + try { + return { form: "zst", stats: await stat(path.join(dir, name + STORED_TEXT_SUFFIX)) }; + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } +} + +/** The LOGICAL size: the plain file's, or the stored frame header's content size. */ +export async function storedTextLogicalSize(dir, name) { + const s = await statStoredText(dir, name); + if (s.form === "plain") return s.stats.size; + const file = path.join(dir, name + STORED_TEXT_SUFFIX); + const fh = await open(file, "r"); + try { + const head = Buffer.alloc(18); + const { bytesRead } = await fh.read(head, 0, 18, 0); + const n = frameContentSize(head.subarray(0, bytesRead)); + if (n === null) throw new Error(`${file}: not a whole stored-text frame (no content size in the frame header)`); + return n; + } finally { + await fh.close(); + } +} diff --git a/common/lib/storedText-read.test.ts b/common/lib/storedText-read.test.ts @@ -0,0 +1,69 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText-read.test.ts +// +// THE PLAIN-JS TWIN (lib/storedText-read.mjs, for umtool's bare-node scripts) +// AND THE TS READ PATH (lib/storedText.ts, lib/storedText-server.ts) GIVE THE +// SAME ANSWERS: which names are declared, the logical listing, the decoded +// bytes and head, the logical size, and a truncated frame refused. Change one, +// change the other. Temp dirs, synthetic names. + +import * as ts from "./storedText"; +import * as tsServer from "./storedText-server"; +import * as mjs from "./storedText-read.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "stored-read-twin-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const NAMES = [ + "transcript.live_chat.json", + "transcript.en.vtt", + "transcript.en-orig.vtt", + "transcript.es.vtt", + "transcript.tmp-77.vtt", + "transcript.json", + "transcript.cues.json", + "metadata.info.json", + "transcript.en.vtt.part", + "transcript.en.srv3", +]; + +test("the declared names and the logical listing are the same in both", () => { + for (const n of NAMES) { + assert.equal(mjs.isStoredTextName(n), ts.isStoredTextName(n), n); + assert.equal(mjs.plainNameOf(`${n}.zst`), ts.plainNameOf(`${n}.zst`), n); + } + const listing = [...NAMES, ...NAMES.map((n) => `${n}.zst`), "x.zst"]; + assert.deepEqual(mjs.logicalEntries(listing), ts.logicalEntries(listing)); +}); + +test("the read, the head, the stat and the logical size are the same in both", async () => { + const dir = path.join(ROOT, "v1"); + await mkdir(dir, { recursive: true }); + const body = "WEBVTT\n\n" + "00:00:00.000 --> 00:00:01.000\nline é\n\n".repeat(400); + await writeFile(path.join(dir, "transcript.en.vtt.zst"), await tsServer.encodeStoredBytes(Buffer.from(body))); + await writeFile(path.join(dir, "transcript.es.vtt"), body); + for (const n of ["transcript.en.vtt", "transcript.es.vtt"]) { + assert.equal(await mjs.readStoredText(dir, n, "utf8"), await tsServer.readStoredText(dir, n, "utf8"), n); + assert.deepEqual(await mjs.readStoredTextHead(dir, n, 2048), await tsServer.readStoredTextHead(dir, n, 2048), n); + assert.equal(await mjs.storedTextLogicalSize(dir, n), await tsServer.storedTextLogicalSize(dir, n), n); + assert.equal((await mjs.statStoredText(dir, n)).stats.mtimeMs, (await tsServer.statStoredText(dir, n)).stats.mtimeMs, n); + } + assert.equal(await mjs.readStoredText(dir, "transcript.en.vtt", "utf8"), body); + assert.deepEqual(await mjs.readdirLogical(dir), await tsServer.readdirLogical(dir)); + await assert.rejects(mjs.readStoredText(dir, "transcript.de.vtt"), { code: "ENOENT" }); +}); + +test("a truncated stored frame is refused by both, never read short", async () => { + const dir = path.join(ROOT, "v2"); + await mkdir(dir, { recursive: true }); + const whole = await tsServer.encodeStoredBytes(Buffer.from("WEBVTT\n\n".repeat(5000))); + await writeFile(path.join(dir, "transcript.en.vtt.zst"), whole.subarray(0, Math.floor(whole.length / 2))); + await assert.rejects(mjs.readStoredText(dir, "transcript.en.vtt"), /not a whole stored-text frame/); + await assert.rejects(tsServer.readStoredText(dir, "transcript.en.vtt"), /not a whole stored-text frame/); +}); diff --git a/common/lib/storedText-server.ts b/common/lib/storedText-server.ts @@ -198,6 +198,63 @@ export async function readStoredText( return encoding ? out.toString(encoding) : out; } +// THE HEAD of a declared file: its first `bytes` bytes as the plain file has +// them — read from the plain file when it opens, else DECODED from the stored +// form (the first bytes of a zstd frame are not text: a sniff of them would +// answer wrong, not absent — the caption provenance sniff, the word-timing +// sniff). Only the head is decoded; the frame's checksum is checked by a whole +// read, not here. ENOENT when neither form opens. +export async function readStoredTextHead(dir: string, name: string, bytes: number): Promise<Buffer> { + try { + const fh = await open(path.join(dir, name), "r"); + try { + const buf = Buffer.alloc(bytes); + const { bytesRead } = await fh.read(buf, 0, bytes, 0); + return buf.subarray(0, bytesRead); + } finally { + await fh.close(); + } + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + const storedPath = path.join(dir, storedNameOf(name)); + let fh; + try { + fh = await open(storedPath, "r"); + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } + const src = fh.createReadStream(); + const dec = createStoredTextDecompressor(); + const out: Buffer[] = []; + let n = 0; + try { + await new Promise<void>((resolve, reject) => { + const finish = () => resolve(); + dec.on("data", (chunk: Buffer) => { + if (n >= bytes) return; + out.push(chunk); + n += chunk.length; + if (n >= bytes) { + src.unpipe(dec); + src.destroy(); + dec.destroy(); + finish(); + } + }); + dec.on("end", finish); + dec.on("error", (err) => reject(new StoredTextCorruptError(storedPath, err.message))); + src.on("error", reject); + src.pipe(dec); + }); + } finally { + src.destroy(); + await fh.close().catch(() => {}); + } + return Buffer.concat(out).subarray(0, bytes); +} + export type StoredTextStat = { // Which form answered. form: "plain" | "zst"; diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts @@ -461,7 +461,9 @@ test("an abort mid-write and an appending writer: the original is untouched, no test("not a declared name: refused", async () => { const f = await fixture(false); - const out = await compressStoredText(f.videoDir, "transcript.en.vtt"); + // (A caption track is declared since lane text-compress-captions; the + // metadata is not.) + const out = await compressStoredText(f.videoDir, "metadata.info.json"); assert.equal(out.status === "skipped" && out.reason, "not-declared"); }); diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts @@ -84,6 +84,7 @@ const DEFINITIONS = new Set([ "common/lib/storedText.ts", "common/lib/storedText-server.ts", "common/lib/storedText-write-server.ts", + "common/lib/storedText-read.mjs", ]); async function walk(dir: string, out: string[]): Promise<void> { @@ -184,11 +185,17 @@ test("every app line naming the raw live chat goes through the stored-text helpe const SUB_FLAGS = /(["'])--(?:sub-langs?|all-subs|write-subs|write-auto-subs|write-automatic-subs)\1|["'`]--(?:sub-langs?)=|^\s*["'`]live_chat["'`],?\s*$/; +// CAPTIONS TOO (lane text-compress-captions): a caption track stored as +// `transcript.<lang>.vtt.zst` is fetched again by any pass that asks for it — +// each builder excludes the stored tracks by code (`storedOnlyCaptionTracks`, +// `excludeSubTracks`), and its caller computes them from the PHYSICAL listing. const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string }> = { youtubeHandlingArgs: { file: "common/ytdlp/downloadOneManaged.ts", - guard: "chatStored (storedFormsIn === \"zst\"): the chat left out of --sub-langs", - test: "controller/storedText.chat.test.ts (youtubeHandlingArgs)", + guard: + "chatStored (storedFormsIn === \"zst\"): the chat left out of --sub-langs; storedCaptionTracks " + + "(storedOnlyCaptionTracks): each stored caption excluded by code", + test: "controller/storedText.chat.test.ts (youtubeHandlingArgs); controller/storedText.captions.test.ts (youtubeHandlingArgs)", }, liveChatOnlyArgs: { file: "common/ytdlp/downloadOneManaged.ts", @@ -197,8 +204,8 @@ const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string } }, downloadSubsForUrl: { file: "common/ytdlp/runYtdlp.ts", - guard: "subLangsForVideo: the chat left out of --sub-langs for a stored chat", - test: "controller/storedText.chat.test.ts (subLangsForVideo)", + guard: "subLangsForVideo: the chat left out of --sub-langs for a stored chat, each stored caption excluded by code", + test: "controller/storedText.chat.test.ts (subLangsForVideo); controller/storedText.captions.test.ts (subLangsForVideo)", }, }; @@ -258,3 +265,90 @@ test("every yt-dlp argv that can write the raw chat is a pinned builder, and eve "be tested, and be counted in CALLERS", ); }); + +// ── THE THIRD GATE: CAPTIONS (lane text-compress-captions) ───────────────── +// +// A caption track may be on disk as `transcript.<lang>.vtt.zst`. A raw read, +// stat or delete of a caption NAME (its constants, a `transcript.<x>.vtt` +// literal, a record's `ytVttFile` / `vttFile` / `picked.filename`) outside the +// stored-text helpers sees a compressed track as ABSENT — and the three +// misses that cost the most are a re-fetch of the URL (destinationExists), an +// audio download and a transcription for a video that has captions +// (hasAnyTranscriptOnDisk), and a purge that leaves the `.zst` (the captions +// come back). Two tripwires, like the first gate: +// +// 1. A LINE THAT CALLS A RAW FS READ, STAT OR DELETE and names a caption in +// the same statement (the line or the two before it) must also name a +// sanctioned reader or deleter there, or be ALLOWED_CAPTION with its +// reason. Writes are not gated: every writer writes the plain name, which +// is the truth (lib/storedText.ts). +// 2. A FILE THAT APPLIES A CAPTION RULE to a listing (`englishVttsByPreference`, +// `resolvePrimaryVtt`, `captionInputs`, `listTranscriptVtts`, …) must take +// a LOGICAL listing somewhere in it (`readVideoFiles`, `logicalEntries`, +// `readdirLogical`, `logicalFileNames`, the umtool twin) — a raw readdir +// fed to the rule loses every stored track — or be a RULE_ONLY file with +// its reason (it is handed a logical listing by its callers). +// +// WHAT THEY CANNOT SEE: a variable holding a caption name read far from where +// it was named; a listing passed through a parameter from a raw readdir in +// another file; a shell or Python reader. + +const CAPTION_NAMES = + /\b(?:VTT_FILENAME|ORIG_VTT_FILENAME|CANONICAL_VTT|EN_ORIG_TRACK)\b|transcript\.[A-Za-z-]*\.vtt(?![.\w])|\.ytVttFile\b|\bvttFile\b|picked\.filename\b/; +const RAW_FS = /\b(?:readFile|readFileSync|stat|statSync|lstat|lstatSync|open|openSync|createReadStream|rm|rmSync|unlink|unlinkSync|copyFile|rename|access|existsSync|removeMediaFile|renameMediaFile)\s*\(/; +const CAPTION_SANCTIONED = + /\b(?:readStoredText|readStoredTextHead|statStoredText|storedTextMtimeMs|storedTextExists|storedTextForms|storedTextLogicalSize|removeStoredText|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|decodeStoredBytes|captionBytes|readEnglishVttCues|readEnglishVttTracks|readVttProvenance|resolveVttProvenance)\b/; + +const ALLOWED_CAPTION: { file: string; code: RegExp; why: string }[] = [ + { + file: "common/lib/localMediaCommit-server.ts", + code: /const current = await lstat\(target\);/, + why: "the new record's DIRECTORY, checked before each link of a commit that made it (mkdir, EEXIST refused): no stored form can be in it", + }, +]; + +// The caption rules, and the files that define them. +const CAPTION_RULES = + /\b(?:englishVttsByPreference|resolvePrimaryVtt|captionInputs|listTranscriptVtts|readEnglishVttCues|readEnglishVttTracks|mayHaveAltTracks|resolveCaptionsProvenance)\s*\(/; +const LOGICAL_LISTING = /\b(?:readVideoFiles|logicalEntries|readdirLogical|logicalFileNames)\b/; +const RULE_ONLY: Record<string, string> = { + "common/lib/videoStatus.ts": "the rules themselves (readEnglishVttCues makes its listing logical)", +}; + +test("every app line that reads, stats or deletes a caption track goes through the stored-text helpers", async () => { + const offenders: string[] = []; + for (const { rel, lines } of await appFiles()) { + if (DEFINITIONS.has(rel)) continue; + for (let i = 0; i < lines.length; i++) { + const code = codeOnly(lines[i]); + if (!RAW_FS.test(code)) continue; + const statement = [lines[i - 2] ?? "", lines[i - 1] ?? "", code].map(codeOnly).join("\n"); + if (!CAPTION_NAMES.test(statement)) continue; + if (CAPTION_SANCTIONED.test(statement)) continue; + if (ALLOWED_CAPTION.some((a) => a.file === rel && a.code.test(code))) continue; + offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`); + } + } + assert.deepEqual( + offenders, + [], + "read, stat or delete a caption track through lib/storedText(-server|-write-server).ts — it may be stored as .zst", + ); +}); + +test("every file that applies a caption rule to a listing takes a logical listing", async () => { + const offenders: string[] = []; + for (const { rel, lines } of await appFiles()) { + if (DEFINITIONS.has(rel) || RULE_ONLY[rel]) continue; + const code = lines.map(codeOnly); + const uses = code.findIndex((l) => CAPTION_RULES.test(l) && !/^\s*(?:export\s+)?(?:async\s+)?function\b/.test(l)); + if (uses < 0) continue; + if (code.some((l) => LOGICAL_LISTING.test(l))) continue; + offenders.push(`${rel}:${uses + 1}: ${lines[uses].trim()}`); + } + assert.deepEqual( + offenders, + [], + "a caption rule fed a raw readdir loses every track stored as .zst: list with readVideoFiles / readdirLogical / logicalEntries", + ); +}); diff --git a/common/lib/storedText.test.ts b/common/lib/storedText.test.ts @@ -12,6 +12,7 @@ import path from "node:path"; import { STORED_TEXT_NAMES, + isStoredCaptionName, isStoredTextName, listingHas, logicalEntries, @@ -33,7 +34,7 @@ import { StoredTextCorruptError, } from "./storedText-server"; import { classifyEntry, isScratchEntry, isTierable, LIVE_CHAT_STORED_FILENAME } from "./mediaTier"; -import { LIVE_CHAT_FILENAME } from "./videoStatus"; +import { LIVE_CHAT_FILENAME, isTranscriptVtt } from "./videoStatus"; const ROOT = await mkdtemp(path.join(tmpdir(), "stored-text-")); test.after(() => rm(ROOT, { recursive: true, force: true })); @@ -47,25 +48,50 @@ async function dir(name: string): Promise<string> { return d; } -test("the declared names: the live chat only, its stored form `.zst`", () => { +test("the declared names: the live chat and every caption track, each with its stored form `.zst`", () => { assert.deepEqual([...STORED_TEXT_NAMES], [CHAT]); assert.equal(isStoredTextName(CHAT), true); - assert.equal(isStoredTextName("transcript.en.vtt"), false); + // Every caption track (lane text-compress-captions), any language code. + for (const c of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.en-US.vtt", "transcript.es.vtt", "transcript.en-en-GB.vtt"]) { + assert.equal(isStoredTextName(c), true, c); + assert.equal(isStoredCaptionName(c), true, c); + assert.equal(isTranscriptVtt(c), true, `${c}: the same pattern as videoStatus`); + assert.equal(plainNameOf(`${c}.zst`), c); + } + // Not declared: the metadata, the whisper transcript, the cues, a + // transcriber's temp, a `.part`, another track format. + for (const n of ["metadata.info.json", "transcript.json", "transcript.cues.json", "transcript.tmp-4242.vtt", "transcript.en.vtt.part", "transcript.en.srv3", "live_chat.cues.json"]) { + assert.equal(isStoredTextName(n), false, n); + assert.equal(plainNameOf(`${n}.zst`), null, n); + } + assert.equal(isStoredCaptionName(CHAT), false); assert.equal(storedNameOf(CHAT), "transcript.live_chat.json.zst"); assert.equal(plainNameOf("transcript.live_chat.json.zst"), CHAT); - // Not declared: a `.zst` of another name stands for nothing here. - assert.equal(plainNameOf("transcript.en.vtt.zst"), null); assert.equal(plainNameOf(CHAT), null); assert.equal(LIVE_CHAT_STORED_FILENAME, storedNameOf(CHAT)); }); +test("the classifier: a stored caption is TEXT, never tiered; its compressor's temps and set-aside are scratch", () => { + assert.equal(classifyEntry("transcript.en.vtt.zst"), "text"); + assert.equal(isTierable("transcript.en.vtt.zst"), false); + assert.equal(isScratchEntry(".transcript.en.vtt.zst.compressing-4242-abc123"), true); + assert.equal(isScratchEntry(".transcript.en-orig.vtt.retire-4242-abc123"), true); + assert.equal(isScratchEntry(".transcript.es.vtt.restoring-4242-abc123"), true); + assert.equal(isTierable(".transcript.en.vtt.zst.compressing-4242"), false); +}); + test("a logical listing reports the stored chat under its plain name, once", () => { assert.deepEqual( logicalEntries(["metadata.info.json", "transcript.live_chat.json.zst", CHAT, "x.zst"]), ["metadata.info.json", CHAT, "x.zst"], ); assert.equal(listingHas(["transcript.live_chat.json.zst"], CHAT), true); - assert.equal(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), false); + assert.equal(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), true); + assert.equal(listingHas(["metadata.info.json.zst"], "metadata.info.json"), false); + assert.deepEqual( + logicalEntries(["transcript.en-orig.vtt.zst", "transcript.en.vtt", "transcript.en.vtt.zst", "metadata.info.json"]), + ["transcript.en-orig.vtt", "transcript.en.vtt", "metadata.info.json"], + ); assert.equal(storedFormsIn([CHAT], CHAT), "plain"); assert.equal(storedFormsIn(["transcript.live_chat.json.zst"], CHAT), "zst"); assert.equal(storedFormsIn([CHAT, "transcript.live_chat.json.zst"], CHAT), "both"); diff --git a/common/lib/storedText.ts b/common/lib/storedText.ts @@ -4,11 +4,13 @@ // lib/storedText-server.ts, the compressor and the one deleter // lib/storedText-write-server.ts). // -// DECLARED NAMES ONLY. A name is stored compressed only when it is in -// STORED_TEXT_NAMES; for every other name `<name>.zst` means nothing here. The -// raw live-chat replay is the one declared name today (lane text-compress, -// slices 1–2: the media drive's tens of GB of chat). Captions are a later -// slice; `metadata.info.json` is out of scope. +// DECLARED NAMES ONLY. A name is stored compressed only when it is declared +// (`isStoredTextName`); for every other name `<name>.zst` means nothing here. +// Two kinds are declared: the raw live-chat replay (STORED_TEXT_NAMES — lane +// text-compress, slices 1–2: the media drive's tens of GB of chat) and EVERY +// CAPTION TRACK, `transcript.<lang>.vtt` (lane text-compress-captions, slices +// 4–5: about 77 GB on the corpus disk; `isStoredCaptionName`). +// `metadata.info.json` is not declared (a design note only). // // THE RULE: PLAIN, WHEN PRESENT, IS THE TRUTH. Every writer keeps writing the // plain name (yt-dlp, the chat fetch); none has to know about the stored form. @@ -25,14 +27,26 @@ import { LIVE_CHAT_MEDIA_FILENAME } from "./mediaTier"; export const STORED_TEXT_SUFFIX = ".zst"; -// The names stored compressed. One state per name, whatever its size: simpler -// to test than "compressed when big". +// The FIXED names stored compressed. One state per name, whatever its size: +// simpler to test than "compressed when big". export const STORED_TEXT_NAMES: readonly string[] = Object.freeze([LIVE_CHAT_MEDIA_FILENAME]); const DECLARED = new Set(STORED_TEXT_NAMES); +// EVERY CAPTION TRACK: `transcript.<lang>.vtt`, any language code (videoStatus +// `isTranscriptVtt`'s pattern, less the temp below — storedText.test.ts holds +// them together; this module cannot import videoStatus, which imports it). The en / en-orig pair, +// the regional and auto-translated tracks, the foreign-language subtitles. +// Not a transcriber's temp output (`transcript.tmp-<pid>.vtt`, +// controller/transcribeOne.ts): somebody's in-flight bytes, never stored. +const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/; + +export function isStoredCaptionName(name: string): boolean { + return CAPTION_RE.test(name); +} + export function isStoredTextName(name: string): boolean { - return DECLARED.has(name); + return DECLARED.has(name) || CAPTION_RE.test(name); } export function storedNameOf(name: string): string { @@ -44,7 +58,7 @@ export function storedNameOf(name: string): string { export function plainNameOf(name: string): string | null { if (!name.endsWith(STORED_TEXT_SUFFIX)) return null; const plain = name.slice(0, -STORED_TEXT_SUFFIX.length); - return DECLARED.has(plain) ? plain : null; + return isStoredTextName(plain) ? plain : null; } // The name a listing that MATCHES reports for this entry. @@ -83,3 +97,30 @@ export function storedFormsIn(entries: readonly string[], name: string): StoredF if (zst) return "zst"; return null; } + +// THE CAPTION TRACKS ON DISK IN THE STORED FORM ONLY, by their track code +// (`transcript.en-orig.vtt.zst` with no plain `transcript.en-orig.vtt` → +// "en-orig"), from a PHYSICAL listing. These are what a yt-dlp subtitle pass +// must not be asked for: yt-dlp's own "already present" skip looks for the +// plain name, so it would fetch the track again and land a second copy beside +// the stored one (a request against the subtitle 429 limit, and two forms). +export function storedOnlyCaptionTracks(entries: readonly string[]): string[] { + const have = new Set(entries); + const out: string[] = []; + for (const e of entries) { + const plain = plainNameOf(e); + if (plain === null || !CAPTION_RE.test(plain) || have.has(plain)) continue; + out.push(plain.slice("transcript.".length, -".vtt".length)); + } + return out.sort(); +} + +// `--sub-langs` with these tracks EXCLUDED: each appended as `-<code>`, its +// regex characters escaped (yt-dlp matches a code as a regex anchored at both +// ends, and applies the exclusions after the requests before them, so +// `en.*,-en` asks every English track but `en`). Unchanged when there are none. +export function excludeSubTracks(subLangs: string, tracks: readonly string[]): string { + if (tracks.length === 0) return subLangs; + const esc = (t: string) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return [subLangs, ...tracks.map((t) => `-${esc(t)}`)].join(","); +} diff --git a/common/lib/subtitleProvenance.ts b/common/lib/subtitleProvenance.ts @@ -1,7 +1,8 @@ import path from "node:path"; -import { createReadStream } from "node:fs"; import { readFile } from "node:fs/promises"; import { englishVttsByPreference, type VideoFiles } from "./videoStatus"; +import { readStoredTextHead } from "./storedText-server"; +import { logicalEntries } from "./storedText"; // Where a VTT transcript came from: YouTube's speech recognition ("asr", what // yt-dlp downloads under --write-auto-subs) or a human-authored/uploaded track @@ -59,37 +60,24 @@ export function sniffVttProvenance(head: string): SubtitleProvenance { return "unknown"; } -// Read only the head of the VTT (createReadStream start/end), never the whole -// file: a 3-hour ASR transcript is multiple MB. +// Read only the head of the VTT, never the whole file: a 3-hour ASR transcript +// is multiple MB. A track stored compressed (`transcript.en.vtt.zst`, +// lib/storedText.ts) has its head DECODED: the raw bytes of a zstd frame +// would sniff as "unknown" — and an ASR track read as manual is one the purge +// keeps and the replace lane never schedules. export async function readVttProvenance( videoDir: string, vttFile: string, ): Promise<SubtitleProvenance> { let head: string; try { - head = await readHead(path.join(videoDir, vttFile), PROVENANCE_SNIFF_BYTES); + head = (await readStoredTextHead(videoDir, vttFile, PROVENANCE_SNIFF_BYTES)).toString("utf8"); } catch { return "unknown"; } return sniffVttProvenance(head); } -function readHead(file: string, bytes: number): Promise<string> { - return new Promise((resolve, reject) => { - const stream = createReadStream(file, { - encoding: "utf8", - start: 0, - end: bytes - 1, - }); - let out = ""; - stream.on("data", (chunk) => { - out += chunk; - }); - stream.on("error", reject); - stream.on("end", () => resolve(out)); - }); -} - // The language/track segment of a transcript sidecar filename: // "transcript.en-US.vtt" -> "en-US". Null for anything else. export function vttTrackName(filename: string): string | null { @@ -150,7 +138,7 @@ export async function resolveCaptionsProvenance( videoDir: string, entries: readonly string[], ): Promise<SubtitleProvenance | null> { - const vtts = englishVttsByPreference(entries); + const vtts = englishVttsByPreference(logicalEntries(entries)); if (vtts.length === 0) return null; let unknown = false; for (const name of vtts) { diff --git a/common/lib/videoStatus.ts b/common/lib/videoStatus.ts @@ -3,6 +3,7 @@ import { readdir, readFile, stat } from "node:fs/promises"; import { isPartAudioFile, isRealAudioFile } from "./mediaFiles"; import { parseVtt, type Cue } from "./vtt"; import { logicalEntries } from "./storedText"; +import { readStoredText } from "./storedText-server"; export type VideoFiles = { hasMeta: boolean; @@ -29,7 +30,12 @@ export type VideoFiles = { // Surfaced separately so the UI can offer a Resume action; audio-check's // own internal snapshots (.part.good, .part.testing) are excluded. partAudioFiles: string[]; - // The raw readdir() listing this whole record was derived from. + // The LOGICAL readdir() listing this whole record was derived from + // (lib/storedText.ts): a file stored compressed — `transcript.en.vtt.zst`, + // `transcript.live_chat.json.zst` — is listed under its plain name, once, + // and every reader of its bytes goes through lib/storedText-server.ts. A + // caller that OPERATES on each entry as a file (the byte walk, a mover) + // takes `physicalEntries`. // // Exposed so a caller that needs a question this type does not already answer // — "is there a source container?", "is there a saved-video pointer?" — can @@ -39,6 +45,8 @@ export type VideoFiles = { // that is free and one that doubles the report's I/O. See // lib/operations.ts, which classifies missing vs missing-input from it. entries: string[]; + // The raw readdir(): every entry under its own name (a `.zst` is a file). + physicalEntries: string[]; }; export type IndexTranscript = @@ -187,20 +195,22 @@ export function captionInputs(entries: readonly string[]): string[] { // preference order, that parses to at least one cue. When every track parses // to nothing, the most preferred one is returned with its empty list (the // video has captions, they say nothing). Null when there is no English VTT, or -// none can be read. `entries` is the caller's readdir of `videoDir`, when it -// has one. +// none can be read. `entries` is the caller's LOGICAL listing of `videoDir` +// (readVideoFiles().entries), when it has one — a physical readdir is made +// logical here too, so a track stored as `transcript.en.vtt.zst` is read +// (lib/storedText.ts) and the name answered is always the plain one. export async function readEnglishVttCues( videoDir: string, entries?: readonly string[], ): Promise<{ filename: string; cues: Cue[] } | null> { const names = englishVttsByPreference( - entries ?? (await readdir(videoDir).catch(() => [] as string[])), + logicalEntries(entries ?? (await readdir(videoDir).catch(() => [] as string[]))), ); let first: { filename: string; cues: Cue[] } | null = null; for (const filename of names) { let cues: Cue[]; try { - cues = parseVtt(await readFile(path.join(videoDir, filename), "utf8")); + cues = parseVtt(await readStoredText(videoDir, filename, "utf8")); } catch { continue; } @@ -230,7 +240,8 @@ export async function readVideoFiles( videoDir: string, opts: { checkUntranscribable?: boolean } = {}, ): Promise<VideoFiles> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const physicalEntries = await readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(physicalEntries); const hasMeta = entries.includes(META_FILENAME); const ytVttFile = resolvePrimaryVtt(entries); const hasYtVtt = ytVttFile !== null; @@ -270,6 +281,7 @@ export async function readVideoFiles( audioFiles, partAudioFiles, entries, + physicalEntries, }; } diff --git a/common/package.json b/common/package.json @@ -78,6 +78,7 @@ "./lib/sourceStatus.mjs": "./lib/sourceStatus.mjs", "./lib/sourceStatus-server.mjs": "./lib/sourceStatus-server.mjs", "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", + "./lib/storedText-read.mjs": "./lib/storedText-read.mjs", "./lib/videoDirId.mjs": "./lib/videoDirId.mjs", "./ytdlp/platformArgs.mjs": "./ytdlp/platformArgs.mjs", "./lib/*": "./lib/*.ts", diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -71,11 +71,12 @@ import { isLocalRecord } from "../lib/localMedia"; import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view"; -import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { publishFileSizeProblem } from "../lib/builtExport"; import type { Paths } from "../lib/paths"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; +import { readStoredText, readdirLogical } from "../lib/storedText-server"; import { type Site } from "../lib/site"; import { storeReportDir } from "../lib/report/store"; import { getSettings } from "../lib/settings"; @@ -295,9 +296,10 @@ export type CitedRecord = { wayback: WaybackProvenance | null; }; -async function readCues(file: string, kind: "vtt" | "whisper"): Promise<Cue[]> { +// Either form (lib/storedText.ts): a caption stored as `.zst` is read. +async function readCues(dir: string, name: string, kind: "vtt" | "whisper"): Promise<Cue[]> { try { - const raw = await readFile(file, "utf8"); + const raw = await readStoredText(dir, name, "utf8"); return kind === "vtt" ? parseVtt(raw) : parseTranscriptJson(raw); } catch { return []; @@ -315,7 +317,8 @@ export async function readCitedRecord( // The record's directory: a Twitch record's v<n> is data/<n>/ (release 23 // F1b). The record keeps the id it is cited by. const dir = await resolveVideoDir(channelsDir, slug, id); - const entries = await readdir(dir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a stored caption is listed under its name. + const entries = await readdirLogical(dir); if (entries.length === 0) return null; let summary: CitedRecord["summary"] | null = null; let cues: Cue[] = []; @@ -332,7 +335,7 @@ export async function readCitedRecord( const meta = await loadRawMetadataFromDir(dir); if (!meta) return null; summary = summarize(slug, id, meta, channelName); - if (entries.includes(WHISPER_FILENAME)) cues = await readCues(path.join(dir, WHISPER_FILENAME), "whisper"); + if (entries.includes(WHISPER_FILENAME)) cues = await readCues(dir, WHISPER_FILENAME, "whisper"); } // The caption-track rule (videoStatus.ts): the first English VTT, `en-orig` // first, that has cues. @@ -343,11 +346,11 @@ export async function readCitedRecord( if (n?.cues?.length) tracks.push({ name: path.basename(fresh.cuesPath), cues: n.cues }); } if (entries.includes(WHISPER_FILENAME)) { - const w = await readCues(path.join(dir, WHISPER_FILENAME), "whisper"); + const w = await readCues(dir, WHISPER_FILENAME, "whisper"); if (w.length > 0) tracks.push({ name: WHISPER_FILENAME, cues: w }); } for (const name of englishVttsByPreference(entries)) { - const v = await readCues(path.join(dir, name), "vtt"); + const v = await readCues(dir, name, "vtt"); if (v.length > 0) tracks.push({ name, cues: v }); } if (tracks.length === 0 && cues.length > 0) tracks.push({ name: "cues", cues }); diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -70,7 +70,13 @@ import { evaluateDownloadFilters } from "../lib/downloadFilters"; import { normalizeLiveChat } from "../controller/normalizeLiveChat"; import { writeCuesAfterDownload } from "../controller/normalizeTranscript"; import { LIVE_CHAT_FILENAME } from "../lib/videoStatus"; -import { listingHas, storedFormsIn } from "../lib/storedText"; +import { + excludeSubTracks, + listingHas, + logicalEntries, + storedFormsIn, + storedOnlyCaptionTracks, +} from "../lib/storedText"; import { upsertMetadataScan, type MetadataScanEntry, @@ -296,12 +302,16 @@ export type ManagedDownloadOpts = { // A CHAT ALREADY STORED (`chatStored`, lib/storedText.ts): yt-dlp's own // "already present" skip looks for the plain `transcript.live_chat.json`, so // over a compressed one it would fetch the whole replay again. The chat is -// left out of the sub-langs instead, as for a `later` channel. Exported for -// its test. +// left out of the sub-langs instead, as for a `later` channel. The same for +// a CAPTION TRACK stored compressed (`storedCaptionTracks`, its codes from +// lib/storedText.ts `storedOnlyCaptionTracks`): each is excluded by its code +// (`,-en,-en-orig`), so a re-download never fetches it again beside the +// stored copy. Exported for its test. export function youtubeHandlingArgs( config: ChannelConfig, reuseInfoJson = false, chatStored = false, + storedCaptionTracks: readonly string[] = [], ): string[] { const args = [ "--write-auto-subs", @@ -309,7 +319,10 @@ export function youtubeHandlingArgs( "--sub-langs", // Without the live chat unless the channel fetches it with the download // (ChannelConfig.chat). - effectiveSubLangs(chatStored ? { ...config, chat: "later" } : config), + excludeSubTracks( + effectiveSubLangs(chatStored ? { ...config, chat: "later" } : config), + storedCaptionTracks, + ), ]; if (!reuseInfoJson) args.push("--write-info-json"); args.push( @@ -671,8 +684,11 @@ async function sourceMediaPartials(videoDir: string): Promise<string[]> { return out; } +// LOGICAL (lib/storedText.ts): a caption stored as `transcript.en.vtt.zst` is +// a transcript on disk — a miss here downloads the audio and queues a +// transcription for a video that has captions. async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(await readdir(videoDir).catch(() => [] as string[])); return entries.some((e) => { if (e === "transcript.json") return true; const m = e.match( @@ -685,6 +701,9 @@ async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> { }); } +// Exported for the unit test ONLY (controller/storedText.captions.test.ts). +export const __hasAnyTranscriptOnDiskForTest = hasAnyTranscriptOnDisk; + // Listed, none of them (lib/listedCaptions-server.ts — the one rule): the // no-subs fallback's reason to fetch audio. No readable metadata says nothing. async function metadataReportsNoCaptions( @@ -1323,18 +1342,19 @@ async function runManagedDownload( // its own args; youtube handling downloads subtitles (the persistence plan only // applies to the no-subs fallback below). For transcribe handling the plan // chooses audio-only vs. keep-source-video and yt-dlp vs. app extraction. - const chatStored = + // What is stored compressed in the video's dir (lib/storedText.ts): the + // chat, and the caption tracks — each left out of the subtitle request. + const storedListing = opts.channelConfig.handling === "youtube" && canonicalId - ? storedFormsIn( - await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]), - LIVE_CHAT_FILENAME, - ) === "zst" - : false; + ? await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]) + : []; + const chatStored = storedFormsIn(storedListing, LIVE_CHAT_FILENAME) === "zst"; + const storedCaptionTracks = storedOnlyCaptionTracks(storedListing); const mediaArgs = opts.channelConfig.handling === "youtube" ? [ ...outputArgsForUrl(opts.videoUrl), - ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson, chatStored), + ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson, chatStored, storedCaptionTracks), ] : transcribeMediaArgs( opts.videoUrl, diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -2,7 +2,12 @@ // process's outward doors refuse before any request. import "../lib/noNetwork.mjs"; import { tierChannelMedia } from "../lib/mediaTier-server"; -import { logicalEntries, storedFormsIn } from "../lib/storedText"; +import { + excludeSubTracks, + logicalEntries, + storedFormsIn, + storedOnlyCaptionTracks, +} from "../lib/storedText"; import path from "node:path"; import { mkdir, readdir, readFile } from "node:fs/promises"; import { writeFileAtomic } from "../lib/jsonFile-server"; @@ -1483,13 +1488,18 @@ function compileSubLangMatcher(spec: string): (track: string) => boolean { const SUB_EXT_PATTERN = "(?:vtt|json|json3|srv1|srv2|srv3)"; -// One video's `--sub-langs` for the missing-subs fetch. A chat stored -// compressed (lib/storedText.ts) is on disk, but yt-dlp's own "already -// present" skip looks for the plain name and would fetch the whole replay -// again: it is left out, as for a `later` channel. Exported for its test. +// One video's `--sub-langs` for the missing-subs fetch, from its PHYSICAL +// listing. A chat or a caption track stored compressed (lib/storedText.ts) is +// on disk, but yt-dlp's own "already present" skip looks for the plain name +// and would fetch it again, landing a second copy beside the stored one: a +// stored chat is left out as for a `later` channel, and each stored caption +// track is excluded by its code (`,-en,-en-orig`). Exported for its test. export function subLangsForVideo(entries: readonly string[], subLangs: string): string { - if (storedFormsIn(entries, LIVE_CHAT_FILENAME) !== "zst") return subLangs; - return effectiveSubLangs({ subLangs, chat: "later" }); + const chatLeftOut = + storedFormsIn(entries, LIVE_CHAT_FILENAME) === "zst" + ? effectiveSubLangs({ subLangs, chat: "later" }) + : subLangs; + return excludeSubTracks(chatLeftOut, storedOnlyCaptionTracks(entries)); } // Over a LOGICAL listing (lib/storedText.ts): a chat stored as @@ -1807,7 +1817,9 @@ export async function destinationExists( } = {}, ): Promise<boolean> { const dir = path.join(dataDir, id); - const entries = await readdir(dir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption stored as `transcript.en.vtt.zst` + // is the destination on disk — a miss here re-fetches the URL. + const entries = logicalEntries(await readdir(dir).catch(() => [] as string[])); // A retry of a corrupt full source asks the source again whatever is on // disk — the kept container, or a salvage transcript made from it (release // 30, lane Q). Only the retry asks; a sweep still counts it as there. diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -79,6 +79,18 @@ stored chat again on purpose: the stored capture is kept as `chat-capture-kept.<stamp>.json.zst` and never removed automatically; the log compares both. An empty replay leaves the stored capture the chat. - Two different captures are never settled by deleting one. A second editor process waits for a video's lock. +- **Caption tracks may be on disk compressed, and every reader still finds them.** + - A caption track (`transcript.en.vtt`, `transcript.en-orig.vtt`, any `transcript.<lang>.vtt`) may be stored as + `transcript.<lang>.vtt.zst`. Every reader reads either form with the same times: the index, normalize, the + snapshot's buckets, the caption-provenance sniff (it decodes the head), report compose, the remote worker's + inputs (sent plain), the clip tools. Nothing is fetched or transcribed again because a track is stored: + "already downloaded" and "has a transcript" count it, and a subtitle download leaves a stored track out of + `--sub-langs`. + - The superseded-auto-caption purge and the clear-transcript fix remove both forms; the purge keeps both when + they differ. The tier migration's reclaim takes a platter copy whose twin is stored only when it decodes to the + same bytes. + - The video page lists and labels a stored track under its own name; the files card shows the `.zst` as a file + and previews its decoded text. - **Clean audio without checking, and a rate-limited clean that says so.** - The channel page's Cleanup stage has **Clean without checking…** beside Clean audio. It first counts what it would remove (files, bytes, videos, and what it keeps; no request to the source) and asks: "Remove N audio files (X) diff --git a/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.test.ts b/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.test.ts @@ -66,3 +66,36 @@ test("a path that leaves the video dir is refused; a missing file is a 404", asy }); assert.equal(missing.status, 404); }); + +// A CAPTION STORED COMPRESSED (lane text-compress-captions): the files card +// previews `transcript.en.vtt.zst` as its decoded text (`?decoded=1`), and the +// plain name answers the decoded text when only the stored form is on disk. +// Without `?decoded=1` the stored name is its own file, bytes as they are. +test("a stored caption: its decoded text by the plain name or ?decoded=1; its own bytes without", async () => { + const { encodeStoredBytes } = await import("yt-dlp-transcript-common/lib/storedText-server"); + const text = "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nstored words\n"; + const zst = await encodeStoredBytes(Buffer.from(text)); + await writeFile(path.join(VIDEO_DIR, "transcript.en.vtt.zst"), zst); + const ask = (name: string, q = "") => + GET(new Request(`http://localhost/api/channels/chan/videos/vidA/files/${name}${q}`), { + params: Promise.resolve({ slug: "chan", id: "vidA", name }), + }); + const byPlain = await ask("transcript.en.vtt"); + assert.equal(byPlain.status, 200); + assert.match(byPlain.headers.get("content-type") ?? "", /^text\/vtt/); + assert.equal(await byPlain.text(), text); + const decoded = await ask("transcript.en.vtt.zst", "?decoded=1"); + assert.equal(decoded.status, 200); + assert.equal(await decoded.text(), text); + const raw = await ask("transcript.en.vtt.zst"); + assert.equal(raw.status, 200); + assert.equal(raw.headers.get("content-type"), "application/octet-stream"); + assert.deepEqual(Buffer.from(await raw.arrayBuffer()), zst); + // A plain file beside it is the truth: the plain name serves it as it is. + await writeFile(path.join(VIDEO_DIR, "transcript.en.vtt"), "WEBVTT\n\nnewer\n"); + assert.equal(await (await ask("transcript.en.vtt")).text(), "WEBVTT\n\nnewer\n"); + // …and the stored one, asked by its own name decoded, is still its own. + assert.equal(await (await ask("transcript.en.vtt.zst", "?decoded=1")).text(), text); + // Neither form: a 404. + assert.equal((await ask("transcript.de.vtt")).status, 404); +}); diff --git a/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts b/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts @@ -1,6 +1,6 @@ import path from "node:path"; import { createReadStream, type ReadStream } from "node:fs"; -import { lstat, stat } from "node:fs/promises"; +import { lstat, readFile, stat } from "node:fs/promises"; import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { makeSafeController } from "yt-dlp-transcript-common/lib/safeStreamController"; @@ -15,6 +15,8 @@ import { isDriveNotAnswering, onDrive, } from "yt-dlp-transcript-common/lib/storageHealth"; +import { isStoredCaptionName, plainNameOf, storedNameOf } from "yt-dlp-transcript-common/lib/storedText"; +import { decodeStoredBytes, readStoredText } from "yt-dlp-transcript-common/lib/storedText-server"; export const dynamic = "force-dynamic"; @@ -168,6 +170,50 @@ export async function GET( if (onMediaTier && channelMediaStall(channelConfig)) return notAnswering(); const drive = onMediaTier ? mediaDir || legacyDrive : legacyDrive; + // A CAPTION STORED COMPRESSED (lib/storedText.ts) is served as its text, + // decoded: asked by its stored name with `?decoded=1` (the files card's + // preview of `transcript.en.vtt.zst`), or by its plain name when only the + // stored form is on disk (a reader that asks for the track it was listed). + // Captions only — small text on the corpus disk; the raw chat is never read + // whole to be served. Without `?decoded=1` the stored name is its own file. + const decoded = new URL(request.url).searchParams.get("decoded") === "1"; + const storedPlain = plainNameOf(name); + const captionOf = + decoded && storedPlain !== null && isStoredCaptionName(storedPlain) + ? storedPlain + : isStoredCaptionName(name) && + !(await lstat(fullPath).then(() => true, () => false)) && + (await lstat(path.join(path.dirname(fullPath), storedNameOf(name))).then(() => true, () => false)) + ? name + : null; + if (captionOf !== null) { + const dir = path.dirname(fullPath); + let text: string; + try { + // Asked by the plain name: `readStoredText` (the plain file when it is + // there — the truth — else the stored form). Asked by the stored name: + // THAT file's bytes, decoded (its frame's checksum and length checked), + // whatever stands beside it. + const read = async () => + captionOf === name + ? readStoredText(dir, captionOf, "utf8") + : (await decodeStoredBytes(await readFile(fullPath), name)).toString("utf8"); + text = await (legacyDrive ? onDrive(legacyDrive, read) : read()); + } catch (err) { + if (isDriveNotAnswering(err)) return notAnswering(); + return NextResponse.json({ error: `Not read: ${(err as Error).message}` }, { status: 404 }); + } + const body = Buffer.from(text, "utf8"); + return new Response(body, { + status: 200, + headers: { + "Content-Type": contentTypeFor(captionOf), + "Content-Length": String(body.length), + "Cache-Control": "no-store", + }, + }); + } + let stats; try { stats = await (drive ? onDrive(drive, () => stat(fullPath)) : stat(fullPath)); diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts @@ -0,0 +1,35 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/channels/*/lib/fixIncompleteTranscript.test.ts" +// +// CLEARING A TRUNCATED TRANSCRIPT CLEARS ITS CAPTIONS IN BOTH FORMS (lane +// text-compress-captions). A track stored as `transcript.<lang>.vtt.zst` +// (lib/storedText.ts) missed by the clear would bring the cleared transcript +// back. Temp corpus, synthetic names. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "clear-incomplete-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +const { clearIncompleteTranscriptOne } = await import("./fixIncompleteTranscript"); +const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); +const { encodeStoredBytes } = await import("yt-dlp-transcript-common/lib/storedText-server"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("every caption track goes, stored or plain, and the metadata stays", async () => { + const dir = path.join(ROOT, "channels", "synth", "data", "vid00000001"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), "{}"); + await writeFile(path.join(dir, "audio.mp3"), "A"); + await writeFile(path.join(dir, "transcript.json"), "{}"); + await writeFile(path.join(dir, "transcript.en.vtt.zst"), await encodeStoredBytes(Buffer.from("WEBVTT\n\nstored\n"))); + await writeFile(path.join(dir, "transcript.en-orig.vtt"), "WEBVTT\n\nplain\n"); + await writeFile(path.join(dir, "transcript.en-orig.vtt.zst"), await encodeStoredBytes(Buffer.from("WEBVTT\n\nolder\n"))); + const out = await clearIncompleteTranscriptOne({ slug: "synth", videoId: "vid00000001", paths: getPaths() }); + assert.equal(out.removed, 4, "audio, transcript.json and the two caption tracks (each in every form)"); + assert.deepEqual(await readdir(dir), ["metadata.info.json"]); +}); diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts @@ -11,6 +11,7 @@ import { removeMediaFile } from "yt-dlp-transcript-common/lib/mediaTier-server"; import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; import path from "node:path"; import { readdir } from "node:fs/promises"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; @@ -143,7 +144,9 @@ export async function clearIncompleteTranscriptOne(opts: { `Refusing to clear: video path resolved outside the data dir (${videoId})`, ); } - const entries = await readdir(resolved).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption track stored as `.zst` is listed + // under its plain name, so it is cleared too (in both forms, below). + const entries = logicalEntries(await readdir(resolved).catch(() => [] as string[])); const toRemove = entries.filter( (name) => isRealAudioFile(name) || diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -50,6 +50,7 @@ import { isAudioFile, isTranscodeSource, isTranscriptVttName, + logicalFileNames, type VideoFile, } from "./cards/videoFiles"; @@ -159,9 +160,10 @@ export function VideoPanel({ !hasTranscriptJson && primaryVtt !== null && vttProvenance[primaryVtt] === "asr"; - const vttTracks = files - .filter((f) => isTranscriptVttName(f.name)) - .map((f) => f.name) + // LOGICAL (lib/storedText.ts): a track stored as `.zst` is listed under + // its plain name — the name every action on it takes. + const vttTracks = logicalFileNames(files) + .filter((name) => isTranscriptVttName(name)) .sort(); // The transcript the index/viewer will actually use: whisper wins over VTT. const activeTranscript = hasTranscriptJson ? WHISPER_FILENAME : primaryVtt; diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx @@ -7,7 +7,7 @@ import { TextFilePreview } from "../TextFilePreview"; import { deleteVideoFileAction, } from "../../videoActions"; -import { mediaKind, mediaUrl, type VideoFile } from "./videoFiles"; +import { isStoredCaptionFile, mediaKind, mediaUrl, type VideoFile } from "./videoFiles"; export function FilesList({ slug, @@ -27,7 +27,10 @@ export function FilesList({ className="flex flex-col gap-3" > {files.map((f) => { - const kind = mediaKind(f.name); + // A caption stored compressed (`transcript.en.vtt.zst`, lib/storedText.ts) + // is listed as the file it is, and previewed as its decoded text. + const storedCaption = isStoredCaptionFile(f.name); + const kind = storedCaption ? "text" : mediaKind(f.name); return ( <li key={f.name} @@ -53,7 +56,7 @@ export function FilesList({ /> ) : kind === "text" ? ( <TextFilePreview - src={mediaUrl(slug, videoId, f.name)} + src={`${mediaUrl(slug, videoId, f.name)}${storedCaption ? "?decoded=1" : ""}`} filename={f.name} /> ) : null} diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts b/editor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts @@ -2,6 +2,11 @@ import { AUDIO_EXTS, VIDEO_CONTAINER_EXTS, } from "yt-dlp-transcript-common/lib/mediaFiles"; +import { + isStoredCaptionName, + logicalEntries, + plainNameOf, +} from "yt-dlp-transcript-common/lib/storedText"; export type VideoFile = { name: string; @@ -21,6 +26,19 @@ export function isTranscriptVttName(name: string): boolean { return /^transcript\.[^.]+\.vtt$/.test(name); } +// The files card's listing is PHYSICAL: a caption stored compressed is +// `transcript.en.vtt.zst` there (lib/storedText.ts). Everything that MATCHES +// names — which tracks there are, which is primary — takes this LOGICAL list +// of it, where that file is `transcript.en.vtt`, once. +export function logicalFileNames(files: readonly VideoFile[]): string[] { + return logicalEntries(files.map((f) => f.name)); +} + +export function isStoredCaptionFile(name: string): boolean { + const plain = plainNameOf(name); + return plain !== null && isStoredCaptionName(plain); +} + // One list, shared with the detection predicates in lib/mediaFiles.ts — these // were duplicated here and drifting. isAudioFile deliberately stays on // AUDIO_EXTS alone: audio.mp4 is a wrong-format cleanup target, not something diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -1,5 +1,6 @@ import type { Metadata } from "next"; import { LiveRecordingsAttention } from "../../../../components/LiveRecordingsAttention"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; import Link from "next/link"; import { notFound } from "next/navigation"; import path from "node:path"; @@ -196,9 +197,11 @@ export default async function VideoDetailPage({ // auto-captions" vs "manual captions" — and offer to replace the former with a // transcript of our own. One 4 KB head read per VTT (see subtitleProvenance). const vttProvenance: Record<string, SubtitleProvenance> = {}; - for (const f of dirData.files) { - if (!isTranscriptVtt(f.name)) continue; - vttProvenance[f.name] = await resolveVttProvenance(videoDir, f.name); + // By LOGICAL name (lib/storedText.ts): a track stored as `.zst` is sniffed + // decoded, under its plain name. + for (const name of logicalEntries(dirData.files.map((f) => f.name))) { + if (!isTranscriptVtt(name)) continue; + vttProvenance[name] = await resolveVttProvenance(videoDir, name); } const cov = await readTranscriptCoverage(videoDir); const coverage = cov @@ -425,7 +428,7 @@ export default async function VideoDetailPage({ // Read HERE, in the server component, never in the client one: an env // var does not exist in the browser. Unset means no link at all. umtoolUrl={process.env.UMTOOL_URL?.replace(/\/+$/, "") || null} - primaryVtt={resolvePrimaryVtt(dirData.files.map((f) => f.name))} + primaryVtt={resolvePrimaryVtt(logicalEntries(dirData.files.map((f) => f.name)))} vttProvenance={vttProvenance} handling={config.handling} defaultQueueKey={defaultQueueKey} diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -61,6 +61,8 @@ import { import { onDrive } from "yt-dlp-transcript-common/lib/storageHealth"; import { isTierable } from "yt-dlp-transcript-common/lib/mediaTier"; import { removeStoredTextForm } from "yt-dlp-transcript-common/lib/storedText-write-server"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; +import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-server"; import { setExcludedFromTruncatedCheck } from "yt-dlp-transcript-common/lib/excludeTruncatedCheck-server"; import { pinTranscript } from "yt-dlp-transcript-common/lib/transcriptPin-server"; import { readVideoTracks } from "yt-dlp-transcript-common/lib/captionTracks-server"; @@ -756,7 +758,8 @@ export async function whisperVideoAction( : await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries }); if (!audioOnDisk && asr !== true && r.config.handling === "youtube") { - const onDisk = englishVttsByPreference(firstEntries); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is on disk. + const onDisk = englishVttsByPreference(logicalEntries(firstEntries)); if (onDisk.length > 0) { return { ok: false, @@ -1088,7 +1091,7 @@ export async function deleteVideoFileAction( ok: true, note: k.same === "same" - ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still see the chat.` + ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still read it.` : k.same === "differs" ? `Deleted ${filename} only. ${k.name} is still here with different content, and is the file readers read.` : `Deleted ${filename} only. ${k.name} is still here (it could not be read whole to compare).`, @@ -1122,10 +1125,16 @@ export async function setPrimaryTranscriptAction( } let raw: string; try { - raw = await readFile(source, "utf8"); + // Either form (lib/storedText.ts): a track stored as `.zst` is read. + raw = await readStoredText(videoDir, path.basename(source), "utf8"); } catch { return { ok: false, error: `File not found: ${filename}` }; } + // The copy is written under the plain name. A STORED `transcript.en.vtt.zst` + // beside it (YouTube's own `en` track, compressed) is NOT removed: the new + // plain file is what every reader reads (lib/storedText.ts, plain is the + // truth), and the earlier track stays beside it — both forms, different + // content, which compress-text lists and never settles by deleting one. if (filename !== VTT_FILENAME) { await writeFileAtomic(path.join(videoDir, VTT_FILENAME), raw); } diff --git a/editor/app/channels/[slug]/videos/page.tsx b/editor/app/channels/[slug]/videos/page.tsx @@ -1,5 +1,6 @@ import path from "node:path"; import type { Metadata } from "next"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; import { notFound } from "next/navigation"; import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import type { ChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot"; @@ -249,7 +250,7 @@ export default async function ChannelVideosPage({ slug={slug} videoId={selectedVideoId} files={dirData.files} - primaryVtt={resolvePrimaryVtt(dirData.files.map((f) => f.name))} + primaryVtt={resolvePrimaryVtt(logicalEntries(dirData.files.map((f) => f.name)))} handling={config.handling} defaultQueueKey={platformDefaultQueueKey} existingQueues={existingQueues} diff --git a/umtool/lib/ingredients/stages.mjs b/umtool/lib/ingredients/stages.mjs @@ -27,6 +27,7 @@ import { describeClock } from "yt-dlp-transcript-common/lib/recordingClock.mjs"; import { readRecordingClock } from "yt-dlp-transcript-common/lib/recordingClock-read.mjs"; import { audioFilesOf, present, readSavedVideoPointer, WIN_EPS } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; import { readChannelPlatform, recordIdOfVideoDir, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { archiveMomentUrl } from "umtool-report-to-video/site-links"; import { readLog } from "../research/log.mjs"; import { readQuoteCheck, rowIsCurrent } from "../report/quoteCheck.mjs"; @@ -221,7 +222,8 @@ async function downloadedStage({ idn }) { const f = await fileState(dir, n); if (f) media.push(f); } - const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n)); + // LOGICAL (common/lib/storedText-read.mjs): a caption stored as `.zst` is a caption. + const vtts = logicalEntries(names).filter((n) => /^transcript\..+\.vtt$/.test(n)); const problems = []; if (outcome && !outcome.status.startsWith("ok")) problems.push(`the last download ended ${outcome.status}`); if (availability && !AVAILABLE.has(availability.availability)) problems.push(`the recording reads ${availability.availability} (checked ${availability.checkedAt ?? "?"})`); @@ -276,7 +278,7 @@ async function transcribedStage({ idn }) { const outcome = to && typeof to === "object" ? { at: to.transcribedAt ?? null, worker: to.worker?.appId ?? to.worker?.id ?? null, durationMs: fin(to.durationMs) ? to.durationMs : null, salvaged: !!to.salvaged } : null; const words = await statOf(path.join(dir, "words.json")); const names = await readdir(dir).catch(() => []); - const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n)); + const vtts = logicalEntries(names).filter((n) => /^transcript\..+\.vtt$/.test(n)); const line = cues ? `${cues.source ?? "cues"}${cues.engine ?? outcome?.worker ? ` (${cues.engine ?? outcome?.worker})` : ""}${cues.coverage !== null ? `, ${Math.round(cues.coverage * 100)}% of ${hms(cues.duration)}` : ""}${outcome?.salvaged ? ", SALVAGED (gaps)" : ""}${words ? ", timed words" : ""}${pin ? ", pinned" : ""}` : vtts.length diff --git a/umtool/report-to-video/clip-words.mjs b/umtool/report-to-video/clip-words.mjs @@ -21,6 +21,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { hasLocalMedia } from "./local-media.mjs"; import { whisperWords } from "./montage.mjs"; @@ -105,7 +106,8 @@ export async function clipWords(entry, provenance, from, to, { channelsDir }) { const cues = await json("transcript.cues.json"); const names = [...new Set([typeof cues?.vttFile === "string" ? path.basename(cues.vttFile) : null, "transcript.en-orig.vtt", "transcript.en.vtt"].filter(Boolean))]; for (const name of names) { - const text = await readFile(path.join(dir, name), "utf8").catch(() => null); + // Either form (common/lib/storedText-read.mjs): a stored caption is read. + const text = await readStoredText(dir, name, "utf8").catch(() => null); if (!text) continue; const words = vttWordStarts(text).filter(inSpan); if (words.length) return { words, timed: false, from: "captions" }; diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -64,6 +64,7 @@ import os from "node:os"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { readdirLogical, readStoredTextHead, storedTextLogicalSize } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { fetchOnOrigin, readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs"; // For the other readers of an archive that come through this module (linkCheck.mjs). @@ -165,19 +166,23 @@ async function staleCaptionRecord(videoDir, record) { if (record?.source !== "vtt" || record.captionTrackRule === CAPTION_TRACK_RULE_VERSION) { return false; } - const entries = await readdir(videoDir).catch(() => []); + // LOGICAL (common/lib/storedText-read.mjs): a caption stored as + // `transcript.en.vtt.zst` is a track under its plain name; its head is read + // DECODED and its size is the LOGICAL one (the frame header's) — the raw + // bytes of a stored track would sniff and size as something else. + const entries = await readdirLogical(videoDir); const english = entries.filter((e) => ENGLISH_VTT_RE.test(e)); if (!Array.isArray(record.cues) || record.cues.length === 0) { if (english.length !== 1) return true; - const head = (await readFile(path.join(videoDir, english[0]), "utf8").catch(() => "")).slice(0, 2048); + const head = (await readStoredTextHead(videoDir, english[0], 2048).catch(() => Buffer.alloc(0))).toString("utf8"); return !/<\d{2}:\d{2}:\d{2}\.\d{3}>/.test(head); } if (!entries.includes("transcript.en.vtt") || !entries.includes("transcript.en-orig.vtt")) return false; const [en, orig] = await Promise.all([ - stat(path.join(videoDir, "transcript.en.vtt")), - stat(path.join(videoDir, "transcript.en-orig.vtt")), + storedTextLogicalSize(videoDir, "transcript.en.vtt"), + storedTextLogicalSize(videoDir, "transcript.en-orig.vtt"), ]); - return en.size !== orig.size; + return en !== orig; } export class CueLookupError extends Error { diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -10,6 +10,7 @@ import test from "node:test"; import { mkdtemp, mkdir, symlink, writeFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; +import { zstdCompressSync } from "node:zlib"; import { CAPTION_TRACK_RULE_VERSION, @@ -278,6 +279,46 @@ test("a local caption record from before the caption-track rule is refused where } }); +// --- the same, over captions STORED COMPRESSED (lane text-compress-captions) -- +// A track may be `transcript.<lang>.vtt.zst` (common/lib/storedText.ts): one +// zstd frame with its content size. The rule's listing, head and sizes must be +// the LOGICAL ones — on the raw listing a stored en reads as absent, and an +// unversioned record beside an en / en-orig that DIFFER would be cut from. + +const stored = (text) => zstdCompressSync(Buffer.from(text, "utf8")); + +test("over stored captions: a differing pair is still refused, an identical pair and a lone word-timed track are read", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "cues-stored-")); + try { + const vdir = path.join(dir, "chan", "data", "vid1"); + await mkdir(vdir, { recursive: true }); + await writeFile(path.join(vdir, "transcript.en.vtt.zst"), stored("WEBVTT\n\nserved words\n")); + await writeFile(path.join(vdir, "transcript.en-orig.vtt"), "WEBVTT\n\nwhat was said\n"); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ ...RECORD, source: "vtt" })); + const src = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, fetchImpl: stubFetch(ROUTES) }); + await assert.rejects(src.load("chan", "vid1"), /older caption-track rule/); + + // Both stored, byte-identical: equal LOGICAL sizes — read as usual. + await rm(path.join(vdir, "transcript.en-orig.vtt")); + await writeFile(path.join(vdir, "transcript.en.vtt.zst"), stored("WEBVTT\n\nwhat was said\n")); + await writeFile(path.join(vdir, "transcript.en-orig.vtt.zst"), stored("WEBVTT\n\nwhat was said\n")); + assert.equal((await src.load("chan", "vid1")).from, "local"); + + // A zero-cue record beside ONE stored track with word timing: genuinely + // empty, read from the DECODED head. + const lone = path.join(dir, "chan", "data", "vid2"); + await mkdir(lone, { recursive: true }); + await writeFile( + path.join(lone, "transcript.en.vtt.zst"), + stored("WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nword<00:00:01.000><c> timed</c>\n"), + ); + await writeFile(path.join(lone, "transcript.cues.json"), JSON.stringify({ ...RECORD, id: "vid2", source: "vtt", cues: [] })); + assert.equal((await src.load("chan", "vid2")).from, "local"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("a lone-track caption record with cues needs no rule to be read", async () => { const dir = await mkdtemp(path.join(tmpdir(), "cues-rule-")); try {