Files
momentry_core/src/core/proxy.rs
T
Accusys 3d13a06bd9 feat: face fix deployment + trace_* regeneration + executor stderr filter fix
- swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64
- trace_* directories regenerated for KOBA (37 traces, start_frame 5307)
- executor.rs: stderr filter now logs all non-empty stderr (was discarding)
- VAD not skippable in ASRX (main_fixed.py Step 2 always runs)
- Step 2.5 sentence boundary refinement added
- Cluster agent async endpoints + similarity transparency
- Keyword search: relationship text extraction, priority ordering
- Face fix handoff doc for Studio team
2026-08-05 00:13:50 +08:00

269 lines
7.7 KiB
Rust

use anyhow::{Context, Result};
use std::path::PathBuf;
use std::process::Command;
use crate::core::config::{OUTPUT_DIR, PYTHON_PATH};
const PROXY_HEIGHT: u32 = 720;
const PROXY_CRF: u32 = 23;
const MIN_HEIGHT_FOR_PROXY: u32 = 1080;
pub fn needs_proxy(width: u32, height: u32) -> bool {
height >= MIN_HEIGHT_FOR_PROXY || width >= MIN_HEIGHT_FOR_PROXY
}
pub fn proxy_output_path(file_path: &str) -> Result<PathBuf> {
let src = std::path::Path::new(file_path);
let stem = src
.file_stem()
.context("Cannot get file stem")?
.to_string_lossy();
let parent = src.parent().context("Cannot get parent dir")?;
Ok(parent.join(format!("{}_720p.mp4", stem)))
}
fn ffmpeg_cmd() -> Command {
let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string());
let mut cmd = Command::new(&ffmpeg_path);
let full_lib = "/opt/homebrew/opt/ffmpeg-full/lib";
if std::path::Path::new(full_lib).exists() {
cmd.env("DYLD_LIBRARY_PATH", full_lib);
}
cmd
}
pub async fn generate_proxy(file_path: &str, file_uuid: &str) -> Result<Option<String>> {
let src = std::path::Path::new(file_path);
if !src.exists() {
tracing::warn!("[PROXY] Source file not found: {}", file_path);
return Ok(None);
}
let out = proxy_output_path(file_path)?;
if out.exists() {
tracing::info!("[PROXY] Proxy already exists: {}", out.display());
return Ok(Some(out.to_string_lossy().to_string()));
}
let out_str = out.to_string_lossy().to_string();
let file_path_owned = file_path.to_string();
let status = tokio::task::spawn_blocking(move || {
ffmpeg_cmd()
.args([
"-i",
&file_path_owned,
"-vf",
&format!("scale=-2:{}", PROXY_HEIGHT),
"-c:v",
"libx264",
"-preset",
"fast",
"-crf",
&PROXY_CRF.to_string(),
"-c:a",
"aac",
"-b:a",
"128k",
"-movflags",
"+faststart",
"-y",
&out_str,
])
.status()
})
.await
.context("Spawn blocking failed")?
.context("Failed to spawn ffmpeg")?;
if !status.success() {
let _ = tokio::fs::remove_file(&out).await;
tracing::error!(
"[PROXY] ffmpeg failed for {} (exit: {:?})",
file_uuid,
status.code()
);
return Ok(None);
}
tracing::info!(
"[PROXY] Generated 720p proxy: {} -> {}",
file_uuid,
out.display()
);
Ok(Some(out.to_string_lossy().to_string()))
}
/// Audio track classification result
#[derive(Debug, Clone)]
pub struct AudioTrackResult {
pub classification: String,
pub speech_ratio: f64,
pub speech_segments: i32,
pub duration: f64,
}
/// Probe audio track and classify using VAD
pub async fn probe_audio_track(file_path: &str) -> Result<Option<AudioTrackResult>> {
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/audio_track_probe.py");
if !script.exists() {
tracing::warn!("[AUDIO_TRACK] Script not found: {}", script.display());
return Ok(None);
}
let file_path_owned = file_path.to_string();
let script_str = script.to_string_lossy().to_string();
let python_path = PYTHON_PATH.as_str().to_string();
let output = tokio::task::spawn_blocking(move || {
Command::new(&python_path)
.arg(&script_str)
.arg("--file")
.arg(&file_path_owned)
.arg("--json")
.output()
})
.await
.context("Spawn blocking failed")?
.context("Failed to spawn python")?;
if !output.status.success() {
tracing::warn!(
"[AUDIO_TRACK] Probe failed: {}",
String::from_utf8_lossy(&output.stderr)
);
return Ok(None);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = match serde_json::from_str(&stdout) {
Ok(v) => v,
Err(e) => {
tracing::warn!("[AUDIO_TRACK] JSON parse error: {}", e);
return Ok(None);
}
};
let classification = json
.get("classification")
.and_then(|v| v.as_str())
.unwrap_or("speech_only")
.to_string();
let speech_ratio = json
.get("speech_ratio")
.and_then(|v| v.as_f64())
.unwrap_or(0.5);
let speech_segments = json
.get("speech_segments")
.and_then(|v| v.as_i64())
.unwrap_or(0) as i32;
let duration = json.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0);
tracing::info!(
"[AUDIO_TRACK] {} -> {} (ratio: {:.2}, segments: {})",
file_path,
classification,
speech_ratio,
speech_segments
);
Ok(Some(AudioTrackResult {
classification,
speech_ratio,
speech_segments,
duration,
}))
}
/// Extract key frames from each scene in cut.json for VLM analysis
pub async fn extract_cut_key_frames(
file_uuid: &str,
video_path: &str,
output_dir: &str,
) -> Result<Vec<String>> {
let cut_json = PathBuf::from(output_dir).join(format!("{}.cut.json", file_uuid));
if !cut_json.exists() {
tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display());
return Ok(vec![]);
}
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/cut_key_frame.py");
if !script.exists() {
tracing::warn!("[CUT_KEY_FRAME] Script not found: {}", script.display());
return Ok(vec![]);
}
let file_uuid_owned = file_uuid.to_string();
let video_path_owned = video_path.to_string();
let cut_json_str = cut_json.to_string_lossy().to_string();
let output_dir_owned = output_dir.to_string();
let script_str = script.to_string_lossy().to_string();
let python_path = PYTHON_PATH.as_str().to_string();
let output = tokio::task::spawn_blocking(move || {
Command::new(&python_path)
.arg(&script_str)
.arg("--file-uuid")
.arg(&file_uuid_owned)
.arg("--video")
.arg(&video_path_owned)
.arg("--cut-json")
.arg(&cut_json_str)
.arg("--output-dir")
.arg(&output_dir_owned)
.arg("--json")
.output()
})
.await
.context("Spawn blocking failed")?
.context("Failed to spawn python")?;
if !output.status.success() {
tracing::warn!(
"[CUT_KEY_FRAME] Extraction failed: {}",
String::from_utf8_lossy(&output.stderr)
);
return Ok(vec![]);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = match serde_json::from_str(&stdout) {
Ok(v) => v,
Err(e) => {
tracing::warn!("[CUT_KEY_FRAME] JSON parse error: {}", e);
return Ok(vec![]);
}
};
let scenes: Vec<String> = json
.get("scenes")
.and_then(|s| s.as_array())
.map(|arr| {
arr.iter()
.filter_map(|s| {
if s.get("success").and_then(|b| b.as_bool()) == Some(true) {
s.get("output_path")
.and_then(|p| p.as_str().map(|p| p.to_string()))
} else {
None
}
})
.collect()
})
.unwrap_or_default();
tracing::info!(
"[CUT_KEY_FRAME] Extracted {} scene key frames for {}",
scenes.len(),
file_uuid
);
Ok(scenes)
}