Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(cli): let transcribe --to write srt or vtt straight from a media file (#5215)
Miguel Ángel908f4395b4d0
diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdxindex b9a3f30569..412e815e4a 100644--- a/docs/packages/cli.mdx+++ b/docs/packages/cli.mdx@@ -268,8 +268,9 @@ npx hyperframes transcribe video.mp4 --model medium.en --language ennpx hyperframes transcribe subtitles.srtnpx hyperframes transcribe openai-response.json-# Export a caption sidecar+# Export a caption sidecar, from a transcript or straight from the medianpx hyperframes transcribe transcript.json --to srt+npx hyperframes transcribe video.mp4 --to vtt```| Flag | Description |@@ -278,7 +279,7 @@ npx hyperframes transcribe transcript.json --to srt| `--engine, -e` | ASR engine: `auto` (default — Parakeet if installed and the language is one of its 25, else whisper), `parakeet` (fails if Parakeet is missing, broken, or lacks the `--language`), or `whisper` || `--model, -m` | Whisper model (default `small.en`): `tiny.en`, `base.en`, `small.en`, `medium.en`, `large-v3` || `--language, -l` | Language code (`en`, `es`, `ja`, …). Whisper transcribes as this language; Parakeet, used when it covers it, detects the language itself. |-| `--to` | Export a sidecar instead: `srt` or `vtt` |+| `--to` | Write an `srt` or `vtt` sidecar: from a transcript file it exports instead of importing; from audio or video it is written beside `transcript.json`, with cues for languages without spaces grouped, which exporting that `transcript.json` later may split differently || `--output, -o` | Where the exported SRT/VTT goes || `--preserve-cues` | Keep each transcript entry as its own caption cue, skipping word-level grouping || `--optional` | Skip and exit 0 when whisper-cpp is unavailable, instead of failing. For pipelines that can carry on without captions. A broken Parakeet install is a real failure: it exits 1 even when whisper-cpp is missing. |diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 055b5aafd6..2737a92c30 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -46,6 +46,7 @@ import {import { fetchRemoteTemplate } from "../templates/remote.js";import { trackInitTemplate } from "../telemetry/events.js";import { DEFAULT_MODEL, hasFFmpeg } from "../whisper/manager.js";+import { TRANSCRIPT_FILE } from "../whisper/transcriptFile.js";import { initialModelForLanguage } from "../whisper/transcribe.js";import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";import { VERSION } from "../version.js";@@ -938,7 +939,7 @@ export default defineCommand({failCommand();}trackInitTemplate(templateId, { tailwind });- const transcriptFile = resolve(destDir, "transcript.json");+ const transcriptFile = resolve(destDir, TRANSCRIPT_FILE);if (existsSync(transcriptFile)) {await patchTranscript(destDir, transcriptFile);}@@ -1175,7 +1176,7 @@ export default defineCommand({trackInitTemplate(templateId, { tailwind });// 4b. Patch captions with transcript if available- const transcriptFile = resolve(destDir, "transcript.json");+ const transcriptFile = resolve(destDir, TRANSCRIPT_FILE);if (existsSync(transcriptFile)) {await patchTranscript(destDir, transcriptFile);}diff --git a/packages/cli/src/commands/transcribe.test.ts b/packages/cli/src/commands/transcribe.test.tsindex 7657d034bb..2a169869b3 100644--- a/packages/cli/src/commands/transcribe.test.ts+++ b/packages/cli/src/commands/transcribe.test.ts@@ -7,18 +7,27 @@ import {writeFileSync,readFileSync,mkdtempSync,+ realpathSync,rmSync,+ statSync,+ symlinkSync,} from "node:fs";-import { join } from "node:path";+import { basename, dirname, join } from "node:path";import { tmpdir } from "node:os";import { pathToFileURL } from "node:url";import { WhisperUnavailableError } from "../whisper/manager.js";+import { formatVtt, loadTranscript } from "../whisper/normalize.js";import { CliRuntimeError, consumeCommandResult } from "../utils/commandResult.js";// Make the whisper core report "unavailable" so we exercise the soft-skip path.const transcribeMock = vi.fn();const prepareWavMock = vi.fn((input: string) => input);let audioSeconds = 1;+vi.mock("node:fs", async (importOriginal) => {+ const fs = await importOriginal<typeof import("node:fs")>();+ return { ...fs, statSync: vi.fn(fs.statSync) };+});+vi.mock("../whisper/transcribe.js", () => ({transcribe: transcribeMock,prepareWav: (input: string) => prepareWavMock(input),@@ -585,6 +594,10 @@ echo '{"sentences":[{"tokens":[{"text":" hola","start":0,"end":1}]}]}' > "$2/$(bdirs.push(dir);await transcribeCmd.run!({ args: { input, json: true, engine: "auto" } } as never);expect(lastJson()).toMatchObject({ ok: true, engine: "parakeet", wordCount: 0 });++ await transcribeCmd.run!({ args: { input, json: true, engine: "auto", to: "srt" } } as never);+ expect(lastJson()).toMatchObject({ ok: true, wordCount: 0, format: "srt" });+ expect(readFileSync(join(dir, "transcript.srt"), "utf-8")).toBe("");});it.runIf(process.platform === "linux" && process.arch === "x64")(@@ -639,6 +652,357 @@ Render video. Built for agents.});});+ it("transcribes a media file straight to a VTT sidecar in one run", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const words = [+ { id: "w0", text: "Write", start: 0, end: 0.5 },+ { id: "w1", text: "HTML.", start: 0.5, end: 1 },+ ];+ transcribeMock.mockImplementation(async (_input, outputDir) => {+ const result = fakeTranscript(outputDir, "whisper");+ writeFileSync(result.transcriptPath, JSON.stringify(words));+ return { ...result, wordCount: 2 };+ });++ await runCommand(transcribeCmd, {+ rawArgs: [input, "--dir", dir, "--engine", "whisper", "--to", "vtt", "--json"],+ });++ const outputPath = join(dir, "transcript.vtt");+ expect(readFileSync(outputPath, "utf-8")).toBe(formatVtt(words));+ expect(JSON.parse(readFileSync(join(dir, "transcript.json"), "utf8"))).toEqual(words);+ expect(console.log).toHaveBeenCalledTimes(1);+ expect(lastJson()).toMatchObject({ ok: true, wordCount: 2, format: "vtt", outputPath });+ });++ it("fails on a missing --output folder before transcribing", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const output = join(dir, "missing", "captions.srt");++ await expect(+ transcribeCmd.run!({+ args: { input, json: true, engine: "whisper", to: "srt", output },+ } as never),+ ).rejects.toThrow(CliRuntimeError);++ expect(transcribeMock).not.toHaveBeenCalled();+ expect(lastJson()).toEqual({+ ok: false,+ error: `Output folder not found: ${join(dir, "missing")}`,+ });+ });++ it.each([+ ["an existing folder", (dir: string) => dir, "--output is a folder"],+ [+ "a path ending in a slash",+ (dir: string) => join(dir, "captions") + "/",+ "--output is a folder",+ ],+ [+ "a path under a file",+ (dir: string) => join(dir, "narration.wav", "out.srt"),+ "Output folder not found",+ ],+ ["the input media", (dir: string) => join(dir, "narration.wav"), "would overwrite"],+ ["the transcript it writes", (dir: string) => join(dir, "transcript.json"), "would overwrite"],+ [+ "a link to the input media",+ (dir: string) => {+ symlinkSync(join(dir, "narration.wav"), join(dir, "link.wav"));+ return join(dir, "link.wav");+ },+ "would overwrite",+ ],+ [+ "the transcript through a linked folder",+ (dir: string) => {+ symlinkSync(dir, join(dir, "alias"), "dir");+ return join(dir, "alias", "transcript.json");+ },+ "would overwrite",+ ],+ [+ "the input media by its real path",+ (dir: string) => join(realpathSync(dir), "narration.wav"),+ "would overwrite",+ ],+ [+ "the transcript by its real path",+ (dir: string) => join(realpathSync(dir), "transcript.json"),+ "would overwrite",+ ],+ [+ "the transcript in other letter case",+ (dir: string) => join(dir, "Transcript.json"),+ "would overwrite",+ ],+ ])("fails --output naming %s before transcribing", async (_name, output, error) => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);++ await expect(+ transcribeCmd.run!({+ args: { input, json: true, engine: "whisper", to: "srt", output: output(dir) },+ } as never),+ ).rejects.toThrow(CliRuntimeError);++ expect(transcribeMock).not.toHaveBeenCalled();+ expect(lastJson()).toMatchObject({ ok: false, error: expect.stringContaining(error) });+ });++ it("refuses --output naming the input media in other letter case on any disk", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const output = join(dir, "NARRATION.WAV");+ // Case-insensitive disks alias the name to the media (same inode); case-sensitive ones do not.+ if (existsSync(output)) expect(statSync(output).ino).toBe(statSync(input).ino);++ await expect(+ transcribeCmd.run!({+ args: { input, json: true, engine: "whisper", to: "srt", output },+ } as never),+ ).rejects.toThrow(CliRuntimeError);++ expect(transcribeMock).not.toHaveBeenCalled();+ expect(lastJson()).toMatchObject({+ ok: false,+ error: expect.stringContaining("would overwrite"),+ });+ expect(readFileSync(input, "utf8")).toBe("not-real-audio");+ });++ it("refuses the transcript under an upper-cased folder spelling on a first run", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const upper = join(dirname(dir), basename(dir).toUpperCase());+ const caseInsensitive = existsSync(upper);++ await expect(+ transcribeCmd.run!({+ args: {+ input,+ json: true,+ engine: "whisper",+ to: "srt",+ output: join(upper, "transcript.json"),+ },+ } as never),+ ).rejects.toThrow(CliRuntimeError);++ expect(transcribeMock).not.toHaveBeenCalled();+ // Only a case-insensitive disk has the upper-cased folder; elsewhere it is simply missing.+ const error = caseInsensitive ? "would overwrite" : "Output folder not found";+ expect(lastJson()).toMatchObject({ ok: false, error: expect.stringContaining(error) });+ });++ it("refuses an export whose default caption path is its own input", async () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-transcribe-test-"));+ dirs.push(dir);+ const input = join(dir, "transcript.srt");+ const srt = "1\n00:00:00,000 --> 00:00:01,000\n<i>Hello</i>\n";+ writeFileSync(input, srt);++ await expect(+ transcribeCmd.run!({ args: { input, json: true, to: "srt" } } as never),+ ).rejects.toThrow(CliRuntimeError);++ expect(lastJson()).toMatchObject({+ ok: false,+ error: expect.stringContaining("would overwrite"),+ });+ expect(readFileSync(input, "utf8")).toBe(srt);+ });++ it("says why an export's caption file could not be written", async () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-transcribe-test-"));+ dirs.push(dir);+ const input = join(dir, "subtitles.srt");+ writeFileSync(input, "1\n00:00:00,000 --> 00:00:01,000\nHello\n");+ const output = join(dir, "through-file.vtt");+ symlinkSync(join(input, "x.vtt"), output);++ await expect(+ transcribeCmd.run!({ args: { input, json: true, to: "vtt", output } } as never),+ ).rejects.toThrow(CliRuntimeError);++ expect(lastJson()).toMatchObject({+ ok: false,+ error: expect.stringContaining(`The caption file ${output} could not be written: `),+ });+ // Windows and Unix report a path through a file with different error codes.+ expect(lastJson().error).toMatch(/ENOTDIR|ENOENT/);+ });++ async function runWithInodeZero(zero: (path: string) => boolean, args: object): Promise<void> {+ const fs = await vi.importActual<typeof import("node:fs")>("node:fs");+ vi.mocked(statSync).mockImplementation(((path: string, options?: object) => {+ const stats = fs.statSync(path, options);+ return zero(String(path)) ? Object.assign(stats, { ino: 0n }) : stats;+ }) as unknown as typeof statSync);+ transcribeMock.mockImplementation(async (_input, outputDir) =>+ fakeTranscript(outputDir, "whisper"),+ );+ try {+ await transcribeCmd.run!({ args } as never);+ } catch (err) {+ if (!(err instanceof CliRuntimeError)) throw err;+ } finally {+ vi.mocked(statSync).mockImplementation(fs.statSync);+ }+ }++ it("does not call two different files the same when the disk reports inode 0", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const output = join(dir, "captions.srt");+ writeFileSync(output, "old captions");++ await runWithInodeZero(() => true, { input, json: true, engine: "whisper", to: "srt", output });++ expect(lastJson()).toMatchObject({ ok: true, outputPath: output });+ expect(readFileSync(output, "utf8")).toContain("-->");+ });++ it.each([+ ["the media", "every path", "would overwrite"],+ ["the media", "the caption path only", "would overwrite"],+ ["the media", "the media only", "would overwrite"],+ ["the transcript", "every path", "it is the same file as"],+ ["the transcript", "the caption path only", "it is the same file as"],+ ["the transcript", "the transcript only", "it is the same file as"],+ ])("refuses a link to %s when %s reports inode 0", async (target, zeroed, error) => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const kept = target === "the media" ? input : join(dir, "transcript.json");+ const output = join(dir, "link.srt");+ symlinkSync(kept, output);+ const zeroPath = zeroed === "the caption path only" ? output : kept;++ await runWithInodeZero((path) => zeroed === "every path" || path === zeroPath, {+ input,+ json: true,+ engine: "whisper",+ to: "srt",+ output,+ });++ expect(lastJson()).toMatchObject({ ok: false, error: expect.stringContaining(error) });+ expect(readFileSync(kept, "utf8")).not.toContain("-->");+ });++ it("fails a trailing -o with no path before transcribing", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);++ await expect(+ runCommand(transcribeCmd, { rawArgs: [input, "--to", "srt", "--json", "-o"] }),+ ).rejects.toThrow(CliRuntimeError);++ expect(transcribeMock).not.toHaveBeenCalled();+ expect(lastJson()).toEqual({ ok: false, error: "--output needs a file path" });+ });++ it.each([+ [+ "a link to the transcript it is about to write",+ (dir: string) => {+ symlinkSync(join(dir, "transcript.json"), join(dir, "dangling.srt"));+ return join(dir, "dangling.srt");+ },+ "it is the same file as",+ ],+ [+ "a relative link to it inside a linked folder",+ (dir: string) => {+ mkdirSync(join(dir, "sub"));+ symlinkSync("../transcript.json", join(dir, "sub", "cap.srt"));+ symlinkSync(join(dir, "sub"), join(dir, "lnk"), "dir");+ return join(dir, "lnk", "cap.srt");+ },+ "it is the same file as",+ ],+ [+ "a link that runs through a file",+ (dir: string) => {+ symlinkSync(join(dir, "narration.wav", "x.srt"), join(dir, "through-file.srt"));+ return join(dir, "through-file.srt");+ },+ /ENOTDIR|ENOENT/,+ ],+ ])("keeps the transcript when --output is %s", async (_name, output, reason) => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const transcript = join(dir, "transcript.json");+ const caption = output(dir);+ transcribeMock.mockImplementation(async (_input, outputDir) =>+ fakeTranscript(outputDir, "whisper"),+ );++ await transcribeCmd.run!({+ args: { input, json: true, engine: "whisper", to: "srt", output: caption },+ } as never);++ expect(consumeCommandResult().exitCode).toBe(1);+ expect(lastJson()).toMatchObject({+ ok: false,+ error: expect.stringContaining(+ `Transcript saved to ${transcript}, but the caption file ${caption} could not be written: `,+ ),+ });+ expect(lastJson().error).toMatch(reason);+ expect(JSON.parse(readFileSync(transcript, "utf8"))).toMatchObject([{ text: "whisper" }]);+ });++ it("says the transcript was saved when the caption file cannot be written", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ const output = join(dir, "captions.srt");+ transcribeMock.mockImplementation(async (_input, outputDir) => {+ // A folder at the caption path makes the write fail on any OS, even as root.+ mkdirSync(output);+ return fakeTranscript(outputDir, "whisper");+ });++ await transcribeCmd.run!({+ args: { input, json: true, engine: "whisper", to: "srt", output },+ } as never);++ expect(consumeCommandResult().exitCode).toBe(1);+ expect(lastJson()).toMatchObject({+ ok: false,+ error: expect.stringContaining(+ `Transcript saved to ${join(dir, "transcript.json")}, but the caption file ${output} could not be written: `,+ ),+ });+ expect(existsSync(join(dir, "transcript.json"))).toBe(true);+ });++ it("groups transcribed CJK words into captions instead of one cue per word", async () => {+ const { dir, input } = dummyAudio();+ dirs.push(dir);+ transcribeMock.mockImplementation(async (_input, outputDir) => {+ const result = fakeTranscript(outputDir, "whisper");+ writeFileSync(+ result.transcriptPath,+ JSON.stringify([+ { text: "今日はいい", start: 0, end: 0.8 },+ { text: "天気ですね", start: 0.8, end: 1.6 },+ ]),+ );+ return { ...result, wordCount: 2 };+ });++ await transcribeCmd.run!({+ args: { input, dir, json: true, engine: "whisper", to: "srt" },+ } as never);++ const { words: cues } = loadTranscript(join(dir, "transcript.srt"));+ expect(cues.map((cue) => cue.text)).toEqual(["今日はいい天気ですね"]);+ });+it("rejects a below-minimum --timeout with a discoverable error", async () => {const { dir, input } = dummyAudio();dirs.push(dir);diff --git a/packages/cli/src/commands/transcribe.ts b/packages/cli/src/commands/transcribe.tsindex 0f2bde7892..5bfe97fb61 100644--- a/packages/cli/src/commands/transcribe.ts+++ b/packages/cli/src/commands/transcribe.ts@@ -4,7 +4,7 @@ import { normalizeErrorMessage } from "../utils/errorMessage.js";// fallow-ignore-file code-duplicationimport { defineCommand } from "citty";import type { Example } from "./_examples.js";-import { existsSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";import {PARAKEET_INSTALL_COMMAND,PARAKEET_LANGUAGES,@@ -13,6 +13,13 @@ import {} from "../whisper/parakeet.js";type CaptionExportFormat = "srt" | "vtt";+type CaptionSidecar = {+ to: CaptionExportFormat;+ outPath: string;+ preserveCues: boolean;+ /** Files the caption write must never replace: the input and the transcript. */+ keep: string[];+};export const examples: Example[] = [["Transcribe an audio file", "hyperframes transcribe audio.mp3"],@@ -22,15 +29,18 @@ export const examples: Example[] = [["Import an existing SRT file", "hyperframes transcribe subtitles.srt"],["Import an OpenAI Whisper JSON response", "hyperframes transcribe response.json"],["Export captions to SRT", "hyperframes transcribe transcript.json --to srt"],+ ["Transcribe a video straight to VTT captions", "hyperframes transcribe video.mp4 --to vtt"],["Export single-word/CJK captions without re-grouping","hyperframes transcribe transcript.json --to vtt --preserve-cues",],];-import { resolve, join, extname, dirname } from "node:path";+import { resolve, join, extname, dirname, basename } from "node:path";import * as clack from "@clack/prompts";import { c } from "../ui/colors.js";import { DEFAULT_MODEL, isWhisperUnavailable } from "../whisper/manager.js";+import { TRANSCRIPT_FILE } from "../whisper/transcriptFile.js";+import type { Word } from "../whisper/normalize.js";import type { ParakeetRunner } from "../whisper/parakeetRunner.js";// Minimum accepted value for `--timeout` / `HYPERFRAMES_TRANSCRIBE_TIMEOUT_MS`.@@ -84,7 +94,8 @@ export default defineCommand({},to: {type: "string",- description: "Export transcript sidecar format: srt or vtt",+ description:+ "Write an srt or vtt caption sidecar: exported from a transcript file, or written after transcribing audio/video",},output: {type: "string",@@ -136,16 +147,10 @@ export default defineCommand({// ── Import mode: convert existing transcript ──────────────────────────const isImport = ext === ".json" || ext === ".srt" || ext === ".vtt";- const to = parseExportFormat(args.to, args.json);+ const sidecar = parseSidecar(args, inputPath, dir);- if (to) {- if (!isImport) {- failWith(- "--to can only export from transcript files (.json, .srt, .vtt). Run transcribe first.",- args.json,- );- }- return exportTranscript(inputPath, dir, to, args.output, args.json, args["preserve-cues"]);+ if (sidecar && isImport) {+ return exportTranscript(inputPath, sidecar, args.json);}if (isImport) {@@ -163,6 +168,7 @@ export default defineCommand({optional: args.optional,installRuntime: args["runtime-install"],timeoutMs,+ sidecar,});},});@@ -210,6 +216,60 @@ function parseExportFormat(failWith(`Unsupported caption export format: ${value}. Use srt or vtt.`, json);}+function parseSidecar(+ args: { to?: string; output?: string; "preserve-cues": boolean; json: boolean },+ inputPath: string,+ dir: string,+): CaptionSidecar | undefined {+ const to = parseExportFormat(args.to, args.json);+ if (!to) return undefined;+ const outPath = resolve(args.output ?? join(dir, `transcript.${to}`));+ const keep = [inputPath, join(dir, TRANSCRIPT_FILE)];+ const problem =+ (args.output !== undefined && outputProblem(args.output, outPath, to)) ||+ overwriteProblem(outPath, keep);+ if (problem) failWith(problem, args.json);+ return { to, outPath, preserveCues: args["preserve-cues"], keep };+}++/** Why an explicit --output cannot be used, checked before any transcription work. */+function outputProblem(+ output: string,+ outPath: string,+ to: CaptionExportFormat,+): string | undefined {+ if (!output) return "--output needs a file path";+ const folder = dirname(outPath);+ if (!existsSync(folder) || !statSync(folder).isDirectory()) {+ return `Output folder not found: ${folder}`;+ }+ if (/[\\/]$/.test(output) || (existsSync(outPath) && statSync(outPath).isDirectory())) {+ return `--output is a folder; give a file path such as ${join(outPath, `transcript.${to}`)}`;+ }+ return undefined;+}++/** Early refusal before the engine runs; the same check at write time is the owner. */+function overwriteProblem(outPath: string, keep: string[]): string | undefined {+ const hit = keep.find((file) => sameFile(outPath, file));+ return hit && `The caption file would overwrite ${hit}; choose another file with --output`;+}++function sameFile(out: string, file: string): boolean {+ if (existsSync(out) && existsSync(file)) {+ const [a, b] = [statSync(out, { bigint: true }), statSync(file, { bigint: true })];+ if (a.ino !== 0n && b.ino !== 0n) return a.dev === b.dev && a.ino === b.ino;+ // Some network shares report inode 0, which proves nothing; let the OS resolve the paths.+ return realpathSync.native(out) === realpathSync.native(file);+ }+ // Letter case is ignored so a case-insensitive disk cannot alias.+ const realDir = (p: string) =>+ existsSync(dirname(p)) ? realpathSync.native(dirname(p)) : dirname(p);+ return (+ realDir(out) === realDir(file) && basename(out).toLowerCase() === basename(file).toLowerCase()+ );+}+// ---------------------------------------------------------------------------// Import existing transcript// ---------------------------------------------------------------------------@@ -224,7 +284,7 @@ async function importTranscript(inputPath: string, dir: string, json: boolean):if (words.length === 0) exitNoWords(json);- const outPath = join(dir, "transcript.json");+ const outPath = join(dir, TRANSCRIPT_FILE);writeFileSync(outPath, JSON.stringify(words, null, 2));patchCaptionHtml(dir, words);@@ -243,37 +303,62 @@ async function importTranscript(inputPath: string, dir: string, json: boolean):// Export transcript sidecars// ----------------------------------------------------------------------------async function exportTranscript(- inputPath: string,- dir: string,- to: CaptionExportFormat,- output: string | undefined,- json: boolean,- preserveCues: boolean,+async function writeCaptionSidecar(+ words: Word[],+ { to, outPath, preserveCues, keep }: CaptionSidecar,+ phraseLevelSource: boolean | undefined,): Promise<void> {- const { loadTranscript, formatSrt, formatVtt } = await import("../whisper/normalize.js");- const { words, format } = loadTranscript(inputPath);-- if (words.length === 0) exitNoWords(json);-+ // Checked at write time, when the transcript exists, so the OS resolves every link and alias.+ const hit = keep.find((file) => sameFile(outPath, file));+ if (hit) throw new Error(`it is the same file as ${hit}`);+ const { formatSrt, formatVtt } = await import("../whisper/normalize.js");// A .srt/.vtt source is already phrase-level; keep its cue boundaries 1:1.// --preserve-cues forces the same for an already-cued transcript.json whose// entries have no internal whitespace (single-word or CJK captions), which// the automatic whitespace heuristic in wordsToCues can't detect.- const preGrouped = preserveCues || format === "srt" || format === "vtt" || undefined;- const outPath = resolve(output ?? join(dir, `transcript.${to}`));+ const preGrouped = preserveCues || phraseLevelSource;const content =to === "srt" ? formatSrt(words, { preGrouped }) : formatVtt(words, { preGrouped });writeFileSync(outPath, content);+}++function reportSidecar(to: CaptionExportFormat, wordCount: number, outPath: string): void {+ console.log(+ `${c.success("◇")} Exported ${c.accent(String(wordCount))} words to ${c.accent(to.toUpperCase())} → ${c.accent(outPath)}`,+ );+}++async function exportTranscript(+ inputPath: string,+ sidecar: CaptionSidecar,+ json: boolean,+): Promise<void> {+ const { loadTranscript } = await import("../whisper/normalize.js");+ const { words, format } = loadTranscript(inputPath);++ if (words.length === 0) exitNoWords(json);++ const { outPath } = sidecar;+ try {+ await writeCaptionSidecar(words, sidecar, format === "srt" || format === "vtt" || undefined);+ } catch (err) {+ failWith(+ `The caption file ${outPath} could not be written: ${normalizeErrorMessage(err)}`,+ json,+ );+ }if (json) {console.log(- JSON.stringify({ ok: true, format: to, wordCount: words.length, outputPath: outPath }),+ JSON.stringify({+ ok: true,+ format: sidecar.to,+ wordCount: words.length,+ outputPath: outPath,+ }),);} else {- console.log(- `${c.success("◇")} Exported ${c.accent(String(words.length))} words to ${c.accent(to.toUpperCase())} → ${c.accent(outPath)}`,- );+ reportSidecar(sidecar.to, words.length, outPath);}}@@ -308,6 +393,7 @@ async function transcribeAudio(optional?: boolean;installRuntime?: boolean;timeoutMs?: number;+ sidecar?: CaptionSidecar;},): Promise<void> {const { transcribe } = await import("../whisper/transcribe.js");@@ -415,6 +501,19 @@ async function transcribeAudio(writeFileSync(result.transcriptPath, JSON.stringify(words, null, 2));patchCaptionHtml(dir, words);+ const { sidecar } = opts;+ if (sidecar) {+ try {+ await writeCaptionSidecar(words, sidecar, false);+ } catch (err) {+ const message = `Transcript saved to ${result.transcriptPath}, but the caption file ${sidecar.outPath} could not be written: ${normalizeErrorMessage(err)}`;+ if (opts.json) console.log(JSON.stringify({ ok: false, error: message }));+ else spin?.stop(c.error(message));+ setCommandExitCode(1);+ return;+ }+ }+ const exported = sidecar && { format: sidecar.to, outputPath: sidecar.outPath };if (opts.json) {console.log(@@ -427,6 +526,7 @@ async function transcribeAudio(durationSeconds: result.durationSeconds,speechOnsetSeconds: result.speechOnsetSeconds,transcriptPath: result.transcriptPath,+ ...exported,}),);} else {@@ -439,6 +539,7 @@ async function transcribeAudio(`Transcribed ${c.accent(String(words.length))} words (${result.durationSeconds.toFixed(1)}s${onsetNote})`,),);+ if (exported) reportSidecar(exported.format, words.length, exported.outputPath);}} catch (err) {if (err instanceof DecodeCancelled || cancellation?.signal.aborted) {diff --git a/packages/cli/src/whisper/parakeet.ts b/packages/cli/src/whisper/parakeet.tsindex a46eb780a8..095f470fee 100644--- a/packages/cli/src/whisper/parakeet.ts+++ b/packages/cli/src/whisper/parakeet.ts@@ -17,6 +17,7 @@ import { execFileSync } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { basename, extname, join } from "node:path";+import { TRANSCRIPT_FILE } from "./transcriptFile.js";import type { Word } from "./normalize.js";import type { TranscribeProgress, TranscribeResult } from "./transcribe.js";@@ -330,7 +331,7 @@ export function transcribeWithParakeet(export function writeParakeetTranscript(dir: string, words: Word[]): TranscribeResult {mkdirSync(dir, { recursive: true });- const transcriptPath = join(dir, "transcript.json");+ const transcriptPath = join(dir, TRANSCRIPT_FILE);writeFileSync(transcriptPath, JSON.stringify(words, null, 2));const durationSeconds = words.length > 0 ? words[words.length - 1]!.end : 0;return {diff --git a/packages/cli/src/whisper/transcribe.ts b/packages/cli/src/whisper/transcribe.tsindex caac298f65..8e1fc8b9e3 100644--- a/packages/cli/src/whisper/transcribe.ts+++ b/packages/cli/src/whisper/transcribe.ts@@ -4,12 +4,13 @@ import { once } from "node:events";import { createInterface } from "node:readline";import type { Readable } from "node:stream";import { existsSync, readFileSync, mkdirSync, rmSync, statSync, unlinkSync } from "node:fs";-import { join, extname } from "node:path";+import { basename, join, extname } from "node:path";import { tmpdir } from "node:os";import { randomUUID } from "node:crypto";import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";import { stoppedByCancelSignal } from "../utils/renderCancellation.js";import { ensureWhisper, ensureModel, hasFFmpeg, DEFAULT_MODEL } from "./manager.js";+import { TRANSCRIPT_FILE } from "./transcriptFile.js";import { findWavChunk } from "./wav.js";import type { Word } from "./normalize.js";import { emitWords } from "./progress.js";@@ -483,7 +484,7 @@ export async function transcribe(status: "started",durationSeconds: wavSeconds,});- const outputBase = join(outputDir, "transcript");+ const outputBase = join(outputDir, basename(TRANSCRIPT_FILE, ".json"));mkdirSync(outputDir, { recursive: true });const whisperArgs = [diff --git a/packages/cli/src/whisper/transcriptFile.ts b/packages/cli/src/whisper/transcriptFile.tsnew file mode 100644index 0000000000..e0304ffc93--- /dev/null+++ b/packages/cli/src/whisper/transcriptFile.ts@@ -0,0 +1 @@+export const TRANSCRIPT_FILE = "transcript.json";