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..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> caption<00:00:02.000> line.\n\n" + "00:01:00.000 --> 00:01:50.000 align:start position:0%\n" + "Second<00:01:10.000> caption<00:01:20.000> line.\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, extra: Record = {}): Promise { 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 { 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 missing-subs pass leaves every stored track out of --sub-langs (under --no-overwrites main skipped a present one)", 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]; // The managed download fetches a stored caption AGAIN (main's re-download // rule, REVIEW-1 F1): no exclusion there; the pass is settled afterwards // (ytdlp/captionsRefetch.test.ts). Only the stored chat is left out. assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat"); assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true)), "en.*"); }); 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")); });