commit 7980ea1ae4ccfd170608dbfc821668ed7808de02 parent 73ba923c71bb4ad2cacaa2b97a60b6f4f21276a3 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sun, 25 Oct 2026 00:55:42 -0400 whisper-video hands the transcription off: only the download holds the platform queue The page's Transcribe and `pnpm ops transcribe-one` with no file ran the whole transcription on the platform queue, holding it 20-40 minutes per video while it waited for the one GPU worker. Now the audio download (and any full-audio attempt a salvage owes) runs as the whisper-video on the platform queue, then the transcription is queued as a transcribe-one job on the video's own queue and the whisper-video ends. With nothing to download, the transcribe-one job is queued at once and no whisper-video runs. The job records where its work went (JobRunContext.handOff -> handedOffTo, on the record and the sidecar); the log route and the ops job route name it; `pnpm ops --wait`, researchRuns jobOfPaths (research proposals, find-clips) follow it to the end of the transcription. The action's returned stream is both jobs' logs and its `done` settles with the transcription (jobs/handOff.ts), so the page's run panel reads as before. The ops route: with "file" it now uses the per-file row's default queue (the video's own queue unless a download is owed); "queueKey" names one. A youtube-handling video with no audio whose metadata lists English captions has them fetched instead (the designated pipeline), unless "asr": true; the page's "Audio + Whisper" passes asr. The listed-captions rule moved to lib/listedCaptions-server.ts and downloadOneManaged's no-subs fallback and the metadata refresh read it from there. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
17 files changed, 529 insertions(+), 90 deletions(-)
diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts @@ -248,8 +248,10 @@ export type FindClipsDeps = { // The editor's ops actions, in process (editor: _researchEditor.ts // findClipsEditor). A refusal throws with the action's sentence. editor: ResearchEditor; - // An editor job's state (researchRuns.ts jobOfPaths). - jobOf: (id: string) => Promise<{ status: string } | null>; + // An editor job's state (researchRuns.ts jobOfPaths) — its WORK's: a job + // that handed its work on (a whisper-video's transcription, queued as its own + // transcribe-one job) answers with that job's state, `via` naming it. + jobOf: (id: string) => Promise<{ status: string; via?: string } | null>; umtoolUrl?: string | null; workerToken?: string; fetch?: typeof fetch; @@ -299,9 +301,14 @@ async function waitForJob( const pollMs = deps.pollMs ?? 2000; let misses = 0; let last = ""; + let via = ""; for (;;) { if (signal.aborted) throw new StepError(step, `cancelled while job ${jobId} ran (it keeps running)`); const j = await deps.jobOf(jobId).catch(() => null); + if (j?.via && j.via !== via) { + via = j.via; + onLog(` job ${jobId} handed off to job ${via}`); + } if (j && TERMINAL.has(j.status)) return j.status; if (!j && ++misses > 30) throw new StepError(step, `job ${jobId} is not in the registry`); if (j && j.status !== last) { diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts @@ -71,6 +71,7 @@ import { type AttemptOutcome, } from "../ytdlp/runOneYtdlp"; import { findVideoSourceUrl } from "./undownloadedVideos"; +import { englishCaptionTracks } from "../lib/listedCaptions-server"; const INFO_JSON = "metadata.info.json"; @@ -259,12 +260,8 @@ function describeAudioFormat(f: Json): string { } // The English track names of a caption map (en, en-US, en-orig, …), sorted. -function englishTracks(map: unknown): string[] { - if (!isObject(map)) return []; - return Object.keys(map) - .filter((k) => /^en(-|$)/i.test(k)) - .sort(); -} +// lib/listedCaptions-server.ts: the one rule for an English caption track. +const englishTracks = englishCaptionTracks; function list(values: string[]): string { return values.length ? values.join(", ") : "none"; diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts @@ -50,11 +50,26 @@ export class ResearchInputError extends Error {} type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir" | "jobsDir">; -// An editor job's state, from the registry or its `.jobs` sidecar. +// An editor job's state, from the registry or its `.jobs` sidecar — THE +// WORK's state: a job that ended `done` having handed its work on to another +// (`handedOffTo`: a whisper-video's transcription, queued as a transcribe-one +// job once the audio is down) answers with that job's state, followed to the +// end of the chain (`via` names the job answering). A caller asking "is the +// transcript there" would otherwise read `done` while it still waits for a +// worker. export function jobOfPaths(paths: Pick<Paths, "jobsDir">): JobOf { return async (id) => { - const e = await getJobEntry(paths as Paths, id); - return e ? { status: e.status, ...(e.endedAt ? { endedAt: e.endedAt } : {}) } : null; + let e = await getJobEntry(paths as Paths, id); + let via: string | undefined; + for (let hops = 0; e && e.status === "done" && e.handedOffTo && hops < 5; hops++) { + const next = await getJobEntry(paths as Paths, e.handedOffTo); + if (!next) return { status: "archived", via: e.handedOffTo }; + via = next.id; + e = next; + } + return e + ? { status: e.status, ...(e.endedAt ? { endedAt: e.endedAt } : {}), ...(via ? { via } : {}) } + : null; }; } diff --git a/common/jobs/handOff.ts b/common/jobs/handOff.ts @@ -0,0 +1,76 @@ +// A JOB THAT HANDS ITS WORK ON TO ANOTHER, AS ITS CALLER SEES IT. +// +// A whisper-video downloads the audio on its platform's queue, then queues the +// transcription as a transcribe-one job of its own and ends — so the platform +// queue is free the moment the bytes are down, while the transcription waits +// for a worker (videoActions.ts whisperVideoAction). The job records where +// the work went (JobRunContext.handOff → `handedOffTo`); this is the other +// half, for the caller holding the action's result: ONE stream, the first +// job's log and then the second's, and a `done` that settles when the work +// does — so a run panel reads "… Transcribe <id> done" as it did when the two +// were one job. +// +// const slot = handOffSlot(); +// const r = await runManagedFunction({ …, fn: async (…, ctx) => { +// const child = await queueTheRest(); +// if (child.ok) { ctx.handOff(child.jobId); slot.set(child); } +// } }); +// return r.ok ? slot.wrap(r) : r; +// +// A consumer that goes away (the ops route cancels the stream at once) cancels +// the second stream too, the moment it exists: an unread job stream would +// otherwise buffer a long transcription's whole log. Cancelling a stream never +// stops a job (streamCommand.ts). + +import type { JobDoneResult, StreamActionResult } from "./streamCommand"; + +export type StartedJob = Extract<StreamActionResult, { ok: true }>; + +export type HandOffSlot = { + // Inside the first job: the job it handed its work on to. + set: (child: StartedJob) => void; + // The first job's result, as its caller should hold it. + wrap: (parent: StartedJob) => StartedJob; +}; + +export function handOffSlot(): HandOffSlot { + let child: StartedJob | null = null; + let consumerGone = false; + return { + set(c) { + child = c; + if (consumerGone) void c.stream.cancel().catch(() => {}); + }, + wrap(parent) { + let current = parent.stream.getReader(); + let onChild = false; + const stream = new ReadableStream<string>({ + async pull(controller) { + for (;;) { + const { value, done } = await current.read(); + if (!done) { + controller.enqueue(value); + return; + } + if (!onChild && child) { + onChild = true; + current = child.stream.getReader(); + continue; + } + controller.close(); + return; + } + }, + cancel() { + consumerGone = true; + void current.cancel().catch(() => {}); + if (child && !onChild) void child.stream.cancel().catch(() => {}); + }, + }); + const done: Promise<JobDoneResult> = parent.done.then((r) => + r.status === "done" && child ? child.done : r, + ); + return { ...parent, stream, done }; + }, + }; +} diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -35,6 +35,8 @@ export type JobMeta = { // LIVE process owns right now — `archilyzer run` writes into the same // `.jobs/`. Absent on metas written before release 17. pid?: number; + // The job this one handed its work on to (JobRecord.handedOffTo). + handedOffTo?: string; }; export function metaPath(paths: Paths, id: string): string { @@ -62,6 +64,7 @@ export async function writeJobMeta( exitCode: record.exitCode, spec: record.spec, pid: process.pid, + ...(record.handedOffTo ? { handedOffTo: record.handedOffTo } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); } catch { @@ -90,6 +93,7 @@ export async function readJobMeta( // Sanitize the replay descriptor: drop it if malformed so a stale sidecar // can't surface an un-runnable Retry. meta.spec = m.spec === undefined ? undefined : (parseJobSpec(m.spec) ?? undefined); + if (m.handedOffTo !== undefined && typeof m.handedOffTo !== "string") delete meta.handedOffTo; return meta; } catch { return null; diff --git a/common/jobs/listJobs.ts b/common/jobs/listJobs.ts @@ -35,6 +35,8 @@ export type JobListEntry = { // e.g. "server restarted; the scheduler re-derives syncs". From the sidecar; // absent on every other job. cancelReason?: string; + // The job this one handed its work on to (JobRecord.handedOffTo). + handedOffTo?: string; }; export type JobsPage = { @@ -114,6 +116,7 @@ async function buildEntry( inRegistry: true, replayable: Boolean(live_.spec), detail: jobSpecDetail(live_.kind, live_.spec), + ...(live_.handedOffTo ? { handedOffTo: live_.handedOffTo } : {}), logPath, logSize, }; @@ -145,6 +148,7 @@ async function buildEntry( ...(meta.status === "cancelled" && meta.cancelReason ? { cancelReason: meta.cancelReason } : {}), + ...(meta.handedOffTo ? { handedOffTo: meta.handedOffTo } : {}), logPath, logSize, }; diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -159,6 +159,13 @@ export type JobRecord = { // begins. The /jobs row draws "waiting 4m12s: …" from it. pacedUntil?: number; pacedReason?: string; + // THE JOB THIS ONE HANDED ITS WORK ON TO (JobRunContext.handOff): a + // whisper-video downloads the audio on its platform queue, then queues the + // transcription as its own transcribe-one job and ends, so the platform + // queue is free while the transcription waits for a worker. A caller that + // waits for the work rather than the job follows it (researchRuns.ts + // jobOfPaths, `pnpm ops --wait`). + handedOffTo?: string; }; // Store a progress snapshot on the record, stamping `progressAt` only when the diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -112,6 +112,10 @@ export type JobRunContext = { ) => void; removeTask: (taskId: string) => void; recordTaskDone: (durationMs: number, audioSeconds?: number) => void; + // This job's work goes on in another job (`jobId`), which this one queued: + // recorded on the record and its sidecar as `handedOffTo`, so a caller + // waiting for the work follows it there. + handOff: (jobId: string) => void; }; export type RunManagedFunctionOpts = CommonOpts & { @@ -462,6 +466,10 @@ export async function runManagedFunction( // coalesces sub-operations that finish close together. requestSnapshotOnFinish(id, opts); }, + handOff: (jobId) => { + record.handedOffTo = jobId; + persistMeta(); + }, }; // THE GUARD AGAIN, NOW THAT THE QUEUE HAS STARTED THE JOB (see diff --git a/common/lib/listedCaptions-server.ts b/common/lib/listedCaptions-server.ts @@ -0,0 +1,60 @@ +import path from "node:path"; +import { readFile } from "node:fs/promises"; + +// THE CAPTION TRACKS A VIDEO'S metadata.info.json LISTS: yt-dlp's +// `subtitles` (uploaded by the channel) and `automatic_captions` (YouTube's +// speech recognition). `live_chat` is left out — yt-dlp files YouTube's chat +// replay under `subtitles`, and it is not a transcript of speech. +// +// The one rule for "this video has captions to fetch": the managed download's +// no-subs fallback (downloadOneManaged: audio + whisper only when none is +// listed), and a Transcribe asked of a youtube-handling video with no audio +// (videoActions.ts whisperVideoAction: its English captions are fetched +// instead, unless `asr: true`). + +type CaptionMaps = { + subtitles?: unknown; + automatic_captions?: unknown; +}; + +// Every listed track, null when the metadata cannot say (not an object, or a +// map that is not one). +export function listedCaptionTracks(meta: unknown): string[] | null { + if (!meta || typeof meta !== "object") return null; + const m = meta as CaptionMaps; + const subs = m.subtitles ?? {}; + const auto = m.automatic_captions ?? {}; + if (typeof subs !== "object" || typeof auto !== "object") return null; + const tracks = new Set<string>(); + for (const k of Object.keys(subs as object)) if (k !== "live_chat") tracks.add(k); + for (const k of Object.keys(auto as object)) if (k !== "live_chat") tracks.add(k); + return [...tracks]; +} + +// The listed tracks of the video in `videoDir`; null with no readable +// metadata.info.json. +export async function readListedCaptionTracks(videoDir: string): Promise<string[] | null> { + let raw: string; + try { + raw = await readFile(path.join(videoDir, "metadata.info.json"), "utf8"); + } catch { + return null; + } + try { + return listedCaptionTracks(JSON.parse(raw)); + } catch { + return null; + } +} + +// An English track key — `en`, `en-orig`, `en-US`, … (yt-dlp's language +// codes; `es-en` is a Spanish track, not this). +export function isEnglishCaptionTrack(track: string): boolean { + return /^en(-|$)/i.test(track); +} + +// The English keys of one caption map, sorted. +export function englishCaptionTracks(map: unknown): string[] { + if (!map || typeof map !== "object" || Array.isArray(map)) return []; + return Object.keys(map).filter(isEnglishCaptionTrack).sort(); +} diff --git a/common/lib/report/draft/research/state.ts b/common/lib/report/draft/research/state.ts @@ -142,7 +142,9 @@ export async function writeResearchState(article: string, n: number, state: Rese // ─── jobs ─── // One editor job as the refresh needs it (common/jobs/listJobs getJobEntry). -export type JobState = { status: string; endedAt?: number }; +// `via`: the job that answered, when the one asked handed its work on to it +// (researchRuns.ts jobOfPaths). +export type JobState = { status: string; endedAt?: number; via?: string }; export type JobOf = (id: string) => Promise<JobState | null>; export const jobIdsOf = (p: Pick<Proposal, "jobId">): string[] => diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -116,6 +116,7 @@ import { type StoredUrlWhy, } from "../lib/storedMediaUrl"; import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import { readListedCaptionTracks } from "../lib/listedCaptions-server"; import { fullAudioLine, fullAudioState } from "../lib/fullAudioFirst"; import type { DownloadFailureClass } from "../lib/availability"; import { platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; @@ -666,36 +667,13 @@ async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> { }); } +// 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( videoDir: string, ): Promise<boolean> { - let raw: string; - try { - raw = await readFile( - path.join(videoDir, "metadata.info.json"), - "utf8", - ); - } catch { - return false; - } - let parsed: { - subtitles?: Record<string, unknown>; - automatic_captions?: Record<string, unknown>; - }; - try { - parsed = JSON.parse(raw); - } catch { - return false; - } - const subs = parsed.subtitles ?? {}; - const auto = parsed.automatic_captions ?? {}; - if (typeof subs !== "object" || typeof auto !== "object") return false; - // live_chat is YouTube's chat replay, not a caption track. yt-dlp places - // it under `subtitles`, so a video whose only listed track is live_chat - // should be treated as having no captions for fallback purposes. - const realSubs = Object.keys(subs).filter((k) => k !== "live_chat"); - const realAuto = Object.keys(auto).filter((k) => k !== "live_chat"); - return realSubs.length === 0 && realAuto.length === 0; + const listed = await readListedCaptionTracks(videoDir); + return listed !== null && listed.length === 0; } function trimError(stderrTail: string): string | undefined { diff --git a/editor/app/api/jobs/[id]/log/route.ts b/editor/app/api/jobs/[id]/log/route.ts @@ -58,5 +58,8 @@ export async function GET( status, queueKey, queuePosition, + // The job its work went on in (JobRecord.handedOffTo): `pnpm ops --wait` + // follows it there. + ...(record?.handedOffTo ? { handedOffTo: record.handedOffTo } : {}), }); } diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts @@ -2,22 +2,37 @@ import { transcribeOneAction, whisperVideoAction, } from "../../../channels/[slug]/videos/[id]/videoActions"; +import { NextResponse } from "next/server"; import { jobResponse, ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib"; import { optStoredUrlMode } from "../_storedUrl"; export const dynamic = "force-dynamic"; -// POST { slug, id, file?, salvage? } +// POST { slug, id, file?, salvage?, storedUrl?, whilePaused?, queueKey?, asr? } // // One video, transcribed — the video page's two buttons: // - with "file" (an audio file in the video's dir, e.g. "audio.mp3"): that // file, through the worker pool (transcribeOneAction — the per-file -// Transcribe on the Files list); +// Transcribe on the Files list), with the row's own default queue: audio +// that owes no download runs at once on the video's own queue +// (`transcribe-one:<slug>:<id>`), one that owes one waits the channel's +// platform queue; // - without: the page's Transcribe (whisperVideoAction), which uses the audio // on disk, or first downloads it through the channel's managed path when -// there is none (the disk floor applies to that download only). -// A job on the video's platform queue: { ok, jobId }, so --wait follows it. +// there is none (the disk floor applies to that download only). Only the +// download runs on the platform's queue: the transcription is then handed +// off to a transcribe-one job on the video's own queue, and with nothing +// to download it is that job at once. +// { ok, jobId }, so --wait follows it — through the hand-off, to the end of +// the transcription. // The file name is one path segment; a refused one is the action's sentence. +// "queueKey": the queue the job runs on instead (a named queue; "" = the +// default described above). +// "asr" (no "file"): a youtube-handling video with no audio whose metadata +// lists English captions has those fetched instead — the designated +// pipeline's caption download, answered { ok, jobId, instead: "captions", +// message } — and one with an English caption track on disk is refused; +// "asr": true transcribes it anyway. // "salvage" (release 30, lane Q): true decodes the audio with error tolerance // and transcribes what decodes, its gaps recorded (transcribeOne's salvage); // false forbids it; absent, a corrupt-full-source video is salvaged and any @@ -33,25 +48,37 @@ export const dynamic = "force-dynamic"; // drained, degraded or disabled by hand); the pause stays on. Absent or false // = held by the pause, as before. export async function POST(request: Request) { - return ops(request, ["slug", "id", "file", "salvage", "storedUrl", "whilePaused"], async (body) => { - const slug = reqSlug(body, "slug"); - const id = reqVideoId(body, "id"); - const file = optString(body, "file"); - const salvage = optBool(body, "salvage"); - const storedUrl = optStoredUrlMode(body); - const whilePaused = optBool(body, "whilePaused") === true; - if (storedUrl !== undefined && file !== undefined) { - return opsFail(`"storedUrl" is for a download; with "file" nothing is downloaded`); - } - // One path segment, checked at the door as reqVideoId checks an id: the - // name is joined under the video's directory. - if (file !== undefined && (file === "" || /[/\\\0]/.test(file) || file.startsWith("."))) { - return opsFail(`"${file}" is not a file name in the video's directory`); - } - return jobResponse( - file !== undefined - ? await transcribeOneAction(slug, id, file, undefined, salvage, whilePaused) - : await whisperVideoAction(slug, id, undefined, salvage, storedUrl, whilePaused), - ); - }); + return ops( + request, + ["slug", "id", "file", "salvage", "storedUrl", "whilePaused", "queueKey", "asr"], + async (body) => { + const slug = reqSlug(body, "slug"); + const id = reqVideoId(body, "id"); + const file = optString(body, "file"); + const salvage = optBool(body, "salvage"); + const storedUrl = optStoredUrlMode(body); + const whilePaused = optBool(body, "whilePaused") === true; + const queueKey = optString(body, "queueKey"); + const asr = optBool(body, "asr") === true; + if (storedUrl !== undefined && file !== undefined) { + return opsFail(`"storedUrl" is for a download; with "file" nothing is downloaded`); + } + // One path segment, checked at the door as reqVideoId checks an id: the + // name is joined under the video's directory. + if (file !== undefined && (file === "" || /[/\\\0]/.test(file) || file.startsWith("."))) { + return opsFail(`"${file}" is not a file name in the video's directory`); + } + if (file !== undefined) { + // The row's "now": the action picks the video's own queue or the + // platform's (transcribeOneQueueKey). + return jobResponse(await transcribeOneAction(slug, id, file, queueKey ?? "", salvage, whilePaused)); + } + const r = await whisperVideoAction(slug, id, queueKey, salvage, storedUrl, whilePaused, asr); + if (r.ok && "instead" in r) { + void r.stream.cancel(); + return NextResponse.json({ ok: true, jobId: r.jobId, instead: r.instead, message: r.message }); + } + return jobResponse(r); + }, + ); } diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/RedownloadSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/RedownloadSection.tsx @@ -73,7 +73,9 @@ export function RedownloadSection({ : "Running pipeline…"; const actionLabel = `${verb} for ${videoId}`; const trigger = mode === "whisper" - ? () => whisperVideoAction(slug, videoId, queueKey, undefined, stored) + ? // The mode IS the ask for speech recognition (asr: true): a video whose + // captions are listed is transcribed anyway, as chosen. + () => whisperVideoAction(slug, videoId, queueKey, undefined, stored, undefined, true) : () => downloadVideoPipelineAction( slug, diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -22,11 +22,16 @@ import { diskGate } from "yt-dlp-transcript-common/lib/diskSpace"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { audioFilesToRemove, + englishVttsByPreference, isRealAudioFile, isTranscriptVtt, VTT_FILENAME, } from "yt-dlp-transcript-common/lib/videoStatus"; import { + isEnglishCaptionTrack, + readListedCaptionTracks, +} from "yt-dlp-transcript-common/lib/listedCaptions-server"; +import { clipWindowQueueKey, downloadQueueKey, resolveQueueKey, @@ -139,6 +144,7 @@ import { } from "yt-dlp-transcript-common/jobs/streamCommand"; import { requestChannelSnapshot } from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import { makeTaskTracker } from "yt-dlp-transcript-common/jobs/taskHooks"; +import { handOffSlot } from "yt-dlp-transcript-common/jobs/handOff"; import { fixIncompleteTranscriptOne } from "../../lib/fixIncompleteTranscript"; import { writeFileAtomic, writeJsonAtomic } from "yt-dlp-transcript-common/lib/jsonFile-server"; import { formValues, type FormErrorState } from "../../../../lib/formState"; @@ -168,7 +174,7 @@ async function transcribeOneQueueKey( ...(config.storedUrlDownloads ? { mode: config.storedUrlDownloads } : {}), }) : null; - return owed && !owed.exhausted ? downloadQueueKey(config) : `transcribe-one:${slug}:${videoId}`; + return owed && !owed.exhausted ? downloadQueueKey(config) : ownTranscribeQueue(slug, videoId); } function videoDirOf(slug: string, videoId: string): string { @@ -245,30 +251,67 @@ export async function transcribeOneAction( ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; + return queueTranscribeOne({ + slug, + videoId, + config: r.config, + audioFilename, + queueKey: await transcribeOneQueueKey(slug, videoId, r.config, queueKey, salvage), + fullAudioFirst: salvage === undefined, + ...(salvage !== undefined ? { salvage } : {}), + ...(whilePaused ? { whilePaused: true } : {}), + }); +} + +// The video's own transcription queue: one transcription of a video at a time, +// beside every other video's, never behind a platform's downloads. +function ownTranscribeQueue(slug: string, videoId: string): string { + return `transcribe-one:${slug}:${videoId}`; +} + +// ONE TRANSCRIPTION AS A transcribe-one JOB on `queueKey` (resolved by the +// caller): transcribeOneAction's, and whisper-video's once nothing it does +// asks the network any more (whisperVideoAction). `fullAudioFirst` makes the +// stored-URL downloads a salvage still owes first (fullAudioBeforeSalvage) — +// false when the caller made them or nothing is owed. `prelude`: lines the +// job's log opens with (what the whisper-video found on disk). +async function queueTranscribeOne(o: { + slug: string; + videoId: string; + config: ChannelConfig; + audioFilename: string; + queueKey: string; + fullAudioFirst: boolean; + salvage?: boolean; + whilePaused?: boolean; + prelude?: string[]; +}): Promise<StreamActionResult> { + const { slug, videoId, salvage, whilePaused } = o; const paths = getPaths(); const videoDir = videoDirOf(slug, videoId); return runManagedFunction({ kind: "transcribe-one", - queueKey: await transcribeOneQueueKey(slug, videoId, r.config, queueKey, salvage), + queueKey: o.queueKey, paths, channelSlug: slug, videoId, fn: async (onLog, signal, _setProgress, ctx) => { - if (salvage === undefined) { - await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal }); + for (const line of o.prelude ?? []) onLog(line); + if (o.fullAudioFirst) { + await fullAudioBeforeSalvage({ slug, videoId, config: o.config, paths, onLog, signal }); } await transcribeWithWorker({ paths, videoDir, videoId, - audioFilename, + audioFilename: o.audioFilename, tracker: makeTaskTracker(ctx, onLog), onLog, signal, ...(salvage !== undefined ? { salvage } : {}), ...(whilePaused ? { whilePaused: true } : {}), }); - safeRevalidate([`/channels/${slug}/videos/${videoId}`]); + safeRevalidate([`/channels/${slug}/videos/${videoId}`, `/channels/${slug}`]); }, }); } @@ -285,6 +328,31 @@ export async function downloadVideoPipelineAction( ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; + return queuePipelineDownload({ + slug, + videoId, + config: r.config, + ...(queueKey !== undefined ? { queueKey } : {}), + ...(downloadFormat !== undefined ? { downloadFormat } : {}), + ...(storedUrl !== undefined ? { storedUrl } : {}), + }); +} + +// The designated pipeline for one video as a download-one-pipeline job +// (downloadVideoPipelineAction's): on a youtube-handling channel the caption +// download, with audio + whisper only when none is listed. `prelude`: lines +// its log opens with (why a Transcribe was turned into it). +async function queuePipelineDownload(o: { + slug: string; + videoId: string; + config: ChannelConfig; + queueKey?: string; + downloadFormat?: string; + storedUrl?: string; + prelude?: string[]; +}): Promise<StreamActionResult> { + const { slug, videoId, queueKey, downloadFormat, storedUrl } = o; + const r = { config: o.config }; const paths = getPaths(); // This action fetches a full container. Its sibling redownloadToArchiveAction // has always preflighted the disk; this one never did. @@ -310,6 +378,7 @@ export async function downloadVideoPipelineAction( channelSlug: slug, videoId, fn: async (onLog, signal, _setProgress, ctx) => { + for (const line of o.prelude ?? []) onLog(line); const task = makeTaskTracker(ctx, onLog).start({ id: videoId, label: videoId, @@ -582,6 +651,46 @@ async function lowDiskError( }; } +// What whisperVideoAction answers: the job it started — and, when a +// Transcribe of a youtube-handling video with English captions listed and no +// audio was turned into the caption download, `instead: "captions"` with the +// sentence that says so (the started job is then that download). +export type WhisperVideoResult = + | StreamActionResult + | (Extract<StreamActionResult, { ok: true }> & { instead: "captions"; message: string }); + +// A queue the caller NAMED for the transcription, else null: no override, the +// immediate "", and the platform's own queue (the page's default) all mean +// "wherever it belongs" — the video's own transcription queue. +function namedTranscribeQueue(config: ChannelConfig, override: string | undefined): string | null { + const q = override?.trim(); + if (!q || q === downloadQueueKey(config)) return null; + return q; +} + +// THE PAGE'S TRANSCRIBE ("Audio + Whisper"), and `pnpm ops transcribe-one` +// with no "file": the audio on disk, else downloaded first. +// +// ONLY WHAT ASKS THE NETWORK RUNS ON THE PLATFORM'S QUEUE. The audio download +// (plain or through the stored media URL) and the full-audio attempts a +// salvage still owes run as a whisper-video job on `videoQueueKey`; the +// transcription is then HANDED OFF — queued as a transcribe-one job on the +// video's own queue (`transcribe-one:<slug>:<id>`), its id recorded as the +// job's `handedOffTo` — and the whisper-video ends, so the platform's queue is +// free the moment the bytes are down. It used to hold it for the whole +// transcription: 20–40 minutes of waiting for the one GPU worker and +// transcribing, during which no other download on that platform ran. +// When nothing is owed at all (audio on disk with no full-audio attempt owed, +// or a container to transcribe from) no whisper-video is queued: the +// transcription job is the answer, at once. +// +// The returned stream is the whisper-video's log and then the transcription's +// (jobs/handOff.ts), and `done` settles when the transcription does. +// +// CAPTIONS FIRST: a youtube-handling video with no audio on disk whose +// metadata lists English captions (lib/listedCaptions-server.ts) has those +// fetched instead — the designated pipeline's caption download — unless `asr` +// is true; with an English caption track already on disk it is refused. export async function whisperVideoAction( slug: string, videoId: string, @@ -596,19 +705,91 @@ export async function whisperVideoAction( storedUrl?: StoredUrlMode, // See transcribeOneAction's `whilePaused`. whilePaused?: boolean, -): Promise<StreamActionResult> { + // true: speech recognition even for a youtube-handling video that lists + // English captions (the page's "Audio + Whisper" is that ask). + asr?: boolean, +): Promise<WhisperVideoResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; const paths = getPaths(); const videoDir = videoDirOf(slug, videoId); - return runManagedFunction({ + const audioFormat = r.config.audioFormat ?? "mp3"; + const audioFilename = `audio.${audioFormat}`; + const transcribeQueue = namedTranscribeQueue(r.config, queueKey) ?? ownTranscribeQueue(slug, videoId); + const opts = { + ...(salvage !== undefined ? { salvage } : {}), + ...(whilePaused ? { whilePaused: true } : {}), + }; + const firstEntries = await readdir(videoDir).catch(() => [] as string[]); + const audioOnDisk = firstEntries.some(isRealAudioFile); + + if (!audioOnDisk && asr !== true && r.config.handling === "youtube") { + const listed = (await readListedCaptionTracks(videoDir)) ?? []; + if (listed.some(isEnglishCaptionTrack)) { + const onDisk = englishVttsByPreference(firstEntries); + if (onDisk.length > 0) { + return { + ok: false, + error: `${videoId} already has YouTube captions on disk (${onDisk[0]}); pass asr: true to transcribe it anyway.`, + }; + } + const message = `${videoId} has YouTube captions; fetching those instead — pass asr: true to transcribe it anyway.`; + const dl = await queuePipelineDownload({ + slug, + videoId, + config: r.config, + ...(queueKey !== undefined ? { queueKey } : {}), + ...(storedUrl !== undefined ? { storedUrl } : {}), + prelude: [message], + }); + return dl.ok ? { ...dl, instead: "captions", message } : dl; + } + } + + // NOTHING OWED TO THE NETWORK: the transcription itself. + if (audioOnDisk) { + const mode = storedUrl ?? r.config.storedUrlDownloads; + const owed = + salvage === undefined + ? await fullAudioGate(videoDir, { handling: r.config.handling, ...(mode ? { mode } : {}) }) + : null; + if (!owed || owed.exhausted) { + return queueTranscribeOne({ + slug, + videoId, + config: r.config, + audioFilename, + queueKey: transcribeQueue, + fullAudioFirst: false, + ...opts, + prelude: [`Audio already on disk for ${videoId}; skipping download.`], + }); + } + } else { + const held = await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries }); + if (held?.kind === "container") { + return queueTranscribeOne({ + slug, + videoId, + config: r.config, + audioFilename, + queueKey: transcribeQueue, + fullAudioFirst: false, + ...opts, + prelude: [containerLine(videoId, held)], + }); + } + } + + const platformQueue = videoQueueKey(r.config, queueKey); + const slot = handOffSlot(); + const res = await runManagedFunction({ kind: "whisper-video", - queueKey: videoQueueKey(r.config, queueKey), + queueKey: platformQueue, paths, channelSlug: slug, videoId, fn: async (onLog, signal, _setProgress, ctx) => { - const audioFormat = r.config.audioFormat ?? "mp3"; const entries = await readdir(videoDir).catch(() => [] as string[]); const hasAudio = entries.some(isRealAudioFile); // NO AUDIO, BUT A CONTAINER (release 23 F2): a source-media.<ext> here or @@ -616,17 +797,14 @@ export async function whisperVideoAction( // resolves it (resolveAudioFile) — and nothing is downloaded. A pointer // whose container cannot be read is refused with the media guard's // sentence, never downloaded around; a container with no sound takes the - // download path below. + // download path below. (One found before the job was queued never gets + // here: its transcription was queued at once, above.) const held = hasAudio ? null : await transcriptionContainer({ paths, slug, videoDir, entries }); if (held?.kind === "unreadable") throw new Error(held.error); if (held?.kind === "container") { - onLog( - `No audio on disk for ${videoId}; transcribing from ` + - `${held.from === "saved-video" ? "the saved container" : "the source container"} ` + - `${held.file} — nothing downloaded.`, - ); + onLog(containerLine(videoId, held)); } else if (!hasAudio) { if (held?.kind === "no-audio") { onLog(`The container ${held.file} has no sound; downloading the audio instead.`); @@ -697,23 +875,42 @@ export async function whisperVideoAction( await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal, storedUrl }); } } - await transcribeWithWorker({ - paths, - videoDir, + if (signal.aborted) return; + // THE HAND-OFF: everything after this line asks no platform anything. + const child = await queueTranscribeOne({ + slug, videoId, - audioFilename: `audio.${audioFormat}`, - tracker: makeTaskTracker(ctx, onLog), - onLog, - signal, - ...(salvage !== undefined ? { salvage } : {}), - ...(whilePaused ? { whilePaused: true } : {}), + config: r.config, + audioFilename, + queueKey: transcribeQueue, + fullAudioFirst: false, + ...opts, }); + if (!child.ok) { + throw new Error(`The audio is on disk, but its transcription was not queued: ${child.error}`); + } + ctx.handOff(child.jobId); + onLog( + `Transcription handed off to transcribe-one job ${child.jobId} (queue ${transcribeQueue}); ` + + `${platformQueue} is free for the next download.`, + ); + slot.set(child); safeRevalidate([ `/channels/${slug}/videos/${videoId}`, `/channels/${slug}`, ]); }, }); + return res.ok ? slot.wrap(res) : res; +} + +// The release 23 F2 sentence: what a container-only video is transcribed from. +function containerLine(videoId: string, held: { from: string; file: string }): string { + return ( + `No audio on disk for ${videoId}; transcribing from ` + + `${held.from === "saved-video" ? "the saved container" : "the source container"} ` + + `${held.file} — nothing downloaded.` + ); } // Fix a truncated transcript: the audio download silently stopped early, so the diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -2141,7 +2141,28 @@ export function tokenHint(status, sources, url = baseUrl()) { // `--wait-timeout` bounds the whole thing for a caller that cannot hang (CI, // an agent). Default none, because the honest default for a queue that may hold // a job behind hours of other work is to wait. +// +// A JOB THAT HANDED ITS WORK ON is followed to where the work went: a +// whisper-video (`transcribe-one` with no "file") downloads the audio on the +// platform's queue and queues the transcription as a job of its own, and its +// log route and job route then name that job (`handedOffTo`). Ending `done` +// there is not the transcript being written, so the follow goes on in the +// next job ("[j1] handed off to job j2") and ends with how that one ended. export async function followJob(jobId, quiet, opts = {}) { + let handedOffTo = null; + const status = await followOne(jobId, quiet, opts, (next) => { + handedOffTo = next; + }); + const hops = opts.hops ?? 0; + if (status === "done" && handedOffTo && handedOffTo !== jobId && hops < 5) { + const say = opts.say ?? ((line) => process.stderr.write(`${line}\n`)); + if (!quiet) say(`[${jobId}] handed off to job ${handedOffTo}`); + return followJob(handedOffTo, quiet, { ...opts, hops: hops + 1 }); + } + return status; +} + +async function followOne(jobId, quiet, opts, noteHandOff) { const doFetch = opts.fetch ?? fetch; const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))); const now = opts.now ?? (() => Date.now()); @@ -2183,6 +2204,7 @@ export async function followJob(jobId, quiet, opts = {}) { // Only advance once the chunk is in hand: a poll that failed halfway // must re-ask for the same offset. from = payload.nextOffset ?? from; + if (typeof payload.handedOffTo === "string") noteHandOff(payload.handedOffTo); notePlace(payload.status, payload.queueKey, payload.queuePosition); return payload.status ?? null; } catch { @@ -2200,6 +2222,7 @@ export async function followJob(jobId, quiet, opts = {}) { if (!payload || typeof payload !== "object") return null; if (res.status === 404 && payload.ok === false) return "gone"; if (!res.ok || !payload.job) return null; + if (typeof payload.job.handedOffTo === "string") noteHandOff(payload.job.handedOffTo); return payload.job.status ?? null; } catch { return null; diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -288,6 +288,35 @@ test("'archived' is not an outcome: the sidecar's status is", async () => { assert.equal(await follow("j1", unknown), "archived"); }); +test("a job that handed its work on is followed to the job it named", async () => { + // whisper-video downloads on the platform queue and hands the transcription + // to a transcribe-one job: `done` on the first is not the transcript. + const logs = { + j1: [{ content: "downloaded\n", nextOffset: 11, status: "done", handedOffTo: "j2" }], + j2: [ + { content: "", nextOffset: 0, status: "running" }, + { content: "transcribed\n", nextOffset: 12, status: "failed" }, + ], + }; + const seen = { j1: 0, j2: 0 }; + const lines = []; + const doFetch = async (url) => { + const id = /\/api\/jobs\/([^/]+)\/log/.exec(url)?.[1]; + const seq = logs[id]; + const body = seq[Math.min(seen[id]++, seq.length - 1)]; + return { ok: true, status: 200, json: async () => body }; + }; + const status = await followJob("j1", false, { + fetch: doFetch, + sleep: async () => {}, + baseUrl: "http://editor", + say: (l) => lines.push(l), + }); + assert.equal(status, "failed", "the follow ends with how the handed-off job ended"); + assert.ok(seen.j2 >= 2); + assert.deepEqual(lines, ["[j1] handed off to job j2"]); +}); + test("a waiting job's queue position is said once per change", async () => { const lines = []; const editor = fakeEditor({