fix: rust_asr_asrx handles MLX Whisper non-finite JSON literals
- MLX Whisper emits 'avg_logprob: NaN' / 'compression_ratio: Infinity' when a clip has no intelligible audio (e.g. near-silent test clips). serde_json strictly refuses those literals, so rust_asr_asrx failed with 'expected value at line 1 column 151' and asrx never completed. - Sanitize NaN / Infinity / -Infinity literals outside strings into null before parsing (sanitize_json_nonfinite). - Add no-audio-track early-out. Clean up .wav byproduct after success. Verified on dev (m5max48): 002.mp4 asrx re-scan now completes and produces output/df6376c8....asrx.json; processor_results asrx = completed.
This commit is contained in:
@@ -571,7 +571,48 @@ fn main() -> Result<()> {
|
||||
anyhow::bail!("Input file not found: {}", cli.input);
|
||||
}
|
||||
|
||||
// Step 1: Extract audio (if video)
|
||||
// Step 1: Check for audio track and extract (if video)
|
||||
if is_video_file(&cli.input) {
|
||||
println!("[1/7] Checking for audio track...");
|
||||
if !has_audio_track(&cli.input) {
|
||||
println!("[ASR-ASRX] No audio track found in video, skipping ASR");
|
||||
// Write empty output with no_audio_track status
|
||||
let empty_output = serde_json::json!({
|
||||
"status": "no_audio_track",
|
||||
"language": null,
|
||||
"n_speakers": 0,
|
||||
"segments": [],
|
||||
"speaker_stats": {},
|
||||
"processing_time": {
|
||||
"total": 0.0
|
||||
},
|
||||
"garbled_fallback": false,
|
||||
"recovery": {
|
||||
"triggered": false,
|
||||
"final_result": "no_audio_track",
|
||||
"attempts": [],
|
||||
"garbled_check_enabled": false,
|
||||
"language_candidates": [],
|
||||
"no_intelligible_speech": false
|
||||
},
|
||||
"processor": "rust_asr_asrx",
|
||||
"model": cli.model,
|
||||
"source": cli.input
|
||||
});
|
||||
|
||||
let output_path = Path::new(&cli.output);
|
||||
if let Some(parent) = output_path.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
std::fs::write(&cli.output, serde_json::to_string_pretty(&empty_output)?)
|
||||
.context("Failed to write output")?;
|
||||
|
||||
println!("[ASR-ASRX] Output: {}", cli.output);
|
||||
println!("[ASR-ASRX] Done in 0.0s (no audio track)");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
println!("[1/7] Extracting audio...");
|
||||
let audio_path = if is_video_file(&cli.input) {
|
||||
extract_audio(&cli.input)?
|
||||
@@ -730,6 +771,64 @@ fn print_recovery_summary(kind: &str, attempts: &[serde_json::Value], garbled_fa
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Get ffmpeg path from environment variable or default to "ffmpeg"
|
||||
fn get_ffmpeg_path() -> String {
|
||||
std::env::var("MOMENTRY_FFMPEG")
|
||||
.unwrap_or_else(|_| "ffmpeg".to_string())
|
||||
}
|
||||
|
||||
/// Check if a video file has an audio track
|
||||
/// Tries ffprobe first, then falls back to ffmpeg metadata check
|
||||
fn has_audio_track(input: &str) -> bool {
|
||||
// Try ffprobe first (preferred)
|
||||
let ffprobe_result = std::process::Command::new("ffprobe")
|
||||
.args(&[
|
||||
"-v", "error",
|
||||
"-select_streams", "a",
|
||||
"-show_entries", "stream=codec_type",
|
||||
"-of", "csv=p=0",
|
||||
input,
|
||||
])
|
||||
.output();
|
||||
|
||||
if let Ok(out) = ffprobe_result {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
if !stdout.trim().is_empty() {
|
||||
return stdout.trim().contains("audio");
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try ffmpeg to extract audio and check if it succeeds
|
||||
// Use a temp file and check if ffmpeg can extract audio
|
||||
let temp_audio = format!("/tmp/asr_audio_check_{}.wav", std::process::id());
|
||||
let ffmpeg_result = std::process::Command::new(get_ffmpeg_path())
|
||||
.args(&[
|
||||
"-y",
|
||||
"-i", input,
|
||||
"-vn",
|
||||
"-acodec", "pcm_s16le",
|
||||
"-ar", "16000",
|
||||
"-ac", "1",
|
||||
"-t", "1", // Just extract 1 second to check
|
||||
&temp_audio,
|
||||
])
|
||||
.output();
|
||||
|
||||
// Clean up temp file
|
||||
let _ = std::fs::remove_file(&temp_audio);
|
||||
|
||||
match ffmpeg_result {
|
||||
Ok(out) => out.status.success(),
|
||||
Err(_) => {
|
||||
// If both fail, assume there might be audio
|
||||
// The extraction step will handle the actual error
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_video_file(path: &str) -> bool {
|
||||
let ext = Path::new(path)
|
||||
.extension()
|
||||
@@ -742,7 +841,7 @@ fn is_video_file(path: &str) -> bool {
|
||||
fn extract_audio(input: &str) -> Result<String> {
|
||||
let output = input.replace(".mp4", ".wav").replace(".mkv", ".wav");
|
||||
|
||||
let status = Command::new("ffmpeg")
|
||||
let status = Command::new(get_ffmpeg_path())
|
||||
.args(&[
|
||||
"-y",
|
||||
"-i",
|
||||
@@ -804,6 +903,53 @@ fn run_vad(audio_path: &str, vad_model: &str) -> Result<Vec<(f64, f64)>> {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Replace JSON non-finite literals (`NaN`, `Infinity`, `-Infinity`) with `null`
|
||||
/// when they appear outside string literals. Python's `json` module emits these
|
||||
/// (allow_nan=True), but serde_json strictly refuses to parse them.
|
||||
fn sanitize_json_nonfinite(input: &str) -> String {
|
||||
let mut out = String::with_capacity(input.len() + 16);
|
||||
let mut in_string = false;
|
||||
let mut escaped = false;
|
||||
let mut chars = input.char_indices().peekable();
|
||||
|
||||
while let Some((idx, ch)) = chars.next() {
|
||||
if in_string {
|
||||
out.push(ch);
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == '"' {
|
||||
in_string = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let rest = &input[idx..];
|
||||
if rest.starts_with("NaN") {
|
||||
out.push_str("null");
|
||||
// skip "aN"
|
||||
for _ in 0..2 {
|
||||
chars.next();
|
||||
}
|
||||
} else if rest.starts_with("Infinity") {
|
||||
out.push_str("null");
|
||||
// skip "nfinity"
|
||||
for _ in 0..7 {
|
||||
chars.next();
|
||||
}
|
||||
} else if rest.starts_with("-Infinity") {
|
||||
out.push_str("null");
|
||||
// skip "Infinity"
|
||||
for _ in 0..8 {
|
||||
chars.next();
|
||||
}
|
||||
} else {
|
||||
out.push(ch);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result<AsrResult> {
|
||||
let mut args = vec![
|
||||
audio_path.to_string(),
|
||||
@@ -847,6 +993,11 @@ fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Res
|
||||
let json_content =
|
||||
std::fs::read_to_string(&json_path).context("Failed to read MLX Whisper output")?;
|
||||
|
||||
// MLX Whisper emits non-strict JSON (avg_logprob: NaN, compression_ratio:
|
||||
// Infinity, ...) whenever a run has no meaningful audio, so serde fails with
|
||||
// "expected value". Sanitize non-finite literals outside strings → null.
|
||||
let json_content = sanitize_json_nonfinite(&json_content);
|
||||
|
||||
let json: serde_json::Value = serde_json::from_str(&json_content)?;
|
||||
|
||||
let segments = json["segments"]
|
||||
|
||||
Reference in New Issue
Block a user