commit a5a1ccf63f49b7f16800fbe09485e2ed4ea19624 parent 134548c889d7eca7db133b69d350c45e4f55e135 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 15 Oct 2026 17:02:13 -0400 common, editor, scripts: salvage transcription of a damaged recording (release 30 lane Q2) — a whisper-video on a corrupt-full-source file failed outright at the first bad window and threw away the ~95 % that decodes; transcribeOne now decodes such a file with error tolerance into a 16 kHz WAV on the recording's own clock (lib/salvageAudio-server salvageDecode: one ffmpeg run, the framecrc scan of the unpadded decode says where the holes are, aresample async + apad make them silence of their own length — verified with a synthetic damaged tone-burst recording: bursts after the damage keep their source times, a plain decode shifts them by the gap) and transcribes that; automatic for a corrupt-full-source video, or `transcribe-one {"salvage": true}` (false forbids it); parakeet-stitch --salvage makes a window that cannot be sliced or transcribed a gap (its neighbours own their whole reach) and records it in salvage.failedWindows; transcribe-outcome.json records salvaged {source, decodedSeconds, totalSeconds, gaps}; the snapshot lists salvage transcripts in the new salvagedTranscript bucket (still transcribed; a corrupt full source stays in its own bucket), the channel flow has a siding for it and the video page says what the transcript is missing; end-to-end test through the real stitch wrapper with a fake parakeet-cli that transcribes tone bursts; ops help and COMMANDS.md Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
19 files changed, 598 insertions(+), 25 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md @@ -136,7 +136,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | -| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. | | +| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts @@ -854,3 +854,59 @@ test("a channel with no clips/ reports 0 clip bytes, not undefined", async () => await rm(dir, { recursive: true, force: true }); } }); + +// Release 30 lane Q: a salvage transcript is listed in salvagedTranscript, and +// a corrupt-full-source video stays in its bucket after one is made from its +// kept file — a retry can still bring a clean copy. +test("a salvage transcript is salvagedTranscript; its corrupt full source stays corruptFullSource", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "ttb-snap-salvage-")); + try { + const paths = { channelsDir: path.join(dir, "channels") } as Paths; + const channelDir = path.join(paths.channelsDir, "alpha"); + const ids = ["aaaa0000001", "bbbb0000002", "cccc0000003", "dddd0000004"]; + for (const id of ids) await mkdir(path.join(channelDir, "data", id), { recursive: true }); + await writeFile( + path.join(channelDir, "config.json"), + JSON.stringify({ handling: "transcribe", url: "https://www.youtube.com/@alpha/videos" }), + ); + await writeFile( + path.join(channelDir, "playlist"), + ids.map((id) => `https://www.youtube.com/watch?v=${id}`).join("\n"), + ); + const put = (id: string, name: string, body: unknown) => + writeFile(path.join(channelDir, "data", id, name), typeof body === "string" ? body : JSON.stringify(body)); + const cfs = { + videoId: "", + status: "corrupt-full-source", + startedAt: "2026-10-01T00:00:00.000Z", + finishedAt: "2026-10-01T00:01:00.000Z", + attempts: [], + }; + const salvaged = { source: "audio.mp4", decodedSeconds: 2335, totalSeconds: 6000, gaps: [[2335, 6000]] }; + for (const id of ids) await put(id, "metadata.info.json", { id, duration: 6000 }); + // a: corrupt full source, kept file, no transcript yet. + await put("aaaa0000001", "audio.mp4", "x"); + await put("aaaa0000001", "download-outcome.json", { ...cfs, videoId: "aaaa0000001" }); + // b: corrupt full source, salvaged. + await put("bbbb0000002", "audio.mp4", "x"); + await put("bbbb0000002", "download-outcome.json", { ...cfs, videoId: "bbbb0000002" }); + await put("bbbb0000002", "transcript.json", "{}"); + await put("bbbb0000002", "transcribe-outcome.json", { videoId: "bbbb0000002", transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }); + // c: a clean download whose transcript was salvaged on request. + await put("cccc0000003", "audio.mp4", "x"); + await put("cccc0000003", "transcript.json", "{}"); + await put("cccc0000003", "transcribe-outcome.json", { videoId: "cccc0000003", transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }); + // d: an ordinary transcript. + await put("dddd0000004", "audio.mp4", "x"); + await put("dddd0000004", "transcript.json", "{}"); + await put("dddd0000004", "transcribe-outcome.json", { videoId: "dddd0000004", transcribedAt: "2026-10-15T00:00:00.000Z" }); + + const snap = await generateChannelSnapshot(paths, "alpha"); + assert.deepEqual(snap.buckets.corruptFullSource, ["aaaa0000001", "bbbb0000002"]); + assert.deepEqual(snap.buckets.salvagedTranscript, ["bbbb0000002", "cccc0000003"]); + // Still transcripts: what is there is real and searchable. + assert.equal(snap.totals.transcribed, 3); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -53,6 +53,8 @@ import { } from "../jobs/autoQueuePolicy"; import { isExcludedFromTruncatedCheck } from "../lib/excludeTruncatedCheck-server"; import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; +import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server"; +import { TRANSCRIBE_OUTCOME_FILENAME } from "../lib/transcribeOutcome"; import { chatOnlyIdsFrom, loadMetadataScan, @@ -192,8 +194,9 @@ export type ChannelSnapshot = { // (download-outcome.json "corrupt-full-source"). The downloaded container is // KEPT on disk. NOT counted as a failed transcription and NOT re-queued for // download by a lane; a retry of the bucket refetches it (release 30, lane Q - // — ytdlp/corruptRefetch.ts). Optional: older snapshots lack it; readers - // default to []. + // — ytdlp/corruptRefetch.ts). A salvage transcript made from the kept file + // does not take it out of this bucket (it is in salvagedTranscript too). + // Optional: older snapshots lack it; readers default to []. corruptFullSource: string[]; // Videos whose transcript rides on a non-canonical VTT name (e.g. only // transcript.en-US.vtt, or a foreign-only transcript.<lang>.vtt) instead of @@ -254,6 +257,14 @@ export type ChannelSnapshot = { // the user can re-download/re-transcribe. Optional: older snapshots lack it; // readers must default to []. incompleteTranscript: string[]; + // Videos whose transcript is a SALVAGE (release 30, lane Q): made from a + // damaged file decoded with error tolerance, with gaps where nothing + // decoded (transcribe-outcome.json `salvaged`). Counted as transcribed — + // what is there is real and searchable — but not a clean full transcript. + // A corrupt-full-source video stays in corruptFullSource too: a retry can + // still bring a clean copy. Optional: older snapshots lack it; readers + // default to []. + salvagedTranscript: string[]; // Videos whose download COMPLETED (yt-dlp exit 0) but whose audio is far // shorter than the metadata duration — the source served a truncated stream // (download-outcome.json "failed-short-audio"). Caught at download time by @@ -998,6 +1009,13 @@ export async function generateChannelSnapshot( const excludedFromTruncatedCheck = await isExcludedFromTruncatedCheck(dir); const outcome = await loadDownloadOutcome(dir); + // A salvage transcript says so in its transcribe-outcome.json (release + // 30, lane Q). Only a whisper transcript can be one, so only those + // with the sidecar pay the small read. + const salvaged = + files.hasWhisper && files.entries.includes(TRANSCRIBE_OUTCOME_FILENAME) + ? Boolean((await loadTranscribeOutcome(dir))?.salvaged) + : false; // Only transcribed (non-untranscribable) dirs can have a truncated // transcript; skip the cues.json read for everything else. const coverage = @@ -1056,6 +1074,7 @@ export async function generateChannelSnapshot( doNotClean, excludedFromTruncatedCheck, outcome, + salvaged, coverage, vttProvenance, digest, @@ -1171,6 +1190,7 @@ export async function generateChannelSnapshot( // and the reason this is a bucket rather than a derived count. const chatOnlyPending: string[] = []; const incompleteTranscript: string[] = []; + const salvagedTranscript: string[] = []; const shortAudio: string[] = []; const autoSubsOnly: string[] = []; const downloadedAutoSubsOnly: string[] = []; @@ -1215,6 +1235,7 @@ export async function generateChannelSnapshot( backfill, effectiveAvailability, outcome, + salvaged, coverage, vttProvenance, digest, @@ -1283,6 +1304,9 @@ export async function generateChannelSnapshot( // downloadedNoTranscript (which would transcribe corrupt audio, or offer // the kept file to the wrong-format sweep) or the wrong-format cleanup // estimate (which would delete it). + // A salvage transcript, whatever the download says (before the + // corrupt-full-source short-circuit: most salvages are of those). + if (salvaged) salvagedTranscript.push(id); if (outcome?.status === "corrupt-full-source") { corruptFullSource.push(id); continue; @@ -1669,6 +1693,7 @@ export async function generateChannelSnapshot( chatOnly: chatOnly.sort(), chatOnlyPending: chatOnlyPending.sort(), incompleteTranscript: incompleteTranscript.sort(), + salvagedTranscript: salvagedTranscript.sort(), shortAudio: shortAudio.sort(), autoSubsOnly: autoSubsOnly.sort(), downloadedAutoSubsOnly: downloadedAutoSubsOnly.sort(), diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -21,6 +21,16 @@ import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus"; import { pickPreferredAudio } from "../lib/mediaFiles"; import { resolveSavedVideo } from "../lib/savedVideo-server"; import { writeTranscribeOutcome } from "../lib/transcribeOutcome-server"; +import type { TranscriptSalvage } from "../lib/transcribeOutcome"; +import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; +import { + SALVAGE_WAV_FILENAME, + describeSalvage, + gapSeconds, + mergeGaps, + salvageDecode, + type SalvageGap, +} from "../lib/salvageAudio-server"; import { writeFileAtomic } from "../lib/jsonFile-server"; import { probeMedia } from "../lib/evidenceClip-server"; import { savedWindowSource } from "../lib/savedVideoWindow-server"; @@ -157,6 +167,13 @@ export type TranscribeOneOptions = { // True asks the engine to keep word timestamps in transcript.json (see // TranscribeBuildInput.words). Only the one-off file transcription asks. words?: boolean; + // A SALVAGE transcription (release 30, lane Q): decode the audio with error + // tolerance into a WAV on the source's clock and transcribe that, recording + // what is missing in transcribe-outcome.json's `salvaged`. Asked for by + // `transcribe-one {"salvage": true}`; AUTOMATIC for a video whose download + // outcome is corrupt-full-source (its file is known to be malformed, and a + // plain run fails at the first bad window). False forces a plain run. + salvage?: boolean; }; export type TranscribeOneOutcome = "transcribed" | "already-exists" | "paused"; @@ -200,6 +217,86 @@ export async function transcribeOneVideo( log(`Using ${resolvedAudio} instead of ${opts.audioFilename}`); } + const salvage = await salvageWanted(opts); + try { + return await transcribeResolved(opts, resolvedAudio, salvage, log); + } finally { + // The salvage WAV is scratch: gone whatever the run ended as. A paused + // parakeet run keeps its window cache, keyed on the WAV's duration, and a + // re-run decodes the same WAV again. + if (salvage) await fs.rm(path.join(opts.videoDir, SALVAGE_WAV_FILENAME), { force: true }); + } +} + +// Salvage when asked, or when the video is a corrupt full source and nobody +// said not to. +async function salvageWanted(opts: TranscribeOneOptions): Promise<boolean> { + if (opts.salvage !== undefined) return opts.salvage; + const outcome = await loadDownloadOutcome(opts.videoDir).catch(() => null); + return outcome?.status === "corrupt-full-source"; +} + +// The windows a salvaging engine could not transcribe, from its output +// (parakeet-stitch --salvage: `salvage.failedWindows`). Empty for any other. +async function failedWindowsOf(transcriptPath: string): Promise<SalvageGap[]> { + try { + const doc = JSON.parse(await fs.readFile(transcriptPath, "utf8")) as { + salvage?: { failedWindows?: unknown }; + }; + const w = doc.salvage?.failedWindows; + if (!Array.isArray(w)) return []; + return w.filter( + (g): g is SalvageGap => + Array.isArray(g) && g.length === 2 && typeof g[0] === "number" && typeof g[1] === "number", + ); + } catch { + return []; + } +} + +async function transcribeResolved( + opts: TranscribeOneOptions, + resolvedAudio: string, + salvage: boolean, + log: (msg: string) => void, +): Promise<TranscribeOneOutcome> { + const transcriptPath = path.join(opts.videoDir, "transcript.json"); + // What the engine reads: the resolved audio, or its salvage WAV. + let engineAudio = resolvedAudio; + let salvaged: TranscriptSalvage | null = null; + if (salvage) { + log( + `Salvage: decoding ${resolvedAudio} with error tolerance — undecodable spans become silence on the recording's clock.`, + ); + let r; + try { + r = await salvageDecode( + path.join(opts.videoDir, resolvedAudio), + path.join(opts.videoDir, SALVAGE_WAV_FILENAME), + { + ffmpegBin: opts.paths.ffmpegBin, + ffprobeBin: opts.paths.ffprobeBin, + signal: opts.signal, + onLog: (l) => log(l.trimEnd()), + }, + ); + } catch (err) { + if (opts.signal?.aborted) throw err; + throw new TranscribeError( + `salvage decode of ${resolvedAudio} failed: ${(err as Error).message}`, + "transcription", + ); + } + log(`Salvage: ${describeSalvage(r)}.`); + engineAudio = SALVAGE_WAV_FILENAME; + salvaged = { + source: resolvedAudio, + decodedSeconds: r.decodedSeconds, + totalSeconds: r.totalSeconds, + gaps: r.gaps, + }; + } + const worker = opts.worker; const start = Date.now(); // Each app writes "<outputBase><ext>" relative to cwd (the ext differs: whisper @@ -223,8 +320,8 @@ export async function transcribeOneVideo( try { bytes = await transcribeViaRemote({ worker, - audioPath: path.join(opts.videoDir, resolvedAudio), - audioName: resolvedAudio, + audioPath: path.join(opts.videoDir, engineAudio), + audioName: engineAudio, videoId: opts.videoId, channelSlug: deriveChannelSlug(opts.paths, opts.videoDir) ?? undefined, onLog: (line: string) => log(line), @@ -249,13 +346,14 @@ export async function transcribeOneVideo( const appConfig = worker.config ?? {}; const bin = appConfig.bin?.trim() || app.defaultBin(); log( - `Transcribe ${opts.videoId} start (${resolvedAudio}) via ${app.id} [${worker.id}]`, + `Transcribe ${opts.videoId} start (${engineAudio}) via ${app.id} [${worker.id}]`, ); const build = app.build({ - audioFile: resolvedAudio, + audioFile: engineAudio, outputBase: tmpBase, config: appConfig, ...(opts.words ? { words: true } : {}), + ...(salvage ? { salvage: true } : {}), }); const child = execa(bin, build.argv, { cwd: opts.videoDir, @@ -326,12 +424,30 @@ export async function transcribeOneVideo( // "content added over time" by transcription date. Best-effort: a failed // sidecar write must not fail an otherwise-successful transcription (the build // falls back to the transcript file mtime when the sidecar is absent). + // A salvage's gaps: what did not decode, and any window the engine could + // not transcribe (parakeet --salvage). Decoded seconds never claim a gap. + if (salvaged) { + const failed = await failedWindowsOf(transcriptPath); + if (failed.length > 0) { + log(`Salvage: ${failed.length} window(s) could not be transcribed; recorded as gaps.`); + const gaps = mergeGaps([...salvaged.gaps, ...failed]); + salvaged = { + ...salvaged, + gaps, + decodedSeconds: Math.min( + salvaged.decodedSeconds, + Math.max(0, Math.round((salvaged.totalSeconds - gapSeconds(gaps)) * 1000) / 1000), + ), + }; + } + } try { await writeTranscribeOutcome(opts.videoDir, { videoId: opts.videoId, transcribedAt: new Date().toISOString(), worker: { id: worker.id, appId: worker.appId, kind: worker.kind }, durationMs: Date.now() - start, + ...(salvaged ? { salvaged } : {}), }); } catch (err) { log( @@ -444,6 +560,8 @@ export type TranscribeWithWorkerOptions = { skipInlineDiarization?: boolean; // See TranscribeOneOptions.words. words?: boolean; + // See TranscribeOneOptions.salvage. + salvage?: boolean; }; // Acquire a worker from the global pool and transcribe one video through it, @@ -510,6 +628,7 @@ export async function transcribeWithWorker( partialSignal: partialController?.signal, skipInlineDiarization: opts.skipInlineDiarization, words: opts.words, + ...(opts.salvage !== undefined ? { salvage: opts.salvage } : {}), }); pool.markSuccess(worker.id); return outcome; diff --git a/common/controller/transcribeSalvage.test.ts b/common/controller/transcribeSalvage.test.ts @@ -0,0 +1,137 @@ +// A SALVAGE TRANSCRIPTION KEEPS THE RECORDING'S CLOCK (release 30, lane Q). +// +// A corrupt-full-source video's kept file is transcribed with salvage (it is +// automatic for that status): decoded with error tolerance into a WAV whose +// undecodable spans are silence of their own length, then the normal parakeet +// path (the real scripts/parakeet-stitch.mjs, in overlapping windows) over a +// FAKE parakeet-cli that "transcribes" tone bursts — one word per burst, at +// the burst's time in its window. So the cues it produces are where the +// bursts are in the WAV, and the test checks they are where the bursts are in +// the SOURCE. No real ASR; real ffmpeg over a synthetic damaged recording. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/transcribeSalvage.test.ts + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { + burstTimes, + corruptBytes, + hasFfmpeg, + makeToneFile, +} from "../testing/audio/corruptAudio.mjs"; + +const tools = hasFfmpeg(); +let ROOT = ""; +let VIDEO_DIR = ""; +let DAMAGED = ""; +const SLUG = "tones"; +const ID = "vid1"; + +before(async () => { + ROOT = await mkdtemp(path.join(tmpdir(), "transcribe-salvage-")); + // Before anything reads getPaths(): a scratch corpus, and the fake CLI. + process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); + const cli = path.join(ROOT, "fake-parakeet-cli.mjs"); + const kit = pathToFileURL(path.resolve(import.meta.dirname, "../testing/audio/corruptAudio.mjs")).href; + await writeFile( + cli, + `#!/usr/bin/env node +import { readWavMono16, toneOnsets } from ${JSON.stringify(kit)}; +const argv = process.argv.slice(2); +const wav = argv[argv.indexOf("--input") + 1]; +const { samples, rate } = readWavMono16(wav); +const words = toneOnsets(samples, rate).map((t) => ({ w: "beep", start: t, end: t + 0.3 })); +process.stdout.write(JSON.stringify({ words })); +`, + ); + await chmod(cli, 0o755); + process.env.PARAKEET_CLI = cli; + if (!tools) return; + VIDEO_DIR = path.join(process.env.TRANSCRIPTS_DIR, "channels", SLUG, "data", ID); + await mkdir(VIDEO_DIR, { recursive: true }); + const clean = makeToneFile(path.join(ROOT, "clean.mp4")); + DAMAGED = corruptBytes(clean, path.join(VIDEO_DIR, "audio.mp4")); + await writeFile( + path.join(VIDEO_DIR, "metadata.info.json"), + JSON.stringify({ id: ID, title: "Tones", duration: 30, upload_date: "20260105", webpage_url: "https://example.invalid/v/vid1" }), + ); + await writeFile( + path.join(VIDEO_DIR, "download-outcome.json"), + JSON.stringify({ + videoId: ID, + status: "corrupt-full-source", + startedAt: "2026-10-01T00:00:00.000Z", + finishedAt: "2026-10-01T00:01:00.000Z", + attempts: [], + }), + ); +}); +after(() => rm(ROOT, { recursive: true, force: true })); + +const near = (a: number, b: number, tol = 0.06) => Math.abs(a - b) <= tol; + +test( + "a corrupt full source is salvaged: cues on the recording's clock, the gap recorded, the WAV gone", + { skip: !tools && "ffmpeg/ffprobe not installed" }, + async () => { + const { transcribeOneVideo } = await import("./transcribeOne"); + const { getPaths } = await import("../lib/paths"); + const paths = getPaths(); + const lines: string[] = []; + const outcome = await transcribeOneVideo({ + paths, + videoDir: VIDEO_DIR, + videoId: ID, + audioFilename: "audio.mp4", + worker: { + id: "w1", + name: "fake parakeet", + kind: "local", + enabled: true, + priority: 0, + appId: "parakeet", + // A model file must exist; the fake CLI never reads it. 20 s windows + // with the default 6 s overlap: the 30 s recording is two windows, so + // the stitch's offsets are exercised too. + config: { model: DAMAGED, chunkSize: 20 }, + }, + onLog: (l) => lines.push(l), + skipInlineDiarization: true, + }); + assert.equal(outcome, "transcribed", lines.join("\n")); + assert.match(lines.join("\n"), /Salvage: decoding audio\.mp4 with error tolerance/); + + const record = JSON.parse(await readFile(path.join(VIDEO_DIR, "transcribe-outcome.json"), "utf8")); + assert.ok(record.salvaged, "transcribe-outcome.json records the salvage"); + assert.equal(record.salvaged.source, "audio.mp4"); + assert.ok(near(record.salvaged.totalSeconds, 30), `total ${record.salvaged.totalSeconds}`); + assert.equal(record.salvaged.gaps.length, 1, JSON.stringify(record.salvaged.gaps)); + const [from, to] = record.salvaged.gaps[0]; + assert.ok(to - from > 1); + assert.ok(record.salvaged.decodedSeconds < 30 - 1); + + // The cues: one per surviving burst, each at its SOURCE time. + const transcript = JSON.parse(await readFile(path.join(VIDEO_DIR, "transcript.json"), "utf8")); + const starts: number[] = transcript.chunk_data.map((c: { start_time: number }) => c.start_time); + const expected = burstTimes().filter((t) => t + 0.3 < from || t > to); + assert.ok(expected.some((t) => t > to), "a burst after the damage is checked"); + for (const t of expected) { + assert.ok(starts.some((s) => near(s, t)), `no cue at ${t}s (cues ${starts.join(", ")})`); + } + for (const s of starts) { + assert.ok(!(s > from + 0.05 && s < to - 0.05), `cue at ${s}s inside the gap ${from}-${to}`); + } + // Normalized, as every transcription is. + assert.ok(existsSync(path.join(VIDEO_DIR, "transcript.cues.json"))); + // The salvage WAV and parakeet's window cache are gone. + assert.equal(existsSync(path.join(VIDEO_DIR, "audio.salvage.wav")), false); + assert.equal(existsSync(path.join(VIDEO_DIR, ".audio.salvage.wav.parakeet")), false); + // The kept file is untouched. + assert.ok(existsSync(path.join(VIDEO_DIR, "audio.mp4"))); + }, +); diff --git a/common/lib/transcribeOutcome.ts b/common/lib/transcribeOutcome.ts @@ -18,6 +18,24 @@ export type TranscribeOutcomeRecord = { worker?: { id: string; appId?: string; kind: "local" | "remote" | "llm" }; // Wall-clock transcription time in milliseconds. durationMs?: number; + // Set when the transcript is a SALVAGE (release 30, lane Q): made from a + // damaged file decoded with error tolerance, its undecodable spans silence + // on the source's clock (lib/salvageAudio-server.ts). Not a clean full + // transcript — the channel report lists it in `salvagedTranscript`, and the + // video page says what is missing. + salvaged?: TranscriptSalvage; +}; + +export type TranscriptSalvage = { + // The file the salvage decoded (a name in the video dir). + source: string; + // Seconds of audio that decoded and were transcribed. + decodedSeconds: number; + // The recording's length (the container's duration). + totalSeconds: number; + // Spans of the recording with no transcript, [from, to] seconds: what did + // not decode, and any window the engine could not transcribe. Sorted, merged. + gaps: Array<[number, number]>; }; export const TRANSCRIBE_OUTCOME_FILENAME = "transcribe-outcome.json"; diff --git a/common/lib/transcriptionApps.test.ts b/common/lib/transcriptionApps.test.ts @@ -25,3 +25,18 @@ test("an engine with no words to give ignores the ask", () => { assert.deepEqual(app.build({ ...input, words: true }).argv, app.build(input).argv); } }); + +// Release 30 lane Q: a salvage run tells parakeet's wrapper that a bad window +// is a gap; the engines with no windows ignore it. +test("parakeet takes --salvage only on a salvage run; whisper.cpp and chough ignore it", () => { + const app = getTranscriptionApp("parakeet"); + assert.ok(!app.build(input).argv.includes("--salvage")); + const salvaging = app.build({ ...input, salvage: true }).argv; + assert.ok(salvaging.includes("--salvage")); + assert.equal(salvaging.at(-1), "audio.wav"); + for (const id of ["whisper-cpp", "chough"]) { + const other = getTranscriptionApp(id); + assert.equal(other.id, id); + assert.deepEqual(other.build({ ...input, salvage: true }).argv, other.build(input).argv); + } +}); diff --git a/common/lib/transcriptionApps.ts b/common/lib/transcriptionApps.ts @@ -78,6 +78,12 @@ export type TranscribeBuildInput = { // them to give; the others ignore it. Off for corpus transcriptions, whose // transcript.json would otherwise carry every word twice. words?: boolean; + // A SALVAGE run (release 30, lane Q): the input is a damaged recording + // decoded on its own clock, and a window the engine cannot transcribe is a + // gap, not a failed file. Only parakeet's wrapper has windows to tolerate + // (--salvage, which records them in the output's `salvage.failedWindows`); + // the others ignore it. + salvage?: boolean; }; export type TranscriptionApp = { @@ -249,11 +255,12 @@ const parakeet: TranscriptionApp = { supportsPartialStop: true, defaultBin: () => getPaths().parakeetBin, resolveModel: (config) => config.model?.trim() || getPaths().parakeetModel, - build({ audioFile, outputBase, config, words }) { + build({ audioFile, outputBase, config, words, salvage }) { const paths = getPaths(); const model = parakeet.resolveModel(config) as string; const argv = ["--model", model, "--output", outputBase]; if (words) argv.push("--words"); + if (salvage) argv.push("--salvage"); if (typeof config.chunkSize === "number" && config.chunkSize > 0) { argv.push("--segment", String(Math.floor(config.chunkSize))); } diff --git a/common/views/pipeline/channelFlow.ts b/common/views/pipeline/channelFlow.ts @@ -460,6 +460,12 @@ export function computeChannelFlow( "The transcript covers a fraction of the runtime — the audio download truncated silently.", ), ...siding( + "salvaged transcript", + buckets.salvagedTranscript.length, + "transcribe", + "Transcribed from a damaged file: the parts that would not decode are gaps. A retry of the corrupt full source can bring a clean copy.", + ), + ...siding( "short audio", buckets.shortAudio.length, "transcribe", diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts @@ -42,6 +42,7 @@ export function normalizeBuckets( chatOnly: raw?.chatOnly ?? [], chatOnlyPending: raw?.chatOnlyPending ?? [], incompleteTranscript: raw?.incompleteTranscript ?? [], + salvagedTranscript: raw?.salvagedTranscript ?? [], shortAudio: raw?.shortAudio ?? [], autoSubsOnly: raw?.autoSubsOnly ?? [], downloadedAutoSubsOnly: raw?.downloadedAutoSubsOnly ?? [], diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -115,6 +115,10 @@ test("transcribe-one, delete-file and do-not-clean refuse before anything is tou const noChannel = await callPost(one, { slug: "no-such", id: VIDEO }); assert.equal(noChannel.status, 400); assert.match(String(noChannel.body.error), /no-such/); + // Release 30 lane Q: "salvage" is a boolean, checked at the door. + const badSalvage = await callPost(one, { slug: SLUG, id: VIDEO, salvage: "yes" }); + assert.equal(badSalvage.status, 400); + assert.match(String(badSalvage.body.error), /"salvage" must be a boolean/); const del = await route("delete-file"); const suspicious = await callPost(del, { slug: SLUG, id: VIDEO, file: "../config.json" }); diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts @@ -2,11 +2,11 @@ import { transcribeOneAction, whisperVideoAction, } from "../../../channels/[slug]/videos/[id]/videoActions"; -import { jobResponse, ops, opsFail, optString, reqSlug, reqVideoId } from "../_lib"; +import { jobResponse, ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, file? } +// POST { slug, id, file?, salvage? } // // One video, transcribed — the video page's two buttons: // - with "file" (an audio file in the video's dir, e.g. "audio.mp3"): that @@ -17,11 +17,16 @@ export const dynamic = "force-dynamic"; // 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. // The file name is one path segment; a refused one is the action's sentence. +// "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 +// other is not. export async function POST(request: Request) { - return ops(request, ["slug", "id", "file"], async (body) => { + return ops(request, ["slug", "id", "file", "salvage"], async (body) => { const slug = reqSlug(body, "slug"); const id = reqVideoId(body, "id"); const file = optString(body, "file"); + const salvage = optBool(body, "salvage"); // 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("."))) { @@ -29,8 +34,8 @@ export async function POST(request: Request) { } return jobResponse( file !== undefined - ? await transcribeOneAction(slug, id, file) - : await whisperVideoAction(slug, id), + ? await transcribeOneAction(slug, id, file, undefined, salvage) + : await whisperVideoAction(slug, id, undefined, salvage), ); }); } diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -13,6 +13,8 @@ import type { ChannelHandling, } from "yt-dlp-transcript-common/lib/channelConfig"; import type { DownloadOutcomeRecord } from "yt-dlp-transcript-common/lib/downloadOutcome"; +import type { TranscriptSalvage } from "yt-dlp-transcript-common/lib/transcribeOutcome"; +import { SalvagedTranscriptNotice } from "./cards/SalvagedTranscriptNotice"; import type { SavedVideoPointer } from "yt-dlp-transcript-common/lib/savedVideo"; import type { SourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import type { AvailabilityHistoryEntry } from "yt-dlp-transcript-common/lib/availability"; @@ -65,6 +67,8 @@ type Props = { defaultQueueKey: string; existingQueues: string[]; downloadOutcome: DownloadOutcomeRecord | null; + // The transcript is a salvage (release 30, lane Q): what it is missing. + salvaged?: TranscriptSalvage | null; availabilityHistory: AvailabilityHistoryEntry[]; channelAudioFormat?: AudioFormat; doNotClean?: boolean; @@ -108,6 +112,7 @@ export function VideoPanel({ defaultQueueKey, existingQueues, downloadOutcome, + salvaged = null, availabilityHistory, channelAudioFormat, doNotClean = false, @@ -149,9 +154,12 @@ export function VideoPanel({ ? "No audio on disk — run the pipeline (VTT first, whisper if needed)." : "Audio not yet downloaded." : `${audioFiles.length} audio file${audioFiles.length === 1 ? "" : "s"} on disk.`; + const salvageShown = hasTranscriptJson && salvaged !== null; const transcribeSummary = autoSubsOnly ? "YouTube auto-captions only — can be replaced with an AI transcript." - : hasTranscript + : salvageShown + ? "Salvaged transcript — gaps where the file would not decode." + : hasTranscript ? "Transcript present." : noAudio ? "No audio yet — run the download pipeline (or use Audio + Whisper) to produce a transcript." @@ -191,6 +199,7 @@ export function VideoPanel({ downloadFailed={downloadFailed} /> {downloadOutcome && <DownloadOutcomeBadge outcome={downloadOutcome} />} + {salvageShown && salvaged && <SalvagedTranscriptNotice salvaged={salvaged} />} {/* BOTH BANNERS ARE RENDERED UNCONDITIONALLY, and each decides for itself whether to draw anything. THE RULE (plans/FACTS.md, fae99f1): a component carrying a StreamActionLog must not be UNMOUNTED when the @@ -297,7 +306,7 @@ export function VideoPanel({ summary={transcribeSummary} defaultOpen={true} tone={ - incompleteTranscript + incompleteTranscript || salvageShown ? "attention" : hasTranscript ? "ok" diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/SalvagedTranscriptNotice.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/SalvagedTranscriptNotice.tsx @@ -0,0 +1,31 @@ +import type { TranscriptSalvage } from "yt-dlp-transcript-common/lib/transcribeOutcome"; +import { formatDuration } from "yt-dlp-transcript-common/lib/format"; + +// A SALVAGE TRANSCRIPT SAYS WHAT IT IS MISSING (release 30, lane Q): made +// from a damaged file decoded with error tolerance, so where nothing decoded +// there is no transcript. The times are the recording's own. +const clock = (s: number) => formatDuration(s) || "0:00"; +const MAX_LISTED = 8; + +export function SalvagedTranscriptNotice({ salvaged }: { salvaged: TranscriptSalvage }) { + const listed = salvaged.gaps.slice(0, MAX_LISTED); + const more = salvaged.gaps.length - listed.length; + return ( + <div + role="status" + aria-label="salvaged transcript" + className="rounded border px-3 py-2 text-sm border-warning/30 bg-warning-soft text-warning" + > + Salvaged transcript — {clock(salvaged.decodedSeconds)} of{" "} + {clock(salvaged.totalSeconds)} of {salvaged.source} decoded. + {salvaged.gaps.length > 0 && ( + <> + {" "} + No transcript for{" "} + {listed.map(([a, b]) => `${clock(a)}–${clock(b)}`).join(", ")} + {more > 0 ? ` and ${more} more` : ""}. + </> + )} + </div> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -4,6 +4,7 @@ import { notFound } from "next/navigation"; import path from "node:path"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { loadDownloadOutcome } from "yt-dlp-transcript-common/lib/downloadOutcome-server"; +import { loadTranscribeOutcome } from "yt-dlp-transcript-common/lib/transcribeOutcome-server"; import { loadAvailability } from "yt-dlp-transcript-common/lib/availability-server"; import { loadMetadataHistory } from "yt-dlp-transcript-common/lib/metadataHistory-server"; import { metadataHistoryView } from "yt-dlp-transcript-common/views/metadataHistoryView"; @@ -127,6 +128,8 @@ export default async function VideoDetailPage({ const meta = await loadMeta(slug, id); const videoDir = path.join(getPaths().channelsDir, slug, "data", id); const downloadOutcome = await loadDownloadOutcome(videoDir); + // A salvage transcript's gaps (release 30, lane Q); null for any other. + const salvaged = (await loadTranscribeOutcome(videoDir))?.salvaged ?? null; const availabilityRecord = await loadAvailability(videoDir); const availabilityHistory = availabilityRecord?.history ?? []; // Every rewrite of metadata.info.json that changed its bytes (release 10 @@ -190,6 +193,7 @@ export default async function VideoDetailPage({ meta, videoDir, downloadOutcome, + salvaged, availabilityHistory, metadataHistory, doNotClean, @@ -219,6 +223,7 @@ export default async function VideoDetailPage({ meta, videoDir, downloadOutcome, + salvaged, availabilityHistory, metadataHistory, doNotClean, @@ -335,6 +340,7 @@ export default async function VideoDetailPage({ defaultQueueKey={defaultQueueKey} existingQueues={existingQueues} downloadOutcome={downloadOutcome} + salvaged={salvaged} availabilityHistory={availabilityHistory} channelAudioFormat={config.audioFormat} doNotClean={doNotClean} diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -185,6 +185,10 @@ export async function transcribeOneAction( videoId: string, audioFilename: string, queueKey?: string, + // A salvage transcription (release 30, lane Q — transcribeOne's `salvage`): + // true forces it, false forbids it, undefined leaves it automatic (a + // corrupt-full-source video is salvaged). + salvage?: boolean, ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -205,6 +209,7 @@ export async function transcribeOneAction( tracker: makeTaskTracker(ctx, onLog), onLog, signal, + ...(salvage !== undefined ? { salvage } : {}), }); safeRevalidate([`/channels/${slug}/videos/${videoId}`]); }, @@ -447,6 +452,8 @@ export async function whisperVideoAction( slug: string, videoId: string, queueKey?: string, + // See transcribeOneAction's `salvage`. + salvage?: boolean, ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -524,6 +531,7 @@ export async function whisperVideoAction( tracker: makeTaskTracker(ctx, onLog), onLog, signal, + ...(salvage !== undefined ? { salvage } : {}), }); safeRevalidate([ `/channels/${slug}/videos/${videoId}`, diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -912,7 +912,10 @@ export function usage() { 'transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file"', ' (an audio file in its dir) that file; without, the video page\'s', ' Transcribe — the audio on disk, or downloaded first through the channel\'s', - ' managed path. A job; --wait follows it.', + ' managed path. A job; --wait follows it. "salvage": true decodes a damaged', + ' file with error tolerance and transcribes what decodes, on the', + ' recording\'s clock, its gaps recorded (the transcript is listed as', + ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false.', "", 'delete-file deletes one file of one video, as its Files list does:', ' {"slug", "id", "file"}. A tiered media file goes with its bytes on the', diff --git a/scripts/parakeet-stitch.mjs b/scripts/parakeet-stitch.mjs @@ -51,6 +51,13 @@ // --words also write the stitched words, as a top-level // `words: [{w, start, end, conf}]` beside chunk_data // (seconds; readers of chunk_data ignore it) +// --salvage a damaged recording (release 30, lane Q): slice with +// ffmpeg's error tolerance, and a window that cannot be +// sliced or transcribed is a GAP, not the end of the +// file. The output gains `salvage: { failedWindows: +// [[from, to], ...] }` (seconds: the span each failed +// window owned). A failed window is not cached, so a +// re-run asks it again. // -h, --help show this help import { execFile } from "node:child_process"; @@ -97,6 +104,7 @@ function parseArgs(argv) { maxCue: 8, keepTemp: false, words: false, + salvage: false, output: undefined, audio: undefined, }; @@ -124,6 +132,7 @@ function parseArgs(argv) { case "-o": case "--output": opts.output = next(); break; case "--keep-temp": opts.keepTemp = true; break; case "--words": opts.words = true; break; + case "--salvage": opts.salvage = true; break; default: if (a.startsWith("-")) fail(`unknown option ${a}`); positional.push(a); @@ -200,8 +209,11 @@ async function probeDuration(ffprobe, audio) { // Slice [start, start+len) of the source into a 16kHz-mono s16 WAV. Input // seeking (-ss before -i) is fast and accurate enough given the overlap. -async function sliceWav(ffmpeg, audio, start, len, outWav) { +async function sliceWav(ffmpeg, audio, start, len, outWav, { salvage = false } = {}) { const args = ["-nostdin", "-v", "error", "-y"]; + // Salvage: keep decoding past a refused frame, drop packets the demuxer + // flags as corrupt (lib/salvageAudio-server.ts decodes the same way). + if (salvage) args.push("-err_detect", "ignore_err", "-fflags", "+discardcorrupt"); if (start > 0) args.push("-ss", String(start)); args.push("-i", audio); if (len !== undefined) args.push("-t", String(len)); @@ -496,6 +508,7 @@ async function main() { let paused = false; const segTimes = []; // measured wall-time (ms) per freshly-transcribed window, for ETA let done = 0; // windows present (cached or freshly done) + const failed = new Set(); // salvage: windows that could not be sliced or transcribed try { for (let i = 0; i < N; i += 1) { const start = offsets[i]; @@ -515,12 +528,24 @@ async function main() { const len = isLast ? undefined : opts.segment; const wav = path.join(tmp, `win-${String(i).padStart(4, "0")}.wav`); const eta = etaSuffix(segTimes, N - i); - progress(`segment ${i + 1}/${N} @${round3(start)}s — slicing${eta}`); - await sliceWav(opts.ffmpeg, opts.audio, start, len, wav); - progress(`segment ${i + 1}/${N} @${round3(start)}s — transcribing${eta}`); - const t0 = Date.now(); - const doc = await transcribeWindow(opts, wav); - segTimes.push(Date.now() - t0); + let doc; + try { + progress(`segment ${i + 1}/${N} @${round3(start)}s — slicing${eta}`); + await sliceWav(opts.ffmpeg, opts.audio, start, len, wav, { salvage: opts.salvage }); + progress(`segment ${i + 1}/${N} @${round3(start)}s — transcribing${eta}`); + const t0 = Date.now(); + doc = await transcribeWindow(opts, wav); + segTimes.push(Date.now() - t0); + } catch (err) { + if (!opts.salvage) throw err; + // SALVAGE: one bad window is a gap, not the end of the file. + const msg = String(err?.message ?? err).split("\n").filter(Boolean).slice(-1)[0] ?? ""; + progress(`segment ${i + 1}/${N} @${round3(start)}s — failed, recorded as a gap (salvage): ${msg}`); + failed.add(i); + done += 1; + if (!opts.keepTemp) await rm(wav, { force: true }); + continue; + } // Persist the raw parakeet-cli payload for this window (the "original json"), // tagged with its absolute start offset. This is the durable, resumable // artifact; stitching happens only at the end. @@ -536,9 +561,16 @@ async function main() { process.exit(PARTIAL_PAUSE_CODE); } + // A salvage with nothing salvaged is a failed transcription, not an empty one. + if (failed.size === N) fail(`every one of ${N} window(s) failed (salvage)`, 1); + // All windows present — load the raw payloads and stitch the final transcript. const windowWords = []; for (let i = 0; i < N; i += 1) { + if (failed.has(i)) { + windowWords.push([]); + continue; + } const { start, doc } = JSON.parse(await readFile(winPath(i), "utf8")); const words = Array.isArray(doc.words) ? doc.words : []; windowWords.push( @@ -558,10 +590,15 @@ async function main() { for (let i = 0; i < N - 1; i += 1) { cuts.push(offsets[i + 1] + overlap / 2); } + // Salvage: a window beside a FAILED one owns its whole reach on that side — + // nothing else will cover the overlap there. + const ok = (i) => i >= 0 && i < N && !failed.has(i); + const reach = (i) => (i === N - 1 ? Infinity : offsets[i] + opts.segment); const stitched = []; for (let i = 0; i < N; i += 1) { - const lo = i > 0 ? cuts[i - 1] : -Infinity; - const hi = i < N - 1 ? cuts[i] : Infinity; + if (!ok(i)) continue; + const lo = i === 0 ? -Infinity : ok(i - 1) ? cuts[i - 1] : offsets[i]; + const hi = i === N - 1 ? Infinity : ok(i + 1) ? cuts[i] : reach(i); for (const w of windowWords[i]) { if (w.start >= lo && w.start < hi) stitched.push(w); } @@ -570,12 +607,23 @@ async function main() { const chunkData = groupCues(stitched, { gap: opts.gap, maxCue: opts.maxCue }); const text = chunkData.map((c) => c.text).join(" "); + // What no transcribed window reached: the gaps the failed windows left. + const failedWindows = []; + let cursor = 0; + for (let i = 0; i < N; i += 1) { + if (!ok(i)) continue; + if (offsets[i] > cursor) failedWindows.push([round3(cursor), round3(offsets[i])]); + cursor = Math.max(cursor, Math.min(reach(i), duration)); + } + if (failed.size > 0 && cursor < duration) failedWindows.push([round3(cursor), round3(duration)]); + if (failedWindows.length) progress(`salvage: ${failedWindows.length} of ${N} window(s) failed and are gaps`); const doc = { duration_seconds: round3(duration), chunks: chunkData.length, text, chunk_data: chunkData, ...(opts.words ? { words: wordsOut(stitched) } : {}), + ...(opts.salvage ? { salvage: { failedWindows } } : {}), }; const json = JSON.stringify(doc); diff --git a/scripts/parakeet-stitch.test.mjs b/scripts/parakeet-stitch.test.mjs @@ -116,3 +116,78 @@ test("the live owner check: this process owns a dir it marked; a dead pid does n rmSync(dir, { recursive: true, force: true }); } }); + +// Release 30 lane Q: --salvage. A window that cannot be sliced or transcribed +// is a gap, recorded in the output; without the flag it is the end of the file. +function salvageFixture(root, { failSlice = false } = {}) { + const bin = path.join(root, "bin"); + const work = path.join(root, "video"); + mkdirSync(bin); + mkdirSync(work); + writeFileSync(path.join(work, "audio.wav"), "not audio"); + writeFileSync(path.join(root, "model.gguf"), "not a model"); + sh(path.join(bin, "ffprobe"), "echo 1000"); + // ffmpeg writes the window wav (its last argument), named for its window; + // with failSlice the second window's slice fails as a damaged file does. + sh( + path.join(bin, "ffmpeg"), + `for a; do last="$a"; done; case "$last" in *win-0001.wav) ${failSlice ? 'echo "Invalid data found when processing input" >&2; exit 1' : "echo wav > \"$last\""};; *) echo wav > "$last";; esac`, + ); + // parakeet-cli: one word 1 s into each window; the second window fails. + sh( + path.join(bin, "parakeet-cli"), + 'for a; do last="$a"; done; case "$last" in *win-0001.wav) echo "parakeet: decode failed" >&2; exit 1;; esac; echo \'{"words":[{"w":"word","start":1,"end":1.5}]}\'', + ); + return { bin, work }; +} + +function runStitch(root, bin, work, extra = []) { + return spawnSync( + process.execPath, + [SCRIPT, "--model", path.join(root, "model.gguf"), "--cli", path.join(bin, "parakeet-cli"), "--ffmpeg", path.join(bin, "ffmpeg"), ...extra, path.join(work, "audio.wav"), path.join(work, "out.json")], + { env: { ...process.env, TMPDIR: path.join(root, "tmp") }, encoding: "utf8", timeout: 30_000 }, + ); +} + +for (const failSlice of [false, true]) { + test(`--salvage: a window whose ${failSlice ? "slice" : "transcription"} fails is a gap, the rest is stitched`, async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "stitch-salvage-")); + try { + mkdirSync(path.join(root, "tmp")); + const { bin, work } = salvageFixture(root, { failSlice }); + // Without the flag: the whole file fails. + const plain = runStitch(root, bin, work); + assert.equal(plain.status, 1); + assert.ok(!existsSync(path.join(work, "out.json"))); + // With it: windows 0 and 2 are transcribed, window 1 is a gap. + const r = runStitch(root, bin, work, ["--salvage"]); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stderr, /segment 2\/3 @474s — failed, recorded as a gap \(salvage\)/); + const doc = JSON.parse((await import("node:fs")).readFileSync(path.join(work, "out.json"), "utf8")); + // 1000 s in 480 s windows with 6 s overlap: starts 0, 474, 948. With the + // middle one gone, its neighbours own their whole reach — 0–480 and + // 948–1000 — and only what neither reaches is a gap. + assert.deepEqual(doc.salvage, { failedWindows: [[480, 948]] }); + assert.deepEqual(doc.chunk_data.map((c) => c.start_time), [1, 949]); + // A failed window is not cached; the next run asks it again. + assert.ok(!existsSync(path.join(work, ".audio.wav.parakeet")), "work dir removed after the stitch"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +} + +test("--salvage: every window failing is a failed transcription, not an empty one", () => { + const root = mkdtempSync(path.join(os.tmpdir(), "stitch-salvage-all-")); + try { + mkdirSync(path.join(root, "tmp")); + const { bin, work } = salvageFixture(root); + sh(path.join(bin, "parakeet-cli"), "exit 1"); + const r = runStitch(root, bin, work, ["--salvage"]); + assert.equal(r.status, 1); + assert.match(r.stderr, /every one of 3 window\(s\) failed \(salvage\)/); + assert.ok(!existsSync(path.join(work, "out.json"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +});