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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! The verbs that answer about the product instead of listening to audio.
//!
//! `config`, `locale`, `schema`, `commands`, `version`, `licenses` and
//! `completions` share a shape: they read state or describe the contract, they
//! touch no GPU, no model and no media, and they finish in milliseconds. They
//! were carved out of `commands.rs`, which had become the largest module in the
//! crate by holding both these and the whole transcription pipeline.
//!
//! The cut is where the coupling already was, not where a line count suggested:
//! measured before the move, this block referenced nothing from the
//! transcription side — not the batch loop, not the resource gates, not the
//! resolved knobs. Splitting anywhere else would have meant widening a private
//! interface to fit a file size, which trades one large module for two coupled
//! ones.
//!
//! Everything here is `pub(crate)` because `commands::dispatch` is the only
//! caller, and the verbs are not part of the library's public surface.
//!
//! `inspect`, `models` and `doctor` joined those seven afterwards, and the two
//! paragraphs above describe the original block rather than these three: they do
//! touch the GPU, the catalogue and the media header. The rule they share is the
//! narrower one the file now enforces without exception — a verb that does not
//! transcribe lives here. Three of them were still in `commands.rs`, so the rule
//! was not true, and nothing told the next reader where to look for a verb or
//! where to put a new one.

use std::path::Path;

use serde_json::json;

use crate::audio;
use crate::catalog::Catalog;
use crate::cli::{ConfigAction, InspectArgs, LocaleAction, ModelsAction};
use crate::commands::Ctx;
use crate::error::Error;
use crate::gpu;
use crate::i18n::UiLang;
use crate::output::{self, SCHEMA_VERSION};

pub(crate) fn config_cmd(ctx: &mut Ctx<'_>, action: ConfigAction) -> Result<(), Error> {
    match action {
        ConfigAction::Path => output::write_value(
            &json!({
                "schema_version": SCHEMA_VERSION,
                "correlation_id": ctx.correlation_id,
                "path": ctx.paths.config_file().display().to_string(),
            }),
            ctx.surface,
        ),
        ConfigAction::List => {
            let keys: Vec<_> = ctx
                .store
                .list_map()
                .into_iter()
                .map(|(k, v)| json!({"key": k, "value": v}))
                .collect();
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "keys": keys,
                }),
                ctx.surface,
            )
        }
        ConfigAction::Get { target } => {
            let value = ctx.store.get_key(&target)?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "key": target,
                    "value": value,
                }),
                ctx.surface,
            )
        }
        ConfigAction::Set { target, value } => {
            ctx.store.set_key(&target, &value)?;
            ctx.store.save(&ctx.paths.config_file())?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "key": target,
                    "value": value,
                    "action": "set",
                }),
                ctx.surface,
            )
        }
        ConfigAction::Unset { target } => {
            ctx.store.unset_key(&target)?;
            ctx.store.save(&ctx.paths.config_file())?;
            let value = ctx.store.get_key(&target)?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "key": target,
                    "value": value,
                    "action": "unset",
                }),
                ctx.surface,
            )
        }
    }
}

/// Serve one published contract, or list them all.
///
/// The verb used to know a single payload while the surface had twenty-one
/// verbs, so an agent asking for any other contract was told it did not exist.
/// Both this and `docs/schemas/` now read from `crate::schema`.
pub(crate) fn schema(ctx: &Ctx<'_>, name: Option<&str>) -> Result<(), Error> {
    let payload = match name {
        None => json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "schemas": crate::schema::names(),
        }),
        Some(wanted) => {
            let Some(doc) = crate::schema::get(wanted) else {
                return Err(Error::Usage(format!(
                    "unknown schema: {wanted}; known: {}",
                    crate::schema::names().join(", ")
                )));
            };
            json!({
                "schema_version": SCHEMA_VERSION,
                "correlation_id": ctx.correlation_id,
                "name": wanted,
                "schema": doc,
            })
        }
    };
    output::write_value(&payload, ctx.surface)
}

/// Every leaf verb, walked out of the parser instead of repeated by hand.
///
/// This list used to be twenty-one string literals inside `commands_tree`.
/// `Commands::target` had already learnt the lesson its own doc comment states —
/// deriving from the parsed verb "means a verb added later cannot forget to
/// carry it" — while the one function whose entire contract is to name EVERY
/// verb the binary accepts still spelled them out. A verb added to the enum
/// would have been missing here and nothing would have failed, because a
/// literal agrees with itself no matter what the parser does.
///
/// A parent is never emitted on its own: `models` alone is not invocable, so
/// only the leaves are named. `help` is skipped because clap injects it, it
/// serves prose rather than an envelope, and it has no published contract in
/// `docs/schemas/`.
fn leaf_verbs() -> Vec<String> {
    fn walk(cmd: &clap::Command, prefix: &str, out: &mut Vec<String>) {
        for sub in cmd.get_subcommands() {
            let name = sub.get_name();
            if name == "help" {
                continue;
            }
            let path = if prefix.is_empty() {
                name.to_string()
            } else {
                format!("{prefix} {name}")
            };
            if sub.get_subcommands().next().is_none() {
                out.push(path);
            } else {
                walk(sub, &path, out);
            }
        }
    }
    let mut out = Vec::new();
    walk(
        &<crate::cli::Cli as clap::CommandFactory>::command(),
        "",
        &mut out,
    );
    out
}

pub(crate) fn commands_tree(ctx: &Ctx<'_>) -> Result<(), Error> {
    output::write_value(
        &json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "commands": leaf_verbs(),
        }),
        ctx.surface,
    )
}

pub(crate) fn version(ctx: &Ctx<'_>) -> Result<(), Error> {
    output::write_value(
        &json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "name": "whisper-nvidia-cli",
            "version": env!("CARGO_PKG_VERSION"),
            "contract": SCHEMA_VERSION,
            // Which inference backend was compiled in. A build carrying the
            // test seam has to be identifiable from the contract alone.
            "engine": crate::engine::backend(),
        }),
        ctx.surface,
    )
}

/// Emit a shell completion script on stdout.
///
/// The one place stdout carries something other than a JSON envelope, and the
/// exception is deliberate. The canonical use is `eval "$(whisper-nvidia-cli
/// completions bash)"`, which reads stdout; putting the script on stderr — where
/// the rendered `--help` correctly goes — would break the only way this output
/// is consumed. `--help` is prose for a human to read, so stderr costs nothing;
/// this script is the command's product, so the channel is part of the contract.
///
/// Stated here because an undocumented exception is indistinguishable from an
/// oversight, and the next reader has no way to tell which one they found.
pub(crate) fn completions(shell: clap_complete::Shell) -> Result<(), Error> {
    use clap::CommandFactory;
    use std::io::Write;

    let mut cmd = crate::cli::Cli::command();
    // Generated into memory first, because `generate` writes straight into the
    // sink and unwraps the result. Handed `io::stdout()` with a closed reader,
    // it panics and the process exits 101 — an exit code this product does not
    // define — instead of the 141 FR-046 assigns to a broken pipe. A buffer
    // makes the single write ours, so the failure is classified like every
    // other write in the binary.
    let mut script: Vec<u8> = Vec::new();
    clap_complete::generate(shell, &mut cmd, "whisper-nvidia-cli", &mut script);
    let mut stdout = std::io::stdout().lock();
    stdout
        .write_all(&script)
        .and_then(|()| stdout.flush())
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::BrokenPipe {
                Error::BrokenPipe
            } else {
                Error::Io(e)
            }
        })
}

pub(crate) fn licenses(ctx: &Ctx<'_>) -> Result<(), Error> {
    output::write_value(
        &json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "licenses": [
                "MIT OR Apache-2.0",
                "whisper.cpp MIT",
                "OpenAI Whisper MIT"
            ]
        }),
        ctx.surface,
    )
}

pub(crate) fn locale_cmd(ctx: &mut Ctx<'_>, action: LocaleAction) -> Result<(), Error> {
    match action {
        LocaleAction::Show => output::write_value(
            &json!({
                "schema_version": SCHEMA_VERSION,
                "correlation_id": ctx.correlation_id,
                "locale": ctx.ui.tag(),
            }),
            ctx.surface,
        ),
        LocaleAction::Set { target } => {
            // `resolve_strict`, not `resolve`: this writes the value to disk,
            // and a language with no translation must be refused here rather
            // than degraded, which is what `--lang` does for a single run.
            let _ = UiLang::resolve_strict(&target)?;
            ctx.store.set_key("locale", &target)?;
            ctx.store.save(&ctx.paths.config_file())?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "locale": target,
                    "action": "set",
                }),
                ctx.surface,
            )
        }
        LocaleAction::Clear => {
            ctx.store.unset_key("locale")?;
            ctx.store.save(&ctx.paths.config_file())?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "action": "clear",
                    "locale": ctx.ui.tag(),
                }),
                ctx.surface,
            )
        }
    }
}

pub(crate) fn inspect(ctx: &Ctx<'_>, args: InspectArgs) -> Result<(), Error> {
    // The persisted helper is offered first; `resolve_helper` falls back to
    // `ffmpeg` on PATH so a video is measurable before anything is configured.
    let effective = ctx.store.effective();
    let helper = effective.helper.unwrap_or_default();
    let probe = audio::inspect_file(&args.target, Some(helper.as_str()))?;
    output::write_value(
        &json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "target_resolved": args.target.display().to_string(),
            "target_source": "argv",
            "file": args.target.display().to_string(),
            "format": probe.format,
            "sample_rate": probe.sample_rate,
            "channels": probe.channels,
            "duration_seconds": probe.duration_seconds,
            "is_video": probe.is_video,
            "text": serde_json::Value::Null,
        }),
        ctx.surface,
    )
}

pub(crate) fn models(ctx: &Ctx<'_>, action: ModelsAction) -> Result<(), Error> {
    let effective = ctx.store.effective();
    let catalog = Catalog::load_or_seed(ctx.paths, effective.origin())?;
    match action {
        ModelsAction::List => {
            let rows: Vec<_> = catalog
                .models
                .iter()
                .map(|m| {
                    json!({
                        "name": m.name,
                        "filename": m.filename,
                        "present": crate::model::is_present(ctx.paths, m),
                        "verified": crate::model::is_verified(ctx.paths, m),
                        "size_bytes": m.size_bytes,
                        "sha1": m.sha1,
                        "url": m.url,
                    })
                })
                .collect();
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "models": rows,
                }),
                ctx.surface,
            )
        }
        ModelsAction::Download { target } => {
            let entry = catalog.get(&target)?.clone();
            let dl = effective.download_knobs();
            let path = crate::model::download(ctx.paths, &entry, &dl, ctx.offline)?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "model": entry.name,
                    "action": "download",
                    "path": path.display().to_string(),
                }),
                ctx.surface,
            )
        }
        ModelsAction::Path { target } => {
            let entry = catalog.get(&target)?;
            if !crate::model::is_present(ctx.paths, entry) {
                return Err(Error::ModelNotFound { name: target });
            }
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "path": crate::model::model_path(ctx.paths, entry).display().to_string(),
                }),
                ctx.surface,
            )
        }
        ModelsAction::Remove { target, yes } => {
            if !yes {
                return Err(Error::NeedsYes);
            }
            let entry = catalog.get(&target)?.clone();
            // Whether a file was actually deleted is the one fact this verb
            // knows and the caller cannot recover. Without it the envelope for
            // "removed 3 GB" was byte-identical to "there was nothing here",
            // so a typo in `--cache-dir` read as a successful cleanup.
            let removed = crate::model::remove(ctx.paths, &entry)?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "model": entry.name,
                    "action": "remove",
                    "removed": removed,
                }),
                ctx.surface,
            )
        }
        ModelsAction::Verify { target } => {
            let entry = catalog.get(&target)?;
            let digest = crate::model::verify(ctx.paths, entry)?;
            output::write_value(
                &json!({
                    "schema_version": SCHEMA_VERSION,
                    "correlation_id": ctx.correlation_id,
                    "target_resolved": target,
                    "target_source": "argv",
                    "ok": true,
                    "sha1": digest,
                }),
                ctx.surface,
            )
        }
    }
}

/// Diagnose the host, optionally for a specific card.
///
/// `--device` used to exist only on `transcribe`, so diagnosing the second
/// card of a machine meant editing the persisted configuration first. The
/// argv value wins over the persisted one, as everywhere else.
pub(crate) fn doctor(ctx: &mut Ctx<'_>, device_arg: Option<u32>) -> Result<(), Error> {
    gpu::warn_ignored_cuda_env(ctx.ui);
    let effective = ctx.store.effective();
    let device = device_arg.unwrap_or_else(|| effective.device.unwrap_or(0));
    let device_source = if device_arg.is_some() {
        "argv"
    } else if ctx.store.device.is_some() {
        "config"
    } else {
        "default"
    };
    let info = gpu::probe_checked(device)?;
    let catalog = Catalog::load_or_seed(ctx.paths, effective.origin())?;
    // Unknown free memory yields no suggestion at all; a guess here would be
    // indistinguishable from a measurement to the agent reading the envelope.
    let suggested = gpu::suggest_model(info.free_bytes, &catalog.models);
    let helper = effective.helper.unwrap_or_default();
    let helper_ok = !helper.is_empty() && Path::new(&helper).exists();
    let device_ok = info.present && device < info.count;
    let checks = json!([
        {"name": "gpu", "ok": info.present, "detail": info.name},
        {"name": "driver", "ok": !info.driver.is_empty(), "detail": info.driver},
        {"name": "vram_free_bytes", "ok": info.free_bytes.is_some(), "detail": info.free_bytes},
        {"name": "device", "ok": device_ok, "detail": device},
        {"name": "toolkit", "ok": info.toolkit, "detail": info.nvcc},
        {"name": "c_compiler", "ok": info.cc.is_some(), "detail": info.cc},
        {"name": "helper", "ok": helper_ok, "detail": helper},
        {"name": "suggested_model", "ok": suggested.is_some(), "detail": suggested},
        // A host reading a clean report has to be able to tell whether the
        // binary can actually infer, or was built with the test seam.
        {"name": "engine", "ok": crate::engine::backend() == "cuda", "detail": crate::engine::backend()},
        // `--max-memory` degrades to "satisfied" wherever the resident size
        // cannot be read, so the flag can be accepted on a platform where it
        // protects nothing. An agent that relies on the cap has to be able to
        // read whether the number behind it exists, rather than infer it from
        // the operating system.
        // `detail` names the source of the measurement, never the measurement
        // itself: FR-023 requires the same argv to produce the same stdout, and
        // a live RSS reading differs between two runs a second apart. A
        // diagnostic states what this build can do, not what it weighed.
        {"name": "memory_cap", "ok": gpu::memory_cap_is_measurable(), "detail": gpu::memory_cap_source()},
        // The signal reaches a helper's own children only where the process
        // group exists. Without it a forced exit kills the direct child and
        // leaves its descendants running, which the caller must know before
        // trusting the cleanup promise.
        {"name": "child_tree_signal", "ok": cfg!(unix), "detail": std::env::consts::FAMILY},
    ]);
    // The verdict is decided BEFORE the document is written, so one object can
    // carry both the report and the failure. Writing the report and then
    // returning the error made the top level emit a SECOND envelope, which put
    // two JSON documents on stdout and broke FR-047. Suppressing that second
    // envelope alone would have traded one defect for another: the caller would
    // keep the report but lose the code, the category and the hint FR-041
    // promises on every failure. Merging them satisfies both requirements at
    // once, and the exit code still carries the same condition.
    //
    // The order of the checks is the order of the answers: an absent card is 70
    // before anything else, a device index the host lacks is the argv fault 78,
    // and only then does a missing toolkit answer 69.
    let failure = if !info.present {
        Some(Error::GpuMissing)
    } else if let Err(err) = gpu::ensure_device(&info, device) {
        Some(err)
    } else if !info.toolkit {
        Some(Error::ToolkitMissing)
    } else {
        None
    };
    let mut report = json!({
        "schema_version": SCHEMA_VERSION,
        "correlation_id": ctx.correlation_id,
        "gpu_present": info.present,
        "gpu_name": info.name,
        "driver": info.driver,
        "free_bytes": info.free_bytes,
        "total_bytes": info.total_bytes,
        "device": device,
        "device_source": device_source,
        "device_count": info.count,
        "toolkit": info.toolkit,
        "engine": crate::engine::backend(),
        "suggested_model": suggested,
        "checks": checks,
    });
    if let (Some(err), Some(obj)) = (failure.as_ref(), report.as_object_mut()) {
        obj.insert("error".into(), json!(true));
        obj.insert("ok".into(), json!(false));
        obj.insert("code".into(), json!(err.exit_code()));
        obj.insert("message".into(), json!(err.to_string()));
        obj.insert("category".into(), json!(err.category()));
        obj.insert("retryable".into(), json!(err.retryable()));
        obj.insert("hint".into(), json!(err.hint()));
    }
    output::write_value(&report, ctx.surface)?;
    // The document above already carries this failure, so the top level must
    // not write it again: that duplicate was the second JSON document on
    // stdout. The error still travels, because the exit code is decided by it.
    ctx.error_reported = true;
    match failure {
        Some(err) => Err(err),
        None => Ok(()),
    }
}