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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Published JSON contracts, one per payload the CLI can emit.
//!
//! This module is the single source. The `schema` verb serves from it and the
//! files under `docs/schemas/` are generated from it, with a test asserting the
//! two never diverge. Documentation written by hand beside a contract drifts
//! away from it silently, and an agent that trusted the drifted copy has no way
//! to tell.

use serde_json::{json, Value};

/// Shorthand for a required string property.
fn string() -> Value {
    json!({"type": "string"})
}

/// The origin of an argv target: a closed set, everywhere it appears.
///
/// Nine contracts used to declare this as a free string while three declared
/// the closed set, so a consumer validating one document accepted an origin the
/// others forbade. One helper means a fourth origin can only be added in one
/// place.
fn target_source() -> Value {
    json!({
        "type": "string",
        "enum": ["argv", "stdin", "active"],
        "description": "where the target came from; absent when the verb has no single target",
    })
}

fn number() -> Value {
    json!({"type": "number"})
}

fn integer() -> Value {
    json!({"type": "integer"})
}

fn boolean() -> Value {
    json!({"type": "boolean"})
}

/// Properties every successful envelope carries.
fn envelope_base() -> Value {
    json!({
        "schema_version": string(),
        "correlation_id": string(),
    })
}

/// Merge extra properties onto the common envelope.
fn with_base(extra: Value) -> Value {
    let mut props = envelope_base();
    let map = props.as_object_mut().expect("object");
    for (k, v) in extra.as_object().expect("object") {
        map.insert(k.clone(), v.clone());
    }
    props
}

fn object(required: &[&str], properties: Value, description: &str) -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "description": description,
        "required": required,
        "properties": properties,
    })
}

/// Every published contract, in a stable order.
///
/// The order is the order `schema` lists them and the order the index in
/// `docs/schemas/README.md` follows.
pub fn all() -> Vec<(&'static str, Value)> {
    vec![
        ("transcribe", transcribe()),
        ("transcribe-summary", transcribe_summary()),
        ("transcribe-dry-run", transcribe_dry_run()),
        ("inspect", inspect()),
        ("models-list", models_list()),
        ("models-download", models_download()),
        ("models-path", models_path()),
        ("models-remove", models_remove()),
        ("models-verify", models_verify()),
        ("doctor", doctor()),
        ("config-path", config_path()),
        ("config-list", config_list()),
        ("config-get", config_get()),
        ("config-set", config_set()),
        ("config-unset", config_unset()),
        ("schema", schema_doc()),
        ("commands", commands()),
        ("version", version()),
        ("licenses", licenses()),
        ("locale-show", locale_show()),
        ("locale-set", locale_set()),
        ("locale-clear", locale_clear()),
        ("error", error()),
    ]
}

/// Names of every published contract.
pub fn names() -> Vec<&'static str> {
    all().into_iter().map(|(name, _)| name).collect()
}

/// One contract by name.
pub fn get(name: &str) -> Option<Value> {
    all().into_iter().find(|(n, _)| *n == name).map(|(_, v)| v)
}

fn segment() -> Value {
    json!({
        "type": "object",
        "required": ["start", "end", "text"],
        "properties": {
            "start": {"type": "number", "description": "seconds from the start of the audio"},
            "end": {"type": "number", "description": "seconds from the start of the audio"},
            "text": string(),
        }
    })
}

fn transcribe() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "target_source",
            "file",
            "language",
            "language_source",
            "model",
            "device",
            "duration_seconds",
            "text",
            "vad_chunks",
            "hallucinations_removed",
            "processing_time_ms",
            "cold_load",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "file": string(),
            "language": string(),
            "language_source": {"type": "string", "enum": ["argv", "config", "default", "detection"]},
            "model": string(),
            "device": integer(),
            "duration_seconds": number(),
            "text": string(),
            "segments": {
                "type": "array",
                "description": "present only with --timestamps",
                "items": segment(),
            },
            "vad_chunks": integer(),
            "hallucinations_removed": integer(),
            "processing_time_ms": integer(),
            "cold_load": {
                "type": "boolean",
                "description": "true when this pass loaded the model rather than reusing it",
            },
        })),
        "One transcription result. In a batch this is one NDJSON line per input file.",
    )
}

fn transcribe_summary() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "summary",
            "ok",
            "failed",
            "total",
        ],
        with_base(json!({
            "summary": {"type": "boolean", "const": true},
            "ok": integer(),
            "failed": integer(),
            "total": {
                "type": "integer",
                "description": "always equal to ok plus failed",
            },
        })),
        "Final NDJSON line of a batch, tallying results.",
    )
}

fn transcribe_dry_run() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "dry_run",
            "would_transcribe",
        ],
        with_base(json!({
            "dry_run": {"type": "boolean", "const": true},
            "target_resolved": string(),
            // Same closed vocabulary as the success and failure envelopes. A
            // free string here meant a consumer validating this document would
            // accept an origin the other two contracts forbid.
            "target_source": target_source(),
            "would_transcribe": {
                "type": "object",
                "required": ["files", "model", "language", "beam_size", "device", "concurrency", "vad"],
                "properties": {
                    "files": integer(),
                    "model": string(),
                    "language": string(),
                    "beam_size": integer(),
                    "device": integer(),
                    "concurrency": integer(),
                    "vad": number(),
                }
            },
        })),
        "Plan of a transcription that was not executed.",
    )
}

fn inspect() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "file",
            "format",
            "duration_seconds",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "file": string(),
            "format": string(),
            "sample_rate": integer(),
            "channels": integer(),
            "duration_seconds": number(),
            "is_video": boolean(),
            "text": {"type": "null", "description": "always null; inspect never transcribes"},
        })),
        "Container facts read from a media file header.",
    )
}

fn models_list() -> Value {
    object(
        &["schema_version", "correlation_id", "models"],
        with_base(json!({
            "models": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["name", "filename", "present", "verified", "size_bytes", "sha1", "url"],
                    "properties": {
                        "name": string(),
                        "filename": string(),
                        "present": {"type": "boolean", "description": "on disk with the declared size"},
                        "verified": {"type": "boolean", "description": "digest matched"},
                        "size_bytes": integer(),
                        "sha1": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
                        "url": string(),
                    }
                }
            },
        })),
        "The model catalog and what is cached locally.",
    )
}

fn models_download() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "model",
            "action",
            "path",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "model": string(),
            "action": {"type": "string", "const": "download"},
            "path": string(),
        })),
        "A model fetched and verified into the cache.",
    )
}

fn models_path() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "path",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "path": string(),
        })),
        "Where a cached model lives.",
    )
}

fn models_remove() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "model",
            "action",
            "removed",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "model": string(),
            "action": {"type": "string", "const": "remove"},
            "removed": {
                "type": "boolean",
                "description": "whether a cached file was actually deleted; false means it was already absent, which is still a success",
            },
        })),
        "A model deleted from the cache.",
    )
}

fn models_verify() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "ok",
            "sha1",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "ok": {"type": "boolean", "const": true},
            "sha1": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
        })),
        "The measured digest of a cached model.",
    )
}

fn doctor() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "gpu_present",
            "toolkit",
            "checks",
            "engine",
        ],
        with_base(json!({
            "gpu_present": boolean(),
            "gpu_name": string(),
            "driver": string(),
            "free_bytes": {
                "type": ["integer", "null"],
                "description": "null when the probe could not measure; never read as unlimited",
            },
            "total_bytes": {"type": ["integer", "null"]},
            "device": integer(),
            // Emitted since the device gained an explicit argv slot, and left
            // out of the contract. A field the report carries but the schema
            // does not name is invisible to an agent that discovers the tool by
            // reading it, which is the whole point of publishing a contract.
            "device_source": {
                "type": "string",
                "enum": ["argv", "config", "default"],
                "description": "where the device index came from",
            },
            "device_count": integer(),
            "toolkit": boolean(),
            "engine": {"type": "string", "enum": ["cuda", "cpu", "stub", "none"]},
            "suggested_model": {"type": ["string", "null"]},
            "checks": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["name", "ok"],
                    "properties": {"name": string(), "ok": boolean(), "detail": {}},
                }
            },
        })),
        "Host readiness report. Written before the verb fails, so a broken host still gets one.",
    )
}

fn config_path() -> Value {
    object(
        &["schema_version", "correlation_id", "path"],
        with_base(json!({"path": string()})),
        "Where the configuration file lives.",
    )
}

fn config_list() -> Value {
    object(
        &["schema_version", "correlation_id", "keys"],
        with_base(json!({
            "keys": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["key", "value"],
                    "properties": {"key": string(), "value": {}},
                }
            },
        })),
        "Every configuration key and its effective value.",
    )
}

fn config_get() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "key",
            "value",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "key": string(),
            "value": {},
        })),
        "One configuration value.",
    )
}

fn config_set() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "key",
            "value",
            "action",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "key": string(),
            "value": {},
            "action": {"type": "string", "const": "set"},
        })),
        "A configuration value written to disk.",
    )
}

fn config_unset() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "key",
            "action",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "key": string(),
            "value": {"description": "the value after removal, which is the default"},
            "action": {"type": "string", "const": "unset"},
        })),
        "A configuration key returned to its default.",
    )
}

/// The contract for `schema` itself, which has two shapes.
///
/// `schema --name X` answers one contract; bare `schema` answers the list. The
/// description said "or the list of them" while `required` demanded `name` and
/// `schema`, so the listing failed to validate against its own published
/// contract — and the listing is the entry point, the first call an agent
/// discovering this binary makes.
///
/// The two shapes are expressed as `oneOf` rather than by weakening `required`
/// to nothing. Dropping the requirement would let an envelope carrying neither
/// shape validate, which trades a contract that is wrong for one that says
/// nothing.
fn schema_doc() -> Value {
    let mut doc = object(
        &["schema_version", "correlation_id"],
        with_base(json!({
            "name": string(),
            "schema": {"type": "object"},
            "schemas": {
                "type": "array",
                "description": "present when no name was asked for",
                "items": string(),
            },
        })),
        "A published contract, or the list of them.",
    );
    doc["oneOf"] = json!([
        {"required": ["name", "schema"], "description": "one contract, asked for by name"},
        {"required": ["schemas"], "description": "the list, when no name was asked for"},
    ]);
    doc
}

fn commands() -> Value {
    object(
        &["schema_version", "correlation_id", "commands"],
        with_base(json!({
            "commands": {"type": "array", "items": string()},
        })),
        "Every verb this binary accepts.",
    )
}

fn version() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "name",
            "version",
            "contract",
            "engine",
        ],
        with_base(json!({
            "name": string(),
            "version": string(),
            "contract": string(),
            "engine": {
                "type": "string",
                "enum": ["cuda", "cpu", "stub", "none"],
                "description": "which inference backend was compiled in",
            },
        })),
        "Identity of this binary, including which engine it can actually run.",
    )
}

fn licenses() -> Value {
    object(
        &["schema_version", "correlation_id", "licenses"],
        with_base(json!({
            "licenses": {"type": "array", "items": string()},
        })),
        "Licences of this product and of what it embeds.",
    )
}

fn locale_show() -> Value {
    object(
        &["schema_version", "correlation_id", "locale"],
        with_base(json!({"locale": string()})),
        "The interface language in effect.",
    )
}

fn locale_set() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "target_resolved",
            "locale",
            "action",
        ],
        with_base(json!({
            "target_resolved": string(),
            "target_source": target_source(),
            "locale": string(),
            "action": {"type": "string", "const": "set"},
        })),
        "The interface language written to disk.",
    )
}

fn locale_clear() -> Value {
    object(
        &["schema_version", "correlation_id", "locale", "action"],
        with_base(json!({
            "locale": {"description": "the language after removal, which is the host default"},
            "action": {"type": "string", "const": "clear"},
        })),
        "The interface language returned to the host default.",
    )
}

fn error() -> Value {
    object(
        &[
            "schema_version",
            "correlation_id",
            "error",
            "ok",
            "code",
            "message",
        ],
        with_base(json!({
            "error": {"type": "boolean", "const": true},
            "ok": {"type": "boolean", "const": false},
            "code": {"type": "integer", "description": "the process exit code"},
            "category": string(),
            "message": string(),
            "hint": string(),
            "retryable": {
                "type": "boolean",
                "description": "false means retrying the same invocation cannot help",
            },
            "target_resolved": {
                "type": "string",
                "description": "the argv slot this failure belongs to; absent for verbs with no target",
            },
            // Same vocabulary as the success envelope above. A second spelling
            // for the same field would force a consumer to accept two words
            // for one concept, and the batch path already emits `active`.
            "target_source": target_source(),
        })),
        "Failure envelope. Never suppressed by output shaping.",
    )
}

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

    #[test]
    fn every_name_resolves_and_is_unique() {
        let names = names();
        let mut sorted = names.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), names.len(), "schema names must be unique");
        for name in names {
            let doc = get(name).unwrap_or_else(|| panic!("{name} must resolve"));
            assert_eq!(doc["type"], "object", "{name} must describe an object");
            assert!(
                doc["required"].as_array().is_some_and(|r| !r.is_empty()),
                "{name} must declare required properties"
            );
        }
    }

    #[test]
    fn an_unknown_name_does_not_resolve() {
        assert!(get("not-a-contract").is_none());
    }

    /// Every envelope carries the two fields an agent correlates on.
    #[test]
    fn every_contract_requires_the_common_envelope() {
        for (name, doc) in all() {
            let required: Vec<&str> = doc["required"]
                .as_array()
                .expect("required")
                .iter()
                .filter_map(|v| v.as_str())
                .collect();
            assert!(
                required.contains(&"schema_version") && required.contains(&"correlation_id"),
                "{name} must require schema_version and correlation_id"
            );
        }
    }
}