diff --git a/tools/cli/rust/src/bin/rust_asr_asrx.rs b/tools/cli/rust/src/bin/rust_asr_asrx.rs index f93dc400..e337b3ce 100644 --- a/tools/cli/rust/src/bin/rust_asr_asrx.rs +++ b/tools/cli/rust/src/bin/rust_asr_asrx.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::BTreeMap; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Instant; @@ -614,8 +614,11 @@ fn main() -> Result<()> { } println!("[1/7] Extracting audio..."); + let temp_guard = TempAudioGuard::default(); let audio_path = if is_video_file(&cli.input) { - extract_audio(&cli.input)? + let p = extract_audio(&cli.input)?; + temp_guard.set(&p); + p } else { cli.input.clone() }; @@ -838,8 +841,66 @@ fn is_video_file(path: &str) -> bool { matches!(ext.to_lowercase().as_str(), "mp4" | "mkv" | "avi" | "mov") } +/// Resolve the processor temp dir: `MOMENTRY_TEMP_DIR` env override, default +/// `~/momentry/temp`. Process artifacts (extracted wav etc.) must never be +/// written next to the source file — that pollutes the library listing. +fn process_temp_dir() -> PathBuf { + let dir = std::env::var("MOMENTRY_TEMP_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| { + let home = std::env::var("HOME").unwrap_or_default(); + PathBuf::from(home).join("momentry/temp") + }); + if !dir.exists() { + let _ = std::fs::create_dir_all(&dir); + } + dir +} + +/// RAII guard: removes the extracted temp audio (and the mlx_whisper JSON +/// sidecar derived from its stem) when it goes out of scope — success, early +/// bail, or error all end the function, and Drop fires either way. +#[derive(Default)] +struct TempAudioGuard { + audio_path: std::cell::Cell>, +} + +impl TempAudioGuard { + fn set(&self, path: &str) { + self.audio_path.set(Some(path.to_string())); + } +} + +impl Drop for TempAudioGuard { + fn drop(&mut self) { + if let Some(audio) = self.audio_path.take() { + let _ = std::fs::remove_file(&audio); + if let Some(stem) = Path::new(&audio).file_stem().and_then(|s| s.to_str()) { + let sidecar = format!("/tmp/{}.json", stem); + let _ = std::fs::remove_file(&sidecar); + } + println!("[ASR-ASRX] cleaned temp audio: {}", audio); + } + } +} + fn extract_audio(input: &str) -> Result { - let output = input.replace(".mp4", ".wav").replace(".mkv", ".wav"); + let temp_dir = process_temp_dir(); + let stem = Path::new(input) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("audio") + .to_string(); + // Unique per run: concurrent jobs with the same basename won't collide, + // and no stray wav ever appears in the source directory. + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let output = temp_dir + .join(format!("{}_asr_{}.wav", stem, millis)) + .to_string_lossy() + .to_string(); let status = Command::new(get_ffmpeg_path()) .args(&[