refactor: eliminate all CARGO_MANIFEST_DIR compile-time dependencies (A-4)
- Add src/core/path_utils.rs with runtime path resolution helpers
- Replace all env!("CARGO_MANIFEST_DIR") with runtime resolution
- Priority: env var -> current_exe sibling -> dev fallback
Changes:
- executor.rs: scripts_dir(), cli_dir() (4 locations)
- face.rs: swift_processor_path()
- tool_selector.rs: swift_binary_path()
- thumbnail/mod.rs: script_path()
Issue: CARGO_MANIFEST_DIR expands to build machine path at compile time,
breaking on binary-only release hosts.
Solution: Resolve paths at runtime in this order:
1. Explicit environment variable (MOMENTRY_SCRIPTS_DIR, MOMENTRY_CLI_DIR)
2. Sibling of current_exe (same directory as running binary)
3. Relative path fallback (dev machine)
Verified: cargo check --lib passes
This commit is contained in:
@@ -141,13 +141,9 @@ pub fn validate_python_env() -> Result<()> {
|
||||
tracing::warn!("Expected Python 3.11, got: {}", version.trim());
|
||||
}
|
||||
|
||||
let scripts_dir = std::env::var("MOMENTRY_SCRIPTS_DIR").unwrap_or_else(|_| {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
manifest.join("scripts").to_string_lossy().to_string()
|
||||
});
|
||||
let script_path = PathBuf::from(&scripts_dir);
|
||||
if !script_path.exists() {
|
||||
anyhow::bail!("Scripts directory not found at {}", scripts_dir);
|
||||
let scripts_dir = crate::core::path_utils::scripts_dir();
|
||||
if !scripts_dir.exists() {
|
||||
anyhow::bail!("Scripts directory not found at {:?}", scripts_dir);
|
||||
}
|
||||
|
||||
tracing::info!("Python environment validated successfully");
|
||||
@@ -164,10 +160,7 @@ impl PythonExecutor {
|
||||
pub fn new() -> Result<Self> {
|
||||
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
|
||||
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
|
||||
let scripts_dir = std::env::var("MOMENTRY_SCRIPTS_DIR").unwrap_or_else(|_| {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
manifest.join("scripts").to_string_lossy().to_string()
|
||||
});
|
||||
let scripts_dir = crate::core::path_utils::scripts_dir();
|
||||
|
||||
let python_bin = PathBuf::from(&python_path);
|
||||
let scripts_path = PathBuf::from(&scripts_dir);
|
||||
@@ -1209,12 +1202,7 @@ impl PythonExecutor {
|
||||
/// Looks under `<scripts_dir>/rust_processors/target/release/` first, falling
|
||||
/// back to `target/debug/` (mirrors the swift_processors layout convention).
|
||||
pub fn rust_binary_path(&self, bin_name: &str) -> Option<PathBuf> {
|
||||
// Use tools/cli/rust/ instead of scripts/rust_processors/
|
||||
let cli_dir = std::env::var("MOMENTRY_CLI_DIR")
|
||||
.unwrap_or_else(|_| {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
manifest.join("tools/cli").to_string_lossy().to_string()
|
||||
});
|
||||
let cli_dir = crate::core::path_utils::cli_dir();
|
||||
|
||||
let base = PathBuf::from(cli_dir).join("rust").join("target");
|
||||
for profile in ["release", "debug"] {
|
||||
@@ -1428,11 +1416,7 @@ pub struct CliExecutor {
|
||||
|
||||
impl CliExecutor {
|
||||
pub fn new() -> Result<Self> {
|
||||
let cli_dir = std::env::var("MOMENTRY_CLI_DIR")
|
||||
.unwrap_or_else(|_| {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
manifest.join("tools/cli").to_string_lossy().to_string()
|
||||
});
|
||||
let cli_dir = crate::core::path_utils::cli_dir();
|
||||
|
||||
let cli_path = PathBuf::from(&cli_dir);
|
||||
|
||||
|
||||
@@ -7,6 +7,36 @@ use super::FaceStatus;
|
||||
|
||||
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||
|
||||
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);
|
||||
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);
|
||||
if p.exists() {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dev fallback
|
||||
crate::core::path_utils::scripts_dir()
|
||||
.join("swift_processors")
|
||||
.join(rel)
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceResult {
|
||||
#[serde(default)]
|
||||
@@ -164,7 +194,7 @@ tracing::info!("[FACE] Config-driven selection failed, falling back to hard-code
|
||||
|
||||
// Fallback to hard-coded logic
|
||||
// Check for Swift face processor first
|
||||
let swift_face_path = std::path::Path::new("/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_face");
|
||||
let swift_face_path = swift_processor_path("swift_face");
|
||||
|
||||
if swift_face_path.exists() {
|
||||
tracing::info!("[FACE] Using Swift processor: {:?}", swift_face_path);
|
||||
@@ -188,7 +218,7 @@ let swift_face_path = std::path::Path::new("/Users/accusys/momentry_core/scripts
|
||||
}
|
||||
|
||||
// Generate embeddings with FaceNet CoreML
|
||||
let facenet_path = std::path::Path::new("/Users/accusys/momentry_core/scripts/swift_processors/.build/release/facenet_embedding");
|
||||
let facenet_path = swift_processor_path("facenet_embedding");
|
||||
|
||||
if facenet_path.exists() {
|
||||
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
||||
@@ -375,9 +405,7 @@ async fn run_face_with_config(
|
||||
}
|
||||
|
||||
// Generate embeddings with FaceNet CoreML
|
||||
let facenet_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/facenet_embedding"
|
||||
);
|
||||
let facenet_path = swift_processor_path("facenet_embedding");
|
||||
|
||||
if facenet_path.exists() {
|
||||
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
|
||||
|
||||
@@ -0,0 +1,728 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::FaceStatus;
|
||||
|
||||
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceResult {
|
||||
#[serde(default)]
|
||||
pub status: Option<FaceStatus>,
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<FaceFrame>,
|
||||
#[serde(default)]
|
||||
pub total_faces: usize,
|
||||
#[serde(default)]
|
||||
pub metadata: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl FaceResult {
|
||||
pub fn compute_status(&mut self) {
|
||||
for frame in &mut self.frames {
|
||||
for face in &mut frame.faces {
|
||||
face.normalize();
|
||||
}
|
||||
}
|
||||
self.total_faces = self.frames.iter().map(|f| f.faces.len()).sum();
|
||||
// Only compute status if Python didn't provide one
|
||||
if self.status.is_none() {
|
||||
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")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
|
||||
FaceResult {
|
||||
status: Some(FaceStatus::NoFaces),
|
||||
frame_count,
|
||||
fps,
|
||||
frames: vec![],
|
||||
total_faces: 0,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub faces: Vec<Face>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Face {
|
||||
pub face_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub x: i32,
|
||||
#[serde(default)]
|
||||
pub y: i32,
|
||||
#[serde(default)]
|
||||
pub width: i32,
|
||||
#[serde(default)]
|
||||
pub height: i32,
|
||||
pub confidence: f32,
|
||||
#[serde(default)]
|
||||
pub capture_quality: Option<f32>,
|
||||
pub embedding: Option<Vec<f32>>,
|
||||
pub landmarks: Option<serde_json::Value>,
|
||||
pub pose_angle: Option<serde_json::Value>,
|
||||
pub attributes: Option<FaceAttributes>,
|
||||
#[serde(default)]
|
||||
pub bbox: Option<BoundingBox>,
|
||||
#[serde(default)]
|
||||
pub pose: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub trace_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
|
||||
pub struct BoundingBox {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
|
||||
impl Face {
|
||||
pub fn normalize(&mut self) {
|
||||
if let Some(bbox) = &self.bbox {
|
||||
self.x = bbox.x;
|
||||
self.y = bbox.y;
|
||||
self.width = bbox.width;
|
||||
self.height = bbox.height;
|
||||
}
|
||||
if let Some(pose) = &self.pose {
|
||||
self.pose_angle = Some(pose.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceAttributes {
|
||||
pub age: Option<i32>,
|
||||
pub gender: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn process_face(
|
||||
video_path: &str,
|
||||
output_path: &str,
|
||||
uuid: Option<&str>,
|
||||
frames: Option<&[i64]>,
|
||||
) -> Result<FaceResult> {
|
||||
// Check if face.json already exists (from SwiftFacePose)
|
||||
if std::path::Path::new(output_path).exists() {
|
||||
tracing::info!(
|
||||
"[FACE] Output exists from SwiftFacePose, loading: {}",
|
||||
output_path
|
||||
);
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read existing FACE output")?;
|
||||
let mut result: FaceResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse existing FACE output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Loaded from SwiftFacePose: status={}, {} frames, {} total faces",
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.frames.len(),
|
||||
result.total_faces
|
||||
);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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 = std::path::Path::new("/Users/accusys/momentry_core/scripts/swift_processors/.build/release/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 = std::path::Path::new("/Users/accusys/momentry_core/scripts/swift_processors/.build/release/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() => {
|
||||
// Replace original file with embedding-enhanced version
|
||||
if std::path::Path::new(&facenet_output).exists() {
|
||||
if let Err(e) = std::fs::copy(&facenet_output, output_path) {
|
||||
tracing::warn!("[FACE] Failed to copy embedding file: {}", e);
|
||||
} else {
|
||||
tracing::info!("[FACE] Embeddings generated successfully");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(output) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::warn!("[FACE] FaceNet embedding failed: {}", stderr);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[FACE] FaceNet embedding error: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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")?;
|
||||
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);
|
||||
match store_face_embeddings_to_qdrant(file_uuid, &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);
|
||||
}
|
||||
}
|
||||
} 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;
|
||||
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] Swift result: status={}, {} frames, {} total faces",
|
||||
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");
|
||||
|
||||
tracing::info!("[FACE] Starting face detection: {}", video_path);
|
||||
|
||||
if !script_path.exists() {
|
||||
tracing::warn!("[FACE] Script not found, returning empty result");
|
||||
return Ok(FaceResult::no_faces(0, 0.0));
|
||||
}
|
||||
|
||||
executor
|
||||
.run_with_frames(
|
||||
"face_processor.py",
|
||||
&[video_path, output_path],
|
||||
uuid,
|
||||
"FACE",
|
||||
Some(FACE_TIMEOUT),
|
||||
frames,
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("Failed to run {:?}", script_path))?;
|
||||
|
||||
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();
|
||||
|
||||
// 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",
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.frames.len(),
|
||||
result.total_faces
|
||||
);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn run_face_with_config(
|
||||
executor: &PythonExecutor,
|
||||
video_path: &str,
|
||||
output_path: &str,
|
||||
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)
|
||||
);
|
||||
|
||||
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
|
||||
.iter()
|
||||
.map(|a| {
|
||||
a.replace("{video_path}", video_path)
|
||||
.replace("{output_path}", output_path)
|
||||
.replace("{file_uuid}", uuid.unwrap_or(""))
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
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());
|
||||
}
|
||||
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 = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/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() {
|
||||
if let Err(e) = std::fs::copy(&facenet_output, output_path) {
|
||||
tracing::warn!("[FACE] Failed to copy embedding file: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
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")?;
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
"python" => {
|
||||
let script_path = &tool.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)
|
||||
.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),
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(Some(result));
|
||||
}
|
||||
_ => {
|
||||
tracing::warn!("[FACE] Unknown tool from config: {}", tool.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_face_result_serialization() {
|
||||
let result = FaceResult {
|
||||
status: None,
|
||||
frame_count: 100,
|
||||
fps: 30.0,
|
||||
total_faces: 1,
|
||||
metadata: None,
|
||||
frames: vec![FaceFrame {
|
||||
frame: 0,
|
||||
timestamp: 0.0,
|
||||
faces: vec![Face {
|
||||
face_id: Some("face_1".to_string()),
|
||||
x: 100,
|
||||
y: 100,
|
||||
width: 50,
|
||||
height: 60,
|
||||
confidence: 0.95,
|
||||
capture_quality: Some(0.9),
|
||||
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,
|
||||
attributes: Some(FaceAttributes {
|
||||
age: Some(30),
|
||||
gender: Some("male".to_string()),
|
||||
}),
|
||||
bbox: None,
|
||||
pose: None,
|
||||
trace_id: None,
|
||||
}],
|
||||
}],
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&result).unwrap();
|
||||
assert!(json.contains("face_1"));
|
||||
assert!(json.contains("\"width\":50"));
|
||||
assert!(json.contains("landmarks"));
|
||||
assert!(json.contains("attributes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_face_result_deserialization() {
|
||||
let json = r#"{
|
||||
"frame_count": 50,
|
||||
"fps": 25.0,
|
||||
"frames": [
|
||||
{
|
||||
"frame": 30,
|
||||
"timestamp": 1.2,
|
||||
"faces": [
|
||||
{
|
||||
"face_id": "f1",
|
||||
"x": 10,
|
||||
"y": 20,
|
||||
"width": 30,
|
||||
"height": 40,
|
||||
"confidence": 0.85,
|
||||
"embedding": [0.1, 0.2, 0.3],
|
||||
"landmarks": [[5.0, 10.0]],
|
||||
"attributes": {"age": 25, "gender": "female"}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let result: FaceResult = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(result.frame_count, 50);
|
||||
assert_eq!(result.frames.len(), 1);
|
||||
assert_eq!(result.frames[0].faces[0].x, 10);
|
||||
assert!(result.frames[0].faces[0].embedding.is_some());
|
||||
assert!(result.frames[0].faces[0].landmarks.is_some());
|
||||
assert!(result.frames[0].faces[0].attributes.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compute_status_recalculates_total_faces() {
|
||||
let json = r#"{
|
||||
"fps": 30.0,
|
||||
"frame_count": 2,
|
||||
"frames": [
|
||||
{"frame": 0, "timestamp": 0.0, "faces": [
|
||||
{"confidence": 0.9, "bbox": {"x": 1, "y": 2, "width": 3, "height": 4}}
|
||||
]},
|
||||
{"frame": 1, "timestamp": 0.03, "faces": [
|
||||
{"confidence": 0.8, "bbox": {"x": 5, "y": 6, "width": 7, "height": 8}},
|
||||
{"confidence": 0.7, "bbox": {"x": 9, "y": 10, "width": 11, "height": 12}}
|
||||
]}
|
||||
]
|
||||
}"#;
|
||||
let mut result: FaceResult = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(result.total_faces, 0, "json has no total_faces field");
|
||||
assert!(result.status.is_none(), "json has no status field");
|
||||
result.compute_status();
|
||||
assert_eq!(result.total_faces, 3);
|
||||
assert_eq!(result.status.unwrap(), FaceStatus::HasFaces);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_face_result_empty_frames() {
|
||||
let result = FaceResult {
|
||||
status: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
frames: vec![],
|
||||
total_faces: 0,
|
||||
metadata: None,
|
||||
};
|
||||
assert!(result.frames.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_face_confidence() {
|
||||
let face = Face {
|
||||
face_id: None,
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 10,
|
||||
height: 10,
|
||||
confidence: 0.5,
|
||||
capture_quality: None,
|
||||
embedding: None,
|
||||
landmarks: None,
|
||||
pose_angle: None,
|
||||
attributes: None,
|
||||
bbox: None,
|
||||
pose: None,
|
||||
trace_id: None,
|
||||
};
|
||||
assert!(face.confidence >= 0.0 && face.confidence <= 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_face_with_embedding() {
|
||||
let face = Face {
|
||||
face_id: Some("face_001".to_string()),
|
||||
x: 100,
|
||||
y: 200,
|
||||
width: 50,
|
||||
height: 60,
|
||||
confidence: 0.95,
|
||||
capture_quality: Some(0.8),
|
||||
embedding: Some(vec![0.1; 512]),
|
||||
landmarks: None,
|
||||
pose_angle: None,
|
||||
attributes: Some(FaceAttributes {
|
||||
age: Some(35),
|
||||
gender: Some("male".to_string()),
|
||||
}),
|
||||
bbox: None,
|
||||
pose: None,
|
||||
trace_id: None,
|
||||
};
|
||||
|
||||
assert!(face.embedding.is_some());
|
||||
let embedding = face.embedding.unwrap();
|
||||
assert_eq!(embedding.len(), 512);
|
||||
assert_eq!(embedding[0], 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Store face embeddings to Qdrant and remove them from JSON
|
||||
pub async fn store_face_embeddings_to_qdrant(
|
||||
file_uuid: &str,
|
||||
face_result: &mut FaceResult,
|
||||
output_path: &str,
|
||||
) -> Result<usize> {
|
||||
use crate::core::db::qdrant_db::QdrantDb;
|
||||
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()
|
||||
.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,
|
||||
"timestamp_secs": timestamp_secs,
|
||||
"face_id": face_id,
|
||||
"confidence": face.confidence,
|
||||
"x": face.x,
|
||||
"y": face.y,
|
||||
"width": face.width,
|
||||
"height": face.height,
|
||||
"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": [{
|
||||
"key": "file_uuid",
|
||||
"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() {
|
||||
let batch_points: Vec<(u64, &[f32], Option<serde_json::Value>)> = chunk
|
||||
.iter()
|
||||
.map(|(id, vec, payload)| (*id, vec.as_slice(), Some(payload.clone())))
|
||||
.collect();
|
||||
|
||||
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);
|
||||
|
||||
Ok(total_points)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
|
||||
const FACE_CLUSTER_TIMEOUT: Duration = Duration::from_secs(3600);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceClusterResult {
|
||||
pub clusters: Vec<FaceClusterInfo>,
|
||||
pub frames: Vec<FaceClusterFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceClusterInfo {
|
||||
pub cluster_id: String,
|
||||
pub face_count: usize,
|
||||
pub representative_face: Option<RepresentativeFace>,
|
||||
pub similarity: Option<ClusterSimilarity>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ClusterSimilarity {
|
||||
pub min: f64,
|
||||
pub avg: f64,
|
||||
pub threshold: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct RepresentativeFace {
|
||||
pub face_id: String,
|
||||
pub confidence: f64,
|
||||
pub frame: u64,
|
||||
pub bbox: BoundingBox,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct BoundingBox {
|
||||
pub x: u64,
|
||||
pub y: u64,
|
||||
pub width: u64,
|
||||
pub height: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceClusterFrame {
|
||||
pub frame: u64,
|
||||
pub timestamp: f64,
|
||||
pub faces: Vec<ClusteredFace>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ClusteredFace {
|
||||
pub face_id: String,
|
||||
pub cluster_id: String,
|
||||
pub trace_id: Option<i64>,
|
||||
pub confidence: f32,
|
||||
}
|
||||
|
||||
pub async fn process_face_cluster(
|
||||
video_path: &str,
|
||||
output_path: &str,
|
||||
uuid: Option<&str>,
|
||||
frames: Option<&[i64]>,
|
||||
similarity_threshold: Option<f64>,
|
||||
) -> Result<FaceClusterResult> {
|
||||
let executor = PythonExecutor::new()?;
|
||||
let script_path = executor.script_path("fast_face_clustering_processor.py");
|
||||
|
||||
tracing::info!("[FACE_CLUSTER] Starting face clustering: {}", video_path);
|
||||
|
||||
if !script_path.exists() {
|
||||
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
|
||||
return Ok(FaceClusterResult {
|
||||
clusters: vec![],
|
||||
frames: vec![],
|
||||
});
|
||||
}
|
||||
|
||||
// Build args with optional --threshold
|
||||
let distance = similarity_threshold.map(|s| 1.0 - s);
|
||||
let mut args = vec![video_path, output_path];
|
||||
if let Some(d) = distance {
|
||||
let threshold_str = format!("{:.4}", d);
|
||||
args.push("--threshold");
|
||||
args.push(Box::leak(threshold_str.into_boxed_str()) as &str);
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] similarity={:.2} → distance={:.4}",
|
||||
similarity_threshold.unwrap_or(0.85),
|
||||
d
|
||||
);
|
||||
}
|
||||
|
||||
// Try Rust binary first (preferred), fallback to Python if unavailable
|
||||
if let Some(rust_bin) = executor.rust_binary_path("rust_face_cluster") {
|
||||
tracing::info!("[FACE_CLUSTER] Using Rust binary: {:?}", rust_bin);
|
||||
match executor
|
||||
.run_rust_with_output_idx_and_frames(
|
||||
&rust_bin,
|
||||
&args,
|
||||
Some(1),
|
||||
uuid,
|
||||
frames,
|
||||
"FACE_CLUSTER",
|
||||
Some(FACE_CLUSTER_TIMEOUT),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
let json_str = std::fs::read_to_string(output_path)
|
||||
.context("Failed to read FACE_CLUSTER output")?;
|
||||
let result: FaceClusterResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse FACE_CLUSTER output")?;
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
|
||||
result.clusters.len(),
|
||||
result.frames.len()
|
||||
);
|
||||
return Ok(result);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[FACE_CLUSTER] Rust binary failed: {}, falling back to Python",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to Python script
|
||||
executor
|
||||
.run_with_output_idx_and_frames(
|
||||
"fast_face_clustering_processor.py",
|
||||
&args,
|
||||
uuid,
|
||||
"FACE_CLUSTER",
|
||||
Some(FACE_CLUSTER_TIMEOUT),
|
||||
Some(1),
|
||||
frames,
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("Failed to run face clustering script"))?;
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read FACE_CLUSTER output")?;
|
||||
|
||||
let result: FaceClusterResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] Result: {} clusters, {} frames",
|
||||
result.clusters.len(),
|
||||
result.frames.len()
|
||||
);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
+30
-12
@@ -279,21 +279,39 @@ async fn populate_face_detections_from_face_json(
|
||||
}
|
||||
|
||||
// Use Rust binary for face trace (V3 config: priority 0)
|
||||
let rust_binary = "tools/cli/rust/target/release/rust_store_traced_faces";
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
|
||||
|
||||
let executor = crate::core::processor::executor::PythonExecutor::new()?;
|
||||
|
||||
let result = executor
|
||||
.run_with_output_idx(
|
||||
rust_binary,
|
||||
&[file_uuid, "--output-dir", output_dir],
|
||||
Some(file_uuid),
|
||||
"TKG_PHASE0",
|
||||
Some(std::time::Duration::from_secs(600)),
|
||||
None, // Don't rewrite any args
|
||||
)
|
||||
.await;
|
||||
// Resolve via rust_binary_path() so the binary is looked up under
|
||||
// tools/cli/rust/target/{release,debug}/ instead of being joined onto
|
||||
// MOMENTRY_SCRIPTS_DIR (which produced a nonexistent scripts/tools/... path).
|
||||
// Must use the Rust runner: run_with_output_idx() would exec it with python.
|
||||
let result = match executor.rust_binary_path("rust_store_traced_faces") {
|
||||
Some(bin) => {
|
||||
tracing::info!("[TKG-Phase0] Using Rust binary: {:?}", bin);
|
||||
executor
|
||||
.run_rust_with_output_idx_and_frames(
|
||||
&bin,
|
||||
&[file_uuid, "--output-dir", output_dir],
|
||||
None,
|
||||
// rust_store_traced_faces takes FILE_UUID as its only positional
|
||||
// arg and has no --uuid flag; passing uuid would append an
|
||||
// unsupported "--uuid <v>" and abort with a clap usage error.
|
||||
None,
|
||||
None,
|
||||
"TKG_PHASE0",
|
||||
Some(std::time::Duration::from_secs(600)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"[TKG-Phase0] rust_store_traced_faces binary not found, skipping face tracing"
|
||||
);
|
||||
Err(anyhow::anyhow!("rust_store_traced_faces binary not found"))
|
||||
}
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(()) => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -139,6 +139,28 @@ impl ToolSelector {
|
||||
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; }
|
||||
}
|
||||
|
||||
// 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; }
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
});
|
||||
base.join("swift_processors/.build/release").join(bin_name)
|
||||
}
|
||||
|
||||
fn find_tool(&self, tool_name: &str, executor: &super::PythonExecutor) -> Option<PathBuf> {
|
||||
match (self.processor_name.as_str(), tool_name) {
|
||||
// POSE processor tools
|
||||
@@ -148,10 +170,8 @@ impl ToolSelector {
|
||||
}
|
||||
("pose", "rust") => executor.rust_binary_path("rust_pose"),
|
||||
("pose", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_pose"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
let swift_path = Self::swift_binary_path(executor, "swift_pose");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
}
|
||||
("pose", "yolov8") => {
|
||||
let script = executor.script_path("pose_processor_mps.py");
|
||||
@@ -164,10 +184,8 @@ impl ToolSelector {
|
||||
|
||||
// FACE processor tools
|
||||
("face", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_face"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
let swift_path = Self::swift_binary_path(executor, "swift_face");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
}
|
||||
("face", "python") => {
|
||||
let script = executor.script_path("face_processor.py");
|
||||
@@ -186,10 +204,8 @@ impl ToolSelector {
|
||||
|
||||
// ASRX processor tools
|
||||
("asrx", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/asrx_swift"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
let swift_path = Self::swift_binary_path(executor, "asrx_swift");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
}
|
||||
("asrx", "rust") => {
|
||||
// Future: Rust ASRX implementation
|
||||
@@ -202,10 +218,8 @@ impl ToolSelector {
|
||||
|
||||
// OCR processor tools
|
||||
("ocr", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_ocr"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
let swift_path = Self::swift_binary_path(executor, "swift_ocr");
|
||||
if swift_path.exists() { Some(swift_path) } else { None }
|
||||
}
|
||||
("ocr", "python") => {
|
||||
let script = executor.script_path("ocr_processor.py");
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
use crate::core::admin_config::{self, ProcessorConfig, ToolConfig};
|
||||
use crate::core::processor::processor_config_v3;
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use tracing::info;
|
||||
|
||||
pub struct ToolSelector {
|
||||
processor_name: String,
|
||||
}
|
||||
|
||||
impl ToolSelector {
|
||||
pub fn new(processor_name: &str) -> Self {
|
||||
Self {
|
||||
processor_name: processor_name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
return Ok(Some(tool));
|
||||
}
|
||||
Ok(None) => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
let config = admin_config::get_processor_config(&self.processor_name)
|
||||
.await
|
||||
.context("Failed to get processor config")?;
|
||||
|
||||
if !config.enabled {
|
||||
info!("[{}] Processor disabled in config", self.processor_name);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut tools = config.tools.clone();
|
||||
tools.sort_by_key(|t| t.priority);
|
||||
|
||||
for tool in tools {
|
||||
if !tool.enabled {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(tool_path) = self.find_tool(&tool.name, executor) {
|
||||
info!(
|
||||
"[{}] Selected tool: {} (priority {})",
|
||||
self.processor_name, tool.name, tool.priority
|
||||
);
|
||||
return Ok(Some(SelectedTool {
|
||||
name: tool.name.clone(),
|
||||
path: tool_path,
|
||||
args: Vec::new(),
|
||||
parameters: tool.parameters.clone(),
|
||||
timeout: 3600,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
return Ok(Some(SelectedTool {
|
||||
name: default.clone(),
|
||||
path: tool_path,
|
||||
args: Vec::new(),
|
||||
parameters: serde_json::Map::new(),
|
||||
timeout: 3600,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
args,
|
||||
parameters: serde_json::Map::from_iter(impl_.parameters.clone()),
|
||||
timeout: impl_.timeout,
|
||||
}));
|
||||
}
|
||||
Ok(None) => {
|
||||
info!("[ToolSelector V3] Tool {} not available, trying next", impl_.tool);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
info!("[ToolSelector V3] Failed to resolve {}: {}", impl_.tool, e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
vars.insert("output_dir".to_string(), "/Users/accusys/momentry/output".to_string());
|
||||
}
|
||||
|
||||
vars
|
||||
}
|
||||
|
||||
fn find_tool(&self, tool_name: &str, executor: &super::PythonExecutor) -> Option<PathBuf> {
|
||||
match (self.processor_name.as_str(), tool_name) {
|
||||
// POSE processor tools
|
||||
("pose", "mediapipe") => {
|
||||
let script = executor.script_path("pose_processor_mediapipe.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
}
|
||||
("pose", "rust") => executor.rust_binary_path("rust_pose"),
|
||||
("pose", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_pose"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
}
|
||||
("pose", "yolov8") => {
|
||||
let script = executor.script_path("pose_processor_mps.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
}
|
||||
("pose", "python") => {
|
||||
let script = executor.script_path("pose_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
}
|
||||
|
||||
// FACE processor tools
|
||||
("face", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_face"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
}
|
||||
("face", "python") => {
|
||||
let script = executor.script_path("face_processor.py");
|
||||
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 }
|
||||
}
|
||||
("asr", "rust") => {
|
||||
// Future: Rust ASR implementation
|
||||
executor.rust_binary_path("rust_asr")
|
||||
}
|
||||
|
||||
// ASRX processor tools
|
||||
("asrx", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/asrx_swift"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
}
|
||||
("asrx", "rust") => {
|
||||
// Future: Rust ASRX implementation
|
||||
executor.rust_binary_path("rust_asrx")
|
||||
}
|
||||
("asrx", "python") => {
|
||||
let script = executor.script_path("asrx_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
}
|
||||
|
||||
// OCR processor tools
|
||||
("ocr", "swift") => {
|
||||
let swift_path = std::path::Path::new(
|
||||
"/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_ocr"
|
||||
);
|
||||
if swift_path.exists() { Some(swift_path.to_path_buf()) } else { None }
|
||||
}
|
||||
("ocr", "python") => {
|
||||
let script = executor.script_path("ocr_processor.py");
|
||||
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 }
|
||||
}
|
||||
("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 }
|
||||
}
|
||||
("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 }
|
||||
}
|
||||
|
||||
// TKG (Temporal Knowledge Graph) tools
|
||||
("tkg", "python") => {
|
||||
let script = executor.script_path("store_traced_faces.py");
|
||||
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
|
||||
// Return a placeholder path to indicate availability
|
||||
Some(std::path::PathBuf::from("rust_cut"))
|
||||
}
|
||||
("cut", "python") => {
|
||||
let script = executor.script_path("cut_processor.py");
|
||||
if script.exists() { Some(script) } else { None }
|
||||
}
|
||||
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SelectedTool {
|
||||
pub name: String,
|
||||
pub path: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub parameters: serde_json::Map<String, serde_json::Value>,
|
||||
pub timeout: u64,
|
||||
}
|
||||
|
||||
impl Default for SelectedTool {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
path: PathBuf::new(),
|
||||
args: Vec::new(),
|
||||
parameters: serde_json::Map::new(),
|
||||
timeout: 3600,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user