Download utils.rs from montreal-forced-align-polygot/MFA-RUST: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/montreal-forced-align-polygot/MFA-RUST/resolve/main/utils.rs
- Command line
-
hf download hf://spaces/montreal-forced-align-polygot/MFA-RUST/utils.rs
-
curl -L -o utils.rs https://huggingface.co/spaces/montreal-forced-align-polygot/MFA-RUST/resolve/main/utils.rs
10.4 kB
| use axum::{http::StatusCode, Json}; | |
| use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; | |
| use chrono::Utc; | |
| use hound::{WavReader, WavSpec, WavWriter}; | |
| use regex::Regex; | |
| use fancy_regex::Regex as FancyRegex; | |
| use std::io::Cursor; | |
| const MIN_AUDIO_SECONDS: f64 = 0.3; | |
| const MAX_AUDIO_SECONDS: f64 = 180.0; | |
| pub fn clean_text_mfa(text: &str) -> String { | |
| let mut text = text.to_string(); | |
| // Unicode normalization | |
| text = text.replace("\u{2018}", "'").replace("\u{2019}", "'"); | |
| text = text.replace("\u{201c}", "\"").replace("\u{201d}", "\""); | |
| text = text.replace("\u{2014}", " ").replace("\u{2013}", " "); | |
| text = text.replace("\u{2026}", " "); | |
| text = text.replace('\n', " ").replace('\r', " "); | |
| // Strip digits (MFA doesn't handle numbers) | |
| let re = Regex::new(r"[0-9]+").unwrap(); | |
| text = re.replace_all(&text, " ").to_string(); | |
| // Keep only letters, apostrophes, hyphens, spaces | |
| let re = Regex::new(r"[^a-zA-Z'\- ]").unwrap(); | |
| text = re.replace_all(&text, " ").to_string(); | |
| // Mid-word apostrophe: keep only apostrophes flanked by letters on both sides. | |
| // fancy-regex supports lookbehind/lookahead unlike the standard regex crate. | |
| let re = FancyRegex::new(r"(?<![a-zA-Z])'|'(?![a-zA-Z])").unwrap(); | |
| text = re.replace_all(&text, " ").to_string(); | |
| // Mid-word hyphen: keep only hyphens flanked by letters on both sides. | |
| let re = FancyRegex::new(r"(?<![a-zA-Z])-|-(?![a-zA-Z])").unwrap(); | |
| text = re.replace_all(&text, " ").to_string(); | |
| // Collapse whitespace | |
| let re = Regex::new(r"\s+").unwrap(); | |
| text = re.replace_all(&text, " ").to_string(); | |
| text.trim().to_lowercase() | |
| } | |
| pub fn validate_audio(audio_b64: &str) -> Result<(Vec<u8>, f64), (StatusCode, Json<serde_json::Value>)> { | |
| // Decode base64 | |
| let raw = match BASE64.decode(audio_b64) { | |
| Ok(data) => data, | |
| Err(_) => { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Invalid audio", | |
| "error_code": "AUDIO_DECODE_ERROR", | |
| "detail": "audio_base64 is not valid base64.", | |
| })), | |
| )); | |
| } | |
| }; | |
| // Parse WAV | |
| let cursor = Cursor::new(&raw); | |
| let reader = match WavReader::new(cursor) { | |
| Ok(r) => r, | |
| Err(e) => { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Invalid audio", | |
| "error_code": "AUDIO_PARSE_ERROR", | |
| "detail": format!("Could not parse as WAV: {}", e), | |
| })), | |
| )); | |
| } | |
| }; | |
| let spec = reader.spec(); | |
| // Check format | |
| if spec.bits_per_sample != 16 && spec.bits_per_sample != 32 { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Unsupported audio format", | |
| "error_code": "AUDIO_FORMAT_ERROR", | |
| "detail": format!("Only 16-bit PCM or 32-bit float WAV supported (got {}).", spec.bits_per_sample), | |
| })), | |
| )); | |
| } | |
| if spec.sample_rate < 8000 { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Unsupported audio format", | |
| "error_code": "AUDIO_RATE_ERROR", | |
| "detail": format!("Sample rate too low: {} Hz (minimum 8000 Hz).", spec.sample_rate), | |
| })), | |
| )); | |
| } | |
| // Calculate duration | |
| let samples: Vec<i16> = reader.into_samples::<i16>().filter_map(Result::ok).collect(); | |
| let duration = samples.len() as f64 / spec.sample_rate as f64 / spec.channels as f64; | |
| if duration < MIN_AUDIO_SECONDS { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Audio too short", | |
| "error_code": "AUDIO_TOO_SHORT", | |
| "detail": format!("Audio is {:.2}s — minimum is {}s.", duration, MIN_AUDIO_SECONDS), | |
| })), | |
| )); | |
| } | |
| if duration > MAX_AUDIO_SECONDS { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Audio too long", | |
| "error_code": "AUDIO_TOO_LONG", | |
| "detail": format!("Audio is {:.1}s — maximum is {}s.", duration, MAX_AUDIO_SECONDS), | |
| })), | |
| )); | |
| } | |
| // Re-parse for normalization | |
| let cursor = Cursor::new(&raw); | |
| let reader = WavReader::new(cursor).unwrap(); | |
| let wav_normalised = normalize_wav(&raw, &reader.spec())?; | |
| Ok((wav_normalised, duration)) | |
| } | |
| fn normalize_wav(raw: &[u8], spec: &hound::WavSpec) -> Result<Vec<u8>, (StatusCode, Json<serde_json::Value>)> { | |
| // If already mono 16-bit, return as is | |
| if spec.bits_per_sample == 16 && spec.channels == 1 { | |
| return Ok(raw.to_vec()); | |
| } | |
| let cursor = Cursor::new(raw); | |
| let mut reader = WavReader::new(cursor).unwrap(); | |
| // Read samples based on bit depth | |
| let samples: Vec<i16> = match spec.bits_per_sample { | |
| 16 => { | |
| reader.samples::<i16>() | |
| .filter_map(Result::ok) | |
| .collect() | |
| } | |
| 32 => { | |
| reader.samples::<f32>() | |
| .filter_map(Result::ok) | |
| .map(|s| (s.clamp(-1.0, 1.0) * 32767.0) as i16) | |
| .collect() | |
| } | |
| _ => { | |
| return Err(( | |
| StatusCode::BAD_REQUEST, | |
| Json(serde_json::json!({ | |
| "error": "Unsupported audio format", | |
| "error_code": "AUDIO_FORMAT_ERROR", | |
| "detail": format!("Only 16-bit PCM or 32-bit float WAV supported (got {}).", spec.bits_per_sample), | |
| })), | |
| )); | |
| } | |
| }; | |
| // Convert to mono if needed | |
| let mono_samples: Vec<i16> = if spec.channels > 1 { | |
| samples.chunks(spec.channels as usize) | |
| .map(|chunk| { | |
| let sum: i32 = chunk.iter().map(|&s| s as i32).sum(); | |
| (sum / spec.channels as i32) as i16 | |
| }) | |
| .collect() | |
| } else { | |
| samples | |
| }; | |
| // Write to new WAV | |
| let mut cursor = Cursor::new(Vec::new()); | |
| let new_spec = WavSpec { | |
| channels: 1, | |
| sample_rate: spec.sample_rate, | |
| bits_per_sample: 16, | |
| sample_format: hound::SampleFormat::Int, | |
| }; | |
| let mut writer = WavWriter::new(&mut cursor, new_spec).unwrap(); | |
| for sample in mono_samples { | |
| writer.write_sample(sample).unwrap(); | |
| } | |
| writer.finalize().unwrap(); | |
| Ok(cursor.into_inner()) | |
| } | |
| pub fn get_tmp_free_mb() -> Option<f64> { | |
| let output = std::process::Command::new("df") | |
| .args(["-m", "/dev/shm"]) | |
| .output() | |
| .ok()?; | |
| let stdout = String::from_utf8_lossy(&output.stdout); | |
| let line = stdout.lines().nth(1)?; | |
| let avail: f64 = line.split_whitespace().nth(3)?.parse().ok()?; | |
| Some(avail) | |
| } | |
| pub fn job_view(job: &crate::models::Job, slim: bool, avg_align_s: f64) -> serde_json::Value { | |
| let mut base = serde_json::json!({ | |
| "job_id": job.id, | |
| "status": job.status.as_str(), | |
| "created_at": job.created_at.to_rfc3339(), | |
| }); | |
| match job.status.as_str() { | |
| "queued" => { | |
| base["queue_position"] = serde_json::Value::from(1); | |
| base["estimated_wait_s"] = serde_json::Value::from(avg_align_s); | |
| base["message"] = serde_json::Value::from("Queued at position 1. Poll /job/{id} every 2 s."); | |
| } | |
| "running" => { | |
| if let Some(started_at) = job.started_at { | |
| let elapsed = (Utc::now() - started_at).num_milliseconds() as f64 / 1000.0; | |
| let estimated_remaining = (avg_align_s - elapsed).max(0.0); | |
| base["started_at"] = serde_json::Value::from(started_at.to_rfc3339()); | |
| base["elapsed_s"] = serde_json::Value::from((elapsed * 10.0).round() / 10.0); | |
| base["estimated_remaining_s"] = serde_json::Value::from((estimated_remaining * 10.0).round() / 10.0); | |
| base["message"] = serde_json::Value::from("Running."); | |
| } | |
| } | |
| "completed" => { | |
| if let Some(result) = &job.result { | |
| let duration = if let (Some(started), Some(terminal)) = (job.started_at, job.terminal_at) { | |
| Some((terminal - started).num_milliseconds() as f64 / 1000.0) | |
| } else { | |
| None | |
| }; | |
| base["total_words"] = serde_json::Value::from(result.len()); | |
| base["language"] = serde_json::Value::from(job.request.language.clone()); | |
| base["pass_number"] = serde_json::Value::from(job.request.pass_number); | |
| base["model"] = serde_json::Value::from(crate::MODEL_ID); | |
| base["fine_tuned"] = serde_json::Value::from(false); | |
| if let Some(started) = job.started_at { | |
| base["started_at"] = serde_json::Value::from(started.to_rfc3339()); | |
| } | |
| if let Some(terminal) = job.terminal_at { | |
| base["completed_at"] = serde_json::Value::from(terminal.to_rfc3339()); | |
| } | |
| if let Some(d) = duration { | |
| base["duration_s"] = serde_json::Value::from((d * 100.0).round() / 100.0); | |
| } | |
| if !slim { | |
| let timestamps: Vec<serde_json::Value> = result.iter() | |
| .map(|w| serde_json::json!({ | |
| "word": w.word, | |
| "start": (w.start * 1000.0).round() / 1000.0, | |
| "end": (w.end * 1000.0).round() / 1000.0, | |
| })) | |
| .collect(); | |
| base["word_timestamps"] = serde_json::Value::from(timestamps); | |
| } | |
| } | |
| } | |
| "failed" | "abandoned" => { | |
| if let Some(error) = &job.error { | |
| base["error"] = serde_json::Value::from(error.clone()); | |
| } | |
| if let Some(terminal) = job.terminal_at { | |
| base["completed_at"] = serde_json::Value::from(terminal.to_rfc3339()); | |
| } | |
| } | |
| _ => {} | |
| } | |
| base | |
| } |