File size: 10,377 Bytes
c595b0e 1e0e692 c595b0e b3564ef c595b0e b3564ef 4edea6c 1e0e692 c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e 4edea6c c595b0e b3564ef c595b0e b3564ef 4edea6c 37266a7 b3564ef c595b0e 4edea6c c595b0e 4edea6c b3564ef 4edea6c c595b0e 4edea6c c595b0e 4edea6c c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e b3564ef c595b0e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | 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
} |