whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
Documentation
//! Compact JSON on stdout. Logs never go here.

use std::io::{self, Write};

use serde::Serialize;
use serde_json::Value;

use crate::error::Error;
use crate::surface::Surface;

/// Contract version equals the crate version.
pub const SCHEMA_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Successful transcription object (FR-041).
#[derive(Debug, Clone, Serialize)]
pub struct TranscriptionResult {
    /// Contract version of this envelope, equal to the crate version.
    pub schema_version: &'static str,
    /// Identifier shared by every line this run emits, for correlating logs.
    pub correlation_id: String,
    /// Target this run resolved to, echoed back so a caller can match it.
    pub target_resolved: String,
    /// Where the target came from: `argv`, `stdin` or `active`.
    pub target_source: String,
    /// Path of the audio or video file that was transcribed.
    pub file: String,
    /// Language code used for inference, or the one detection settled on.
    pub language: String,
    /// Where the language came from: `argv`, `config`, `default` or `detection`.
    pub language_source: String,
    /// Name of the whisper model that produced the text.
    pub model: String,
    /// Zero-based index of the GPU that ran the inference.
    pub device: u32,
    /// Length of the decoded audio, in seconds.
    pub duration_seconds: f64,
    /// Full transcript, every segment joined into one string.
    pub text: String,
    /// Timestamped slices of the transcript. Present only with `--timestamps`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub segments: Option<Vec<Segment>>,
    /// Voice-activity chunks the audio was split into before inference.
    pub vad_chunks: usize,
    /// Lines the caption filter dropped from the transcript.
    ///
    /// The removal used to be silent, so a transcript could come back shorter
    /// than the audio with nothing admitting that anything had been taken out.
    /// A non-zero count here is the caller's cue to re-run with the filter off
    /// if it suspects the words were real.
    pub hallucinations_removed: usize,
    /// Wall-clock time this transcription took, in milliseconds.
    pub processing_time_ms: u128,
    /// True when this pass loaded the model rather than reusing a warm one.
    pub cold_load: bool,
}

/// Timestamped slice.
#[derive(Debug, Clone, Serialize)]
pub struct Segment {
    /// Start of the slice, in seconds from the start of the audio.
    pub start: f64,
    /// End of the slice, in seconds from the start of the audio.
    pub end: f64,
    /// Transcript text of this slice.
    pub text: String,
}

/// Write one JSON object plus newline.
pub fn write_value(value: &Value, surface: &Surface) -> Result<(), Error> {
    let shaped = surface.apply(value.clone())?;
    let mut stdout = io::stdout().lock();
    if let Err(e) = serde_json::to_writer(&mut stdout, &shaped) {
        return map_write(e);
    }
    if let Err(e) = stdout.write_all(b"\n") {
        return map_io(e);
    }
    if let Err(e) = stdout.flush() {
        return map_io(e);
    }
    Ok(())
}

/// Write a serializable envelope.
pub fn write_json<T: Serialize>(value: &T, surface: &Surface) -> Result<(), Error> {
    let raw = serde_json::to_value(value).map_err(|e| Error::Config(e.to_string()))?;
    write_value(&raw, surface)
}

/// Write an error envelope. Failures are never hidden by `--filter`.
///
/// `target` is the argv slot the failing verb was aimed at, echoed back so a
/// caller that fired several named targets can tell which one failed.
pub fn write_error(
    err: &Error,
    correlation_id: &str,
    surface: &Surface,
    target: Option<crate::error::TargetRef<'_>>,
) -> Result<(), Error> {
    write_value(&err.to_json(correlation_id, target), surface)
}

/// Classify a failed serialize-to-stdout, keeping the reason it failed.
///
/// Every I/O fault used to be relabelled `BrokenPipe`, so a full disk answered
/// 141 — "the consumer closed the pipe" — when nothing had closed anything.
/// FR-046 owns 141 and means one specific thing; handing that code to ENOSPC
/// tells an agent to stop reading when it should free space and retry.
/// `io_error_kind` carries the real kind through, so the classification below
/// sees ENOSPC as the I/O error it is and answers 74.
fn map_write(err: serde_json::Error) -> Result<(), Error> {
    if let Some(kind) = err.io_error_kind() {
        return map_io(io::Error::new(kind, err));
    }
    Err(Error::Config(err.to_string()))
}

fn map_io(err: io::Error) -> Result<(), Error> {
    if err.kind() == io::ErrorKind::BrokenPipe {
        Err(Error::BrokenPipe)
    } else {
        Err(Error::Io(err))
    }
}