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:
Accusys
2026-10-04 13:44:40 +08:00
parent 3d363e6266
commit a3c3ed8dc1
850 changed files with 130339 additions and 91 deletions
+94
View File
@@ -0,0 +1,94 @@
use axum::{
extract::Path,
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
pub name: String,
pub r#type: String,
pub size: u64,
pub modified: String,
pub is_dir: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FolderInfo {
pub name: String,
pub parent: String,
}
// 列出用戶文件夾
pub async fn list_user_folders(
Path(username): Path<String>,
) -> Result<Json<Vec<FolderInfo>>, StatusCode> {
let base_path = PathBuf::from("/Users/nextorageai/momentry_studio/data")
.join(&username)
.join("files");
let mut folders = Vec::new();
if let Ok(mut entries) = fs::read_dir(&base_path).await {
while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(file_type) = entry.file_type().await {
if file_type.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
folders.push(FolderInfo {
name: name.clone(),
parent: String::new(),
});
}
}
}
}
Ok(Json(folders))
}
// 列出用戶文件
pub async fn list_user_files(
Path(username): Path<String>,
) -> Result<Json<Vec<FileInfo>>, StatusCode> {
let base_path = PathBuf::from("/Users/nextorageai/momentry_studio/data")
.join(&username)
.join("files");
let mut files = Vec::new();
if let Ok(mut entries) = fs::read_dir(&base_path).await {
while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(metadata) = entry.metadata().await {
let name = entry.file_name().to_string_lossy().to_string();
let is_dir = metadata.is_dir();
let size = if is_dir { 0 } else { metadata.len() };
let modified = metadata.modified()
.ok()
.map(|t| format!("{:?}", t))
.unwrap_or_else(|| "Unknown".to_string());
files.push(FileInfo {
name,
r#type: if is_dir { "directory".to_string() } else { "file".to_string() },
size,
modified,
is_dir,
});
}
}
}
Ok(Json(files))
}
pub fn markbase_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v2/myfiles/:username/folders", get(list_user_folders))
.route("/api/v2/myfiles/:username/files", get(list_user_files))
}
+1
View File
@@ -21,6 +21,7 @@ pub mod profile;
pub mod scan;
pub mod search;
pub mod server;
pub mod markbase_compat;
pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
+30
View File
@@ -0,0 +1,30 @@
pub mod admin_config;
pub mod agent_api;
pub mod agent_search;
pub mod auth;
pub mod billing;
pub mod checkin_api;
pub mod cluster_agent;
pub mod docs;
pub mod face_filter;
pub mod files;
pub mod health;
pub mod identities;
pub mod identity_api;
pub mod identity_binding;
pub mod llm_search;
pub mod media_api;
pub mod middleware;
pub mod pipeline;
pub mod processing;
pub mod profile;
pub mod scan;
pub mod search;
pub mod server;
pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
pub mod universal_search;
pub mod vlm_search;
pub use server::start_server;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2
View File
@@ -19,6 +19,7 @@ use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::files;
use super::markbase_compat;
use super::health;
use super::health::{health, health_consistency, health_detailed};
use super::identities;
@@ -128,6 +129,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(markbase_compat::markbase_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
+193
View File
@@ -0,0 +1,193 @@
use std::time::Duration;
use axum::{Json, Router};
use serde_json::json;
use tokio::time::timeout;
use tower_http::cors::{Any, CorsLayer};
use crate::core::cache::{MongoCache, RedisCache};
use crate::core::db::{Database, PostgresDb, QdrantDb};
use crate::Embedder;
use super::admin_config;
use super::agent_api;
use super::agent_search;
use super::auth;
use super::billing;
use super::checkin_api;
use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::files;
use super::health;
use super::health::{health, health_consistency, health_detailed};
use super::identities;
use super::identity_api;
use super::identity_binding;
use super::llm_search;
use super::media_api;
use super::middleware::unified_auth;
use super::pipeline;
use super::processing;
use super::profile;
use super::scan;
use super::search::search_routes;
use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::universal_search::universal_search_routes;
use super::vlm_search;
pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
health::init_server_state(host, port);
let embedder = std::sync::Arc::new(Embedder::new("embeddinggemma-300m".to_string()));
// ── ⚠️ WARNING: DO NOT move MongoCache::init() back to critical path ──
//
// MongoDB is ONLY a cache layer — if unavailable, the server MUST still
// start with Redis cache alone. This keeps 3002 bootable on machines
// without MongoDB installed. If you add a new dependency here, ask:
// "Can this service degrade gracefully if the dependant is missing?"
//
// See also: MongoCache::disabled() in mongo_cache.rs
let mongo_cache = match timeout(Duration::from_secs(5), MongoCache::init()).await {
Ok(Ok(cache)) => cache,
Ok(Err(e)) => {
tracing::warn!("MongoDB cache unavailable (continuing without): {e}");
MongoCache::disabled().await
}
Err(_) => {
tracing::warn!("MongoDB init timed out (continuing without cache)");
MongoCache::disabled().await
}
};
let redis_cache = RedisCache::new()?;
let db = PostgresDb::init().await?;
// Run migrations (create identity_history table if not exists)
PostgresDb::run_migrations(db.pool()).await?;
let schema_health = health::check_schema_migrations(db.pool()).await;
if schema_health.ok {
tracing::info!(
"[SCHEMA] All {}/{} required migrations applied ✓",
schema_health.required.len(),
schema_health.required.len()
);
} else if !schema_health.table_exists {
tracing::warn!("[SCHEMA] schema_migrations table not found!");
} else {
let missing: Vec<&str> = schema_health
.required
.iter()
.filter(|req| {
!schema_health
.applied
.iter()
.any(|app| app.filename == req.filename && app.checksum == req.checksum)
})
.map(|m| m.filename.as_str())
.collect();
tracing::warn!(
"[SCHEMA] {}/{} migrations match. Missing: {}",
schema_health.applied.len(),
schema_health.required.len(),
missing.join(", ")
);
}
let db = std::sync::Arc::new(db);
let api_state = super::middleware::ApiState { db: db.clone() };
let qdrant = std::sync::Arc::new(QdrantDb::new());
// Initialize AdminConfigManager
let admin_config_manager = std::sync::Arc::new(
crate::core::admin_config::AdminConfigManager::new(
&crate::core::admin_config::get_default_config_path(),
)
.expect("Failed to initialize AdminConfigManager"),
);
// Ensure trash collection exists for trace hard-delete undo
if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await {
tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e);
}
let state = AppState {
db,
qdrant,
embedder,
embedder_model: "nomic-embed-text-v2-moe:latest".to_string(),
mongo_cache,
redis_cache,
api_state,
admin_config_manager,
};
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
.merge(tmdb_api::tmdb_routes())
.merge(identity_api::identity_routes())
.merge(agent_api::agent_routes())
.merge(agent_search::agent_search_routes())
.merge(processing::processing_routes())
.merge(media_api::bbox_routes())
.merge(media_api::media_proxy_routes())
.merge(media_api::pose_appearance_routes())
.merge(trace_agent_api::trace_agent_routes())
.merge(search_routes())
.merge(llm_search::llm_smart_routes())
.merge(universal_search_routes())
.merge(pipeline::pipeline_routes())
.merge(checkin_api::checkin_routes())
.merge(cluster_agent::cluster_agent_routes())
.merge(profile::profile_routes())
.merge(face_filter::face_filter_routes())
.merge(admin_config::admin_config_routes())
.merge(vlm_search::vlm_search_routes())
.merge(billing::billing_routes())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
))
.with_state(state.clone());
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let public_health_routes = Router::new()
.route("/api/v1/health", axum::routing::get(health))
.route(
"/api/v1/health/detailed",
axum::routing::get(health_detailed),
)
.route(
"/api/v1/health/consistency",
axum::routing::get(health_consistency),
);
let app = Router::new()
.merge(auth::auth_routes())
.merge(public_health_routes)
.merge(health::health_routes())
.merge(docs::doc_routes())
.merge(protected_routes)
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.with_state(state);
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap();
tracing::info!("Starting API server at http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
+1
View File
@@ -18,6 +18,7 @@ pub mod identity;
pub mod ingestion;
pub mod llm;
pub mod overlay;
pub mod path_utils;
pub mod person_identity;
pub mod pipeline;
pub mod probe;
+38
View File
@@ -0,0 +1,38 @@
use std::path::PathBuf;
/// Resolve asset path at runtime (not compile-time).
///
/// Priority:
/// 1. Explicit environment variable (e.g., MOMENTRY_SCRIPTS_DIR)
/// 2. Sibling of current_exe (same directory as running binary)
/// 3. Relative path fallback (dev machine)
///
/// This avoids CARGO_MANIFEST_DIR being baked into the binary at compile time,
/// which breaks on binary-only release hosts.
pub fn resolve_asset_path(env_var: &str, fallback_relative: &str) -> PathBuf {
std::env::var_os(env_var)
.map(PathBuf::from)
.filter(|p| p.exists())
.or_else(|| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join(fallback_relative)))
.filter(|p| p.exists())
})
.unwrap_or_else(|| PathBuf::from(fallback_relative))
}
/// Get scripts directory.
pub fn scripts_dir() -> PathBuf {
resolve_asset_path("MOMENTRY_SCRIPTS_DIR", "scripts")
}
/// Get CLI tools directory.
pub fn cli_dir() -> PathBuf {
resolve_asset_path("MOMENTRY_CLI_DIR", "tools/cli")
}
/// Get config directory.
pub fn config_dir() -> PathBuf {
resolve_asset_path("MOMENTRY_CONFIG_DIR", "config")
}
+6 -22
View File
@@ -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);
+33 -5
View File
@@ -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)
}
+158
View File
@@ -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
View File
@@ -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
+30 -16
View File
@@ -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,
}
}
}
+1 -2
View File
@@ -23,8 +23,7 @@ impl ThumbnailExtractor {
}
pub fn extract(&self, video_path: &str, uuid: &str) -> Result<ThumbnailResult> {
let script_path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("scripts")
let script_path = crate::core::path_utils::scripts_dir()
.join("thumbnail_extractor.py");
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
+14
View File
@@ -18,6 +18,20 @@ fn init_tracing() {
}
fn load_env() {
// Resolve .env at runtime so the binary is portable across machines.
// Order: MOMENTRY_ENV_FILE -> ./.env -> <exe_dir>/../../.env -> legacy M5 path.
if let Ok(p) = std::env::var("MOMENTRY_ENV_FILE") {
let _ = dotenv::from_filename(p);
return;
}
if dotenv::from_filename(".env").is_ok() {
return;
}
if let Ok(exe) = std::env::current_exe() {
if let Some(root) = exe.parent().and_then(|p| p.parent()).and_then(|p| p.parent()) {
let _ = dotenv::from_filename(root.join(".env"));
}
}
let _ = dotenv::from_filename("/Users/accusys/momentry_core/.env");
}
+351
View File
@@ -0,0 +1,351 @@
//! Momentry Core - Digital asset management system with video analysis and RAG
//!
//! This is the main entry point for the CLI application.
use anyhow::Result;
use clap::Parser;
// Local modules
mod cli;
mod processing;
fn init_tracing() {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.with_target(true)
.with_writer(|| std::io::LineWriter::new(std::io::stdout()))
.init();
}
fn load_env() {
let _ = dotenv::from_filename("/Users/accusys/momentry_core/.env");
}
use cli::*;
use processing::handlers::*;
/// Main entry point
#[tokio::main]
async fn main() -> Result<()> {
load_env();
init_tracing();
let cli = Cli::parse();
match cli.command {
Commands::Register { path } => {
handle_register(&path).await?;
}
Commands::Process {
target,
modules,
cloud,
force,
resume,
} => {
handle_process(&target, modules, cloud, force, resume).await?;
}
Commands::Chunk { uuid } => {
handle_chunk(&uuid).await?;
}
Commands::StoreAsrx { uuid } => {
handle_store_asrx(&uuid).await?;
}
Commands::TkgBackfill { file_uuid } => {
handle_tkg_backfill(&file_uuid).await?;
}
Commands::Vectorize { uuid } => {
handle_vectorize(&uuid).await?;
}
Commands::Phase1 { uuid } => {
handle_phase1(&uuid).await?;
}
Commands::Complete { uuid } => {
handle_complete(&uuid).await?;
}
Commands::Play { target } => {
handle_play(&target).await?;
}
Commands::Watch { directories } => {
handle_watch(directories).await?;
}
Commands::System { gpu } => {
handle_system(gpu).await?;
}
Commands::Server { host, port } => {
handle_server(&host, port).await?;
}
Commands::Worker {
max_concurrent,
poll_interval,
batch_size,
} => {
handle_worker(max_concurrent, poll_interval, batch_size).await?;
}
Commands::Query { query } => {
handle_query(&query).await?;
}
Commands::Lookup { path } => {
handle_lookup(&path).await?;
}
Commands::Resolve { uuid } => {
handle_resolve(&uuid).await?;
}
Commands::Thumbnails { uuid, count } => {
handle_thumbnails(uuid, count).await?;
}
Commands::Status { uuid } => {
handle_status(uuid).await?;
}
Commands::Backup { action, days } => {
handle_backup(&action, days).await?;
}
Commands::ApiKey {
action,
name,
key_type,
ttl,
key,
} => {
handle_api_key(action, name, key_type, ttl, key).await?;
}
Commands::Gitea {
action,
username,
password,
token_name,
scopes,
} => {
handle_gitea(action, username, password, token_name, scopes).await?;
}
Commands::Agent { tool, args } => {
cli::agent::handle_agent(&tool, &args).await?;
}
Commands::Detect {
image,
objects,
cascade,
threshold,
} => {
cli::vision::handle_detect_command(image, objects, cascade, threshold).await?;
}
Commands::Vision(cmd) => {
cli::vision::handle_vision_command(cmd).await?;
}
}
Ok(())
}
/// Handle register command
async fn handle_register(path: &str) -> Result<()> {
println!("Registering video: {}", path);
// TODO: Implement registration logic
Ok(())
}
/// Handle process command
async fn handle_process(
target: &str,
modules: Option<Vec<String>>,
cloud: Option<Vec<String>>,
force: bool,
resume: bool,
) -> Result<()> {
println!("Processing video: {}", target);
println!("Modules: {:?}", modules);
println!("Cloud modules: {:?}", cloud);
println!("Force: {}, Resume: {}", force, resume);
// TODO: Implement processing logic
Ok(())
}
/// Handle chunk command
async fn handle_chunk(uuid: &str) -> Result<()> {
println!("Generating chunks for: {}", uuid);
// TODO: Implement chunk logic
Ok(())
}
/// Handle story command
/// Handle vectorize command
async fn handle_vectorize(uuid: &str) -> Result<()> {
println!("Vectorizing chunks for: {}", uuid);
// TODO: Implement vectorize logic
Ok(())
}
/// Handle play command
async fn handle_play(target: &str) -> Result<()> {
println!("Playing video: {}", target);
// TODO: Implement play logic
Ok(())
}
/// Handle watch command
async fn handle_watch(directories: Option<String>) -> Result<()> {
println!("Watching directories: {:?}", directories);
// TODO: Implement watch logic
Ok(())
}
/// Handle system command
async fn handle_system(gpu: bool) -> Result<()> {
println!("Checking system resources...");
// TODO: Implement proper system resource checking
println!("System Information:");
println!(" CPU: (would show CPU info)");
println!(" Memory: (would show memory info)");
if gpu {
println!("GPU details: (would show GPU info if available)");
}
println!("(System resource checking would be implemented here)");
Ok(())
}
/// Handle server command
async fn handle_server(host: &str, port: Option<u16>) -> Result<()> {
let port = port.unwrap_or(3002);
println!("Starting API server on {}:{}", host, port);
// Start the actual API server
momentry_core::api::start_server(host, port).await?;
Ok(())
}
/// Handle worker command
async fn handle_worker(
max_concurrent: Option<usize>,
poll_interval: Option<u64>,
batch_size: Option<i32>,
) -> Result<()> {
use momentry_core::core::db::{Database, PostgresDb, RedisClient};
use momentry_core::worker::{JobWorker, WorkerConfig};
println!("Starting job worker");
println!("Max concurrent: {:?}", max_concurrent);
println!("Poll interval: {:?}", poll_interval);
println!("Batch size: {:?}", batch_size);
let config = WorkerConfig {
max_concurrent: max_concurrent.unwrap_or(2),
poll_interval_secs: poll_interval.unwrap_or(5),
enabled: true,
batch_size: batch_size.unwrap_or(10),
processor_timeout_secs: 3600,
};
let db = PostgresDb::init().await?;
let redis = RedisClient::new()?;
let worker = JobWorker::new(
std::sync::Arc::new(db),
std::sync::Arc::new(redis),
config.clone(),
);
println!(
"Starting worker with max_concurrent={}, poll_interval={}s",
config.max_concurrent, config.poll_interval_secs
);
worker.run().await?;
Ok(())
}
/// Handle query command
async fn handle_query(query: &str) -> Result<()> {
println!("Querying: {}", query);
// TODO: Implement query logic
Ok(())
}
/// Handle lookup command
async fn handle_lookup(path: &str) -> Result<()> {
println!("Looking up UUID for path: {}", path);
// TODO: Implement lookup logic
Ok(())
}
/// Handle resolve command
async fn handle_resolve(uuid: &str) -> Result<()> {
println!("Resolving path for UUID: {}", uuid);
// TODO: Implement resolve logic
Ok(())
}
/// Handle thumbnails command
async fn handle_thumbnails(uuid: Option<String>, count: u32) -> Result<()> {
println!("Generating thumbnails");
println!("UUID: {:?}", uuid);
println!("Count: {}", count);
// TODO: Implement thumbnails logic
Ok(())
}
/// Handle status command
async fn handle_status(uuid: Option<String>) -> Result<()> {
println!("Checking storage status");
println!("UUID: {:?}", uuid);
// TODO: Implement status logic
Ok(())
}
/// Handle backup command
async fn handle_backup(action: &str, days: Option<u32>) -> Result<()> {
println!("Backup action: {}", action);
println!("Days to keep: {:?}", days);
// TODO: Implement backup logic
Ok(())
}
/// Handle API key command
async fn handle_api_key(
action: ApiKeyAction,
name: Option<String>,
key_type: Option<String>,
ttl: Option<i64>,
key: Option<String>,
) -> Result<()> {
println!("API Key action: {:?}", action);
println!("Name: {:?}", name);
println!("Key type: {:?}", key_type);
println!("TTL: {:?}", ttl);
println!("Key: {:?}", key);
// TODO: Implement API key logic
Ok(())
}
/// Handle Gitea command
async fn handle_gitea(
action: GiteaAction,
username: Option<String>,
password: Option<String>,
token_name: Option<String>,
scopes: Option<String>,
) -> Result<()> {
println!("Gitea action: {:?}", action);
println!("Username: {:?}", username);
println!("Token name: {:?}", token_name);
println!("Scopes: {:?}", scopes);
// TODO: Implement Gitea logic
Ok(())
}