whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
Documentation
//! `whisper-nvidia-cli` — one-shot local NVIDIA speech-to-text for agents.
//!
//! The process is born, executes one verb, prints compact JSON, and dies.
//! Logs stay on stderr. Product environment variables are ignored.

pub mod audio;
pub mod catalog;
pub mod cli;
pub mod commands;
pub mod config;
pub mod engine;
pub mod error;
pub mod gpu;
pub mod i18n;
pub mod media_helper;
pub mod model;
pub mod output;
pub mod paths;
pub mod schema;
pub mod signal;
pub mod surface;
pub mod transcribe;
pub mod verbs;

// libc signal restore is the only unsafe call and lives in signal.rs
// behind an explicit allow on that function.

use std::io::Write;
use std::process::ExitCode;

use clap::{CommandFactory, Parser};
use tracing::level_filters::LevelFilter;

use crate::cli::{Cli, Commands};
use crate::commands::Ctx;
use crate::error::Error;
use crate::i18n::UiLang;
use crate::paths::AppPaths;

/// Removes every tracked temporary on the way out, whichever way that is.
///
/// `cleanup_temps` used to be reachable only from the forced-exit path, so it
/// ran when a signal arrived and never when a verb simply failed. Each callsite
/// paired `register_temp` with a `release_temp` placed AFTER the work, which
/// means any early return between the two left the directory on disk. FR-039
/// asks for no residue without qualifying how the run ended, so tying the
/// cleanup to one exit route could only ever satisfy part of it.
///
/// A destructor covers every route the type system knows about — `?`, an early
/// `return`, or a panic that unwinds — which is why this is a guard and not a
/// call placed at the end of `run`.
struct TempGuard;

impl Drop for TempGuard {
    fn drop(&mut self) {
        signal::cleanup_temps();
    }
}

/// Parse argv, run one verb, die with a semantic exit code.
pub fn run() -> ExitCode {
    signal::reset_sigpipe();
    signal::install_handlers();
    // Held for the whole invocation: dropped last, after every verb returned.
    let _temps = TempGuard;

    let cli = match Cli::try_parse() {
        Ok(c) => c,
        Err(e) => {
            // Help and version are a successful request for information,
            // not an argv fault, and they must not land on stdout.
            let informational = matches!(
                e.kind(),
                clap::error::ErrorKind::DisplayHelp
                    | clap::error::ErrorKind::DisplayVersion
                    | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
            );
            let rendered = e.render().to_string();
            let _ = std::io::stderr().write_all(rendered.as_bytes());
            if informational {
                return ExitCode::SUCCESS;
            }
            // An argv fault caught by clap is still an argv fault, and the
            // contract says every failure reaches stdout as an envelope. A
            // value rejected here used to leave stdout empty while a value
            // rejected one layer deeper produced JSON, so the same class of
            // mistake had two different shapes depending on who caught it.
            //
            // The rendered help stays on stderr for a human; the envelope
            // carries the first line, which is the diagnosis without the
            // usage block.
            let summary = rendered
                .lines()
                .find(|l| !l.trim().is_empty())
                .unwrap_or("invalid arguments")
                .trim_start_matches("error: ")
                .to_string();
            let err = Error::Usage(summary);
            // No target: argv did not parse, so no slot was ever resolved.
            let _ = output::write_error(
                &err,
                &commands::new_correlation_id(),
                &surface::Surface::default(),
                None,
            );
            return err.to_exit_code();
        }
    };

    let correlation_id = commands::new_correlation_id();
    let surface = cli.surface();

    let ui = match UiLang::resolve(cli.lang.as_deref()) {
        Ok(l) => l,
        Err(err) => return fail(&err, &correlation_id, &surface, None),
    };

    if cli.print_schema {
        let paths = match AppPaths::resolve(cli.config_dir.as_deref(), cli.cache_dir.as_deref()) {
            Ok(p) => p,
            Err(err) => return fail(&err, &correlation_id, &surface, None),
        };
        let store = match commands::load_store(&paths) {
            Ok(s) => s,
            Err(err) => return fail(&err, &correlation_id, &surface, None),
        };
        init_tracing(cli.quiet, cli.verbose, Some(&store));
        let mut ctx = Ctx {
            paths: &paths,
            store,
            surface: &surface,
            correlation_id: &correlation_id,
            ui,
            no_input: cli.no_input,
            offline: cli.offline,
            timeout: cli.timeout,
            error_reported: false,
        };
        return match commands::dispatch(Commands::Schema { name: None }, &mut ctx) {
            Ok(()) => ExitCode::SUCCESS,
            Err(err) => fail(&err, &correlation_id, &surface, None),
        };
    }

    let Some(command) = cli.command else {
        let mut buf = Vec::new();
        let _ = Cli::command().write_help(&mut buf);
        let _ = std::io::stderr().write_all(&buf);
        return ExitCode::from(2);
    };

    // Completions emit a script, not JSON.
    if matches!(command, Commands::Completions { .. }) {
        init_tracing(cli.quiet, cli.verbose, None);
        return match commands::dispatch(
            command,
            &mut Ctx {
                paths: &AppPaths {
                    config_dir: std::path::PathBuf::from("."),
                    cache_dir: std::path::PathBuf::from("."),
                    state_dir: std::path::PathBuf::from("."),
                },
                store: config::Store::default(),
                surface: &surface,
                correlation_id: &correlation_id,
                ui,
                no_input: cli.no_input,
                offline: cli.offline,
                timeout: cli.timeout,
                error_reported: false,
            },
        ) {
            Ok(()) => ExitCode::SUCCESS,
            Err(err) => fail(&err, &correlation_id, &surface, None),
        };
    }

    // Resolve the argv target once, before `command` is moved into dispatch,
    // so every failure below this line echoes the slot it was aimed at. A
    // caller that fired several named targets can then tell which one failed
    // instead of getting a bare exit code.
    let designated = command.target();
    let target = designated
        .as_ref()
        .map(|(resolved, source)| error::TargetRef { resolved, source });

    let paths = match AppPaths::resolve(cli.config_dir.as_deref(), cli.cache_dir.as_deref()) {
        Ok(p) => p,
        Err(err) => return fail(&err, &correlation_id, &surface, target),
    };
    if let Err(err) = paths.ensure() {
        return fail(&err, &correlation_id, &surface, target);
    }
    let store = match commands::load_store(&paths) {
        Ok(s) => s,
        Err(err) => return fail(&err, &correlation_id, &surface, target),
    };
    init_tracing(cli.quiet, cli.verbose, Some(&store));
    // Published before dispatch, because the reduction that reads it runs deep
    // inside the recursive walk over the envelope.
    surface::publish_content_keys(
        store
            .effective()
            .content_keys
            .or(config::Store::seeds().content_keys)
            .unwrap_or_default(),
    );
    let ui = match UiLang::resolve(cli.lang.as_deref().or(store.locale.as_deref())) {
        Ok(l) => l,
        Err(err) => return fail(&err, &correlation_id, &surface, target),
    };

    let mut ctx = Ctx {
        paths: &paths,
        store,
        surface: &surface,
        correlation_id: &correlation_id,
        ui,
        no_input: cli.no_input,
        offline: cli.offline,
        timeout: cli.timeout,
        error_reported: false,
    };

    match commands::dispatch(command, &mut ctx) {
        Ok(()) => ExitCode::SUCCESS,
        // A verb that already wrote the envelope for this failure only owes the
        // exit code. Writing it again put an error after the NDJSON summary,
        // where an agent reading the last line expects the tally.
        Err(err) if ctx.error_reported => {
            if !cli.quiet {
                if let Some(key) = err.i18n_key() {
                    eprintln!("{}", i18n::tr(ui, key));
                }
            }
            err.to_exit_code()
        }
        Err(err) => fail_localised(&err, &correlation_id, &surface, ui, cli.quiet, target),
    }
}

fn fail(
    err: &Error,
    correlation_id: &str,
    surface: &surface::Surface,
    target: Option<error::TargetRef<'_>>,
) -> ExitCode {
    let _ = output::write_error(err, correlation_id, surface, target);
    err.to_exit_code()
}

/// Emit the machine envelope on stdout and the localised hint on stderr.
fn fail_localised(
    err: &Error,
    correlation_id: &str,
    surface: &surface::Surface,
    ui: UiLang,
    quiet: bool,
    target: Option<error::TargetRef<'_>>,
) -> ExitCode {
    if !quiet {
        if let Some(key) = err.i18n_key() {
            eprintln!("{}", i18n::tr(ui, key));
        }
    }
    fail(err, correlation_id, surface, target)
}

/// Install the stderr subscriber at the level the flags ask for.
///
/// `--quiet` is `OFF`, not `ERROR`. Mapping it to `ERROR` reads as "still show
/// me errors", but the events at that level are not this product's: the decode
/// libraries log there too, so `-q` on an undecodable file still printed
/// `ERROR symphonia_core::probe: probe reach EOF at 54 bytes.` — a line in a
/// foreign format, in one language regardless of `--lang`, from a crate the
/// caller never invoked. The flag says "Suppress stderr", and a caller who asks
/// for silence and gets a stack trace from a dependency has been told nothing
/// useful and given something to filter.
///
/// This product's own prose does not travel through tracing: it is written with
/// `eprintln!` behind an explicit `if !quiet`, so turning the subscriber off
/// silences the dependencies without silencing the localised hints.
///
/// `store` carries the persisted `log-level`, `log-format` and `log-timestamps`
/// keys. The flags still win: `-q` and `-v` are what the operator typed for
/// THIS run, while the configuration is the standing preference. Without the
/// keys there was no standing preference at all, and the JSON writer that
/// `tracing-subscriber` was already compiled with could never be reached.
///
/// This runs after the store is loaded rather than before, because a default
/// that lives in the configuration cannot be honoured by a subscriber that was
/// installed before the configuration was read. Nothing of this product's own
/// prose is lost by the move: it never travelled through tracing.
fn init_tracing(quiet: bool, verbose: u8, store: Option<&config::Store>) {
    let configured = store
        .map(config::Store::effective)
        .and_then(|e| e.log_level.or(config::Store::seeds().log_level))
        .and_then(|name| match name.as_str() {
            "off" => Some(LevelFilter::OFF),
            "error" => Some(LevelFilter::ERROR),
            "warn" => Some(LevelFilter::WARN),
            "info" => Some(LevelFilter::INFO),
            "debug" => Some(LevelFilter::DEBUG),
            "trace" => Some(LevelFilter::TRACE),
            _ => None,
        });
    let level = if quiet {
        LevelFilter::OFF
    } else {
        match verbose {
            0 => configured.unwrap_or(LevelFilter::WARN),
            1 => LevelFilter::INFO,
            2 => LevelFilter::DEBUG,
            _ => LevelFilter::TRACE,
        }
    };
    let effective = store.map(config::Store::effective);
    let seeds = config::Store::seeds();
    let json = effective
        .as_ref()
        .and_then(|e| e.log_format.clone())
        .or(seeds.log_format)
        .is_some_and(|f| f == "json");
    let timestamps = effective
        .as_ref()
        .and_then(|e| e.log_timestamps)
        .or(seeds.log_timestamps)
        .unwrap_or(false);

    // Four shapes, and the builder types differ, so each one is built whole.
    // `without_time` and `.json()` both change the type, which is why this is
    // a match on two booleans rather than a chain of conditional calls.
    let _ = match (json, timestamps) {
        (true, true) => tracing_subscriber::fmt()
            .json()
            .with_max_level(level)
            .with_writer(std::io::stderr)
            .with_ansi(false)
            .try_init(),
        (true, false) => tracing_subscriber::fmt()
            .json()
            .with_max_level(level)
            .with_writer(std::io::stderr)
            .with_ansi(false)
            .without_time()
            .try_init(),
        (false, true) => tracing_subscriber::fmt()
            .with_max_level(level)
            .with_writer(std::io::stderr)
            .with_ansi(false)
            .try_init(),
        (false, false) => tracing_subscriber::fmt()
            .with_max_level(level)
            .with_writer(std::io::stderr)
            .with_ansi(false)
            .without_time()
            .try_init(),
    };
}