whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
Documentation
//! UI locale for stderr. JSON contract keys stay English.

use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::FluentResource;
use std::sync::OnceLock;
use unic_langid::LanguageIdentifier;

const EN: &str = include_str!("../locales/en.ftl");
const PT: &str = include_str!("../locales/pt-BR.ftl");

/// Resolved interface language.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UiLang {
    /// English.
    En,
    /// Brazilian Portuguese.
    PtBr,
}

impl UiLang {
    /// Parse an explicit tag or fall back to the operating system locale.
    ///
    /// A tag that is well-formed but has no translation in this build is not a
    /// usage error: it degrades to English with a warning on stderr and the run
    /// continues. The implicit system-locale path has always degraded that way,
    /// so an operator on a Spanish desktop worked while the same operator
    /// writing `--lang es` was turned away at exit 2 — the same fact, answered
    /// two ways. Only a tag `unic_langid` refuses to parse is malformed argv,
    /// and that still exits 2, because there the argument itself is wrong
    /// rather than merely unsupported.
    pub fn resolve(explicit: Option<&str>) -> Result<Self, crate::error::Error> {
        if let Some(tag) = explicit {
            return Ok(match parse_tag(tag)? {
                Some(lang) => lang,
                None => {
                    // The caller resolves twice per run, once before the stored
                    // configuration is read and once after, so an unguarded
                    // warning printed the same line to stderr twice.
                    static WARNED: OnceLock<()> = OnceLock::new();
                    if WARNED.set(()).is_ok() {
                        eprintln!("{}: {tag}", tr(Self::En, "lang_unsupported"));
                    }
                    Self::En
                }
            });
        }
        let sys = sys_locale::get_locale().unwrap_or_else(|| "en".into());
        Ok(parse_tag(&sys).ok().flatten().unwrap_or(Self::En))
    }

    /// Parse a tag that is about to be written to the stored configuration.
    ///
    /// Deliberately stricter than [`Self::resolve`], and the two must stay
    /// apart. `--lang es` is a decision about the run in front of the operator,
    /// who wants to work now, so a language this build cannot speak degrades to
    /// English and the verb still does its job. `config set locale es` is a
    /// decision about every future run: persisting a value that will never be
    /// honoured writes a preference the product silently ignores forever, and
    /// the operator learns nothing at the one moment they could still fix it.
    ///
    /// So a well-formed tag with no translation is `Err` here and `Ok` there.
    /// A malformed tag is `Err` on both paths, for the same reason as always.
    pub fn resolve_strict(tag: &str) -> Result<Self, crate::error::Error> {
        parse_tag(tag)?
            .ok_or_else(|| crate::error::Error::Usage(format!("unsupported locale: {tag}")))
    }

    /// Fluent resource body for this language.
    pub fn resource(self) -> &'static str {
        match self {
            Self::En => EN,
            Self::PtBr => PT,
        }
    }

    /// The language identifier Fluent resolves plurals and dates against.
    ///
    /// Parsed from [`Self::tag`] so the two can never disagree; both tags are
    /// literals known to be valid BCP47, and a failure here would mean the
    /// constant itself was mistyped.
    pub fn langid(self) -> LanguageIdentifier {
        self.tag()
            .parse()
            .unwrap_or_else(|_| "en".parse().expect("en is a valid language tag"))
    }

    /// BCP47 tag used in envelopes.
    pub fn tag(self) -> &'static str {
        match self {
            Self::En => "en",
            Self::PtBr => "pt-BR",
        }
    }
}

/// Map a language tag to the translation this build ships for it.
///
/// `Ok(None)` says the tag is well-formed but unsupported, which the caller
/// answers by degrading to English. `Err` is reserved for a tag that is not a
/// language tag at all.
fn parse_tag(tag: &str) -> Result<Option<UiLang>, crate::error::Error> {
    let lid: LanguageIdentifier = tag
        .parse()
        .map_err(|_| crate::error::Error::Usage(format!("malformed locale tag: {tag}")))?;
    Ok(match lid.language.as_str() {
        "pt" => Some(UiLang::PtBr),
        "en" => Some(UiLang::En),
        _ => None,
    })
}

/// Build a Fluent bundle for one language.
///
/// A malformed resource yields `None` rather than a panic: a broken translation
/// must degrade to the other language, never take the process down on a path
/// whose only job is to phrase a message.
fn build_bundle(lang: UiLang) -> Option<FluentBundle<FluentResource>> {
    let resource = FluentResource::try_new(lang.resource().to_string()).ok()?;
    let mut bundle = FluentBundle::new_concurrent(vec![lang.langid()]);
    // Fluent isolates interpolated values with Unicode bidi marks by default.
    // They are invisible in a terminal but real bytes, and this text is read by
    // humans on stderr and compared byte-for-byte by tests.
    bundle.set_use_isolating(false);
    bundle.add_resource(resource).ok()?;
    Some(bundle)
}

/// The bundle for one language, parsed once per process.
///
/// This used to build the bundle on every call, which copied the whole `.ftl`
/// into an owned `String` and reparsed it; `tr` tries up to two languages, so a
/// single line of stderr paid for up to two full parses of a file that is
/// baked into the binary and can never change at runtime. `OnceLock` is the
/// same cache the project already uses for the regex in `audio.rs`.
///
/// The concurrent bundle is used rather than the default one because a `static`
/// must be `Sync`, and the default bundle's memoizer is not. A resource that
/// fails to parse is cached as `None`, so degradation to the other language is
/// unchanged — it is simply decided once instead of on every message.
fn bundle_for(lang: UiLang) -> Option<&'static FluentBundle<FluentResource>> {
    static EN_BUNDLE: OnceLock<Option<FluentBundle<FluentResource>>> = OnceLock::new();
    static PT_BUNDLE: OnceLock<Option<FluentBundle<FluentResource>>> = OnceLock::new();
    let cell = match lang {
        UiLang::En => &EN_BUNDLE,
        UiLang::PtBr => &PT_BUNDLE,
    };
    cell.get_or_init(|| build_bundle(lang)).as_ref()
}

/// Look up a stderr message, falling back to English and then to the key.
///
/// This used to scan the `.ftl` line by line looking for one that started with
/// `"{key} ="`, building that needle with `format!` on every candidate line.
/// `fluent-bundle` was already a declared dependency and was never used: the
/// project paid for a Fluent implementation and then hand-rolled a worse one.
///
/// The hand-rolled reader was not merely slower. It could only ever see
/// single-line messages with no placeables, so the two features that justify
/// the Fluent format — multi-line messages and interpolated values like
/// `{ $device }` — silently returned the wrong text, or the key name, the first
/// time anyone used them. Behaviour is unchanged for the six messages that
/// exist today; what changes is that the next message can be a real one.
pub fn tr(lang: UiLang, key: &str) -> String {
    for candidate in [lang, UiLang::En] {
        let Some(bundle) = bundle_for(candidate) else {
            continue;
        };
        let Some(message) = bundle.get_message(key) else {
            continue;
        };
        let Some(pattern) = message.value() else {
            continue;
        };
        let mut errors = Vec::new();
        let text = bundle.format_pattern(pattern, None, &mut errors);
        if errors.is_empty() {
            return text.into_owned();
        }
    }
    // A key with no message anywhere is a programming error, not a user error.
    // Echoing the key is deliberate: it is greppable and it never pretends to
    // be prose the operator was meant to read.
    key.to_string()
}

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

    /// Split a Fluent resource into `key -> value`, skipping comments and blanks.
    fn entries(body: &str) -> BTreeMap<String, String> {
        body.lines()
            .map(str::trim_end)
            .filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
            .filter_map(|l| l.split_once('='))
            .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
            .collect()
    }

    #[test]
    fn pt_does_not_change_json_keys() {
        assert_eq!(UiLang::resolve(Some("pt-BR")).unwrap(), UiLang::PtBr);
        assert_eq!(
            tr(UiLang::PtBr, "warn_cuda_env"),
            tr(UiLang::PtBr, "warn_cuda_env")
        );
        assert!(tr(UiLang::En, "warn_cuda_env").contains("CUDA_VISIBLE_DEVICES"));
    }

    #[test]
    fn both_locales_expose_the_same_keys() {
        let en: Vec<String> = entries(EN).into_keys().collect();
        let pt: Vec<String> = entries(PT).into_keys().collect();
        assert!(!en.is_empty(), "en.ftl must not be empty");
        assert_eq!(en, pt, "en.ftl and pt-BR.ftl must expose identical keys");
    }

    #[test]
    fn every_ftl_key_is_valid_utf8_and_nonempty() {
        for (name, body) in [("en", EN), ("pt-BR", PT)] {
            let map = entries(body);
            assert!(!map.is_empty(), "{name}.ftl has no entries");
            for (key, value) in map {
                assert!(!key.is_empty(), "{name}.ftl has an empty key");
                assert!(
                    !value.is_empty(),
                    "{name}.ftl key `{key}` has an empty value"
                );
                // `tr` must return the translation, never the key fallback.
                let lang = if name == "en" {
                    UiLang::En
                } else {
                    UiLang::PtBr
                };
                assert_eq!(tr(lang, &key), value, "tr mismatch for {name}.ftl `{key}`");
            }
        }
    }

    /// A malformed tag is still argv the parser cannot read, so it still exits 2.
    #[test]
    fn malformed_locale_tag_is_usage() {
        for tag in ["!!", "en_US_bogus_tag"] {
            let err = UiLang::resolve(Some(tag)).expect_err("a malformed tag must be rejected");
            assert_eq!(
                err.exit_code(),
                2,
                "{tag} is malformed and must be a usage error"
            );
        }
    }

    /// A well-formed tag with no translation degrades instead of failing.
    ///
    /// `xx` used to exit 2 here while an `xx` system locale silently produced
    /// English. This test pins the side that keeps the operator working.
    #[test]
    fn unsupported_but_valid_tag_degrades_to_english() {
        for tag in ["es", "xx", "ja-JP"] {
            assert_eq!(
                UiLang::resolve(Some(tag)).expect("a well-formed tag is not a usage error"),
                UiLang::En,
                "{tag} must degrade to English"
            );
        }
    }

    /// Use degrades where configuration refuses, and that gap is the contract.
    ///
    /// `--lang es` must let the operator work now; `config set locale es` must
    /// not write a preference this build can never honour. Both answers come
    /// from the same tag, so only a test can keep them from drifting into one.
    #[test]
    fn strict_refuses_what_resolve_degrades() {
        for tag in ["es", "xx", "ja-JP"] {
            assert_eq!(
                UiLang::resolve(Some(tag)).expect("use must degrade, not fail"),
                UiLang::En,
                "{tag} must degrade for --lang"
            );
            let err = UiLang::resolve_strict(tag).expect_err("config must refuse");
            assert_eq!(err.exit_code(), 2, "{tag} must not be persisted");
        }
        // A shipped language is accepted by both paths.
        assert_eq!(
            UiLang::resolve_strict("pt-BR").expect("pt-BR ships with this build"),
            UiLang::PtBr
        );
        // A malformed tag stays a usage error on the strict path too.
        let err = UiLang::resolve_strict("!!").expect_err("!! is not a language tag");
        assert_eq!(err.exit_code(), 2);
    }

    /// The cached bundle must answer the same bytes every time.
    #[test]
    fn tr_is_stable_across_calls() {
        for lang in [UiLang::En, UiLang::PtBr] {
            let first = tr(lang, "gpu_missing");
            let second = tr(lang, "gpu_missing");
            assert!(!first.is_empty(), "{} lost gpu_missing", lang.tag());
            assert_eq!(first, second, "{} is not stable across calls", lang.tag());
        }
    }

    #[test]
    fn pt_variants_resolve_to_ptbr() {
        for tag in ["pt", "pt-BR", "pt-PT"] {
            assert_eq!(
                UiLang::resolve(Some(tag)).unwrap(),
                UiLang::PtBr,
                "{tag} must resolve to pt-BR"
            );
        }
    }

    /// `tr` anchors on `"{key} ="`, so a key that is a prefix of another key
    /// must never borrow the longer key's value.
    #[test]
    fn tr_does_not_match_key_prefix() {
        // `gpu` is a strict prefix of the real key `gpu_missing`.
        assert!(entries(EN).contains_key("gpu_missing"));
        assert!(!entries(EN).contains_key("gpu"));
        assert_eq!(tr(UiLang::En, "gpu"), "gpu");
        assert_ne!(tr(UiLang::En, "gpu"), tr(UiLang::En, "gpu_missing"));

        // Same for `need`, a strict prefix of `need_yes`.
        assert_eq!(tr(UiLang::PtBr, "need"), "need");
        assert_ne!(tr(UiLang::PtBr, "need"), tr(UiLang::PtBr, "need_yes"));
    }
}