release: v1.3.1 - Pipeline Queue Integration, OCR Fix, Worker Compatibility
Major Changes: - Pipeline Queue integration completed (internal.file + pipeline.commands) - Fixed old job_worker database compatibility with new command_queue table - Compiled Swift OCR binary (was missing, causing empty OCR results) - Added deep scan functionality through re-scan API Fixes: - Changed CommandJob.id from i32 to i64 for database compatibility - Added UUID generation in create_command (message_id field) - Fixed claim_pending_commands to query queue_name = 'internal.file' - Fixed field mappings: command_id → message_id, job_type → command_type - Added support for 'processing' status in CommandJobStatus Queue System: - internal.file queue: for register/unregister/re-scan commands (job_worker) - pipeline.commands queue: for vectorize/store_asrx/etc commands (pipeline_worker) Documentation: - Added comprehensive queue system documentation - Created M4 workspace status reports - Updated AGENTS.md with queue system details
This commit is contained in:
+61
-40
@@ -66,74 +66,86 @@ pub async fn process_asr(
|
||||
tracing::info!("[ASR] Starting ASR processing: {}", video_path);
|
||||
|
||||
let whisper_cli = std::path::Path::new("/opt/homebrew/bin/whisper");
|
||||
|
||||
|
||||
if whisper_cli.exists() {
|
||||
tracing::info!("[ASR] Using whisper CLI: {:?}", whisper_cli);
|
||||
|
||||
|
||||
let output_dir = std::path::Path::new(output_path)
|
||||
.parent()
|
||||
.context("Invalid output path")?;
|
||||
|
||||
|
||||
// Resolve whisper model directory
|
||||
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
|
||||
let models_dir =
|
||||
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
|
||||
let whisper_model_dir = models_dir.join("whisper-small-mlx");
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(whisper_cli)
|
||||
.args(&[
|
||||
video_path,
|
||||
"--model", "small",
|
||||
"--model_dir", whisper_model_dir.to_str().unwrap(),
|
||||
"--output_dir", output_dir.to_str().unwrap(),
|
||||
"--output_format", "json",
|
||||
"--verbose", "False",
|
||||
"--model",
|
||||
"small",
|
||||
"--model_dir",
|
||||
whisper_model_dir.to_str().unwrap(),
|
||||
"--output_dir",
|
||||
output_dir.to_str().unwrap(),
|
||||
"--output_format",
|
||||
"json",
|
||||
"--verbose",
|
||||
"False",
|
||||
])
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute whisper CLI")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[ASR] Whisper CLI failed: {}", stderr);
|
||||
|
||||
|
||||
tracing::warn!("[ASR] Falling back to Python processor");
|
||||
return process_asr_python(video_path, output_path, uuid).await;
|
||||
}
|
||||
|
||||
let json_path = output_dir.join(
|
||||
std::path::Path::new(video_path)
|
||||
.file_stem()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
).with_extension("json");
|
||||
|
||||
|
||||
let json_path = output_dir
|
||||
.join(
|
||||
std::path::Path::new(video_path)
|
||||
.file_stem()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
)
|
||||
.with_extension("json");
|
||||
|
||||
if !json_path.exists() {
|
||||
tracing::warn!("[ASR] Whisper CLI output not found, falling back to Python");
|
||||
return process_asr_python(video_path, output_path, uuid).await;
|
||||
}
|
||||
|
||||
let json_str = std::fs::read_to_string(&json_path)
|
||||
.context("Failed to read whisper output")?;
|
||||
|
||||
let whisper_result: WhisperJsonOutput = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse whisper output")?;
|
||||
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(&json_path).context("Failed to read whisper output")?;
|
||||
|
||||
let whisper_result: WhisperJsonOutput =
|
||||
serde_json::from_str(&json_str).context("Failed to parse whisper output")?;
|
||||
|
||||
std::fs::copy(&json_path, output_path)
|
||||
.context("Failed to copy whisper output to target path")?;
|
||||
|
||||
|
||||
let mut result = convert_whisper_to_asr(whisper_result);
|
||||
result.compute_status();
|
||||
|
||||
|
||||
tracing::info!(
|
||||
"[ASR] Whisper result: status={}, {} segments, language: {:?}",
|
||||
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.segment_count,
|
||||
result.language
|
||||
);
|
||||
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
tracing::warn!("[ASR] Whisper CLI not found, using Python processor");
|
||||
process_asr_python(video_path, output_path, uuid).await
|
||||
}
|
||||
@@ -166,7 +178,11 @@ async fn process_asr_python(
|
||||
|
||||
tracing::info!(
|
||||
"[ASR] Python result: status={}, {} segments, language: {:?}",
|
||||
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.segment_count,
|
||||
result.language
|
||||
);
|
||||
@@ -190,17 +206,22 @@ struct WhisperSegment {
|
||||
}
|
||||
|
||||
fn convert_whisper_to_asr(whisper: WhisperJsonOutput) -> AsrResult {
|
||||
let segments: Vec<AsrSegment> = whisper.segments.into_iter().map(|s| {
|
||||
AsrSegment {
|
||||
let segments: Vec<AsrSegment> = whisper
|
||||
.segments
|
||||
.into_iter()
|
||||
.map(|s| AsrSegment {
|
||||
start_time: s.start,
|
||||
end_time: s.end,
|
||||
start_frame: None,
|
||||
end_frame: None,
|
||||
text: s.text.trim().to_string(),
|
||||
confidence: s.avg_logprob.map(|p| (p.exp() * 100.0).min(100.0)).unwrap_or(0.0),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
confidence: s
|
||||
.avg_logprob
|
||||
.map(|p| (p.exp() * 100.0).min(100.0))
|
||||
.unwrap_or(0.0),
|
||||
})
|
||||
.collect();
|
||||
|
||||
AsrResult {
|
||||
status: None,
|
||||
language: whisper.language,
|
||||
|
||||
@@ -70,7 +70,7 @@ pub async fn process_asrx(
|
||||
uuid: Option<&str>,
|
||||
) -> Result<AsrxResult> {
|
||||
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
|
||||
|
||||
|
||||
// Use Python processor (Swift ASRX disabled - requires GUI authorization)
|
||||
tracing::info!("[ASRX] Using Python processor");
|
||||
process_asrx_python(video_path, output_path, uuid).await
|
||||
|
||||
@@ -1203,7 +1203,7 @@ impl PythonExecutor {
|
||||
/// back to `target/debug/` (mirrors the swift_processors layout convention).
|
||||
pub fn rust_binary_path(&self, bin_name: &str) -> Option<PathBuf> {
|
||||
let cli_dir = crate::core::path_utils::cli_dir();
|
||||
|
||||
|
||||
let base = PathBuf::from(cli_dir).join("rust").join("target");
|
||||
for profile in ["release", "debug"] {
|
||||
let p = base.join(profile).join(bin_name);
|
||||
@@ -1417,29 +1417,35 @@ pub struct CliExecutor {
|
||||
impl CliExecutor {
|
||||
pub fn new() -> Result<Self> {
|
||||
let cli_dir = crate::core::path_utils::cli_dir();
|
||||
|
||||
|
||||
let cli_path = PathBuf::from(&cli_dir);
|
||||
|
||||
|
||||
if !cli_path.exists() {
|
||||
anyhow::bail!(
|
||||
"CLI directory not found at {:?} (set MOMENTRY_CLI_DIR env var)",
|
||||
cli_dir
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
cli_dir: cli_path,
|
||||
})
|
||||
|
||||
Ok(Self { cli_dir: cli_path })
|
||||
}
|
||||
|
||||
|
||||
pub fn swift_cli_path(&self, name: &str) -> PathBuf {
|
||||
self.cli_dir.join("swift").join(".build").join("release").join(name)
|
||||
self.cli_dir
|
||||
.join("swift")
|
||||
.join(".build")
|
||||
.join("release")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
|
||||
pub fn rust_cli_path(&self, name: &str) -> PathBuf {
|
||||
self.cli_dir.join("rust").join("target").join("release").join(name)
|
||||
self.cli_dir
|
||||
.join("rust")
|
||||
.join("target")
|
||||
.join("release")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
|
||||
pub fn cli_dir(&self) -> &PathBuf {
|
||||
&self.cli_dir
|
||||
}
|
||||
|
||||
+148
-108
@@ -11,7 +11,7 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
||||
use std::path::PathBuf;
|
||||
let rel = format!(".build/release/{}", bin);
|
||||
let rel = rel.as_str();
|
||||
|
||||
|
||||
// Priority: env override -> current_exe sibling -> dev fallback
|
||||
if let Ok(dir) = std::env::var("MOMENTRY_SWIFT_PROCESSORS_DIR") {
|
||||
let p = PathBuf::from(dir).join(rel);
|
||||
@@ -19,7 +19,7 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Try sibling of current_exe
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(parent) = exe.parent() {
|
||||
@@ -29,14 +29,13 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Dev fallback
|
||||
crate::core::path_utils::scripts_dir()
|
||||
.join("swift_processors")
|
||||
.join(rel)
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceResult {
|
||||
#[serde(default)]
|
||||
@@ -63,12 +62,10 @@ impl FaceResult {
|
||||
self.status = Some(FaceStatus::from_face_count(self.total_faces));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
let json = serde_json::to_string_pretty(self)
|
||||
.context("Failed to serialize FaceResult")?;
|
||||
std::fs::write(path, json)
|
||||
.context("Failed to write face.json")?;
|
||||
let json = serde_json::to_string_pretty(self).context("Failed to serialize FaceResult")?;
|
||||
std::fs::write(path, json).context("Failed to write face.json")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -103,11 +100,13 @@ pub struct Face {
|
||||
#[serde(default)]
|
||||
pub height: i32,
|
||||
pub confidence: f32,
|
||||
#[serde(default)]
|
||||
#[serde(default, rename = "captureQuality", alias = "capture_quality")]
|
||||
pub capture_quality: Option<f32>,
|
||||
pub embedding: Option<Vec<f32>>,
|
||||
pub landmarks: Option<serde_json::Value>,
|
||||
pub pose_angle: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub lips: Option<serde_json::Value>,
|
||||
pub attributes: Option<FaceAttributes>,
|
||||
#[serde(default)]
|
||||
pub bbox: Option<BoundingBox>,
|
||||
@@ -179,60 +178,61 @@ pub async fn process_face(
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let executor = PythonExecutor::new()?;
|
||||
let executor = PythonExecutor::new()?;
|
||||
|
||||
// Try config-driven tool selection first
|
||||
if let Ok(Some(result)) = run_face_with_config(&executor, video_path, output_path, uuid).await {
|
||||
tracing::info!(
|
||||
"[FACE] Config-driven processing completed: {} faces",
|
||||
result.total_faces
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
// Try config-driven tool selection first
|
||||
if let Ok(Some(result)) = run_face_with_config(&executor, video_path, output_path, uuid).await {
|
||||
tracing::info!(
|
||||
"[FACE] Config-driven processing completed: {} faces",
|
||||
result.total_faces
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
tracing::info!("[FACE] Config-driven selection failed, falling back to hard-coded logic");
|
||||
tracing::info!("[FACE] Config-driven selection failed, falling back to hard-coded logic");
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for Swift face processor first
|
||||
let swift_face_path = swift_processor_path("swift_face");
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for Swift face processor first
|
||||
let swift_face_path = swift_processor_path("swift_face");
|
||||
|
||||
if swift_face_path.exists() {
|
||||
tracing::info!("[FACE] Using Swift processor: {:?}", swift_face_path);
|
||||
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(swift_face_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute swift_face")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[FACE] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift face processor failed");
|
||||
}
|
||||
|
||||
|
||||
// Generate embeddings with FaceNet CoreML
|
||||
let facenet_path = swift_processor_path("facenet_embedding");
|
||||
|
||||
|
||||
if facenet_path.exists() {
|
||||
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
||||
|
||||
|
||||
// Resolve model path
|
||||
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
|
||||
let models_dir =
|
||||
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
|
||||
let model_path = models_dir.join("facenet512.mlpackage");
|
||||
|
||||
|
||||
if !model_path.exists() {
|
||||
tracing::error!("[FACE] FaceNet model not found at {:?}", model_path);
|
||||
tracing::error!("[FACE] Set MOMENTRY_MODELS_DIR environment variable or ensure models/facenet512.mlpackage exists");
|
||||
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
|
||||
}
|
||||
|
||||
|
||||
let facenet_output = format!("{}.with_embedding", output_path);
|
||||
let facenet_args = vec![
|
||||
video_path.to_string(),
|
||||
@@ -241,12 +241,12 @@ let swift_face_path = swift_processor_path("swift_face");
|
||||
"--model".to_string(),
|
||||
model_path.to_string_lossy().to_string(),
|
||||
];
|
||||
|
||||
|
||||
let facenet_result = tokio::process::Command::new(facenet_path)
|
||||
.args(&facenet_args)
|
||||
.output()
|
||||
.await;
|
||||
|
||||
|
||||
match facenet_result {
|
||||
Ok(output) if output.status.success() => {
|
||||
// Replace original file with embedding-enhanced version
|
||||
@@ -258,7 +258,10 @@ let swift_face_path = swift_processor_path("swift_face");
|
||||
tracing::info!("[FACE] Embeddings generated successfully");
|
||||
}
|
||||
} else {
|
||||
tracing::error!("[FACE] FaceNet output file not created: {}", facenet_output);
|
||||
tracing::error!(
|
||||
"[FACE] FaceNet output file not created: {}",
|
||||
facenet_output
|
||||
);
|
||||
anyhow::bail!("FaceNet output file not created");
|
||||
}
|
||||
}
|
||||
@@ -273,14 +276,19 @@ let swift_face_path = swift_processor_path("swift_face");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::warn!("[FACE] FaceNet binary not found at {:?}, skipping embedding generation", facenet_path);
|
||||
tracing::warn!(
|
||||
"[FACE] FaceNet binary not found at {:?}, skipping embedding generation",
|
||||
facenet_path
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Read the JSON (with embeddings from FaceNet)
|
||||
let json_str = std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
|
||||
let mut result: FaceResult = serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
|
||||
let mut result: FaceResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
result.compute_status();
|
||||
|
||||
|
||||
// Store embeddings to Qdrant and remove from JSON
|
||||
if let Some(file_uuid) = uuid {
|
||||
tracing::info!("[FACE] Storing embeddings to Qdrant for {}", file_uuid);
|
||||
@@ -295,7 +303,7 @@ let swift_face_path = swift_processor_path("swift_face");
|
||||
} else {
|
||||
tracing::warn!("[FACE] No UUID provided, skipping Qdrant storage");
|
||||
}
|
||||
|
||||
|
||||
// Execute face tracking
|
||||
tracing::info!("[FACE] Starting face tracking");
|
||||
use crate::core::processor::face_tracker::track_faces;
|
||||
@@ -304,19 +312,23 @@ let swift_face_path = swift_processor_path("swift_face");
|
||||
} else {
|
||||
tracing::info!("[FACE] Face tracking completed successfully");
|
||||
}
|
||||
|
||||
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Swift result: status={}, {} frames, {} total faces",
|
||||
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.frames.len(),
|
||||
result.total_faces
|
||||
);
|
||||
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
// Fallback to Python processor
|
||||
let script_path = executor.script_path("face_processor.py");
|
||||
|
||||
@@ -344,18 +356,18 @@ let swift_face_path = swift_processor_path("swift_face");
|
||||
let mut result: FaceResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
|
||||
result.compute_status();
|
||||
|
||||
// Execute face tracking
|
||||
tracing::info!("[FACE] Starting face tracking");
|
||||
use crate::core::processor::face_tracker::track_faces;
|
||||
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
|
||||
tracing::warn!("[FACE] Face tracking failed: {}", e);
|
||||
} else {
|
||||
tracing::info!("[FACE] Face tracking completed successfully");
|
||||
}
|
||||
|
||||
result.save_to_file(output_path)?;
|
||||
result.compute_status();
|
||||
|
||||
// Execute face tracking
|
||||
tracing::info!("[FACE] Starting face tracking");
|
||||
use crate::core::processor::face_tracker::track_faces;
|
||||
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
|
||||
tracing::warn!("[FACE] Face tracking failed: {}", e);
|
||||
} else {
|
||||
tracing::info!("[FACE] Face tracking completed successfully");
|
||||
}
|
||||
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Result: status={}, {} frames, {} total faces",
|
||||
@@ -378,21 +390,24 @@ async fn run_face_with_config(
|
||||
uuid: Option<&str>,
|
||||
) -> Result<Option<FaceResult>> {
|
||||
use super::tool_selector::ToolSelector;
|
||||
|
||||
|
||||
let selector = ToolSelector::new("face");
|
||||
|
||||
|
||||
if let Some(tool) = selector.select_tool(executor).await? {
|
||||
tracing::info!(
|
||||
"[FACE] Using tool from config: {} (priority {})",
|
||||
tool.name,
|
||||
tool.parameters.get("priority").and_then(|v| v.as_u64()).unwrap_or(99)
|
||||
tool.parameters
|
||||
.get("priority")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(99)
|
||||
);
|
||||
|
||||
|
||||
match tool.name.as_str() {
|
||||
"swift" => {
|
||||
let swift_path = &tool.path;
|
||||
tracing::info!("[FACE] Using Swift processor from config: {:?}", swift_path);
|
||||
|
||||
|
||||
let args = if !tool.args.is_empty() {
|
||||
tracing::info!("[FACE] Using args from config: {:?}", tool.args);
|
||||
tool.args
|
||||
@@ -411,37 +426,37 @@ async fn run_face_with_config(
|
||||
}
|
||||
args
|
||||
};
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(swift_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute swift_face")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[FACE] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift face processor failed");
|
||||
}
|
||||
|
||||
|
||||
// Generate embeddings with FaceNet CoreML
|
||||
let facenet_path = swift_processor_path("facenet_embedding");
|
||||
|
||||
|
||||
if facenet_path.exists() {
|
||||
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
||||
|
||||
|
||||
let facenet_output = format!("{}.with_embedding", output_path);
|
||||
let facenet_args = vec![
|
||||
video_path.to_string(),
|
||||
output_path.to_string(),
|
||||
facenet_output.clone(),
|
||||
];
|
||||
|
||||
|
||||
let facenet_result = tokio::process::Command::new(facenet_path)
|
||||
.args(&facenet_args)
|
||||
.output()
|
||||
.await;
|
||||
|
||||
|
||||
match facenet_result {
|
||||
Ok(output) if output.status.success() => {
|
||||
if std::path::Path::new(&facenet_output).exists() {
|
||||
@@ -451,56 +466,71 @@ async fn run_face_with_config(
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
tracing::warn!("[FACE] FaceNet embedding generation failed, using detections only");
|
||||
tracing::warn!(
|
||||
"[FACE] FaceNet embedding generation failed, using detections only"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read Swift FACE output")?;
|
||||
let mut result: FaceResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse Swift FACE output")?;
|
||||
let mut result: FaceResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse Swift FACE output")?;
|
||||
result.compute_status();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
|
||||
if let Some(uid) = uuid {
|
||||
match store_face_embeddings_to_qdrant(uid, &mut result, output_path).await {
|
||||
Ok(count) => tracing::info!("[FACE] Stored {} embeddings to Qdrant", count),
|
||||
Err(e) => tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e),
|
||||
Err(e) => {
|
||||
tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
"python" => {
|
||||
let script_path = &tool.path;
|
||||
tracing::info!("[FACE] Using Python processor from config: {:?}", script_path);
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Using Python processor from config: {:?}",
|
||||
script_path
|
||||
);
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
|
||||
|
||||
executor
|
||||
.run("face_processor.py", &[video_path, output_path], uuid, "FACE", None)
|
||||
.run(
|
||||
"face_processor.py",
|
||||
&[video_path, output_path],
|
||||
uuid,
|
||||
"FACE",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("Failed to run face_processor.py")?;
|
||||
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read Python FACE output")?;
|
||||
let mut result: FaceResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse Python FACE output")?;
|
||||
result.compute_status();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
|
||||
if let Some(uid) = uuid {
|
||||
match store_face_embeddings_to_qdrant(uid, &mut result, output_path).await {
|
||||
Ok(count) => tracing::info!("[FACE] Stored {} embeddings to Qdrant", count),
|
||||
Err(e) => tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e),
|
||||
Err(e) => {
|
||||
tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
_ => {
|
||||
@@ -508,7 +538,7 @@ async fn run_face_with_config(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
@@ -538,6 +568,7 @@ mod tests {
|
||||
embedding: Some(vec![0.1, 0.2, 0.3]),
|
||||
landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])),
|
||||
pose_angle: None,
|
||||
lips: None,
|
||||
attributes: Some(FaceAttributes {
|
||||
age: Some(30),
|
||||
gender: Some("male".to_string()),
|
||||
@@ -640,6 +671,7 @@ mod tests {
|
||||
embedding: None,
|
||||
landmarks: None,
|
||||
pose_angle: None,
|
||||
lips: None,
|
||||
attributes: None,
|
||||
bbox: None,
|
||||
pose: None,
|
||||
@@ -661,6 +693,7 @@ mod tests {
|
||||
embedding: Some(vec![0.1; 512]),
|
||||
landmarks: None,
|
||||
pose_angle: None,
|
||||
lips: None,
|
||||
attributes: Some(FaceAttributes {
|
||||
age: Some(35),
|
||||
gender: Some("male".to_string()),
|
||||
@@ -687,24 +720,26 @@ pub async fn store_face_embeddings_to_qdrant(
|
||||
use uuid::Uuid;
|
||||
|
||||
let qdrant = QdrantDb::new();
|
||||
|
||||
|
||||
let mut points: Vec<(u64, Vec<f32>, serde_json::Value)> = Vec::new();
|
||||
let fps = face_result.fps;
|
||||
|
||||
|
||||
// Prepare points with embeddings
|
||||
for frame in &face_result.frames {
|
||||
let frame_num = frame.frame;
|
||||
let timestamp_secs = frame_num as f64 / fps;
|
||||
|
||||
|
||||
for (idx, face) in frame.faces.iter().enumerate() {
|
||||
if let Some(embedding) = &face.embedding {
|
||||
let point_id = Uuid::new_v4().as_u128() as u64;
|
||||
|
||||
|
||||
// Generate face_id if not present (format: face_{frame}_{idx})
|
||||
let face_id = face.face_id.as_deref()
|
||||
let face_id = face
|
||||
.face_id
|
||||
.as_deref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("face_{}_{}", frame_num, idx));
|
||||
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"file_uuid": file_uuid,
|
||||
"frame": frame_num,
|
||||
@@ -715,20 +750,21 @@ pub async fn store_face_embeddings_to_qdrant(
|
||||
"y": face.y,
|
||||
"width": face.width,
|
||||
"height": face.height,
|
||||
"capture_quality": face.capture_quality.unwrap_or(0.0),
|
||||
"trace_id": -1i32, // Will be updated by face tracing
|
||||
});
|
||||
|
||||
|
||||
points.push((point_id, embedding.clone(), payload));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let total_points = points.len();
|
||||
if total_points == 0 {
|
||||
tracing::info!("[FACE] No embeddings to store for {}", file_uuid);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
|
||||
// Delete old points for this file
|
||||
let filter = serde_json::json!({
|
||||
"must": [{
|
||||
@@ -736,13 +772,13 @@ pub async fn store_face_embeddings_to_qdrant(
|
||||
"match": {"value": file_uuid}
|
||||
}]
|
||||
});
|
||||
|
||||
|
||||
if let Err(e) = qdrant.delete_points_by_filter("_faces", filter).await {
|
||||
tracing::warn!("[FACE] Failed to delete old points: {}", e);
|
||||
} else {
|
||||
tracing::info!("[FACE] Deleted old points for {}", file_uuid);
|
||||
}
|
||||
|
||||
|
||||
// Upsert new points in batches
|
||||
let batch_size = 100;
|
||||
for (i, chunk) in points.chunks(batch_size).enumerate() {
|
||||
@@ -750,27 +786,31 @@ pub async fn store_face_embeddings_to_qdrant(
|
||||
.iter()
|
||||
.map(|(id, vec, payload)| (*id, vec.as_slice(), Some(payload.clone())))
|
||||
.collect();
|
||||
|
||||
qdrant.upsert_vectors_batch("_faces", &batch_points).await
|
||||
|
||||
qdrant
|
||||
.upsert_vectors_batch("_faces", &batch_points)
|
||||
.await
|
||||
.with_context(|| format!("Failed to upsert batch {}", i + 1))?;
|
||||
}
|
||||
|
||||
|
||||
tracing::info!("[FACE] Stored {} embeddings to Qdrant", total_points);
|
||||
|
||||
|
||||
// Remove embeddings from in-memory result
|
||||
for frame in &mut face_result.frames {
|
||||
for face in &mut frame.faces {
|
||||
face.embedding = None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Save cleaned JSON back
|
||||
let json_str = serde_json::to_string_pretty(&face_result)
|
||||
.context("Failed to serialize cleaned face result")?;
|
||||
std::fs::write(output_path, &json_str)
|
||||
.context("Failed to write cleaned face.json")?;
|
||||
|
||||
tracing::info!("[FACE] Removed embeddings from JSON, saved to {}", output_path);
|
||||
|
||||
std::fs::write(output_path, &json_str).context("Failed to write cleaned face.json")?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Removed embeddings from JSON, saved to {}",
|
||||
output_path
|
||||
);
|
||||
|
||||
Ok(total_points)
|
||||
}
|
||||
|
||||
@@ -90,7 +90,8 @@ pub async fn process_face_cluster(
|
||||
];
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] Using threshold: similarity={:.2}, distance={:.4}",
|
||||
threshold, distance
|
||||
threshold,
|
||||
distance
|
||||
);
|
||||
|
||||
// Try Rust binary first (preferred), fallback to Python if unavailable
|
||||
|
||||
@@ -96,7 +96,8 @@ fn calculate_embedding_similarity(emb1: &[f32], emb2: &[f32]) -> f64 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let dot: f64 = emb1.iter()
|
||||
let dot: f64 = emb1
|
||||
.iter()
|
||||
.zip(emb2.iter())
|
||||
.map(|(a, b)| (*a as f64) * (*b as f64))
|
||||
.sum();
|
||||
@@ -126,7 +127,7 @@ fn match_faces(
|
||||
curr_frame: Option<u64>,
|
||||
) -> Vec<i32> {
|
||||
let mut trace_ids = vec![-1i32; current_faces.len()];
|
||||
|
||||
|
||||
if previous_faces.is_empty() {
|
||||
return trace_ids;
|
||||
}
|
||||
@@ -151,10 +152,10 @@ fn match_faces(
|
||||
width: curr_face.width,
|
||||
height: curr_face.height,
|
||||
};
|
||||
|
||||
|
||||
let mut best_prev_idx = -1i32;
|
||||
let mut best_iou = 0.0;
|
||||
|
||||
|
||||
for (prev_idx, prev_face) in previous_faces.iter().enumerate() {
|
||||
if used_prev.contains(&prev_idx) {
|
||||
continue;
|
||||
@@ -165,14 +166,14 @@ fn match_faces(
|
||||
width: prev_face.width,
|
||||
height: prev_face.height,
|
||||
};
|
||||
|
||||
|
||||
let iou = calculate_bbox_iou(&curr_bbox, &prev_bbox);
|
||||
if iou > best_iou {
|
||||
best_iou = iou;
|
||||
best_prev_idx = prev_idx as i32;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if best_prev_idx >= 0 && best_iou > 0.5 {
|
||||
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
|
||||
used_prev.insert(best_prev_idx as usize);
|
||||
@@ -185,7 +186,7 @@ fn match_faces(
|
||||
|
||||
// Normal matching
|
||||
let mut used_prev = HashSet::new();
|
||||
|
||||
|
||||
for (curr_idx, curr_face) in current_faces.iter().enumerate() {
|
||||
let curr_bbox = BoundingBox {
|
||||
x: curr_face.x,
|
||||
@@ -193,27 +194,29 @@ fn match_faces(
|
||||
width: curr_face.width,
|
||||
height: curr_face.height,
|
||||
};
|
||||
|
||||
|
||||
let mut best_prev_idx = -1i32;
|
||||
let mut best_score = 0.0;
|
||||
|
||||
|
||||
for (prev_idx, prev_face) in previous_faces.iter().enumerate() {
|
||||
if used_prev.contains(&prev_idx) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
let prev_bbox = BoundingBox {
|
||||
x: prev_face.x,
|
||||
y: prev_face.y,
|
||||
width: prev_face.width,
|
||||
height: prev_face.height,
|
||||
};
|
||||
|
||||
|
||||
let iou = calculate_bbox_iou(&curr_bbox, &prev_bbox);
|
||||
let distance = calculate_bbox_distance(&curr_bbox, &prev_bbox);
|
||||
|
||||
|
||||
let similarity = if use_embedding {
|
||||
if let (Some(curr_emb), Some(prev_emb)) = (&curr_face.embedding, &prev_face.embedding) {
|
||||
if let (Some(curr_emb), Some(prev_emb)) =
|
||||
(&curr_face.embedding, &prev_face.embedding)
|
||||
{
|
||||
calculate_embedding_similarity(curr_emb, prev_emb)
|
||||
} else {
|
||||
0.0
|
||||
@@ -221,38 +224,38 @@ fn match_faces(
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
|
||||
// Bbox size consistency check
|
||||
let prev_area = (prev_bbox.width * prev_bbox.height) as f64;
|
||||
let curr_area = (curr_bbox.width * curr_bbox.height) as f64;
|
||||
let area_ratio = curr_area.max(prev_area) / curr_area.min(prev_area).max(1.0);
|
||||
|
||||
|
||||
let mut score = 0.0;
|
||||
|
||||
|
||||
// Reject if both embedding AND IoU disagree
|
||||
if use_embedding && similarity < 0.5 && iou < 0.3 {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Reject if bbox size changes too much
|
||||
if area_ratio > 5.0 && similarity < 0.8 {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Edge exit check
|
||||
let prev_at_edge = prev_bbox.x < 50
|
||||
let prev_at_edge = prev_bbox.x < 50
|
||||
|| prev_bbox.x + prev_bbox.width > 1870
|
||||
|| prev_bbox.y < 50
|
||||
|| prev_bbox.y < 50
|
||||
|| prev_bbox.y + prev_bbox.height > 1030;
|
||||
let curr_at_edge = curr_bbox.x < 50
|
||||
let curr_at_edge = curr_bbox.x < 50
|
||||
|| curr_bbox.x + curr_bbox.width > 1870
|
||||
|| curr_bbox.y < 50
|
||||
|| curr_bbox.y < 50
|
||||
|| curr_bbox.y + curr_bbox.height > 1030;
|
||||
|
||||
|
||||
if prev_at_edge && !curr_at_edge && similarity < 0.8 {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Calculate score
|
||||
if iou > iou_threshold && similarity > similarity_threshold {
|
||||
score = iou + similarity;
|
||||
@@ -269,19 +272,19 @@ fn match_faces(
|
||||
score = similarity + iou;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if score > best_score {
|
||||
best_score = score;
|
||||
best_prev_idx = prev_idx as i32;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if best_prev_idx >= 0 && best_score > 0.0 {
|
||||
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
|
||||
used_prev.insert(best_prev_idx as usize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
trace_ids
|
||||
}
|
||||
|
||||
@@ -298,18 +301,18 @@ pub fn track_faces(
|
||||
tracing::info!("No frames found in face.json");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
|
||||
let fps = face_data.fps;
|
||||
let frames_count = face_data.frames.len();
|
||||
|
||||
|
||||
let mut next_trace_id: i32 = 0;
|
||||
let mut traces: HashMap<i32, Vec<TracePoint>> = HashMap::new();
|
||||
|
||||
|
||||
let mut prev_faces: Vec<Face> = Vec::new();
|
||||
let mut prev_trace_ids: Vec<i32> = Vec::new();
|
||||
let mut prev_frame_num: Option<u64> = None;
|
||||
let mut prev_face_frame: Option<u64> = None;
|
||||
|
||||
|
||||
tracing::info!(
|
||||
"Tracking faces across {} frames (iou={}, similarity={}, distance={})",
|
||||
frames_count,
|
||||
@@ -317,7 +320,7 @@ pub fn track_faces(
|
||||
similarity_threshold,
|
||||
distance_threshold
|
||||
);
|
||||
|
||||
|
||||
for frame_idx in 0..face_data.frames.len() {
|
||||
let frame_num = face_data.frames[frame_idx].frame;
|
||||
let frame_gap = if let Some(prev) = prev_frame_num {
|
||||
@@ -326,15 +329,15 @@ pub fn track_faces(
|
||||
None
|
||||
};
|
||||
prev_frame_num = Some(frame_num);
|
||||
|
||||
|
||||
let faces = &face_data.frames[frame_idx].faces.clone();
|
||||
|
||||
|
||||
if faces.is_empty() {
|
||||
prev_faces.clear();
|
||||
prev_trace_ids.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
let matches = match_faces(
|
||||
faces,
|
||||
&prev_faces,
|
||||
@@ -348,7 +351,7 @@ pub fn track_faces(
|
||||
prev_face_frame,
|
||||
Some(frame_num),
|
||||
);
|
||||
|
||||
|
||||
let mut trace_ids = Vec::new();
|
||||
for (curr_idx, &trace_id) in matches.iter().enumerate() {
|
||||
let trace_id = if trace_id >= 0 {
|
||||
@@ -358,12 +361,12 @@ pub fn track_faces(
|
||||
next_trace_id += 1;
|
||||
new_id
|
||||
};
|
||||
|
||||
|
||||
// Set trace_id on the face
|
||||
face_data.frames[frame_idx].faces[curr_idx].trace_id = Some(trace_id);
|
||||
|
||||
|
||||
trace_ids.push(trace_id);
|
||||
|
||||
|
||||
let face = &faces[curr_idx];
|
||||
let trace_point = TracePoint {
|
||||
frame: frame_num,
|
||||
@@ -376,14 +379,17 @@ pub fn track_faces(
|
||||
},
|
||||
confidence: face.confidence,
|
||||
};
|
||||
|
||||
traces.entry(trace_id).or_insert_with(Vec::new).push(trace_point);
|
||||
|
||||
traces
|
||||
.entry(trace_id)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(trace_point);
|
||||
}
|
||||
|
||||
|
||||
prev_faces = faces.clone();
|
||||
prev_trace_ids = trace_ids;
|
||||
prev_face_frame = Some(frame_num);
|
||||
|
||||
|
||||
if frame_num % 100 == 0 {
|
||||
tracing::info!(
|
||||
"Frame {}: {} faces, {} active traces",
|
||||
@@ -393,7 +399,7 @@ pub fn track_faces(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Build trace statistics
|
||||
let trace_stats: HashMap<String, TraceStats> = traces
|
||||
.into_iter()
|
||||
@@ -402,8 +408,9 @@ pub fn track_faces(
|
||||
let start_frame = path.first().unwrap().frame;
|
||||
let end_frame = path.last().unwrap().frame;
|
||||
let duration_frames = end_frame - start_frame + 1;
|
||||
let avg_confidence = path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64;
|
||||
|
||||
let avg_confidence =
|
||||
path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64;
|
||||
|
||||
let stats = TraceStats {
|
||||
trace_id,
|
||||
start_frame,
|
||||
@@ -414,11 +421,11 @@ pub fn track_faces(
|
||||
avg_confidence,
|
||||
path,
|
||||
};
|
||||
|
||||
|
||||
(trace_id.to_string(), stats)
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
// Store traces in metadata
|
||||
face_data.metadata = Some(serde_json::json!({
|
||||
"traces": trace_stats,
|
||||
@@ -427,9 +434,9 @@ pub fn track_faces(
|
||||
"active_traces": trace_stats.len(),
|
||||
}
|
||||
}));
|
||||
|
||||
|
||||
tracing::info!("✅ Tracking complete: {} traces", trace_stats.len());
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -451,7 +458,7 @@ mod tests {
|
||||
width: 100,
|
||||
height: 100,
|
||||
};
|
||||
|
||||
|
||||
let iou = calculate_bbox_iou(&bbox1, &bbox2);
|
||||
assert!(iou > 0.0 && iou < 1.0);
|
||||
}
|
||||
@@ -470,7 +477,7 @@ mod tests {
|
||||
width: 100,
|
||||
height: 100,
|
||||
};
|
||||
|
||||
|
||||
let distance = calculate_bbox_distance(&bbox1, &bbox2);
|
||||
assert!(distance > 0.0);
|
||||
}
|
||||
@@ -479,12 +486,12 @@ mod tests {
|
||||
fn test_calculate_embedding_similarity() {
|
||||
let emb1 = vec![1.0, 0.0, 0.0];
|
||||
let emb2 = vec![1.0, 0.0, 0.0];
|
||||
|
||||
|
||||
let similarity = calculate_embedding_similarity(&emb1, &emb2);
|
||||
assert!((similarity - 1.0).abs() < 0.001);
|
||||
|
||||
|
||||
let emb3 = vec![0.0, 1.0, 0.0];
|
||||
let similarity2 = calculate_embedding_similarity(&emb1, &emb3);
|
||||
assert!((similarity2 - 0.0).abs() < 0.001);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,5 +195,5 @@ pub use tkg::{
|
||||
build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo,
|
||||
RepresentativeFrameResult, TkgResult,
|
||||
};
|
||||
pub mod tool_selector;
|
||||
pub mod processor_config_v3;
|
||||
pub mod tool_selector;
|
||||
|
||||
@@ -240,32 +240,32 @@ pub async fn process_ocr(
|
||||
|
||||
// Resolve Swift OCR processor path
|
||||
let swift_ocr_path = crate::core::processor::face::swift_processor_path("swift_ocr");
|
||||
|
||||
|
||||
if swift_ocr_path.exists() {
|
||||
tracing::info!("[OCR] Using Swift processor: {:?}", swift_ocr_path);
|
||||
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(swift_ocr_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute swift_ocr")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[OCR] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift OCR failed: {}", stderr);
|
||||
}
|
||||
|
||||
|
||||
tracing::info!("[OCR] Swift processor completed successfully");
|
||||
} else {
|
||||
tracing::warn!("[OCR] Swift binary not found, falling back to Python");
|
||||
|
||||
|
||||
let executor = PythonExecutor::new()?;
|
||||
let script_path = executor.script_path("ocr_processor.py");
|
||||
|
||||
|
||||
+128
-102
@@ -158,26 +158,31 @@ pub async fn process_pose(
|
||||
total_video_frames
|
||||
);
|
||||
|
||||
let executor = PythonExecutor::new()?;
|
||||
let executor = PythonExecutor::new()?;
|
||||
|
||||
// Try config-driven tool selection first
|
||||
if let Ok(Some(result)) = run_pose_with_config(&executor, video_path, output_path, uuid, frames).await {
|
||||
tracing::info!(
|
||||
"[POSE] Config-driven interpolation completed: {} frames",
|
||||
result.frames.len()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
// Try config-driven tool selection first
|
||||
if let Ok(Some(result)) =
|
||||
run_pose_with_config(&executor, video_path, output_path, uuid, frames).await
|
||||
{
|
||||
tracing::info!(
|
||||
"[POSE] Config-driven interpolation completed: {} frames",
|
||||
result.frames.len()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded interpolation logic");
|
||||
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded interpolation logic");
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for MediaPipe Pose first (highest accuracy)
|
||||
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for MediaPipe Pose first (highest accuracy)
|
||||
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
|
||||
if mediapipe_script.exists() {
|
||||
tracing::info!("[POSE] Using MediaPipe Pose for interpolation (highest accuracy): {:?}", mediapipe_script);
|
||||
|
||||
tracing::info!(
|
||||
"[POSE] Using MediaPipe Pose for interpolation (highest accuracy): {:?}",
|
||||
mediapipe_script
|
||||
);
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
@@ -185,7 +190,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
}
|
||||
args.push("--model-complexity".to_string());
|
||||
args.push("2".to_string()); // Highest accuracy
|
||||
|
||||
|
||||
executor
|
||||
.run_with_frames(
|
||||
"pose_processor_mediapipe.py",
|
||||
@@ -197,7 +202,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("Failed to run MediaPipe Pose"))?;
|
||||
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read MediaPipe POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
@@ -208,7 +213,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
tracing::info!("[POSE] MediaPipe Pose not found, trying other processors");
|
||||
|
||||
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
|
||||
@@ -246,43 +251,46 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
}
|
||||
|
||||
// Swift processor path (preferred over Python)
|
||||
let swift_pose_path = crate::core::path_utils::cli_dir()
|
||||
.join("swift/.build/release/swift_pose");
|
||||
|
||||
tracing::info!("[POSE] Looking for Swift processor at: {:?}", swift_pose_path);
|
||||
|
||||
let swift_pose_path =
|
||||
crate::core::path_utils::cli_dir().join("swift/.build/release/swift_pose");
|
||||
|
||||
tracing::info!(
|
||||
"[POSE] Looking for Swift processor at: {:?}",
|
||||
swift_pose_path
|
||||
);
|
||||
|
||||
if swift_pose_path.exists() {
|
||||
tracing::info!("[POSE] Using Swift processor: {:?}", swift_pose_path);
|
||||
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(swift_pose_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute swift_pose")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[POSE] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift pose processor failed");
|
||||
}
|
||||
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read Swift POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse Swift POSE output")?;
|
||||
let result: PoseResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse Swift POSE output")?;
|
||||
tracing::info!(
|
||||
"[POSE] Swift processor completed: {} frames",
|
||||
result.frames.len()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
tracing::info!("[POSE] Swift processor not found, falling back to Python");
|
||||
|
||||
// Call Python pose_processor.py for interpolation
|
||||
@@ -320,29 +328,34 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
}
|
||||
}
|
||||
|
||||
let executor = PythonExecutor::new()?;
|
||||
let executor = PythonExecutor::new()?;
|
||||
|
||||
tracing::info!("[POSE] Starting pose estimation: {}", video_path);
|
||||
tracing::info!("[POSE] Starting pose estimation: {}", video_path);
|
||||
|
||||
// Try config-driven tool selection first
|
||||
if let Ok(Some(result)) = run_pose_with_config(&executor, video_path, output_path, uuid, frames).await {
|
||||
tracing::info!(
|
||||
"[POSE] Config-driven processing completed: {} frames, {} total poses",
|
||||
result.frames.len(),
|
||||
result.frames.iter().map(|f| f.persons.len()).sum::<usize>()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
// Try config-driven tool selection first
|
||||
if let Ok(Some(result)) =
|
||||
run_pose_with_config(&executor, video_path, output_path, uuid, frames).await
|
||||
{
|
||||
tracing::info!(
|
||||
"[POSE] Config-driven processing completed: {} frames, {} total poses",
|
||||
result.frames.len(),
|
||||
result.frames.iter().map(|f| f.persons.len()).sum::<usize>()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded logic");
|
||||
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded logic");
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for MediaPipe Pose first (highest accuracy)
|
||||
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for MediaPipe Pose first (highest accuracy)
|
||||
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
|
||||
if mediapipe_script.exists() {
|
||||
tracing::info!("[POSE] Using MediaPipe Pose (highest accuracy): {:?}", mediapipe_script);
|
||||
|
||||
tracing::info!(
|
||||
"[POSE] Using MediaPipe Pose (highest accuracy): {:?}",
|
||||
mediapipe_script
|
||||
);
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
@@ -350,7 +363,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
}
|
||||
args.push("--model-complexity".to_string());
|
||||
args.push("2".to_string()); // Highest accuracy
|
||||
|
||||
|
||||
executor
|
||||
.run_with_frames(
|
||||
"pose_processor_mediapipe.py",
|
||||
@@ -362,11 +375,11 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("Failed to run MediaPipe Pose"))?;
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read MediaPipe POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse MediaPipe POSE output")?;
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read MediaPipe POSE output")?;
|
||||
let result: PoseResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse MediaPipe POSE output")?;
|
||||
tracing::info!(
|
||||
"[POSE] MediaPipe Pose completed: {} frames, {} total poses",
|
||||
result.frames.len(),
|
||||
@@ -374,7 +387,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
tracing::info!("[POSE] MediaPipe Pose not found, trying other processors");
|
||||
|
||||
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
|
||||
@@ -394,11 +407,14 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
.await
|
||||
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse POSE output")?;
|
||||
tracing::info!("[POSE] Rust processor completed: {} frames", result.frames.len());
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read POSE output")?;
|
||||
let result: PoseResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse POSE output")?;
|
||||
tracing::info!(
|
||||
"[POSE] Rust processor completed: {} frames",
|
||||
result.frames.len()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
tracing::warn!(
|
||||
@@ -407,40 +423,46 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
|
||||
}
|
||||
|
||||
// Swift processor path (Apple Vision - faster but lower accuracy)
|
||||
let swift_pose_path = crate::core::path_utils::cli_dir()
|
||||
.join("swift/.build/release/swift_pose");
|
||||
|
||||
tracing::info!("[POSE] Looking for Swift processor at: {:?}", swift_pose_path);
|
||||
|
||||
let swift_pose_path =
|
||||
crate::core::path_utils::cli_dir().join("swift/.build/release/swift_pose");
|
||||
|
||||
tracing::info!(
|
||||
"[POSE] Looking for Swift processor at: {:?}",
|
||||
swift_pose_path
|
||||
);
|
||||
|
||||
if swift_pose_path.exists() {
|
||||
tracing::info!("[POSE] Using Swift processor: {:?}", swift_pose_path);
|
||||
|
||||
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(swift_pose_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute swift_pose")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[POSE] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift pose processor failed");
|
||||
}
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read Swift POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse Swift POSE output")?;
|
||||
tracing::info!("[POSE] Swift processor completed: {} frames", result.frames.len());
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read Swift POSE output")?;
|
||||
let result: PoseResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse Swift POSE output")?;
|
||||
tracing::info!(
|
||||
"[POSE] Swift processor completed: {} frames",
|
||||
result.frames.len()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
tracing::info!("[POSE] Swift processor not found, falling back to Python");
|
||||
|
||||
let script_path = executor.script_path("pose_processor.py");
|
||||
@@ -484,25 +506,29 @@ async fn run_pose_with_config(
|
||||
frames: Option<&[i64]>,
|
||||
) -> Result<Option<PoseResult>> {
|
||||
use super::tool_selector::ToolSelector;
|
||||
|
||||
|
||||
let selector = ToolSelector::new("pose");
|
||||
|
||||
|
||||
if let Some(tool) = selector.select_tool(executor).await? {
|
||||
tracing::info!(
|
||||
"[POSE] Using tool from config: {} (priority {})",
|
||||
tool.name,
|
||||
tool.parameters.get("priority").and_then(|v| v.as_u64()).unwrap_or(99)
|
||||
tool.parameters
|
||||
.get("priority")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(99)
|
||||
);
|
||||
|
||||
|
||||
match tool.name.as_str() {
|
||||
"mediapipe" => {
|
||||
let model_complexity = tool.parameters
|
||||
let model_complexity = tool
|
||||
.parameters
|
||||
.get("model_complexity")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(2) as u8;
|
||||
|
||||
|
||||
tracing::info!("[POSE] MediaPipe model_complexity={}", model_complexity);
|
||||
|
||||
|
||||
executor
|
||||
.run_with_frames(
|
||||
"pose_processor_mediapipe.py",
|
||||
@@ -514,18 +540,18 @@ async fn run_pose_with_config(
|
||||
)
|
||||
.await
|
||||
.with_context(|| "Failed to run MediaPipe Pose")?;
|
||||
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read MediaPipe POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse MediaPipe POSE output")?;
|
||||
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
"swift" => {
|
||||
let swift_path = &tool.path;
|
||||
tracing::info!("[POSE] Using Swift processor from config: {:?}", swift_path);
|
||||
|
||||
|
||||
let args = if !tool.args.is_empty() {
|
||||
tracing::info!("[POSE] Using args from config: {:?}", tool.args);
|
||||
tool.args.clone()
|
||||
@@ -537,39 +563,39 @@ async fn run_pose_with_config(
|
||||
}
|
||||
args
|
||||
};
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(swift_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute swift_pose")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[POSE] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift pose processor failed");
|
||||
}
|
||||
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read Swift POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse Swift POSE output")?;
|
||||
|
||||
let result: PoseResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse Swift POSE output")?;
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
"rust" => {
|
||||
let rust_path = &tool.path;
|
||||
tracing::info!("[POSE] Using Rust processor from config: {:?}", rust_path);
|
||||
|
||||
|
||||
if !tool.args.is_empty() {
|
||||
tracing::info!("[POSE] Using args from config: {:?}", tool.args);
|
||||
|
||||
|
||||
let output = tokio::process::Command::new(rust_path)
|
||||
.args(&tool.args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute rust_pose")?;
|
||||
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[POSE] Rust processor failed: {}", stderr);
|
||||
@@ -589,12 +615,12 @@ async fn run_pose_with_config(
|
||||
.await
|
||||
.with_context(|| format!("Failed to run Rust binary {:?}", rust_path))?;
|
||||
}
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read POSE output")?;
|
||||
let result: PoseResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse POSE output")?;
|
||||
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read POSE output")?;
|
||||
let result: PoseResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse POSE output")?;
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
_ => {
|
||||
@@ -602,7 +628,7 @@ async fn run_pose_with_config(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,83 +50,90 @@ pub struct ProcessorConfigManager {
|
||||
impl ProcessorConfigManager {
|
||||
pub async fn load() -> Result<Self> {
|
||||
let config_path = std::path::Path::new("config/processor_tools_v3.json");
|
||||
|
||||
|
||||
if !config_path.exists() {
|
||||
anyhow::bail!("Config file not found: {:?}", config_path);
|
||||
}
|
||||
|
||||
|
||||
let content = tokio::fs::read_to_string(config_path)
|
||||
.await
|
||||
.context("Failed to read config file")?;
|
||||
|
||||
let full_config: serde_json::Value = serde_json::from_str(&content)
|
||||
.context("Failed to parse config JSON")?;
|
||||
|
||||
|
||||
let full_config: serde_json::Value =
|
||||
serde_json::from_str(&content).context("Failed to parse config JSON")?;
|
||||
|
||||
let processor_config = full_config
|
||||
.get("processor_config")
|
||||
.context("Missing processor_config in config")?
|
||||
.clone();
|
||||
|
||||
let config: HashMap<String, ProcessorConfigV3> = serde_json::from_value(processor_config)
|
||||
.context("Failed to parse processor configs")?;
|
||||
|
||||
|
||||
let config: HashMap<String, ProcessorConfigV3> =
|
||||
serde_json::from_value(processor_config)
|
||||
.context("Failed to parse processor configs")?;
|
||||
|
||||
info!("[ConfigV3] Loaded {} processor configs", config.len());
|
||||
|
||||
|
||||
Ok(Self { config })
|
||||
}
|
||||
|
||||
|
||||
pub fn get_processor(&self, name: &str) -> Option<&ProcessorConfigV3> {
|
||||
self.config.get(name)
|
||||
}
|
||||
|
||||
|
||||
pub fn get_implementation(&self, processor: &str, tool: &str) -> Option<&Implementation> {
|
||||
self.config.get(processor)?.implementations.iter()
|
||||
self.config
|
||||
.get(processor)?
|
||||
.implementations
|
||||
.iter()
|
||||
.find(|i| i.tool == tool)
|
||||
}
|
||||
|
||||
|
||||
pub fn get_default_implementation(&self, processor: &str) -> Option<&Implementation> {
|
||||
let proc_config = self.config.get(processor)?;
|
||||
let default_tool = &proc_config.default.tool;
|
||||
|
||||
proc_config.implementations.iter()
|
||||
|
||||
proc_config
|
||||
.implementations
|
||||
.iter()
|
||||
.find(|i| i.tool == *default_tool && i.enabled)
|
||||
}
|
||||
|
||||
|
||||
pub fn resolve_command(
|
||||
&self,
|
||||
processor: &str,
|
||||
tool: &str,
|
||||
variables: &HashMap<String, String>,
|
||||
) -> Result<Option<(PathBuf, Vec<String>)>> {
|
||||
let implementation = self.get_implementation(processor, tool)
|
||||
let implementation = self
|
||||
.get_implementation(processor, tool)
|
||||
.context(format!("Implementation not found: {}/{}", processor, tool))?;
|
||||
|
||||
|
||||
if !implementation.enabled {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
|
||||
let executable = Self::resolve_variables(&implementation.command.executable, variables);
|
||||
let executable_path = PathBuf::from(&executable);
|
||||
|
||||
|
||||
if !executable_path.exists() {
|
||||
info!("[ConfigV3] Executable not found: {:?}", executable_path);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
|
||||
let mut args = Vec::new();
|
||||
for arg in &implementation.command.args {
|
||||
let resolved = Self::resolve_variables(arg, variables);
|
||||
args.push(resolved);
|
||||
}
|
||||
|
||||
|
||||
info!(
|
||||
"[ConfigV3] Resolved command: {:?} {:?}",
|
||||
executable_path, args
|
||||
);
|
||||
|
||||
|
||||
Ok(Some((executable_path, args)))
|
||||
}
|
||||
|
||||
|
||||
fn resolve_variables(template: &str, variables: &HashMap<String, String>) -> String {
|
||||
let mut result = template.to_string();
|
||||
for (key, value) in variables {
|
||||
@@ -135,14 +142,16 @@ impl ProcessorConfigManager {
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
pub fn get_all_processors(&self) -> Vec<String> {
|
||||
self.config.keys().cloned().collect()
|
||||
}
|
||||
|
||||
|
||||
pub fn get_implementations_by_priority(&self, processor: &str) -> Vec<&Implementation> {
|
||||
if let Some(proc_config) = self.config.get(processor) {
|
||||
let mut implementations: Vec<_> = proc_config.implementations.iter()
|
||||
let mut implementations: Vec<_> = proc_config
|
||||
.implementations
|
||||
.iter()
|
||||
.filter(|i| i.enabled)
|
||||
.collect();
|
||||
implementations.sort_by_key(|i| i.priority);
|
||||
|
||||
@@ -68,7 +68,7 @@ pub async fn process_scene_classification(
|
||||
// Resolve scene classification model path
|
||||
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
|
||||
let coreml_path = models_dir.join("resnet18_places365.mlpackage");
|
||||
|
||||
|
||||
let mut args = vec![video_path, output_path];
|
||||
if coreml_path.exists() {
|
||||
args.push("--model");
|
||||
|
||||
@@ -1231,7 +1231,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
|
||||
// Use trace_N as primary external_id (consistent with cluster_agent)
|
||||
let external_id = format!("trace_{}", tid);
|
||||
let label = format!("Face Trace {}", tid);
|
||||
let label = String::new();
|
||||
|
||||
// Compute average pose for this trace
|
||||
let mut yaw_sum = 0.0f64;
|
||||
@@ -3551,7 +3551,7 @@ async fn build_face_body_edges(
|
||||
.get("frame")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
|
||||
|
||||
if let Some(persons) = frame_entry.get("persons").and_then(|v| v.as_array()) {
|
||||
for (idx, person) in persons.iter().enumerate() {
|
||||
if let Some(bbox) = person.get("bbox") {
|
||||
@@ -3559,7 +3559,7 @@ async fn build_face_body_edges(
|
||||
let y = bbox.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
let w = bbox.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
let h = bbox.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
|
||||
|
||||
if w > 0.0 && h > 0.0 {
|
||||
frame_poses
|
||||
.entry(frame_num)
|
||||
@@ -3590,7 +3590,7 @@ async fn build_face_body_edges(
|
||||
let body_center_y = py + ph / 2.0;
|
||||
let distance = ((face_center_x - body_center_x).powi(2)
|
||||
+ (face_center_y - body_center_y).powi(2))
|
||||
.sqrt();
|
||||
.sqrt();
|
||||
|
||||
if distance < best_distance {
|
||||
best_distance = distance;
|
||||
|
||||
@@ -16,20 +16,32 @@ impl ToolSelector {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn select_tool(&self, executor: &super::PythonExecutor) -> Result<Option<SelectedTool>> {
|
||||
pub async fn select_tool(
|
||||
&self,
|
||||
executor: &super::PythonExecutor,
|
||||
) -> Result<Option<SelectedTool>> {
|
||||
match self.select_tool_v3().await {
|
||||
Ok(Some(tool)) => {
|
||||
info!("[{}] Selected tool via V3: {}", self.processor_name, tool.name);
|
||||
info!(
|
||||
"[{}] Selected tool via V3: {}",
|
||||
self.processor_name, tool.name
|
||||
);
|
||||
return Ok(Some(tool));
|
||||
}
|
||||
Ok(None) => {
|
||||
info!("[{}] No tool found via V3, falling back to V2", self.processor_name);
|
||||
info!(
|
||||
"[{}] No tool found via V3, falling back to V2",
|
||||
self.processor_name
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
info!("[{}] V3 config failed: {}, falling back to V2", self.processor_name, e);
|
||||
info!(
|
||||
"[{}] V3 config failed: {}, falling back to V2",
|
||||
self.processor_name, e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let config = admin_config::get_processor_config(&self.processor_name)
|
||||
.await
|
||||
.context("Failed to get processor config")?;
|
||||
@@ -64,10 +76,7 @@ impl ToolSelector {
|
||||
|
||||
if let Some(default) = config.default_tool {
|
||||
if let Some(tool_path) = self.find_tool(&default, executor) {
|
||||
info!(
|
||||
"[{}] Using default tool: {}",
|
||||
self.processor_name, default
|
||||
);
|
||||
info!("[{}] Using default tool: {}", self.processor_name, default);
|
||||
return Ok(Some(SelectedTool {
|
||||
name: default.clone(),
|
||||
path: tool_path,
|
||||
@@ -81,30 +90,30 @@ impl ToolSelector {
|
||||
info!("[{}] No available tool found", self.processor_name);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
|
||||
pub async fn select_tool_v3(&self) -> Result<Option<SelectedTool>> {
|
||||
let manager = processor_config_v3::get_config_manager().await?;
|
||||
|
||||
|
||||
let implementations = manager.get_implementations_by_priority(&self.processor_name);
|
||||
|
||||
|
||||
if implementations.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
|
||||
let variables = self.build_variables();
|
||||
|
||||
|
||||
for impl_ in implementations {
|
||||
if !impl_.enabled {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
match manager.resolve_command(&self.processor_name, &impl_.tool, &variables) {
|
||||
Ok(Some((executable, args))) => {
|
||||
info!(
|
||||
"[ToolSelector V3] Selected: {} (priority {}, timeout {}s)",
|
||||
impl_.tool, impl_.priority, impl_.timeout
|
||||
);
|
||||
|
||||
|
||||
return Ok(Some(SelectedTool {
|
||||
name: impl_.tool.clone(),
|
||||
path: executable,
|
||||
@@ -114,7 +123,10 @@ impl ToolSelector {
|
||||
}));
|
||||
}
|
||||
Ok(None) => {
|
||||
info!("[ToolSelector V3] Tool {} not available, trying next", impl_.tool);
|
||||
info!(
|
||||
"[ToolSelector V3] Tool {} not available, trying next",
|
||||
impl_.tool
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -123,43 +135,48 @@ impl ToolSelector {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
|
||||
fn build_variables(&self) -> HashMap<String, String> {
|
||||
let mut vars = HashMap::new();
|
||||
|
||||
|
||||
if let Ok(output_dir) = std::env::var("MOMENTRY_OUTPUT_DIR") {
|
||||
vars.insert("output_dir".to_string(), output_dir);
|
||||
} else {
|
||||
// Resolve output_dir from environment or config
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
vars.insert("output_dir".to_string(), output_dir);
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
vars.insert("output_dir".to_string(), output_dir);
|
||||
}
|
||||
|
||||
|
||||
vars
|
||||
}
|
||||
|
||||
fn swift_binary_path(executor: &super::PythonExecutor, bin_name: &str) -> PathBuf {
|
||||
if let Ok(dir) = std::env::var("MOMENTRY_SWIFT_BIN_DIR") {
|
||||
let p = PathBuf::from(dir).join(bin_name);
|
||||
if p.exists() { return p; }
|
||||
if p.exists() {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Try sibling of current_exe
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(parent) = exe.parent() {
|
||||
let p = parent.join("tools/cli/swift/.build/release").join(bin_name);
|
||||
if p.exists() { return p; }
|
||||
if p.exists() {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Fallback to scripts dir
|
||||
let scripts = executor.script_path("");
|
||||
let base = scripts.parent().map(|p| p.to_path_buf()).unwrap_or_else(|| {
|
||||
crate::core::path_utils::scripts_dir()
|
||||
});
|
||||
let base = scripts
|
||||
.parent()
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| crate::core::path_utils::scripts_dir());
|
||||
base.join("swift_processors/.build/release").join(bin_name)
|
||||
}
|
||||
|
||||
@@ -168,46 +185,78 @@ impl ToolSelector {
|
||||
// POSE processor tools
|
||||
("pose", "mediapipe") => {
|
||||
let script = executor.script_path("pose_processor_mediapipe.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("pose", "rust") => executor.rust_binary_path("rust_pose"),
|
||||
("pose", "swift") => {
|
||||
let swift_path = Self::swift_binary_path(executor, "swift_pose");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
if swift_path.exists() {
|
||||
Some(swift_path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("pose", "yolov8") => {
|
||||
let script = executor.script_path("pose_processor_mps.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("pose", "python") => {
|
||||
let script = executor.script_path("pose_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// FACE processor tools
|
||||
("face", "swift") => {
|
||||
let swift_path = Self::swift_binary_path(executor, "swift_face");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
if swift_path.exists() {
|
||||
Some(swift_path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("face", "python") => {
|
||||
let script = executor.script_path("face_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ASR processor tools
|
||||
("asr", "whisper") => {
|
||||
let whisper_cli = std::path::Path::new("/opt/homebrew/bin/whisper");
|
||||
if whisper_cli.exists() { Some(whisper_cli.to_path_buf()) } else { None }
|
||||
if whisper_cli.exists() {
|
||||
Some(whisper_cli.to_path_buf())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("asr", "rust") => {
|
||||
// Future: Rust ASR implementation
|
||||
executor.rust_binary_path("rust_asr")
|
||||
}
|
||||
|
||||
|
||||
// ASRX processor tools
|
||||
("asrx", "swift") => {
|
||||
let swift_path = Self::swift_binary_path(executor, "asrx_swift");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
if swift_path.exists() {
|
||||
Some(swift_path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("asrx", "rust") => {
|
||||
// Future: Rust ASRX implementation
|
||||
@@ -215,61 +264,87 @@ impl ToolSelector {
|
||||
}
|
||||
("asrx", "python") => {
|
||||
let script = executor.script_path("asrx_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// OCR processor tools
|
||||
("ocr", "swift") => {
|
||||
let swift_path = Self::swift_binary_path(executor, "swift_ocr");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
if swift_path.exists() {
|
||||
Some(swift_path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("ocr", "python") => {
|
||||
let script = executor.script_path("ocr_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Face trace tools
|
||||
("face_trace", "python") => {
|
||||
let script = executor.script_path("store_traced_faces.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("face_trace", "rust") => {
|
||||
executor.rust_binary_path("rust_store_traced_faces")
|
||||
}
|
||||
|
||||
("face_trace", "rust") => executor.rust_binary_path("rust_store_traced_faces"),
|
||||
|
||||
// Face deduplicate tools
|
||||
("face_deduplicate", "python") => {
|
||||
let script = executor.script_path("face_deduplicate.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("face_deduplicate", "rust") => {
|
||||
// Future: Rust face deduplicate implementation
|
||||
executor.rust_binary_path("rust_face_deduplicate")
|
||||
}
|
||||
|
||||
|
||||
// Scene VLM summary tools
|
||||
("scene_vlm_summary", "python") => {
|
||||
let script = executor.script_path("scene_vlm_summary.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// TKG (Temporal Knowledge Graph) tools
|
||||
("tkg", "python") => {
|
||||
let script = executor.script_path("store_traced_faces.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
("tkg", "rust") => {
|
||||
// Future: Rust TKG implementation
|
||||
executor.rust_binary_path("rust_tkg")
|
||||
}
|
||||
|
||||
|
||||
// VLM Summary tools (Rust native implementation)
|
||||
("vlm_summary", "rust") => {
|
||||
// VLM Summary is implemented in Rust, no external binary needed
|
||||
// Return a placeholder path to indicate availability
|
||||
Some(std::path::PathBuf::from("rust_vlm_summary"))
|
||||
}
|
||||
|
||||
|
||||
// CUT (Scene detection) tools
|
||||
("cut", "rust") => {
|
||||
// CUT is implemented in Rust using ffmpeg
|
||||
@@ -278,9 +353,13 @@ impl ToolSelector {
|
||||
}
|
||||
("cut", "python") => {
|
||||
let script = executor.script_path("cut_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
if script.exists() {
|
||||
Some(script)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -304,4 +383,4 @@ impl Default for SelectedTool {
|
||||
timeout: 3600,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user