// usage: tbench_fz use std::collections::{HashMap, HashSet}; use std::ffi::{CString, c_void, c_char, c_int}; use std::io::{BufRead, Write}; use std::sync::{Arc, Mutex, atomic::{AtomicUsize, Ordering}}; unsafe extern "C" { fn klm_load(p: *const c_char) -> *mut c_void; fn klm_state_size(m: *mut c_void) -> c_int; fn klm_begin(m: *mut c_void, st: *mut c_void); fn klm_score(m: *mut c_void, i: *const c_void, w: *const c_char, len: c_int, o: *mut c_void) -> f32; fn klm_end(m: *mut c_void, i: *const c_void, o: *mut c_void) -> f32; } struct LmPtr(*mut c_void); unsafe impl Send for LmPtr {} unsafe impl Sync for LmPtr {} struct Fz { lm: Option, ss: usize, a: f32, b: f32, hw: HashSet, hp: HashMap, w: f32 } fn norm_tokens(s: &str) -> Vec { let t: String = s.chars().map(|c| match c { '\u{200c}' => ' ', 'ي' => 'ی', 'ك' => 'ک', c if c.is_alphanumeric() => c, _ => ' ' }).collect(); t.split_whitespace().map(|x| x.to_string()).collect() } fn hkey(s: &str) -> String { norm_tokens(s).concat() } impl tinyasr::Fusion for Fz { fn begin(&self) -> Vec { let mut v = vec![0u8; self.ss]; if let Some(m) = &self.lm { unsafe { klm_begin(m.0, v.as_mut_ptr() as *mut c_void) } } v } fn word(&self, st: &[u8], w: &str, out: &mut Vec) -> f32 { let toks = norm_tokens(w); let mut cur = st.to_vec(); let mut s = 0.0; if let Some(m) = &self.lm { let mut nx = vec![0u8; self.ss]; for t in &toks { let l = unsafe { klm_score(m.0, cur.as_ptr() as *const c_void, t.as_ptr() as *const c_char, t.len() as c_int, nx.as_mut_ptr() as *mut c_void) }; s += self.a * l * std::f32::consts::LN_10 + self.b; std::mem::swap(&mut cur, &mut nx); } } if !self.hw.is_empty() && self.hw.contains(&toks.concat()) { s += self.w } *out = cur; s } fn end(&self, st: &[u8]) -> f32 { match &self.lm { Some(m) => { let mut nx = vec![0u8; self.ss]; self.a * unsafe { klm_end(m.0, st.as_ptr() as *const c_void, nx.as_mut_ptr() as *mut c_void) } * std::f32::consts::LN_10 } None => 0.0 } } fn prefix(&self, part: &str) -> f32 { if self.hw.is_empty() { return 0.0 } let k = hkey(part); if k.is_empty() { return 0.0 } match self.hp.get(&k) { Some(&ml) => self.w * k.chars().count() as f32 / ml as f32, None => 0.0 } } } fn read_wav(p: &str) -> Vec { let mut r = hound::WavReader::open(p).expect(p); let s = r.spec(); assert_eq!(s.sample_rate, 16000, "{p}"); let ch = s.channels as usize; let v: Vec = match s.sample_format { hound::SampleFormat::Float => r.samples::().map(|x| x.unwrap()).collect(), hound::SampleFormat::Int => { let m = (1i64 << (s.bits_per_sample - 1)) as f32; r.samples::().map(|x| x.unwrap() as f32 / m).collect() } }; if ch == 1 { v } else { v.chunks(ch).map(|c| c.iter().sum::() / ch as f32).collect() } } fn main() { let a: Vec = std::env::args().collect(); let asr = std::fs::read(&a[1]).unwrap(); let vad = std::fs::read(&a[2]).unwrap(); let workers: usize = a[5].parse().unwrap(); let beam: usize = a[6].parse().unwrap(); let (alpha, beta, hww): (f32, f32, f32) = (a[8].parse().unwrap(), a[9].parse().unwrap(), a[11].parse().unwrap()); let (lm, ss) = if a[7] != "-" { let c = CString::new(a[7].clone()).unwrap(); let p = unsafe { klm_load(c.as_ptr()) }; assert!(!p.is_null(), "lm load"); (Some(LmPtr(p)), unsafe { klm_state_size(p) } as usize) } else { (None, 0) }; let mut hw = HashSet::new(); let mut hp: HashMap = HashMap::new(); if a[10] != "-" { for l in std::fs::read_to_string(&a[10]).unwrap().lines() { let w = l.split('#').next().unwrap().trim(); let k = hkey(w); let n = k.chars().count(); if n < 3 { continue } let cs: Vec = k.chars().collect(); for j in 1..=n { let p: String = cs[..j].iter().collect(); let e = hp.entry(p).or_insert(n); if n < *e { *e = n } } hw.insert(k); } } eprintln!("lm {} alpha {alpha} beta {beta} hotwords {} w {hww} beam {beam}", lm.is_some(), hw.len()); if lm.is_some() || !hw.is_empty() { let _ = tinyasr::FUSION.set(Box::new(Fz { lm, ss, a: alpha, b: beta, hw, hp, w: hww })); } let mut models = tinyasr::Models::load(tinyasr::Files { asr: &asr, vad: &vad }).unwrap(); models.set_threads(1); let models = Arc::new(models); let items: Arc> = Arc::new(std::io::BufReader::new(std::fs::File::open(&a[3]).unwrap()).lines() .map(|l| { let l = l.unwrap(); let mut p = l.splitn(2, '\t'); (p.next().unwrap().to_string(), p.next().unwrap().to_string()) }).collect()); let out = Arc::new(Mutex::new(std::fs::File::create(&a[4]).unwrap())); let next = Arc::new(AtomicUsize::new(0)); let t0 = std::time::Instant::now(); let hs: Vec<_> = (0..workers).map(|_| { let (m, it, o, nx) = (models.clone(), items.clone(), out.clone(), next.clone()); std::thread::spawn(move || loop { let i = nx.fetch_add(1, Ordering::SeqCst); if i >= it.len() { break } let (id, p) = &it[i]; let audio = read_wav(p); let mut text = String::new(); for ws in tinyasr::Transcription::new(&m, &audio, &["fa"], beam) { for w in ws { if !text.is_empty() && !w.join { text.push(' ') } text.push_str(&w.text) } } o.lock().unwrap().write_all(format!("{}\t{}\n", id, text.replace(['\t', '\n'], " ")).as_bytes()).unwrap(); if i % 2000 == 0 { eprintln!("{} / {} {:.1}s", i, it.len(), t0.elapsed().as_secs_f32()) } }) }).collect(); for h in hs { h.join().unwrap() } eprintln!("DONE {:.1}s", t0.elapsed().as_secs_f32()); }