capri-voice: add install module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent 9f09566972
commit 5e5131bc6e
1 file changed
+160
+160
View File
@@ -0,0 +1,160 @@
//! Speech installation as a cancellable job with progress (replaces Capri's `speech-install-service.mjs` and its
//! PowerShell/Python setup): pinned, hash-verified downloads only — no Python, venv or package manager.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail, ensure};
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use crate::download::{Pinned, download_verified, free_bytes, http_client};
use crate::{asr, tts};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Phase {
#[default]
Idle,
Installing,
Ready,
Error,
Cancelled,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InstallStatus {
pub phase: Phase,
/// checking, recognition, voice-pack, voice-models.
pub stage: String,
/// 0..1 within the current file.
pub progress: Option<f32>,
/// File being downloaded.
pub detail: String,
pub error: Option<String>,
}
/// What to install. `None` = off.
#[derive(Clone, Debug, PartialEq)]
pub struct Selection {
/// Whisper model id.
pub recognition: Option<String>,
/// Speech language and quality (`balanced` or `full`).
pub speech: Option<(String, String)>,
}
fn log_event(logs: &Path, stage: &str, event: &str, code: Option<&str>) {
use std::io::Write;
let file = logs.join("speech-install.log");
if std::fs::metadata(&file).is_ok_and(|m| m.len() > 2 << 20) {
let _ = std::fs::remove_file(&file);
}
let time = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
// Allowlisted fields only: stage, event and code, never paths, URLs or text.
let line = serde_json::json!({"schemaVersion": 1, "service": "speech-install", "stage": stage, "event": event, "code": code, "time": time});
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(file) {
let _ = writeln!(f, "{line}");
}
}
/// Installs `selection` into `speech` (`<data>/speech`). On return the phase is Ready, Error or Cancelled.
pub async fn install(speech: &Path, logs: &Path, selection: &Selection, status: &watch::Sender<InstallStatus>, cancel: &CancellationToken) -> Result<()> {
let _ = std::fs::create_dir_all(logs);
let result = steps(speech, logs, selection, status, cancel).await;
let stage = status.borrow().stage.clone();
match &result {
Ok(()) => {
log_event(logs, &stage, "ready", None);
status.send_replace(InstallStatus { phase: Phase::Ready, stage: "ready".into(), progress: Some(1.0), ..Default::default() });
}
Err(e) => {
let cancelled = cancel.is_cancelled();
log_event(logs, &stage, "failure", Some(if cancelled { "CANCELLED" } else { "FAILED" }));
status.send_modify(|s| {
s.phase = if cancelled { Phase::Cancelled } else { Phase::Error };
s.error = Some(if cancelled { "Installation cancelled. Partial downloads are kept.".into() } else { format!("{e:#}") });
});
}
}
result
}
async fn steps(speech: &Path, logs: &Path, selection: &Selection, status: &watch::Sender<InstallStatus>, cancel: &CancellationToken) -> Result<()> {
ensure!(selection.recognition.is_some() || selection.speech.is_some(), "Choose a supported voice or recognition language.");
let stage = |name: &str| {
log_event(logs, name, "stage", None);
status.send_replace(InstallStatus { phase: Phase::Installing, stage: name.into(), ..Default::default() });
};
let http = http_client();
let fetch = |pin: Pinned, target: PathBuf| {
let http = http.clone();
async move {
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
status.send_modify(|s| (s.detail, s.progress) = (name, Some(0.0)));
let progress = |done: u64, total: u64| status.send_modify(|s| s.progress = Some(done as f32 / total.max(1) as f32));
tokio::select! {
biased;
_ = cancel.cancelled() => bail!("Installation cancelled"),
r = download_verified(&http, &pin, &target, &progress) => r,
}
}
};
stage("checking");
let mut needed = 0;
if let Some(model) = &selection.recognition {
needed += asr::model_pin(model).context("Unknown speech recognition model")?.bytes;
}
if let Some((language, quality)) = &selection.speech {
ensure!(crate::settings::SPEECH_LANGUAGES.contains(&language.as_str()), "No spoken voice is available for this language.");
needed += tts::download_bytes(language, quality);
}
if let Some(free) = free_bytes(speech) {
ensure!(free >= needed + (1 << 30), "Not enough free space: {:.1} GB needed.", (needed + (1 << 30)) as f64 / 1e9);
}
if let Some(model) = &selection.recognition {
stage("recognition");
fetch(asr::silero_pin(), asr::silero_path(speech)).await?;
fetch(asr::model_pin(model).unwrap(), asr::model_path(speech, model)).await?;
}
let Some((language, quality)) = &selection.speech else { return Ok(()) };
stage("voice-pack");
if !tts::reference_path(speech).is_file() {
let pack = speech.join("downloads/capri-en-v1.zip");
fetch(tts::voice_pack_pin(), pack.clone()).await?;
tts::extract_reference(&pack, &tts::reference_path(speech))?;
}
stage("voice-models");
for (pin, target) in tts::model_files(speech, language, quality) {
fetch(pin, target).await?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn selection_must_choose_something_and_failures_are_logged() {
let dir = tempfile::tempdir().unwrap();
let (status, rx) = watch::channel(InstallStatus::default());
let none = Selection { recognition: None, speech: None };
assert!(install(dir.path(), &dir.path().join("logs"), &none, &status, &CancellationToken::new()).await.is_err());
assert_eq!(rx.borrow().phase, Phase::Error);
let log = std::fs::read_to_string(dir.path().join("logs/speech-install.log")).unwrap();
assert!(log.contains("\"failure\"") && !log.contains(dir.path().to_str().unwrap()), "log holds no paths");
let unknown = Selection { recognition: None, speech: Some(("xx".into(), "balanced".into())) };
assert!(install(dir.path(), &dir.path().join("logs"), &unknown, &status, &CancellationToken::new()).await.is_err());
}
#[tokio::test]
async fn cancellation_stops_a_download() {
let dir = tempfile::tempdir().unwrap();
let (status, rx) = watch::channel(InstallStatus::default());
let cancel = CancellationToken::new();
cancel.cancel();
let selection = Selection { recognition: Some(asr::DEFAULT_MODEL.into()), speech: None };
assert!(install(dir.path(), &dir.path().join("logs"), &selection, &status, &cancel).await.is_err());
assert_eq!(rx.borrow().phase, Phase::Cancelled);
}
}