import test from "node:test"; import assert from "node:assert/strict"; import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { callPost, setupOpsCorpus } from "../_testCorpus"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/transcribe-one/route.test.ts" // // `pnpm ops transcribe-one` against a temp corpus, the fake yt-dlp and the // fake whisper (e2e/fixtures/bin) — nothing here asks a real platform: // // - the whisper-video HANDS OFF: once its audio download is done, the // platform's queue is free — a download queued behind it runs while the // transcription it handed off still waits for a worker; // - with audio on disk the job is a transcribe-one on the video's own queue // (`transcribe-one::`), "file" or not; // - a youtube-handling video with English captions listed and no audio has // its captions fetched instead; "asr": true transcribes it anyway. const corpus = await setupOpsCorpus(null); const SLUG = "handoff-yt"; await corpus.writeSettings({ minFreeDiskGB: 0, pacing: { jobGapSeconds: { youtube: 0, default: 0 } } }); await corpus.writeChannelConfig(SLUG, { handling: "youtube", platform: "youtube", url: "https://www.youtube.com/@handoff", audioFormat: "mp3", }); type Post = Parameters[0]; const POST = (await import("./route")).POST as Post; const { downloadVideoPipelineAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool"); // A job's end still writes after its status reads done (its log and sidecar, // and the report regeneration it arms in the channel dir): waited for before // the corpus is removed (testing/jobs/quiesce.ts). const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { getWorkerPool().resumeAll(); await quiesceJobs(); await corpus.cleanup(); }); const dataDir = (id: string) => path.join(corpus.transcripts, "channels", SLUG, "data", id); const exists = (p: string) => stat(p).then(() => true, () => false); async function video(id: string, meta: Record = {}, files: Record = {}) { const dir = dataDir(id); await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: id, webpage_url: `https://www.youtube.com/watch?v=${id}`, ...meta }), ); for (const [name, text] of Object.entries(files)) await writeFile(path.join(dir, name), text); } const job = (id: string) => { const r = getRegistry().get(id); if (!r) throw new Error(`no job ${id} in the registry`); return r; }; async function until(what: string, ok: () => boolean | Promise, ms = 30_000): Promise { const end = Date.now() + ms; while (!(await ok())) { if (Date.now() > end) throw new Error(`timed out waiting for ${what}`); await new Promise((r) => setTimeout(r, 50)); } } const ended = (id: string) => ["done", "failed", "cancelled"].includes(job(id).status); const logOf = (id: string) => readFile(job(id).logPath, "utf8").catch(() => ""); test("a whisper-video frees platform:youtube once its download is done; a download behind it runs while the transcription waits for a worker", async () => { await video("handoffAAAA"); await video("behindBBBBB"); // The one GPU worker is busy elsewhere: the transcription parks on it. getWorkerPool().pauseAll(); try { const res = await callPost(POST, { slug: SLUG, id: "handoffAAAA" }); assert.equal(res.status, 200, JSON.stringify(res.body)); const w = String(res.body.jobId); assert.equal(job(w).kind, "whisper-video"); assert.equal(job(w).queueKey, "platform:youtube"); // Queued behind it, on the same platform queue. const d = await downloadVideoPipelineAction(SLUG, "behindBBBBB"); if (!d.ok) throw new Error(d.error); void d.stream.cancel(); assert.equal(job(d.jobId).queueKey, "platform:youtube"); await until("the download behind it to end", () => ended(d.jobId)); assert.equal(job(d.jobId).status, "done", await logOf(d.jobId)); assert.equal(job(w).status, "done", await logOf(w)); assert.ok(await exists(path.join(dataDir("handoffAAAA"), "audio.mp3")), "the audio is down"); // The transcription: its own job, on the video's own queue, still waiting. const t = job(w).handedOffTo; assert.ok(t, "the whisper-video names the job it handed off to"); assert.equal(job(t).kind, "transcribe-one"); assert.equal(job(t).queueKey, `transcribe-one:${SLUG}:handoffAAAA`); assert.ok(!ended(t), `the transcription is still waiting for a worker (${job(t).status})`); assert.ok(!(await exists(path.join(dataDir("handoffAAAA"), "transcript.json")))); assert.match(await logOf(w), /Transcription handed off to transcribe-one job \S+ \(queue transcribe-one:handoff-yt:handoffAAAA\); platform:youtube is free/); // The sidecar says it too, for a caller that reads it after the registry forgot. const meta = JSON.parse(await readFile(path.join(corpus.transcripts, ".jobs", `${w}.meta.json`), "utf8")); assert.equal(meta.handedOffTo, t); // And researchRuns' jobOf (find-clips, research proposals) follows it. const { jobOfPaths } = await import("yt-dlp-transcript-common/controller/researchRuns"); const state = await jobOfPaths({ jobsDir: path.join(corpus.transcripts, ".jobs") })(w); assert.deepEqual({ status: state?.status, via: state?.via }, { status: "running", via: t }); getWorkerPool().resumeAll(); await until("the transcription to end", () => ended(t)); assert.equal(job(t).status, "done", await logOf(t)); assert.ok(await exists(path.join(dataDir("handoffAAAA"), "transcript.json"))); } finally { getWorkerPool().resumeAll(); } }); test("the run panel's Cancel, after the hand-off, cancels the transcription", async () => { // cancelJobAction (jobs/actions.ts) is registry.cancel(jobDoingTheWork(id)) // and a revalidation, which needs a request. const { jobDoingTheWork } = await import("yt-dlp-transcript-common/jobs/handOff"); await video("cancelHHHHH"); getWorkerPool().pauseAll(); try { const res = await callPost(POST, { slug: SLUG, id: "cancelHHHHH" }); assert.equal(res.status, 200, JSON.stringify(res.body)); const w = String(res.body.jobId); await until("the audio download", () => ended(w)); const t = job(w).handedOffTo; assert.ok(t); assert.equal(jobDoingTheWork(w), t); assert.equal(getRegistry().cancel(jobDoingTheWork(w)), true); await until("the transcription to stop", () => ended(t)); assert.equal(job(t).status, "cancelled"); assert.equal(job(w).status, "done", "the download it did stays done"); } finally { getWorkerPool().resumeAll(); } }); test("with audio on disk the job is a transcribe-one on the video's own queue, with \"file\" or without", async () => { await video("ondiskCCCCC", {}, { "audio.mp3": "fake audio\n" }); const withFile = await callPost(POST, { slug: SLUG, id: "ondiskCCCCC", file: "audio.mp3" }); assert.equal(withFile.status, 200, JSON.stringify(withFile.body)); const a = String(withFile.body.jobId); assert.equal(job(a).kind, "transcribe-one"); assert.equal(job(a).queueKey, `transcribe-one:${SLUG}:ondiskCCCCC`); await until("the file's transcription", () => ended(a)); assert.equal(job(a).status, "done", await logOf(a)); await video("ondiskDDDDD", {}, { "audio.mp3": "fake audio\n" }); const without = await callPost(POST, { slug: SLUG, id: "ondiskDDDDD" }); assert.equal(without.status, 200, JSON.stringify(without.body)); const b = String(without.body.jobId); assert.equal(job(b).kind, "transcribe-one", "no whisper-video: nothing to download"); assert.equal(job(b).queueKey, `transcribe-one:${SLUG}:ondiskDDDDD`); await until("the transcription", () => ended(b)); assert.equal(job(b).status, "done", await logOf(b)); assert.match(await logOf(b), /Audio already on disk for ondiskDDDDD; skipping download\./); assert.ok(await exists(path.join(dataDir("ondiskDDDDD"), "transcript.json"))); // A named queue is the caller's. await video("ondiskEEEEE", {}, { "audio.mp3": "fake audio\n" }); const named = await callPost(POST, { slug: SLUG, id: "ondiskEEEEE", file: "audio.mp3", queueKey: "my-queue" }); assert.equal(named.status, 200, JSON.stringify(named.body)); assert.equal(job(String(named.body.jobId)).queueKey, "my-queue"); await until("the named-queue transcription", () => ended(String(named.body.jobId))); }); test("English captions listed and no audio: the captions are fetched instead; asr: true transcribes it anyway", async () => { const captions = { automatic_captions: { en: [{ ext: "vtt", url: "https://example.invalid/en.vtt" }] } }; await video("captionFFFF", captions); const res = await callPost(POST, { slug: SLUG, id: "captionFFFF" }); assert.equal(res.status, 200, JSON.stringify(res.body)); assert.equal(res.body.instead, "captions"); assert.equal( res.body.message, "captionFFFF has YouTube captions; fetching those instead — pass asr: true to transcribe it anyway.", ); const d = String(res.body.jobId); assert.equal(job(d).kind, "download-one-pipeline"); assert.equal(job(d).queueKey, "platform:youtube"); await until("the caption download", () => ended(d)); assert.equal(job(d).status, "done", await logOf(d)); assert.match(await logOf(d), /^captionFFFF has YouTube captions; fetching those instead/); assert.ok(await exists(path.join(dataDir("captionFFFF"), "transcript.en.vtt")), "the captions are on disk"); assert.ok(!(await exists(path.join(dataDir("captionFFFF"), "audio.mp3"))), "no audio was fetched"); // Asked again with the captions on disk: refused, nothing queued. const before = (await corpus.listJobIds()).length; const again = await callPost(POST, { slug: SLUG, id: "captionFFFF" }); assert.equal(again.status, 400); assert.match(String(again.body.error), /captionFFFF already has YouTube captions on disk \(transcript\.en\.vtt\); pass asr: true/); assert.equal((await corpus.listJobIds()).length, before); // asr: true: the audio, then the transcription. await video("captionGGGG", captions); const asr = await callPost(POST, { slug: SLUG, id: "captionGGGG", asr: true }); assert.equal(asr.status, 200, JSON.stringify(asr.body)); assert.equal(asr.body.instead, undefined); const w = String(asr.body.jobId); assert.equal(job(w).kind, "whisper-video"); await until("the audio download", () => ended(w)); assert.equal(job(w).status, "done", await logOf(w)); const t = job(w).handedOffTo; assert.ok(t); await until("the transcription", () => ended(t)); assert.equal(job(t).status, "done", await logOf(t)); assert.ok(await exists(path.join(dataDir("captionGGGG"), "transcript.json"))); // "asr" is a boolean, checked at the door. const bad = await callPost(POST, { slug: SLUG, id: "captionGGGG", asr: "yes" }); assert.equal(bad.status, 400); assert.match(String(bad.body.error), /"asr" must be a boolean/); }); // 4 Nov: a transcribe-one on a video that was LIVE downloaded the HLS at 1x and // held platform:youtube for the stream's length. Its record says so, and the // door refuses it with the commands that do the right thing — nothing queued. // The audio, or a container, already here owes no download and is transcribed. test("a live, scheduled or processing stream is refused before anything is queued; with its audio here it transcribes", async () => { const before = (await corpus.listJobIds()).length; await video("liveHHHHHHH", { live_status: "is_live", is_live: true }); const live = await callPost(POST, { slug: SLUG, id: "liveHHHHHHH", asr: true }); assert.equal(live.status, 400, JSON.stringify(live.body)); assert.match(String(live.body.error), /^liveHHHHHHH is live now \(live_status is_live\): a download would read the stream at 1x/); assert.ok( String(live.body.error).includes(`pnpm ops record-live --json '{"slug":"${SLUG}","id":"liveHHHHHHH"}'`), String(live.body.error), ); // Without "asr" and with no captions listed: the audio download is next, refused. const plain = await callPost(POST, { slug: SLUG, id: "liveHHHHHHH" }); assert.equal(plain.status, 400); assert.match(String(plain.body.error), /is live now/); await video("upcomingIII", { live_status: "is_upcoming" }); const upcoming = await callPost(POST, { slug: SLUG, id: "upcomingIII" }); assert.equal(upcoming.status, 400); assert.match(String(upcoming.body.error), /scheduled stream that has not started/); await video("postliveJJJ", { live_status: "post_live" }); const post = await callPost(POST, { slug: SLUG, id: "postliveJJJ" }); assert.equal(post.status, 400); assert.match(String(post.body.error), /VOD is still being processed/); assert.equal((await corpus.listJobIds()).length, before, "nothing was queued"); // A (possibly stale) live record with English captions listed: the captions // fetch is no audio download, so it goes through; asr: true is refused. const captions = { automatic_captions: { en: [{ ext: "vtt", url: "https://example.invalid/en.vtt" }] } }; await video("livecapsMMM", { live_status: "post_live", ...captions }); const caps = await callPost(POST, { slug: SLUG, id: "livecapsMMM" }); assert.equal(caps.status, 200, JSON.stringify(caps.body)); assert.equal(caps.body.instead, "captions"); await until("the live video's caption fetch", () => ended(String(caps.body.jobId))); await video("livecapsNNN", { live_status: "is_live", ...captions }); const capsAsr = await callPost(POST, { slug: SLUG, id: "livecapsNNN", asr: true }); assert.equal(capsAsr.status, 400); assert.match(String(capsAsr.body.error), /livecapsNNN is live now/); // A finished stream (was_live) downloads as any video does. await video("wasliveKKKK", { live_status: "was_live" }); const vod = await callPost(POST, { slug: SLUG, id: "wasliveKKKK", asr: true }); assert.equal(vod.status, 200, JSON.stringify(vod.body)); await until("the VOD's audio download", () => ended(String(vod.body.jobId))); // Audio already on disk: nothing to download, so nothing to refuse. await video("liveaudioLL", { live_status: "is_live" }, { "audio.mp3": "fake audio\n" }); const here = await callPost(POST, { slug: SLUG, id: "liveaudioLL" }); assert.equal(here.status, 200, JSON.stringify(here.body)); assert.equal(job(String(here.body.jobId)).kind, "transcribe-one"); await until("the on-disk transcription", () => ended(String(here.body.jobId))); });