From c1ede4ade820d4c9c11b9b71f070334d5b49f618 Mon Sep 17 00:00:00 2001 From: Accusys Date: Mon, 9 Nov 2026 12:02:19 +0800 Subject: [PATCH] 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. --- src/core/processor/asr_asrx.rs | 17 +++ tools/cli/rust/src/bin/rust_asr_asrx.rs | 155 +++++++++++++++++++++++- 2 files changed, 170 insertions(+), 2 deletions(-) diff --git a/src/core/processor/asr_asrx.rs b/src/core/processor/asr_asrx.rs index 39cc81ac..76028634 100644 --- a/src/core/processor/asr_asrx.rs +++ b/src/core/processor/asr_asrx.rs @@ -76,9 +76,26 @@ pub async fn process_asr_asrx( }) .unwrap_or_default(); + // Clean up wav byproduct after successful processing. + cleanup_wav_byproduct(video_path); + Ok(AsrAsrxResult { language, segments, recovery, }) } + +/// Clean up the .wav audio byproduct left by rust_asr_asrx. +/// The wav file is created next to the video with the same base name. +fn cleanup_wav_byproduct(video_path: &str) { + let mut wav_path = std::path::PathBuf::from(video_path); + wav_path.set_extension("wav"); + if wav_path.exists() { + if let Err(e) = std::fs::remove_file(&wav_path) { + tracing::warn!("[ASR_ASRX] Failed to cleanup {}: {}", wav_path.display(), e); + } else { + tracing::info!("[ASR_ASRX] Cleaned up wav byproduct: {}", wav_path.display()); + } + } +} diff --git a/tools/cli/rust/src/bin/rust_asr_asrx.rs b/tools/cli/rust/src/bin/rust_asr_asrx.rs index 798cd922..f93dc400 100644 --- a/tools/cli/rust/src/bin/rust_asr_asrx.rs +++ b/tools/cli/rust/src/bin/rust_asr_asrx.rs @@ -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 { 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> { .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 { 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"]