11import { existsSync , realpathSync , rmSync , statSync , writeFileSync } from "node:fs" ;
22import { basename , dirname , extname , join , resolve } from "node:path" ;
33import { normalizeErrorMessage } from "../utils/errorMessage.js" ;
4+ import {
5+ createRenderCancellationScope ,
6+ stoppedByCancelSignal ,
7+ } from "../utils/renderCancellation.js" ;
48import { DEFAULT_MODEL , isWhisperUnavailable } from "../whisper/manager.js" ;
9+ import { initialModelForLanguage } from "../whisper/modelForLanguage.js" ;
10+ import {
11+ formatSrt ,
12+ formatVtt ,
13+ loadTranscript ,
14+ patchCaptionHtml ,
15+ type TranscriptFormat ,
16+ type Word ,
17+ } from "../whisper/normalize.js" ;
518import {
619 PARAKEET_INSTALL_COMMAND ,
720 PARAKEET_LANGUAGES ,
821 parakeetSpeaks ,
922 transcribeWithParakeet ,
1023} from "../whisper/parakeet.js" ;
24+ import { parakeetRunner , type ParakeetRunner } from "../whisper/parakeetRunner.js" ;
25+ import {
26+ DecodeCancelled ,
27+ prepareSherpaWav ,
28+ sherpaUnsupportedReason ,
29+ transcribeWithSherpa ,
30+ } from "../whisper/sherpa.js" ;
1131import { TRANSCRIPT_FILE } from "../whisper/transcriptFile.js" ;
12- import type { TranscriptFormat , Word } from "../whisper/normalize.js" ;
13- import type { ParakeetRunner } from "../whisper/parakeetRunner.js" ;
14- import type { TranscribeProgress } from "../whisper/transcribe.js" ;
32+ import {
33+ transcribe as transcribeWithWhisper ,
34+ type TranscribeProgress ,
35+ } from "../whisper/transcribe.js" ;
1536
1637// Smallest accepted whisper timeout. Below it the whisper spawn has no realistic chance of
17- // finishing even on the fastest hardware for the shortest clip. This module never imports
18- // `whisper/transcribe.ts` at the top level, so the command test can hoist its
19- // `vi.mock("../whisper/transcribe.js")` factory without that module entering the sync-import graph.
38+ // finishing even on the fastest hardware for the shortest clip.
2039export const MIN_TIMEOUT_MS = 5000 ;
2140
2241export type TranscribeEngine = "auto" | "parakeet" | "whisper" ;
@@ -37,7 +56,7 @@ export interface TranscribeCaptionsOptions {
3756export interface TranscribeEngineEvent {
3857 runner : TranscribeRunner ;
3958 engine : "parakeet" | "whisper" ;
40- /** The whisper model; meaningful only when `engine` is " whisper" . */
59+ /** The model whisper runs, after `language` picks the multilingual twin; whisper engine only . */
4160 model : string ;
4261 /** Set when auto mode gave up on Parakeet and this runner takes over. */
4362 fallbackReason ?: string ;
@@ -140,6 +159,11 @@ interface CancellationScope {
140159}
141160
142161export async function runTranscribe ( options : TranscribeRequest ) : Promise < TranscribeResult > {
162+ if ( options . signal ?. aborted ) {
163+ throw new TranscribeError ( "cancelled" , "Transcription cancelled" , {
164+ cause : options . signal . reason ,
165+ } ) ;
166+ }
143167 const inputPath = resolve ( options . input ) ;
144168 if ( ! existsSync ( inputPath ) ) {
145169 throw new TranscribeError ( "input_not_found" , `File not found: ${ options . input } ` ) ;
@@ -229,10 +253,7 @@ function sameFile(out: string, file: string): boolean {
229253// Import and export existing transcripts
230254// ---------------------------------------------------------------------------
231255
232- async function readTranscript (
233- inputPath : string ,
234- ) : Promise < { words : Word [ ] ; format : TranscriptFormat } > {
235- const { loadTranscript } = await import ( "../whisper/normalize.js" ) ;
256+ function readTranscript ( inputPath : string ) : { words : Word [ ] ; format : TranscriptFormat } {
236257 let transcript : { words : Word [ ] ; format : TranscriptFormat } ;
237258 try {
238259 transcript = loadTranscript ( inputPath ) ;
@@ -245,23 +266,19 @@ async function readTranscript(
245266 return transcript ;
246267}
247268
248- async function importTranscript ( inputPath : string , dir : string ) : Promise < TranscribeResult > {
249- const { patchCaptionHtml } = await import ( "../whisper/normalize.js" ) ;
250- const { words, format } = await readTranscript ( inputPath ) ;
269+ function importTranscript ( inputPath : string , dir : string ) : TranscribeResult {
270+ const { words, format } = readTranscript ( inputPath ) ;
251271
252272 const transcriptPath = join ( dir , TRANSCRIPT_FILE ) ;
253273 writeFileSync ( transcriptPath , JSON . stringify ( words , null , 2 ) ) ;
254274 patchCaptionHtml ( dir , words ) ;
255275 return { kind : "imported" , format, wordCount : words . length , transcriptPath } ;
256276}
257277
258- async function exportTranscript (
259- inputPath : string ,
260- sidecar : CaptionSidecar ,
261- ) : Promise < TranscribeResult > {
262- const { words, format } = await readTranscript ( inputPath ) ;
278+ function exportTranscript ( inputPath : string , sidecar : CaptionSidecar ) : TranscribeResult {
279+ const { words, format } = readTranscript ( inputPath ) ;
263280 try {
264- await writeCaptionSidecar ( words , sidecar , format === "srt" || format === "vtt" || undefined ) ;
281+ writeCaptionSidecar ( words , sidecar , format === "srt" || format === "vtt" || undefined ) ;
265282 } catch ( err ) {
266283 throw new TranscribeError (
267284 "caption_write_failed" ,
@@ -277,15 +294,14 @@ async function exportTranscript(
277294 } ;
278295}
279296
280- async function writeCaptionSidecar (
297+ function writeCaptionSidecar (
281298 words : Word [ ] ,
282299 { to, outPath, preserveCues, keep } : CaptionSidecar ,
283300 phraseLevelSource : boolean | undefined ,
284- ) : Promise < void > {
301+ ) : void {
285302 // Checked at write time, when the transcript exists, so the OS resolves every link and alias.
286303 const hit = keep . find ( ( file ) => sameFile ( outPath , file ) ) ;
287304 if ( hit ) throw new Error ( `it is the same file as ${ hit } ` ) ;
288- const { formatSrt, formatVtt } = await import ( "../whisper/normalize.js" ) ;
289305 // A .srt/.vtt source is already phrase-level; keep its cue boundaries 1:1.
290306 // preserveCues forces the same for an already-cued transcript.json whose
291307 // entries have no internal whitespace (single-word or CJK captions), which
@@ -344,15 +360,6 @@ async function transcribeAudio(
344360 sidecar : CaptionSidecar | undefined ,
345361 options : TranscribeRequest ,
346362) : Promise < TranscribeResult > {
347- const { transcribe } = await import ( "../whisper/transcribe.js" ) ;
348- const { loadTranscript, patchCaptionHtml } = await import ( "../whisper/normalize.js" ) ;
349-
350- const { DecodeCancelled, prepareSherpaWav, sherpaUnsupportedReason, transcribeWithSherpa } =
351- await import ( "../whisper/sherpa.js" ) ;
352- const { parakeetRunner } = await import ( "../whisper/parakeetRunner.js" ) ;
353- const { createRenderCancellationScope, stoppedByCancelSignal } =
354- await import ( "../utils/renderCancellation.js" ) ;
355-
356363 const engine = ( options . engine ?? "auto" ) . toLowerCase ( ) ;
357364 if ( engine !== "auto" && engine !== "parakeet" && engine !== "whisper" ) {
358365 throw new TranscribeError (
@@ -373,15 +380,17 @@ async function transcribeAudio(
373380 }
374381
375382 const model = options . model ?? DEFAULT_MODEL ;
376- options . onEngine ?.( { runner, engine : engineOf ( runner ) , model } ) ;
383+ const whisperModel = initialModelForLanguage ( model , options . language ) ;
384+ options . onEngine ?.( { runner, engine : engineOf ( runner ) , model : whisperModel } ) ;
377385 const { onStatus, onProgress } = options ;
378386 const startScope = ( ) : CancellationScope =>
379387 options . stopOnProcessSignals
380388 ? createRenderCancellationScope ( )
381389 : { signal : options . signal ?? new AbortController ( ) . signal , dispose : ( ) => { } } ;
382390 let wavPath = inputPath ;
383391 // Before audio prep: under --json no spinner listens for SIGINT, so Ctrl-C would kill Node.
384- let cancellation = runner === "sherpa" ? startScope ( ) : null ;
392+ // A caller's own signal is live from the start, whichever runner it ends up stopping.
393+ let cancellation = runner === "sherpa" || ! options . stopOnProcessSignals ? startScope ( ) : null ;
385394 const run = ( r : TranscribeRunner ) => {
386395 switch ( r ) {
387396 case "sherpa" :
@@ -394,15 +403,17 @@ async function transcribeAudio(
394403 return transcribeWithParakeet ( wavPath , dir , {
395404 onProgress : onStatus ,
396405 onEvent : onProgress ,
406+ signal : cancellation ?. signal ,
397407 } ) ;
398408 case "whisper" :
399- return transcribe ( wavPath , dir , {
409+ return transcribeWithWhisper ( wavPath , dir , {
400410 model,
401411 language : options . language ,
402412 onProgress : onStatus ,
403413 onEvent : onProgress ,
404414 timeoutMs : options . timeoutMs ,
405415 installRuntime : options . installRuntime ,
416+ signal : cancellation ?. signal ,
406417 startCancellation : ( ) => ( cancellation ??= startScope ( ) ) . signal ,
407418 } ) ;
408419 default : {
@@ -431,7 +442,7 @@ async function transcribeAudio(
431442 options . onEngine ?.( {
432443 runner,
433444 engine : engineOf ( runner ) ,
434- model,
445+ model : whisperModel ,
435446 fallbackReason : parakeetError ,
436447 } ) ;
437448 try {
@@ -452,7 +463,7 @@ async function transcribeAudio(
452463 patchCaptionHtml ( dir , words ) ;
453464 if ( sidecar ) {
454465 try {
455- await writeCaptionSidecar ( words , sidecar , false ) ;
466+ writeCaptionSidecar ( words , sidecar , false ) ;
456467 } catch ( err ) {
457468 throw new TranscribeError (
458469 "caption_write_failed" ,
0 commit comments