diff --git a/src/api/cluster_agent.rs b/src/api/cluster_agent.rs index 43d899ef..1ec25fe5 100644 --- a/src/api/cluster_agent.rs +++ b/src/api/cluster_agent.rs @@ -14,6 +14,18 @@ use tokio::sync::RwLock; use super::middleware::UserAuth; use super::types::AppState; use crate::core::config::OUTPUT_DIR; + +/// Resolve output path for a per-library file, falling back to global OUTPUT_DIR. +/// Used by both cluster_agent and profile (get_cluster_results). +pub(crate) async fn resolve_output_path(pool: &sqlx::PgPool, file_uuid: &str, ext: &str) -> std::path::PathBuf { + let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, pool).await; + let candidate = std::path::PathBuf::from(&per_lib).join(format!("{}.{ext}", file_uuid)); + if candidate.exists() { + return candidate; + } + // Fallback: global output dir (legacy) + PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.{ext}", file_uuid)) +} use crate::core::db::schema; use crate::core::processor::{process_face_cluster, FaceClusterResult}; @@ -221,8 +233,8 @@ pub async fn trigger_cluster_agent( .unwrap_or_default() .as_secs() ); - let output_path = - PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid)); + // Resolve output paths (per-library with global fallback) + let output_path = resolve_output_path(state.db.pool(), &file_uuid, "face_cluster.json").await; let cancel_token = tokio_util::sync::CancellationToken::new(); // Register job @@ -242,8 +254,7 @@ pub async fn trigger_cluster_agent( .insert(job_id.clone(), handle); // Reset trace names before re-clustering - let traced_path = - PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid)); + let traced_path = resolve_output_path(state.db.pool(), &file_uuid, "face_traced.json").await; if let Ok(content) = std::fs::read_to_string(&traced_path) { if let Ok(traced_data) = serde_json::from_str::(&content) { if let Some(traces) = traced_data.get("traces") { @@ -502,8 +513,7 @@ async fn update_trace_labels_from_cluster( file_uuid: &str, result: &FaceClusterResult, ) -> anyhow::Result<()> { - let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str()) - .join(format!("{}.face_traced.json", file_uuid)); + let traced_path = resolve_output_path(db.pool(), file_uuid, "face_traced.json").await; let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new(); if let Ok(content) = std::fs::read_to_string(&traced_path) { if let Ok(traced_data) = serde_json::from_str::(&content) { @@ -565,7 +575,7 @@ async fn update_trace_labels_from_cluster( .await; } - if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) { + if let Some(all_trace_ids) = get_all_trace_ids(db.pool(), file_uuid).await { let mut updated_count = 0u64; for tid in &all_trace_ids { if !trace_to_cluster.contains_key(tid) { @@ -594,9 +604,8 @@ async fn update_trace_labels_from_cluster( Ok(()) } -fn get_all_trace_ids(file_uuid: &str) -> Option> { - let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str()) - .join(format!("{}.face_traced.json", file_uuid)); +async fn get_all_trace_ids(pool: &sqlx::PgPool, file_uuid: &str) -> Option> { + let traced_path = resolve_output_path(pool, file_uuid, "face_traced.json").await; let content = std::fs::read_to_string(&traced_path).ok()?; let traced_data: serde_json::Value = serde_json::from_str(&content).ok()?; let traces = traced_data.get("traces")?; diff --git a/src/api/profile.rs b/src/api/profile.rs index 3d189d95..221f40d7 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -9,6 +9,7 @@ use std::collections::HashMap; use crate::api::middleware::UserAuth; use crate::api::types::AppState; +use crate::api::cluster_agent::resolve_output_path; use crate::core::db::schema; use crate::core::file_profile::FaceFilterSettings; @@ -47,8 +48,8 @@ async fn materialize_auto_groups(pool: &PgPool, file_uuid: &str) -> Result<(), S .into_iter() .collect(); - let output_dir = crate::core::config::OUTPUT_DIR.as_str(); - let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); + // Try per-library dir first, fallback to global OUTPUT_DIR + let fc_path = resolve_output_path(pool, file_uuid, "face_cluster.json").await; let Ok(content) = std::fs::read_to_string(&fc_path) else { return Ok(()); // no auto clusters yet — done }; @@ -355,12 +356,22 @@ let row: Option<( file_uuid, trace_id); // Construct path: {output_dir}/{file_uuid}/trace_{trace_id}/trace_profile.json - let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR") - .unwrap_or_else(|_| crate::core::config::OUTPUT_DIR.to_string().to_string()); - let profile_path = std::path::Path::new(&output_dir) + let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, pool).await; + let candidate = std::path::Path::new(&per_lib) .join(file_uuid) .join(format!("trace_{}", trace_id)) .join("trace_profile.json"); + let profile_path = if candidate.exists() { + candidate + } else { + // Fallback: global OUTPUT_DIR (legacy) + let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR") + .unwrap_or_else(|_| crate::core::config::OUTPUT_DIR.to_string()); + std::path::PathBuf::from(&output_dir) + .join(file_uuid) + .join(format!("trace_{}", trace_id)) + .join("trace_profile.json") + }; // Read from filesystem if profile_path.exists() { @@ -2013,8 +2024,7 @@ pub async fn get_cluster_results_handler( // Load face_cluster.json for similarity data only (not for adding clusters) let cluster_similarity: HashMap = { - let output_dir = crate::core::config::OUTPUT_DIR.as_str(); - let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); + let fc_path = resolve_output_path(state.db.pool(), &file_uuid, "face_cluster.json").await; let mut map = HashMap::new(); if let Ok(content) = std::fs::read_to_string(&fc_path) { if let Ok(data) = serde_json::from_str::(&content) { diff --git a/src/api/trace_agent_api.rs b/src/api/trace_agent_api.rs index 8da00fa4..aff706e2 100644 --- a/src/api/trace_agent_api.rs +++ b/src/api/trace_agent_api.rs @@ -237,7 +237,7 @@ async fn list_traces_sorted( entry.best_bbox = bbox; } else { // 如果 Qdrant 沒有,從 trace_profile.json 讀取 - if let Some(profile) = read_trace_profile(&file_uuid, trace_id) { + if let Some(profile) = read_trace_profile(state.db.pool(), &file_uuid, trace_id).await { entry.best_bbox = profile.get("best_bbox").cloned(); } } @@ -252,7 +252,7 @@ async fn list_traces_sorted( entry.best_capture_bbox = bbox; } else { // 如果 Qdrant 沒有,從 trace_profile.json 讀取 - if let Some(profile) = read_trace_profile(&file_uuid, trace_id) { + if let Some(profile) = read_trace_profile(state.db.pool(), &file_uuid, trace_id).await { entry.best_capture_bbox = profile.get("best_bbox").cloned(); } } @@ -2805,9 +2805,23 @@ fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize { } /// Read trace_profile.json for a given file_uuid and trace_id. -fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option { +/// Tries per-library output dir first, falls back to global OUTPUT_DIR. +async fn read_trace_profile(pool: &sqlx::PgPool, file_uuid: &str, trace_id: i32) -> Option { use std::path::PathBuf; + // Try per-library output dir first + let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, pool).await; + let candidate: PathBuf = PathBuf::from(&per_lib) + .join(file_uuid) + .join(format!("trace_{}", trace_id)) + .join("trace_profile.json"); + if let Ok(content) = std::fs::read_to_string(&candidate) { + if let Ok(profile) = serde_json::from_str::(&content) { + return Some(profile); + } + } + + // Fallback: global OUTPUT_DIR (legacy) let output_dir = crate::core::config::OUTPUT_DIR.as_str(); let profile_path: PathBuf = [ output_dir, @@ -2817,7 +2831,6 @@ fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option(&content) { return Some(profile); @@ -2829,6 +2842,7 @@ fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option, Query(params): Query>, ) -> impl IntoResponse { let file_uuid = match params.get("file_uuid") { @@ -2840,7 +2854,7 @@ async fn get_trace_profile_file( None => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": "Missing or invalid trace_id"}))), }; - match read_trace_profile(&file_uuid, trace_id) { + match read_trace_profile(state.db.pool(), &file_uuid, trace_id).await { Some(profile) => (StatusCode::OK, Json(profile)), None => { let output_dir = crate::core::config::OUTPUT_DIR.as_str();