whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Whisper inference. The C motor never writes to stdout.
//!
//! Request and output types live outside `cfg(feature)` on purpose: the
//! default build must still type-check every caller. Types hidden behind a
//! feature gate let API drift accumulate unseen until someone builds with it.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;

use crate::error::Error;
use crate::output::Segment;

/// Speech language codes accepted by the Whisper models, plus `auto`.
///
/// Mirrors `whisper_lang_str` from whisper.cpp. It is duplicated in pure Rust
/// so a bad `--language` is rejected with exit 2 on a host with no GPU and no
/// native feature compiled in.
pub const LANGUAGES: &[&str] = &[
    "auto", "en", "zh", "de", "es", "ru", "ko", "fr", "ja", "pt", "tr", "pl", "ca", "nl", "ar",
    "sv", "it", "id", "hi", "fi", "vi", "he", "uk", "el", "ms", "cs", "ro", "da", "hu", "ta", "no",
    "th", "ur", "hr", "bg", "lt", "la", "mi", "ml", "cy", "sk", "te", "fa", "lv", "bn", "sr", "az",
    "sl", "kn", "et", "mk", "br", "eu", "is", "hy", "ne", "mn", "bs", "kk", "sq", "sw", "gl", "mr",
    "pa", "si", "km", "sn", "yo", "so", "af", "oc", "ka", "be", "tg", "sd", "gu", "am", "yi", "lo",
    "uz", "fo", "ht", "ps", "tk", "nn", "mt", "sa", "lb", "my", "bo", "tl", "mg", "as", "tt",
    "haw", "ln", "ha", "ba", "jw", "su", "yue",
];

/// True when the code is a language the engine can be asked for.
pub fn is_known_language(code: &str) -> bool {
    LANGUAGES.contains(&code)
}

/// One inference request. A named struct keeps callers from swapping
/// same-typed positional arguments by accident.
#[derive(Debug, Clone, Copy)]
pub struct TranscribeRequest<'a> {
    /// Cached model file.
    pub model_path: &'a Path,
    /// 16 kHz mono samples.
    pub samples: &'a [f32],
    /// Requested language, or `auto` to detect.
    pub language: &'a str,
    /// Beam width already validated against the accepted range.
    pub beam: i32,
    /// GPU index the context must bind to.
    pub device: u32,
    /// Hard deadline enforced during inference, not only around it.
    pub deadline: Option<Instant>,
}

/// Result of one engine pass.
#[derive(Debug, Clone)]
pub struct EngineOutput {
    /// Whole transcript, with the segments joined.
    pub text: String,
    /// Timestamped pieces the transcript was built from.
    pub segments: Vec<Segment>,
    /// Language actually used: the request, or what detection resolved.
    pub language: String,
    /// True when `auto` was resolved by the model rather than echoed back.
    pub language_detected: bool,
    /// True when this pass paid for building the model context.
    ///
    /// Reported by the engine, never guessed by the scheduler: only the engine
    /// knows whether the weights were loaded or reused.
    pub cold_load: bool,
}

/// Key of one loaded model context.
///
/// Allowed to be unused in the default build: the cache only has a client when
/// a native feature is on, but the policy below is tested in every build so it
/// cannot drift the way the engine API already did once.
#[allow(dead_code)]
type ContextKey = (PathBuf, u32);

/// Take a lock even if a previous holder panicked.
///
/// A poisoned cache would otherwise force every later target to reload the
/// model, turning one unrelated panic into a silent performance cliff.
#[allow(dead_code)]
fn lock_through_poison<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|e| e.into_inner())
}

/// Return a cached handle, or build one and report that it was built.
///
/// The lock is held across `build` on purpose. Without it, every thread of the
/// first wave would load the same weights at the same time, multiplying both
/// the load cost and the device memory actually consumed, and each of them
/// would truthfully report a cold load. Serializing the load and then running
/// inference in parallel is what makes `cold_load` mean something.
#[allow(dead_code)]
fn load_or_reuse<T, E, F>(
    cache: &Mutex<HashMap<ContextKey, Arc<T>>>,
    key: ContextKey,
    build: F,
) -> Result<(Arc<T>, bool), E>
where
    F: FnOnce() -> Result<T, E>,
{
    let mut guard = lock_through_poison(cache);
    if let Some(found) = guard.get(&key) {
        return Ok((Arc::clone(found), false));
    }
    let built = Arc::new(build()?);
    guard.insert(key, Arc::clone(&built));
    Ok((built, true))
}

// A binary that both stubs and really infers would be unreadable from the
// outside, so the combination is refused at compile time rather than resolved
// by precedence.
#[cfg(all(feature = "stub-engine", any(feature = "cuda", feature = "cpu")))]
compile_error!("`stub-engine` cannot be combined with `cuda` or `cpu`");

/// Which engine this binary was built with, for the version envelope.
///
/// A stub run must never be mistakable for a real one, so the name travels in
/// the contract instead of living only in the build log.
pub const fn backend() -> &'static str {
    #[cfg(feature = "cuda")]
    {
        "cuda"
    }
    #[cfg(feature = "cpu")]
    {
        "cpu"
    }
    #[cfg(feature = "stub-engine")]
    {
        "stub"
    }
    #[cfg(not(any(feature = "cuda", feature = "cpu", feature = "stub-engine")))]
    {
        "none"
    }
}

/// Run transcription on 16 kHz mono samples.
pub fn transcribe(request: &TranscribeRequest<'_>) -> Result<EngineOutput, Error> {
    #[cfg(any(feature = "cuda", feature = "cpu"))]
    {
        native(request)
    }
    #[cfg(feature = "stub-engine")]
    {
        stub(request)
    }
    #[cfg(not(any(feature = "cuda", feature = "cpu", feature = "stub-engine")))]
    {
        let _ = request;
        Err(Error::EngineUnavailable)
    }
}

/// Contexts the stub pretends to have loaded, so `cold_load` is exercised.
#[cfg(feature = "stub-engine")]
static STUB_CONTEXTS: std::sync::OnceLock<Mutex<HashMap<ContextKey, Arc<()>>>> =
    std::sync::OnceLock::new();

/// How long the stub pretends one second of audio takes.
#[cfg(feature = "stub-engine")]
const STUB_COST_PER_SECOND: std::time::Duration = std::time::Duration::from_millis(20);

/// Deterministic inference used only by the test seam.
///
/// It mirrors the real pass in the ways the surrounding stages depend on: it
/// consults the same cache policy, it costs measurable time, it honours the
/// abort conditions while running, and it emits one segment per second of
/// audio. It never claims to have understood anything.
#[cfg(feature = "stub-engine")]
fn stub(request: &TranscribeRequest<'_>) -> Result<EngineOutput, Error> {
    if !request.model_path.exists() {
        return Err(Error::WhisperInference(format!(
            "model not readable: {}",
            request.model_path.display()
        )));
    }
    let cache = STUB_CONTEXTS.get_or_init(|| Mutex::new(HashMap::new()));
    let key = (request.model_path.to_path_buf(), request.device);
    let (_ctx, cold_load) = load_or_reuse::<(), Error, _>(cache, key, || Ok(()))?;

    let seconds = request.samples.len() as f64 / 16_000.0;
    // Cost is paid in slices so an interrupt or a deadline lands mid-pass,
    // which is the whole point of the abort callback in the real engine.
    let slices = (seconds.ceil() as u64).max(1);
    for _ in 0..slices {
        if crate::signal::is_shutdown_requested() {
            return Err(crate::signal::shutdown_error().unwrap_or(Error::Interrupted));
        }
        if request
            .deadline
            .map(|d| Instant::now() > d)
            .unwrap_or(false)
        {
            return Err(Error::Timeout);
        }
        std::thread::sleep(STUB_COST_PER_SECOND);
    }

    let mut segments = Vec::new();
    let mut cursor = 0.0f64;
    while cursor < seconds {
        let end = (cursor + 1.0).min(seconds);
        segments.push(Segment {
            start: cursor,
            end,
            // Accented, because real speech is: criterion 9 requires that a
            // cut never splits a multi-byte character, and a pure-ASCII stub
            // cannot exercise that at all.
            text: format!("trecho de transcrição número {}", segments.len()),
        });
        cursor = end;
    }
    if segments.is_empty() {
        segments.push(Segment {
            start: 0.0,
            end: seconds,
            text: "trecho de transcrição número 0".to_string(),
        });
    }
    // Same shape as the real engine: one segment per line, so the filters
    // downstream see what they will see in production.
    let text = segments
        .iter()
        .map(|s| s.text.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    // `auto` is answered with a fixed resolution so the detection branch of the
    // envelope is exercised rather than skipped.
    let (language, language_detected) = if request.language == "auto" {
        ("en".to_string(), true)
    } else {
        (request.language.to_string(), false)
    };
    Ok(EngineOutput {
        text,
        segments,
        language,
        language_detected,
        cold_load,
    })
}

/// Silence whisper.cpp log hooks by routing them to tracing (stderr).
pub fn silence_native_logs() {
    #[cfg(any(feature = "cuda", feature = "cpu"))]
    {
        whisper_rs::install_logging_hooks();
    }
}

/// Model contexts already loaded by this invocation.
///
/// `WhisperContext` is an `Arc` over a `Send + Sync` inner handle, and the
/// crate's own model is one context feeding many states. Building a fresh
/// context per target reloaded the weights every time, which is why no target
/// was ever warm and `cold_load: false` was never true.
#[cfg(any(feature = "cuda", feature = "cpu"))]
static CONTEXTS: std::sync::OnceLock<Mutex<HashMap<ContextKey, Arc<whisper_rs::WhisperContext>>>> =
    std::sync::OnceLock::new();

#[cfg(any(feature = "cuda", feature = "cpu"))]
fn native(request: &TranscribeRequest<'_>) -> Result<EngineOutput, Error> {
    use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};

    let cache = CONTEXTS.get_or_init(|| Mutex::new(HashMap::new()));
    let key = (request.model_path.to_path_buf(), request.device);
    let (ctx, cold_load) = load_or_reuse(cache, key, || {
        let mut ctx_params = WhisperContextParameters::default();
        ctx_params.gpu_device(request.device as i32);
        WhisperContext::new_with_params(request.model_path.display().to_string(), ctx_params)
            .map_err(|e| Error::WhisperInference(e.to_string()))
    })?;
    let mut state = ctx
        .create_state()
        .map_err(|e| Error::WhisperInference(e.to_string()))?;

    let mut params = if request.beam <= 1 {
        FullParams::new(SamplingStrategy::Greedy { best_of: 1 })
    } else {
        FullParams::new(SamplingStrategy::BeamSearch {
            beam_size: request.beam,
            patience: -1.0,
        })
    };
    params.set_print_progress(false);
    params.set_print_special(false);
    params.set_print_realtime(false);
    params.set_print_timestamps(false);
    if request.language != "auto" {
        params.set_language(Some(request.language));
    }

    // The deadline and the interrupt only become real here. Checking them
    // between stages leaves a long single file uninterruptible.
    let deadline = request.deadline;
    params.set_abort_callback_safe(move || {
        crate::signal::is_shutdown_requested()
            || deadline.map(|d| Instant::now() > d).unwrap_or(false)
    });

    // An abort surfaces either as an error or as an early return with partial
    // segments, depending on how whisper.cpp reports it. Both have to be
    // classified by WHY we aborted, or a blown deadline is reported as a
    // resource fault and the agent retries on another GPU instead of asking
    // for more time.
    let inference = state.full(params, request.samples);
    if let Some(d) = request.deadline {
        if Instant::now() > d {
            return Err(Error::Timeout);
        }
    }
    if let Some(err) = crate::signal::shutdown_error() {
        return Err(err);
    }
    inference.map_err(|e| Error::WhisperInference(e.to_string()))?;

    let (language, language_detected) = if request.language == "auto" {
        let id = state.full_lang_id_from_state();
        match whisper_rs::get_lang_str(id) {
            Some(code) => (code.to_string(), true),
            None => (request.language.to_string(), false),
        }
    } else {
        (request.language.to_string(), false)
    };

    let count = state.full_n_segments();
    let mut segments = Vec::new();
    let mut text = String::new();
    for i in 0..count {
        let Some(segment) = state.get_segment(i) else {
            continue;
        };
        let body = segment
            .to_str_lossy()
            .map_err(|e| Error::WhisperInference(e.to_string()))?;
        let body = body.trim();
        // One segment per line, not one long line. The hallucination filter is
        // a line-anchored regex and the repeat collapser iterates over lines,
        // so joining with a space made both inert in production while their
        // unit tests kept passing on multi-line strings the engine never
        // produced. Worse, a hallucination at the start would have taken the
        // whole transcript with it, because the pattern consumes to end of line.
        if !text.is_empty() {
            text.push('\n');
        }
        text.push_str(body);
        segments.push(Segment {
            // whisper timestamps are centiseconds.
            start: segment.start_timestamp() as f64 / 100.0,
            end: segment.end_timestamp() as f64 / 100.0,
            text: body.to_string(),
        });
    }

    Ok(EngineOutput {
        text,
        segments,
        language,
        language_detected,
        cold_load,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn request<'a>(samples: &'a [f32], path: &'a Path) -> TranscribeRequest<'a> {
        TranscribeRequest {
            model_path: path,
            samples,
            language: "auto",
            beam: 5,
            device: 0,
            deadline: None,
        }
    }

    #[test]
    fn request_carries_device_and_deadline() {
        let samples = [0.0f32; 4];
        let path = Path::new("/nonexistent/model.bin");
        let mut req = request(&samples, path);
        req.device = 3;
        req.deadline = Some(Instant::now() + Duration::from_secs(5));
        assert_eq!(req.device, 3);
        assert!(req.deadline.is_some());
    }

    #[test]
    fn known_languages_cover_auto_and_portuguese() {
        assert!(is_known_language("auto"));
        assert!(is_known_language("pt"));
        assert!(is_known_language("en"));
        assert!(!is_known_language("xx"));
        assert!(!is_known_language(""));
    }

    #[test]
    fn language_list_has_no_duplicates() {
        let mut sorted = LANGUAGES.to_vec();
        sorted.sort_unstable();
        let before = sorted.len();
        sorted.dedup();
        assert_eq!(before, sorted.len());
    }

    /// FR-053: `cold_load` must be a fact, not a guess. The first pass on a
    /// key builds and reports true; every later pass reuses and reports false.
    #[test]
    fn only_the_building_pass_is_a_cold_load() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let cache: Mutex<HashMap<ContextKey, Arc<u32>>> = Mutex::new(HashMap::new());
        let builds = AtomicUsize::new(0);
        let key = (PathBuf::from("/models/small.bin"), 0u32);

        let (first, cold) = load_or_reuse::<u32, Error, _>(&cache, key.clone(), || {
            builds.fetch_add(1, Ordering::SeqCst);
            Ok(7)
        })
        .expect("build");
        assert!(cold, "the pass that builds must report a cold load");

        let (again, cold) = load_or_reuse::<u32, Error, _>(&cache, key, || {
            builds.fetch_add(1, Ordering::SeqCst);
            Ok(9)
        })
        .expect("reuse");
        assert!(!cold, "a reused context is not a cold load");
        assert_eq!(
            builds.load(Ordering::SeqCst),
            1,
            "weights load exactly once"
        );
        assert!(
            Arc::ptr_eq(&first, &again),
            "the same handle must be reused"
        );
    }

    /// A different model or a different device is a different context.
    #[test]
    fn each_model_and_device_is_its_own_context() {
        let cache: Mutex<HashMap<ContextKey, Arc<u32>>> = Mutex::new(HashMap::new());
        let small = (PathBuf::from("/models/small.bin"), 0u32);
        let large = (PathBuf::from("/models/large.bin"), 0u32);
        let second_card = (PathBuf::from("/models/small.bin"), 1u32);

        for key in [small.clone(), large, second_card] {
            let (_, cold) = load_or_reuse::<u32, Error, _>(&cache, key, || Ok(1)).expect("build");
            assert!(cold, "a new key must load its own context");
        }
        let (_, cold) = load_or_reuse::<u32, Error, _>(&cache, small, || Ok(1)).expect("reuse");
        assert!(!cold, "a known key must not reload");
        assert_eq!(cache.lock().expect("cache").len(), 3);
    }

    /// A failed build must not be cached as if it had succeeded.
    #[test]
    fn a_failed_build_is_not_remembered() {
        let cache: Mutex<HashMap<ContextKey, Arc<u32>>> = Mutex::new(HashMap::new());
        let key = (PathBuf::from("/models/missing.bin"), 0u32);
        let err = load_or_reuse::<u32, Error, _>(&cache, key.clone(), || {
            Err(Error::WhisperInference("no such model".into()))
        })
        .expect_err("must fail");
        assert!(matches!(err, Error::WhisperInference(_)));
        assert!(cache.lock().expect("cache").is_empty());

        let (_, cold) = load_or_reuse::<u32, Error, _>(&cache, key, || Ok(1)).expect("retry");
        assert!(cold, "a retry after a failed build still loads cold");
    }

    /// A whole wave hitting the same key must still load the weights once.
    #[test]
    fn a_parallel_wave_loads_the_weights_once() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let cache: Mutex<HashMap<ContextKey, Arc<u32>>> = Mutex::new(HashMap::new());
        let builds = AtomicUsize::new(0);
        let key = (PathBuf::from("/models/small.bin"), 0u32);

        let colds: Vec<bool> = std::thread::scope(|scope| {
            let handles: Vec<_> = (0..8)
                .map(|_| {
                    let key = key.clone();
                    let cache = &cache;
                    let builds = &builds;
                    scope.spawn(move || {
                        load_or_reuse::<u32, Error, _>(cache, key, || {
                            builds.fetch_add(1, Ordering::SeqCst);
                            Ok(1)
                        })
                        .expect("load")
                        .1
                    })
                })
                .collect();
            handles
                .into_iter()
                .map(|h| h.join().expect("join"))
                .collect()
        });

        assert_eq!(builds.load(Ordering::SeqCst), 1, "eight workers, one load");
        assert_eq!(
            colds.iter().filter(|c| **c).count(),
            1,
            "exactly one worker may claim the cold load"
        );
    }

    /// With no backend compiled in, asking to transcribe is a resource fault
    /// rather than a crash. The test seam counts as a backend, so it is
    /// excluded here too.
    #[cfg(not(any(feature = "cuda", feature = "cpu", feature = "stub-engine")))]
    #[test]
    fn no_feature_is_engine_unavailable() {
        let samples = [0.0f32; 4];
        let path = Path::new("/nonexistent/model.bin");
        let err = transcribe(&request(&samples, path)).expect_err("must refuse");
        assert!(matches!(err, Error::EngineUnavailable));
        assert_eq!(err.exit_code(), 70);
    }
}