NERDDISCO's picture
kale-tts-1
f21d6eb
Raw History Blame Contribute Delete
4.63 kB
// usage: cargo run --release -- <model dir> [ids file: one sentence per line] [voice name or id, default kenzie] (IPA -> ids via tokenizer.json; ids file -> speed)
// kale-tts-1-nano only: tiny also needs its Ettin word inputs, which our JS / Python front end makes.
use ort::{session::Session, value::Tensor};
use std::{collections::HashMap, fs, time::Instant};
struct KaleTts { _env: ort::environment::Environment, session: Session, style: Vec<f32>, voice: Vec<(String, Vec<i64>, Vec<f32>)>, vocab: HashMap<String, i64> }
fn floats(p: &str) -> Vec<f32> { fs::read(p).unwrap().chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() }
impl KaleTts {
fn load(dir: &str, voice: &str, threads: usize) -> ort::Result<Self> {
let env = ort::init().build()?;
let session = Session::builder(&env)?.with_auto_device(ort::session::builder::AutoDevicePolicy::PreferCPU)? // the crate defaults to MaxEfficiency (= NPU, CoreML on a Mac): 2.5x slower here
.with_intra_threads(threads)?.with_inter_threads(1)?.commit_from_file(format!("{dir}/model.onnx"))?;
let vj: serde_json::Value = serde_json::from_str(&fs::read_to_string(format!("{dir}/voices.json")).unwrap()).unwrap();
assert!(vj.get("ettin_tokenizer").is_none(), "this model (kale-tts-1-tiny) also needs Ettin word inputs: use js/kale-tts.mjs or python/kale_tts.py");
// a voice by its name (any case, "kenzie") or its id ("s057b")
let voice = vj["voices"].as_array().unwrap().iter().find(|v| [&v["id"], &v["name"]].iter().any(|x| x.as_str().map_or(false, |s| s.eq_ignore_ascii_case(voice))))
.unwrap_or_else(|| panic!("unknown voice {voice} (voices.json lists the names and ids)"))["id"].as_str().unwrap().to_string();
let voice = voice.as_str();
let extra = floats(&format!("{dir}/voices/{voice}.extra.bin")); let mut o = 0; let mut v = vec![];
for vi in vj["voice_inputs"].as_array().unwrap() {
let dims: Vec<i64> = vi["dims"].as_array().unwrap().iter().map(|d| d.as_i64().unwrap()).collect();
let n = dims.iter().product::<i64>() as usize; v.push((vi["name"].as_str().unwrap().to_string(), dims, extra[o..o + n].to_vec())); o += n;
}
let tok: serde_json::Value = serde_json::from_str(&fs::read_to_string(format!("{dir}/tokenizer.json")).unwrap()).unwrap();
let vocab = tok["model"]["vocab"].as_object().unwrap().iter().map(|(k, v)| (k.clone(), v.as_i64().unwrap())).collect();
Ok(Self { _env: env, session, style: floats(&format!("{dir}/voices/{voice}.bin")), voice: v, vocab })
}
fn ids(&self, ipa: &str) -> Vec<i64> { ipa.chars().filter_map(|c| self.vocab.get(&c.to_string()).copied()).collect() }
/// one sentence of token ids (no pads) -> 24 kHz audio
fn say(&mut self, ids: &[i64]) -> ort::Result<Vec<f32>> {
let mut x = vec![0i64]; x.extend_from_slice(ids); x.push(0); let row = ids.len().min(510) - 1;
let mut inputs: Vec<(String, ort::value::DynValue)> = vec![
("input_ids".into(), Tensor::from_array(([1usize, x.len()], x))?.into_dyn()),
("style".into(), Tensor::from_array(([1usize, 256], self.style[row * 256..(row + 1) * 256].to_vec()))?.into_dyn()),
("speed".into(), Tensor::from_array(([1usize], vec![1f32]))?.into_dyn())];
for (n, d, v) in &self.voice { inputs.push((n.clone(), Tensor::from_array((d.iter().map(|&x| x as usize).collect::<Vec<_>>(), v.clone()))?.into_dyn())); }
let out = self.session.run(inputs)?;
let (_, y) = out["waveform"].try_extract_tensor::<f32>()?; Ok(y.to_vec())
}
}
fn main() -> ort::Result<()> {
let a: Vec<String> = std::env::args().collect(); let mut tts = KaleTts::load(&a[1], a.get(3).map_or("kenzie", |s| s.as_str()), 4)?;
let ids = tts.ids("ɐ vɑlkˈAnO ɪz ɐ plˈAs."); let audio = tts.say(&ids)?; // "A volcano is a place." from our front end (Kokoro-native symbols)
eprintln!("hello sentence: {:.2} s", audio.len() as f64 / 24000.0);
if a.len() > 2 {
let lines: Vec<Vec<i64>> = fs::read_to_string(&a[2]).unwrap().lines().map(|l| l.split_whitespace().map(|t| t.parse().unwrap()).collect()).collect();
let t0 = Instant::now(); let (mut first, mut secs) = (-1.0, 0.0);
for l in &lines { let y = tts.say(l)?; secs += y.len() as f64 / 24000.0; if first < 0.0 { first = t0.elapsed().as_secs_f64(); } }
let t = t0.elapsed().as_secs_f64();
println!("{{\"runtime\": \"rust ort crate\", \"audio_s\": {:.1}, \"xrt\": {:.1}, \"first_audio_s\": {:.3}}}", secs, secs / t, first);
}
Ok(())
}