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,
)
}
}
}
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)
}
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,
"engine": crate::engine::backend(),
}),
ctx.surface,
)
}
pub(crate) fn completions(shell: clap_complete::Shell) -> Result<(), Error> {
use clap::CommandFactory;
use std::io::Write;
let mut cmd = crate::cli::Cli::command();
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 } => {
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> {
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();
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,
)
}
}
}
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())?;
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},
{"name": "engine", "ok": crate::engine::backend() == "cuda", "detail": crate::engine::backend()},
{"name": "memory_cap", "ok": gpu::memory_cap_is_measurable(), "detail": gpu::memory_cap_source()},
{"name": "child_tree_signal", "ok": cfg!(unix), "detail": std::env::consts::FAMILY},
]);
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)?;
ctx.error_reported = true;
match failure {
Some(err) => Err(err),
None => Ok(()),
}
}