diff --git a/crates/capri-voice/src/tts.rs b/crates/capri-voice/src/tts.rs new file mode 100644 index 0000000..da33c85 --- /dev/null +++ b/crates/capri-voice/src/tts.rs @@ -0,0 +1,495 @@ +//! Capri's voice in Rust: Chatterbox ONNX exports run with ONNX Runtime, conditioned on Capri's reference voice. +//! +//! Capri 1.0.4 ran Chatterbox in PyTorch: Turbo + a trained Capri LoRA for English, Multilingual v3 with the Capri +//! reference for 22 other languages. Here: `ResembleAI/chatterbox-turbo-ONNX` (English) and +//! `onnx-community/chatterbox-multilingual-ONNX` (23 languages), both zero-shot cloned from Capri's `neutral.wav` +//! reference (CapriCore voice pack). Quality trade-offs are listed in the README: no LoRA adapter, no CFG for +//! multilingual, quantized language models by default, no Perth watermark, CPU by default. +use std::borrow::Cow; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; + +use anyhow::{Context, Result, bail, ensure}; +use ort::session::{Session, SessionInputValue}; +use ort::value::{DynValue, Tensor}; + +use crate::download::{Pinned, present}; + +pub const SAMPLE_RATE: u32 = 24_000; +const START_SPEECH: i64 = 6561; +const STOP_SPEECH: i64 = 6562; +const SILENCE: i64 = 4299; +const KV_HEADS: usize = 16; +const HEAD_DIM: usize = 64; +/// Capri `companion-voice.json`: maxSpeechTokens 800, seed 417. +const MAX_TOKENS: usize = 800; +const SEED: u64 = 417; +const MAX_SAMPLES: usize = 24_000 * 45; + +struct File(&'static str, u64, &'static str); + +struct Model { + repo: &'static str, + revision: &'static str, + dir: &'static str, + common: &'static [File], + balanced: &'static [File], + full: &'static [File], +} + +const TURBO: Model = Model { + repo: "ResembleAI/chatterbox-turbo-ONNX", + revision: "d21799bd0354adb85e348b8a0442a8405110a2cf", + dir: "chatterbox-turbo-onnx", + common: &[ + File("tokenizer.json", 3_562_272, "3f04e34bea22f9144d1a19151154095bc9ce0430bf421304f5797e716288a906"), + File("onnx/conditional_decoder.onnx", 1_889_468, "8c43f3a1d0ddb1a86e226a244d7cda5396c67f5c6412789c23900c646e3ffc50"), + File("onnx/conditional_decoder.onnx_data", 768_593_792, "05f162a519f3e9abaf0b7337ae037f4af8b2b30c4455d39b2c61ed3a9b2b5476"), + ], + balanced: &[ + File("onnx/speech_encoder_q4.onnx", 1_200_346, "37956c20b67bed85a0da4bc83509d67b5969a1b257d1c546516a5236a17ad71e"), + File("onnx/speech_encoder_q4.onnx_data", 229_560_112, "58956db217c6443e49c91bdd54d7cf76b4a243f225c748b7bf746459fc27bc7d"), + File("onnx/embed_tokens_q4.onnx", 2844, "fd6ba1d22902e8f539d3dd6d7c1c44b98ebb4c84ebbb5e47fcb826ddcf667561"), + File("onnx/embed_tokens_q4.onnx_data", 37_286_384, "f54a51e234b509b64c3a03bb79e1149fba7e2eba6c2d9c222f18883379e1f5d8"), + File("onnx/language_model_q4.onnx", 274_572, "b39d03d3f8b943b9e60c6fce3fb41191dbc1df4589f913291db1e214eef669b1"), + File("onnx/language_model_q4.onnx_data", 204_456_572, "2c029dc0acf48752473d8c74c72b5ceaaad76b9886fe106eaf2022142d5b5d5e"), + ], + full: &[ + File("onnx/speech_encoder.onnx", 1_172_072, "4d66128037517dd51d370edc9b89ce36d42c75dcbd96e7216c7fb45dfae36045"), + File("onnx/speech_encoder.onnx_data", 1_044_712_832, "c9915ff6c529e7bb80983b525255e6744d6c39c7e35b12720925ba99ed0d0a2f"), + File("onnx/embed_tokens.onnx", 2058, "27796e8252f36b463b0421cafdcc35b5f1e670ab0d96c9182f37ac6571c2f4bc"), + File("onnx/embed_tokens.onnx_data", 232_812_544, "a1c37edc6ec6adb655351f02e958da297221b50211c2c01b69312cb6f008a293"), + File("onnx/language_model.onnx", 207_266, "c12e31df78c74f9589b165c8d51e65171f5028b77b7fedb41900f55f7f410dc8"), + File("onnx/language_model.onnx_data", 1_269_724_812, "67db106868f5354b2e425651f1791aef36ae3e6f00ac5e1d91e32c985cad6b39"), + ], +}; + +const MULTILINGUAL: Model = Model { + repo: "onnx-community/chatterbox-multilingual-ONNX", + revision: "452d3f434aa592098f1eedac9099f33642ab2da5", + dir: "chatterbox-multilingual-onnx", + common: &[ + File("tokenizer.json", 71_798, "29d48c4a178f6af3ad5130097c34744639e9294847b38a7b912c8c68027cb819"), + File("onnx/speech_encoder.onnx", 1_184_608, "8f1c8a0f89b77bf9cd5dd8f2e034eb2c79dc00fe70d41196b28c257643b00ccb"), + File("onnx/speech_encoder.onnx_data", 591_274_880, "92f8f290fc9720e169bc2412c507209e20b03f6564bc3243739e25c56f7dfb8f"), + File("onnx/embed_tokens.onnx", 13_286, "f785819ca4f6271262d5bb8971d62796c3a909e3b031982c113dbe83a4c3b854"), + File("onnx/embed_tokens.onnx_data", 68_390_912, "2a15f7dd73b2ee47f6edf87740324011594b5a528ed6471ae55e327ed6cad68c"), + File("onnx/conditional_decoder.onnx", 6_350_448, "1656d0d31332bae1854839959a3139300ebb67c178651dfa3f8c5fbfa5351351"), + File("onnx/conditional_decoder.onnx_data", 533_970_816, "51d58345a272747665ec9d5bb61e01835258a940e321a288582ac4c18cf01b5a"), + ], + balanced: &[ + File("onnx/language_model_q4.onnx", 227_911, "7f8cdca83b2493536cbf3acf421199808a3d68736f55f4eabd20ef8a99da4313"), + File("onnx/language_model_q4.onnx_data", 353_621_248, "e79ab8784122a501718868b9631ff46e151c552d9b24e50f25d721f375e3526c"), + ], + full: &[ + File("onnx/language_model.onnx", 171_387, "861a34585605e8ad671051788afc495dcbeaee833a41523a1b33aded9c3babc7"), + File("onnx/language_model.onnx_data", 2_080_632_832, "b3556d41085196c122b7197e4d44ec4475b6d7cfe0971a70faa95caa38ad787a"), + ], +}; + +/// English uses Turbo (Capri's English model); every other speech language the multilingual model. +fn model(language: &str) -> &'static Model { + if language == "en" { &TURBO } else { &MULTILINGUAL } +} + +fn chosen(model: &'static Model, quality: &str) -> impl Iterator { + model.common.iter().chain(if quality == "full" { model.full } else { model.balanced }) +} + +/// Pinned files and their local paths for a language and quality (`balanced` or `full`). +pub fn model_files(speech: &Path, language: &str, quality: &str) -> Vec<(Pinned, PathBuf)> { + let m = model(language); + chosen(m, quality) + .map(|f| (Pinned::new(format!("https://huggingface.co/{}/resolve/{}/{}", m.repo, m.revision, f.0), f.1, f.2), speech.join(m.dir).join(f.0))) + .collect() +} + +pub fn download_bytes(language: &str, quality: &str) -> u64 { + chosen(model(language), quality).map(|f| f.1).sum() +} + +/// Capri's neutral reference voice, extracted from the CapriCore v1.0.4 voice pack. +pub fn reference_path(speech: &Path) -> PathBuf { + speech.join("voices/capri-neutral.wav") +} + +pub fn voice_pack_pin() -> Pinned { + Pinned::new("https://github.com/CapriChooms/CapriCore/releases/download/v1.0.4/capri-en-v1.zip", 12_568_243, "901ef341ffb59a711f375e1625c23679d1c99667c1c3339a2809efaecd4d32f7") +} + +pub fn installed(speech: &Path, language: &str, quality: &str) -> bool { + reference_path(speech).is_file() && model_files(speech, language, quality).iter().all(|(p, path)| present(path, p.bytes)) +} + +/// Extracts `references/neutral.wav` from the voice pack and checks it against the pack's `voice-profile.json`. +pub fn extract_reference(pack: &Path, target: &Path) -> Result<()> { + use std::io::Read; + let mut zip = zip::ZipArchive::new(std::fs::File::open(pack)?)?; + let profile_name = zip.file_names().find_map(|n| n.ok().filter(|n| n.ends_with("voice-profile.json")).map(|n| n.to_string())).context("The Capri voice pack has no profile")?; + let prefix = profile_name.trim_end_matches("voice-profile.json").to_string(); + let mut profile = String::new(); + zip.by_name(&profile_name)?.take(64 << 10).read_to_string(&mut profile)?; + let profile: serde_json::Value = serde_json::from_str(&profile)?; + let reference = &profile["references"]["neutral"]; + let (file, sha) = (reference["file"].as_str().context("No neutral reference")?, reference["sha256"].as_str().context("No reference checksum")?); + ensure!(file.starts_with("references/") && file.ends_with(".wav") && !file.contains(".."), "Invalid reference name"); + let mut wav = Vec::new(); + zip.by_name(&format!("{prefix}{file}"))?.take(50 << 20).read_to_end(&mut wav)?; + ensure!(hex::encode(::digest(&wav)) == sha, "Voice pack checksum mismatch"); + std::fs::create_dir_all(target.parent().unwrap())?; + capri_core::fsutil::write_atomic(target, &wav) +} + +/// Mono f32 at 24 kHz from a WAV file. +pub fn load_wav(path: &Path) -> Result> { + let mut reader = hound::WavReader::open(path)?; + let spec = reader.spec(); + let samples: Vec = match spec.sample_format { + hound::SampleFormat::Float => reader.samples::().collect::>()?, + hound::SampleFormat::Int => { + let scale = (1i64 << (spec.bits_per_sample - 1)) as f32; + reader.samples::().map(|s| s.map(|v| v as f32 / scale)).collect::>()? + } + }; + let channels = spec.channels.max(1) as usize; + let mono: Vec = samples.chunks(channels).map(|c| c.iter().sum::() / channels as f32).collect(); + crate::capture::resample_clip(&mono, spec.sample_rate, SAMPLE_RATE) +} + +/// Chatterbox's `punc_norm`: capital first letter, common punctuation, and a final stop. +pub fn punctuation_normalized(text: &str) -> String { + let mut text = text.split_whitespace().collect::>().join(" "); + if text.is_empty() { + return "You need to add some text for me to talk.".into(); + } + if let Some(first) = text.chars().next().filter(|c| c.is_lowercase()) { + text = first.to_uppercase().chain(text.chars().skip(1)).collect(); + } + for (from, to) in [("...", ", "), ("…", ", "), (":", ","), (" - ", ", "), (";", ", "), ("—", "-"), ("–", "-"), (" ,", ","), ("“", "\""), ("”", "\""), ("‘", "'"), ("’", "'")] { + text = text.replace(from, to); + } + let text = text.trim_end().to_string(); + if [".", "!", "?", "-", ",", "、", ",", "。", "?", "!"].iter().any(|e| text.ends_with(e)) { text } else { text + "." } +} + +/// Korean syllables decomposed into jamo (the multilingual tokenizer's input form). +pub fn korean_normalized(text: &str) -> String { + let mut out = String::new(); + for c in text.chars() { + let code = c as u32; + if (0xAC00..=0xD7A3).contains(&code) { + let base = code - 0xAC00; + out.extend([char::from_u32(0x1100 + base / (21 * 28)), char::from_u32(0x1161 + (base % (21 * 28)) / 28)].into_iter().flatten()); + if !base.is_multiple_of(28) { + out.extend(char::from_u32(0x11A7 + base % 28)); + } + } else { + out.push(c); + } + } + out.trim().to_string() +} + +/// Deterministic generator for per-phrase sampling (SplitMix64). +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_add(0x9E3779B97F4A7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB); + ((z ^ (z >> 31)) >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// Capri's sampling: repetition penalty 1.2, temperature 0.8, top-k 1000, top-p 0.95. +fn sample(logits: &[f32], previous: &[i64], rng: &mut Rng) -> i64 { + let mut l = logits.to_vec(); + let mut seen = std::collections::HashSet::new(); + for &t in previous { + if let Some(s) = l.get_mut(t as usize) + && seen.insert(t) + { + *s = if *s < 0.0 { *s * 1.2 } else { *s / 1.2 }; + } + } + let mut order: Vec = (0..l.len()).collect(); + order.sort_by(|a, b| l[*b].total_cmp(&l[*a])); + order.truncate(1000); + let max = l[order[0]] / 0.8; + let weights: Vec = order.iter().map(|&i| ((l[i] / 0.8 - max) as f64).exp()).collect(); + let total: f64 = weights.iter().sum(); + let (mut kept, mut cumulative) = (0, 0.0); + while kept < order.len() { + cumulative += weights[kept] / total; + kept += 1; + if cumulative >= 0.95 { + break; + } + } + let mut u = rng.next() * weights[..kept].iter().sum::(); + for (i, w) in weights[..kept].iter().enumerate() { + u -= w; + if u <= 0.0 { + return order[i] as i64; + } + } + order[kept - 1] as i64 +} + +fn tensor_f32(shape: Vec, data: Vec) -> Result { + Ok(Tensor::from_array((shape, data))?.into_dyn()) +} + +fn tensor_i64(shape: Vec, data: Vec) -> Result { + Ok(Tensor::from_array((shape, data))?.into_dyn()) +} + +fn owned_f32(value: &DynValue) -> Result<(Vec, Vec)> { + let (shape, data) = value.try_extract_tensor::()?; + Ok((shape.iter().map(|d| *d as usize).collect(), data.to_vec())) +} + +/// Speaker conditioning from the reference voice, computed once per load. +struct Conditioning { + cond_emb: (Vec, Vec), + prompt_tokens: Vec, + speaker_embeddings: (Vec, Vec), + speaker_features: (Vec, Vec), +} + +pub struct Chatterbox { + tokenizer: tokenizers::Tokenizer, + embed: Session, + lm: Session, + decoder: Session, + cond: Conditioning, + multilingual: bool, + past: Vec, + present: Vec, +} + +fn session(env: &ort::environment::Environment, path: &Path, threads: usize) -> Result { + Session::builder(env)? + .with_intra_threads(threads) + .map_err(|e| anyhow::anyhow!("{e}"))? + .commit_from_file(path) + .with_context(|| format!("Cannot load {}", path.display())) +} + +impl Chatterbox { + /// Loads the model for `language` and conditions it on `reference` (24 kHz mono). + pub fn load(speech: &Path, language: &str, quality: &str, reference: &[f32], threads: usize) -> Result { + let m = model(language); + let dir = speech.join(m.dir); + let graph = |name: &str| { + let full = dir.join(format!("onnx/{name}.onnx")); + if quality == "full" || name == "conditional_decoder" || (m.dir == MULTILINGUAL.dir && name != "language_model") { full } else { dir.join(format!("onnx/{name}_q4.onnx")) } + }; + let env = crate::ort_env()?; + let tokenizer = tokenizers::Tokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| anyhow::anyhow!("Invalid voice tokenizer: {e}"))?; + let mut encoder = session(env, &graph("speech_encoder"), threads)?; + ensure!(!reference.is_empty(), "The reference voice is empty"); + let out = encoder.run(ort::inputs!["audio_values" => tensor_f32(vec![1, reference.len()], reference.to_vec())?])?; + let cond = Conditioning { + cond_emb: owned_f32(&out[0])?, + prompt_tokens: out[1].try_extract_tensor::()?.1.to_vec(), + speaker_embeddings: owned_f32(&out[2])?, + speaker_features: owned_f32(&out[3])?, + }; + drop(out); + drop(encoder); // only needed once: frees its memory + let lm = session(env, &graph("language_model"), threads)?; + let past: Vec = lm.inputs().iter().map(|i| i.name().to_string()).filter(|n| n.contains("past_key_values")).collect(); + let present: Vec = lm.outputs().iter().skip(1).map(|o| o.name().to_string()).collect(); + ensure!(past.len() == present.len() && !past.is_empty(), "Unexpected voice model layout"); + let embed = session(env, &graph("embed_tokens"), threads)?; + let multilingual = embed.inputs().iter().any(|i| i.name() == "exaggeration"); + let decoder = session(env, &graph("conditional_decoder"), threads)?; + Ok(Self { tokenizer, embed, lm, decoder, cond, multilingual, past, present }) + } + + fn embed(&mut self, ids: &[i64], positions: &[i64]) -> Result<(Vec, Vec)> { + let mut inputs: Vec<(Cow<'static, str>, SessionInputValue<'_>)> = vec![("input_ids".into(), tensor_i64(vec![1, ids.len()], ids.to_vec())?.into())]; + if self.multilingual { + inputs.push(("position_ids".into(), tensor_i64(vec![1, positions.len()], positions.to_vec())?.into())); + inputs.push(("exaggeration".into(), tensor_f32(vec![1], vec![0.5])?.into())); + } + let out = self.embed.run(inputs)?; + owned_f32(&out[0]) + } + + /// One phrase to 24 kHz PCM. Reaching the token cap is retried once with the next seed (Capri behaviour). + pub fn synthesize(&mut self, text: &str, language: &str, cancel: &AtomicBool) -> Result> { + match self.generate(text, language, SEED, cancel) { + Err(e) if e.to_string() == "CAPRI_VOICE_SPEECH_LIMIT" => self.generate(text, language, SEED + 1, cancel), + other => other, + } + } + + fn generate(&mut self, text: &str, language: &str, seed: u64, cancel: &AtomicBool) -> Result> { + let mut text = punctuation_normalized(text); + if self.multilingual { + // TODO: no Chinese Cangjie, Japanese kana or Hebrew diacritics preprocessing yet; those languages sound degraded. + if language == "ko" { + text = korean_normalized(&text); + } + text = format!("[{language}]{text}"); + } + let encoding = self.tokenizer.encode(text.as_str(), true).map_err(|e| anyhow::anyhow!("{e}"))?; + let ids: Vec = encoding.get_ids().iter().map(|i| *i as i64).collect(); + let positions: Vec = ids.iter().enumerate().map(|(k, id)| if *id >= START_SPEECH { 0 } else { k as i64 - 1 }).collect(); + let (shape, text_embeds) = self.embed(&ids, &positions)?; + let (cshape, cond) = &self.cond.cond_emb; + let dim = *shape.last().context("bad embedding")?; + ensure!(cshape.last() == Some(&dim), "Voice conditioning does not match the model"); + let mut embeds = cond.clone(); + embeds.extend(text_embeds); + let prefix = embeds.len() / dim; + let mut embeds_value = tensor_f32(vec![1, prefix, dim], embeds)?; + let mut past: Vec = (0..self.past.len()).map(|_| tensor_f32(vec![1, KV_HEADS, 0, HEAD_DIM], Vec::new())).collect::>()?; + let mut tokens = vec![START_SPEECH]; + let mut rng = Rng(seed); + for step in 0..MAX_TOKENS { + ensure!(!cancel.load(Ordering::Relaxed), "cancelled"); + let length = prefix + step; + let mut inputs: Vec<(Cow<'static, str>, SessionInputValue<'_>)> = vec![ + ("inputs_embeds".into(), (&embeds_value).into()), + ("attention_mask".into(), tensor_i64(vec![1, length], vec![1; length])?.into()), + ]; + if !self.multilingual { + let ids: Vec = if step == 0 { (0..length as i64).collect() } else { vec![length as i64 - 1] }; + inputs.push(("position_ids".into(), tensor_i64(vec![1, ids.len()], ids)?.into())); + } + for (name, value) in self.past.iter().zip(&past) { + inputs.push((name.clone().into(), value.into())); + } + let mut out = self.lm.run(inputs)?; + let (lshape, logits) = out[0].try_extract_tensor::()?; + let vocab = *lshape.last().context("bad logits")? as usize; + let next = sample(&logits[logits.len() - vocab..], &tokens, &mut rng); + tokens.push(next); + if next == STOP_SPEECH { + break; + } + past = self.present.iter().map(|n| out.remove(n.as_str()).context("missing cache output")).collect::>()?; + drop(out); + let (_, e) = self.embed(&[next], &[step as i64 + 1])?; + embeds_value = tensor_f32(vec![1, 1, dim], e)?; + } + if tokens.last() != Some(&STOP_SPEECH) { + bail!("CAPRI_VOICE_SPEECH_LIMIT"); + } + let mut speech = self.cond.prompt_tokens.clone(); + speech.extend(tokens.iter().copied().filter(|t| *t < START_SPEECH)); + if !self.multilingual { + speech.extend([SILENCE; 3]); + } + let (eshape, e) = self.cond.speaker_embeddings.clone(); + let (fshape, f) = self.cond.speaker_features.clone(); + let n = speech.len(); + let out = self.decoder.run(ort::inputs![ + "speech_tokens" => tensor_i64(vec![1, n], speech)?, + "speaker_embeddings" => tensor_f32(eshape, e)?, + "speaker_features" => tensor_f32(fshape, f)?, + ])?; + let wav: Vec = out[0].try_extract_tensor::()?.1.iter().map(|x| x.clamp(-1.0, 1.0)).collect(); + ensure!(!wav.is_empty() && wav.len() <= MAX_SAMPLES, "CAPRI_VOICE_SPEECH_LIMIT"); + Ok(wav) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_preparation() { + assert_eq!(punctuation_normalized("hello… world: yes"), "Hello, world, yes."); + assert_eq!(punctuation_normalized("Ready?"), "Ready?"); + assert_eq!(punctuation_normalized(""), "You need to add some text for me to talk."); + assert_eq!(korean_normalized("한"), "\u{1112}\u{1161}\u{11AB}"); + } + + #[test] + fn sampling_is_seeded_penalized_and_nucleus_bounded() { + let mut logits = vec![-10.0f32; 50]; + logits[7] = 5.0; + logits[9] = 4.9; + let draw = |seed| { + let mut rng = Rng(seed); + (0..20).map(|_| sample(&logits, &[], &mut rng)).collect::>() + }; + assert_eq!(draw(417), draw(417), "same seed, same phrase"); + assert!(draw(417).iter().all(|t| *t == 7 || *t == 9), "top-p keeps the two likely tokens"); + let mut penalised = vec![0.0f32; 3]; + penalised[0] = 2.0; + penalised[1] = 1.9; + let mut rng = Rng(1); + let picks: Vec = (0..200).map(|_| sample(&penalised, &[0, 0], &mut rng)).collect(); + assert!(picks.iter().filter(|t| **t == 1).count() > picks.iter().filter(|t| **t == 0).count(), "repeated token is penalized"); + } + + #[test] + fn catalog_and_reference_extraction() { + let speech = Path::new("/s"); + let files = model_files(speech, "fr", "balanced"); + assert!(files.iter().any(|(p, path)| p.url.contains("chatterbox-multilingual-ONNX") && path.ends_with("onnx/language_model_q4.onnx_data"))); + assert!(model_files(speech, "en", "full").iter().any(|(_, p)| p.ends_with("onnx/language_model.onnx_data"))); + assert!(download_bytes("en", "balanced") < 1_300_000_000); + + use std::io::Write; + let dir = tempfile::tempdir().unwrap(); + let wav = b"RIFFfake".to_vec(); + let profile = serde_json::json!({"references": {"neutral": {"file": "references/neutral.wav", "sha256": hex::encode(::digest(&wav))}}}); + let pack = dir.path().join("pack.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&pack).unwrap()); + zip.start_file("capri-en-v1/voice-profile.json", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(profile.to_string().as_bytes()).unwrap(); + zip.start_file("capri-en-v1/references/neutral.wav", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(&wav).unwrap(); + zip.finish().unwrap(); + let target = dir.path().join("voices/capri-neutral.wav"); + extract_reference(&pack, &target).unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), wav); + } + + #[test] + fn wav_reference_is_resampled_to_24k() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("r.wav"); + let mut w = hound::WavWriter::create(&path, hound::WavSpec { channels: 2, sample_rate: 48_000, bits_per_sample: 16, sample_format: hound::SampleFormat::Int }).unwrap(); + for i in 0..48_000 { + let v = ((i as f32 * 0.05).sin() * 16000.0) as i16; + w.write_sample(v).unwrap(); + w.write_sample(v).unwrap(); + } + w.finalize().unwrap(); + let pcm = load_wav(&path).unwrap(); + assert!((pcm.len() as i64 - 24_000).abs() < 10); + } + + /// Tokenizer files only: `CAPRI_VOICE_TOKENIZERS= cargo test -- --ignored`. + #[test] + #[ignore] + fn tokenizers_load_and_encode() { + let dir = PathBuf::from(std::env::var("CAPRI_VOICE_TOKENIZERS").unwrap()); + let turbo = tokenizers::Tokenizer::from_file(dir.join("turbo.json")).unwrap(); + assert!(!turbo.encode("Hello, I am Capri.", true).unwrap().get_ids().is_empty()); + let multi = tokenizers::Tokenizer::from_file(dir.join("multilingual.json")).unwrap(); + let ids = multi.encode("[fr]Bonjour, je suis Capri.", true).unwrap().get_ids().to_vec(); + assert!(ids.iter().any(|i| *i as i64 >= START_SPEECH), "template appends the speech start token: {ids:?}"); + } + + /// Real synthesis with installed models: `CAPRI_VOICE_SPEECH_DIR=~/.local/share/capri/speech cargo test -- --ignored`. + #[test] + #[ignore] + fn synthesize_with_installed_models() { + let speech = PathBuf::from(std::env::var("CAPRI_VOICE_SPEECH_DIR").unwrap()); + let reference = load_wav(&reference_path(&speech)).unwrap(); + let mut voice = Chatterbox::load(&speech, "en", "balanced", &reference, 4).unwrap(); + let pcm = voice.synthesize("Hello, I am Capri.", "en", &AtomicBool::new(false)).unwrap(); + assert!(pcm.len() > 12_000); + } +}