edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | #![forbid(unsafe_code)] |
| 2 | |
| 3 | use std::io::Write; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::time::Instant; |
| 6 | |
| 7 | use anyhow::{bail, Context, Result}; |
| 8 | use serde_json::json; |
| 9 | use whisper_rs::vulkan::list_devices; |
| 10 | use whisper_rs::{ |
| 11 | DtwMode, DtwModelPreset, DtwParameters, FullParams, SamplingStrategy, WhisperContext, |
| 12 | WhisperContextParameters, WhisperSegment, |
| 13 | }; |
| 14 | |
| 15 | use crate::{ |
| 16 | fit_words_to_audio, levels, r3, read_wav_16k_mono, silence_reason, span_rel_db, starts_past_end, |
| 17 | Cli, MAX_COMPRESSION_RATIO, MIN_AVG_LOGPROB, NO_SPEECH_PROB, SR, |
| 18 | }; |
| 19 | |
| 20 | const GPU_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"]; |
| 21 | |
| 22 | pub fn probe() -> Result<()> { |
| 23 | if list_devices().is_empty() { |
| 24 | bail!("no Vulkan device found"); |
| 25 | } |
| 26 | Ok(()) |
| 27 | } |
| 28 | |
| 29 | pub fn run(cli: &Cli) -> Result<()> { |
| 30 | let device = list_devices() |
| 31 | .into_iter() |
| 32 | .next() |
| 33 | .context("no Vulkan device found")?; |
| 34 | let (model, preset) = resolve_model(&cli.model)?; |
| 35 | let dtw = if cli.align { preset } else { None }; |
| 36 | |
| 37 | let mut cp = WhisperContextParameters::new(); |
| 38 | cp.use_gpu(true); |
| 39 | if let Some(model_preset) = dtw.clone() { |
| 40 | cp.dtw_parameters(DtwParameters { |
| 41 | mode: DtwMode::ModelPreset { model_preset }, |
| 42 | ..Default::default() |
| 43 | }); |
| 44 | } |
| 45 | let t_start = Instant::now(); |
| 46 | let ctx = WhisperContext::new_with_params(&model, cp) |
| 47 | .with_context(|| format!("failed to load whisper model {}", model.display()))?; |
| 48 | eprintln!( |
| 49 | "model loaded from {} on {} in {:.2}s", |
| 50 | model.display(), |
| 51 | device.name, |
| 52 | t_start.elapsed().as_secs_f64() |
| 53 | ); |
| 54 | |
| 55 | let pcm = read_wav_16k_mono(&cli.input)?; |
| 56 | let audio_s = pcm.len() as f64 / SR as f64; |
| 57 | let lv = levels(&pcm); |
| 58 | let eot = ctx.token_eot(); |
| 59 | |
| 60 | let language = if cli.language.eq_ignore_ascii_case("auto") { |
| 61 | None |
| 62 | } else { |
| 63 | Some(cli.language.to_ascii_lowercase()) |
| 64 | }; |
| 65 | let prompt = cli.prompt.as_deref().map(str::trim).filter(|t| !t.is_empty()); |
| 66 | let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); |
| 67 | |
| 68 | let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 }); |
| 69 | params.set_language(language.as_deref()); |
| 70 | params.set_translate(false); |
| 71 | params.set_no_context(true); |
| 72 | params.set_token_timestamps(dtw.is_some()); |
| 73 | params.set_temperature(0.0); |
| 74 | params.set_temperature_inc(0.2); |
| 75 | params.set_logprob_thold(MIN_AVG_LOGPROB as f32); |
| 76 | params.set_entropy_thold(MAX_COMPRESSION_RATIO as f32); |
| 77 | params.set_no_speech_thold(NO_SPEECH_PROB as f32); |
| 78 | if let Some(p) = prompt { |
| 79 | params.set_initial_prompt(p); |
| 80 | } |
| 81 | params.set_print_special(false); |
| 82 | params.set_print_progress(false); |
| 83 | params.set_print_realtime(false); |
| 84 | params.set_print_timestamps(false); |
| 85 | params.set_n_threads(threads as i32); |
| 86 | params.set_progress_callback_safe(|p: i32| eprintln!("progress {:.4}", p as f64 / 100.0)); |
| 87 | |
| 88 | let mut state = ctx.create_state().context("failed to create whisper state")?; |
| 89 | let t_decode = Instant::now(); |
| 90 | state.full(params, &pcm).context("whisper inference failed")?; |
| 91 | |
| 92 | let offset = cli.offset; |
| 93 | let mut n_segs = 0usize; |
| 94 | for seg in state.as_iter() { |
| 95 | let t0 = seg.start_timestamp() as f64 / 100.0; |
| 96 | let t1 = (seg.end_timestamp() as f64 / 100.0).min(audio_s).max(t0); |
| 97 | if starts_past_end(t0, audio_s) { |
| 98 | eprintln!("dropped segment at {:.2}s: starts at or past the audio end", t0 + offset); |
| 99 | continue; |
| 100 | } |
| 101 | let toks = text_tokens(&seg, eot)?; |
| 102 | let text = String::from_utf8_lossy(&toks.iter().flat_map(|t| t.bytes.iter().copied()).collect::<Vec<u8>>()) |
| 103 | .trim() |
| 104 | .to_string(); |
| 105 | if text.is_empty() { |
| 106 | continue; |
| 107 | } |
| 108 | let avg = toks.iter().map(|t| t.plog).sum::<f64>() / toks.len() as f64; |
| 109 | let no_speech = seg.no_speech_probability() as f64; |
| 110 | let span = span_rel_db(&lv, t0, t1); |
| 111 | if let Some(reason) = silence_reason(no_speech, avg, span) { |
| 112 | if !cli.keep_all { |
| 113 | eprintln!( |
| 114 | "skipped segment {:.2}-{:.2}s ({reason}, no_speech {no_speech:.2}, avg_logprob {avg:.2}): {text:?}", |
| 115 | t0 + offset, |
| 116 | t1 + offset |
| 117 | ); |
| 118 | continue; |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | let groups = word_groups(&toks); |
| 123 | let use_dtw = dtw.is_some() && groups.iter().any(|g| g.start > 0.0); |
| 124 | let mut words = if use_dtw { |
| 125 | dtw_words(&groups, t0, t1, offset) |
| 126 | } else { |
| 127 | proportional_words(&groups, t0, t1, offset) |
| 128 | }; |
| 129 | |
| 130 | let n_words = words.len(); |
| 131 | let cut = fit_words_to_audio(&mut words, offset, audio_s); |
| 132 | if n_words > 0 && words.is_empty() { |
| 133 | eprintln!("dropped segment at {:.2}s: every word starts at or past the audio end: {text:?}", t0 + offset); |
| 134 | continue; |
| 135 | } |
| 136 | let text = if cut > 0 { |
| 137 | eprintln!("cut {cut} word(s) at {:.2}s that start at or past the audio end", t0 + offset); |
| 138 | words.iter().filter_map(|w| w["w"].as_str()).collect::<Vec<_>>().join(" ") |
| 139 | } else { |
| 140 | text |
| 141 | }; |
| 142 | let (start, end) = match (words.first(), words.last()) { |
| 143 | (Some(f), Some(l)) => ( |
| 144 | f["start"].as_f64().unwrap_or(t0 + offset), |
| 145 | l["end"].as_f64().unwrap_or(t1 + offset), |
| 146 | ), |
| 147 | _ => (t0 + offset, t1 + offset), |
| 148 | }; |
| 149 | let line = json!({ |
| 150 | "start": r3(start), |
| 151 | "end": r3(end), |
| 152 | "text": text, |
| 153 | "words": words, |
| 154 | "approx": !use_dtw, |
| 155 | "no_speech": r3(no_speech), |
| 156 | "avg_logprob": r3(avg), |
| 157 | "span_db": span.map(r3), |
| 158 | }); |
| 159 | println!("{line}"); |
| 160 | n_segs += 1; |
| 161 | } |
| 162 | std::io::stdout().flush()?; |
| 163 | |
| 164 | let elapsed = t_decode.elapsed().as_secs_f64(); |
| 165 | eprintln!( |
| 166 | "done: {n_segs} segments, audio {audio_s:.2}s, decode {elapsed:.2}s, RTF {:.3}", |
| 167 | elapsed / audio_s.max(1e-9) |
| 168 | ); |
| 169 | Ok(()) |
| 170 | } |
| 171 | |
| 172 | fn resolve_model(arg: &str) -> Result<(PathBuf, Option<DtwModelPreset>)> { |
| 173 | let (path, name) = if arg.ends_with(".bin") || Path::new(arg).is_file() { |
| 174 | let path = PathBuf::from(arg); |
| 175 | let name = path |
| 176 | .file_stem() |
| 177 | .and_then(|s| s.to_str()) |
| 178 | .unwrap_or_default() |
| 179 | .trim_start_matches("ggml-") |
| 180 | .to_string(); |
| 181 | (path, name) |
| 182 | } else { |
| 183 | if !GPU_SIZES.contains(&arg) { |
| 184 | bail!("model '{arg}' is neither a .bin path nor one of {GPU_SIZES:?}"); |
| 185 | } |
| 186 | let home = std::env::var("HOME").context("HOME not set")?; |
| 187 | let path = PathBuf::from(home) |
| 188 | .join(".cache/edith/models") |
| 189 | .join(format!("ggml-{arg}.bin")); |
| 190 | (path, arg.to_string()) |
| 191 | }; |
| 192 | if !path.is_file() { |
| 193 | bail!("GPU model file not found: {} (--device gpu does not download models)", path.display()); |
| 194 | } |
| 195 | Ok((path, preset(&name))) |
| 196 | } |
| 197 | |
| 198 | fn preset(name: &str) -> Option<DtwModelPreset> { |
| 199 | Some(match name { |
| 200 | "tiny" => DtwModelPreset::Tiny, |
| 201 | "base" => DtwModelPreset::Base, |
| 202 | "small" => DtwModelPreset::Small, |
| 203 | "medium" => DtwModelPreset::Medium, |
| 204 | "large-v3" => DtwModelPreset::LargeV3, |
| 205 | "large-v3-turbo" => DtwModelPreset::LargeV3Turbo, |
| 206 | _ => return None, |
| 207 | }) |
| 208 | } |
| 209 | |
| 210 | struct Tok { |
| 211 | bytes: Vec<u8>, |
| 212 | plog: f64, |
| 213 | dtw: f64, |
| 214 | } |
| 215 | |
| 216 | fn text_tokens(seg: &WhisperSegment<'_>, eot: i32) -> Result<Vec<Tok>> { |
| 217 | let mut out = Vec::new(); |
| 218 | for i in 0..seg.n_tokens() { |
| 219 | let Some(tok) = seg.get_token(i) else { |
| 220 | continue; |
| 221 | }; |
| 222 | if tok.token_id() >= eot { |
| 223 | continue; |
| 224 | } |
| 225 | let bytes = tok.to_bytes().context("failed to read token text")?.to_vec(); |
| 226 | if bytes.is_empty() { |
| 227 | continue; |
| 228 | } |
| 229 | let data = tok.token_data(); |
| 230 | out.push(Tok { bytes, plog: data.plog as f64, dtw: data.t_dtw as f64 / 100.0 }); |
| 231 | } |
| 232 | Ok(out) |
| 233 | } |
| 234 | |
| 235 | struct Group { |
| 236 | text: String, |
| 237 | p: f64, |
| 238 | start: f64, |
| 239 | } |
| 240 | |
| 241 | fn word_groups(toks: &[Tok]) -> Vec<Group> { |
| 242 | let mut words: Vec<(Vec<u8>, Vec<f64>, f64)> = Vec::new(); |
| 243 | for t in toks { |
| 244 | if words.is_empty() || t.bytes[0] == b' ' { |
| 245 | words.push((Vec::new(), Vec::new(), t.dtw)); |
| 246 | } |
| 247 | if let Some(w) = words.last_mut() { |
| 248 | w.0.extend_from_slice(&t.bytes); |
| 249 | w.1.push(t.plog); |
| 250 | } |
| 251 | } |
| 252 | words |
| 253 | .into_iter() |
| 254 | .filter_map(|(bytes, plogs, start)| { |
| 255 | let text = String::from_utf8_lossy(&bytes).trim().to_string(); |
| 256 | if text.is_empty() { |
| 257 | return None; |
| 258 | } |
| 259 | let p = (plogs.iter().sum::<f64>() / plogs.len().max(1) as f64).exp(); |
| 260 | Some(Group { text, p, start }) |
| 261 | }) |
| 262 | .collect() |
| 263 | } |
| 264 | |
| 265 | fn word_json(text: &str, start: f64, end: f64, p: f64, offset: f64) -> serde_json::Value { |
| 266 | json!({"w": text, "start": r3(start + offset), "end": r3(end + offset), "p": r3(p)}) |
| 267 | } |
| 268 | |
| 269 | fn dtw_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec<serde_json::Value> { |
| 270 | let hi = t1.max(t0); |
| 271 | let mut starts: Vec<f64> = Vec::with_capacity(groups.len()); |
| 272 | for g in groups { |
| 273 | let s = if g.start > 0.0 { g.start } else { t0 }; |
| 274 | let prev = starts.last().copied().unwrap_or(t0); |
| 275 | starts.push(s.clamp(t0, hi).max(prev)); |
| 276 | } |
| 277 | groups |
| 278 | .iter() |
| 279 | .enumerate() |
| 280 | .map(|(i, g)| { |
| 281 | let start = starts[i]; |
| 282 | let end = starts.get(i + 1).copied().unwrap_or(hi).clamp(start, hi); |
| 283 | word_json(&g.text, start, end, g.p, offset) |
| 284 | }) |
| 285 | .collect() |
| 286 | } |
| 287 | |
| 288 | fn proportional_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec<serde_json::Value> { |
| 289 | let total: usize = groups.iter().map(|g| g.text.chars().count()).sum(); |
| 290 | let span = (t1 - t0).max(0.0); |
| 291 | let mut t = t0; |
| 292 | groups |
| 293 | .iter() |
| 294 | .map(|g| { |
| 295 | let dur = if total > 0 { span * g.text.chars().count() as f64 / total as f64 } else { 0.0 }; |
| 296 | let (start, end) = (t, t + dur); |
| 297 | t = end; |
| 298 | word_json(&g.text, start, end, g.p, offset) |
| 299 | }) |
| 300 | .collect() |
| 301 | } |