feat: trace_id i64→i32 fix, OCR search filter, Rule1 OCR trigger
- Fix trace_id SQL type mismatch: i64 → i32 in profile.rs structs and queries - Add /ocr /asr /asrx search filter suffix to keyword/semantic/smart search - Fix fetch_ocr_texts to handle both OCR data formats (string array + object array) - Add has_ocr trigger for Rule1 chunk ingestion in job_worker.rs - Add search_bm25 chunk_type filter parameter - Fix single-frame video clip duration (0-frame → 1-frame minimum) - Re-run Rule1 for 14 files with stuck OCR in pre_chunks
This commit is contained in:
+121
-28
@@ -4,7 +4,7 @@ use axum::{
|
||||
routing::post,
|
||||
Extension, Json, Router,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -14,6 +14,11 @@ use crate::core::config::OUTPUT_DIR;
|
||||
use crate::core::db::schema;
|
||||
use crate::core::processor::{process_face_cluster, FaceClusterResult};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ClusterAgentRequest {
|
||||
pub confirm: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ClusterAgentResponse {
|
||||
success: bool,
|
||||
@@ -34,7 +39,19 @@ pub async fn trigger_cluster_agent(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Path(file_uuid): Path<String>,
|
||||
Json(req): Json<ClusterAgentRequest>,
|
||||
) -> Result<Json<ClusterAgentResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
// Require explicit confirmation to prevent accidental reclustering
|
||||
if !req.confirm.unwrap_or(false) {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"success": false,
|
||||
"error": "Confirmation required. Set 'confirm': true to proceed with reclustering. This will reset all trace names and re-cluster faces.",
|
||||
"requires_confirmation": true
|
||||
})),
|
||||
));
|
||||
}
|
||||
let videos_table = schema::table_name("videos");
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT file_path, COALESCE(total_frames, 0) as total_frames, COALESCE(fps, 25.0) as fps, probe_json FROM {} WHERE file_uuid = $1",
|
||||
@@ -88,6 +105,42 @@ pub async fn trigger_cluster_agent(
|
||||
let output_path =
|
||||
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
|
||||
|
||||
// Reset all trace_profiles names to default (Person_N) before re-clustering
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let traced_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid));
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(traces) = traced_data.get("traces") {
|
||||
let trace_list = if traces.is_object() {
|
||||
traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::<i64>().ok()).collect::<Vec<_>>())
|
||||
} else if traces.is_array() {
|
||||
traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(all_trace_ids) = trace_list {
|
||||
for tid in &all_trace_ids {
|
||||
let name = format!("Person_{}", tid);
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
))
|
||||
.bind(&name)
|
||||
.bind(&file_uuid)
|
||||
.bind(tid)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
}
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Reset {} trace names to default for {}",
|
||||
all_trace_ids.len(), file_uuid
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!("[ClusterAgent] Starting face clustering for {}", file_uuid);
|
||||
let result = process_face_cluster(
|
||||
&file_path,
|
||||
@@ -147,43 +200,43 @@ async fn update_trace_labels_from_cluster(
|
||||
file_uuid: &str,
|
||||
result: &FaceClusterResult,
|
||||
) -> anyhow::Result<()> {
|
||||
let scroll_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": file_uuid}}
|
||||
]
|
||||
});
|
||||
|
||||
let all_faces = state
|
||||
.qdrant
|
||||
.scroll_all_points("_faces", scroll_filter, 1000)
|
||||
.await?;
|
||||
|
||||
let mut frame_to_traces: HashMap<u64, Vec<i64>> = HashMap::new();
|
||||
for point in &all_faces {
|
||||
let payload = &point["payload"];
|
||||
if let (Some(frame), Some(trace_id)) =
|
||||
(payload["frame"].as_u64(), payload["trace_id"].as_i64())
|
||||
{
|
||||
if trace_id > 0 {
|
||||
frame_to_traces.entry(frame).or_default().push(trace_id);
|
||||
// Build index: (frame, face_index) → real trace_id from face_traced.json
|
||||
// face_cluster.json's trace_id is cluster-internal (always 0), so we match
|
||||
// by frame number + array index to get the actual traced trace_id.
|
||||
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
|
||||
.join(format!("{}.face_traced.json", file_uuid));
|
||||
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::<serde_json::Value>(&content) {
|
||||
if let Some(frames) = traced_data.get("frames").and_then(|v| v.as_object()) {
|
||||
for (fnum_str, frame_data) in frames {
|
||||
if let (Ok(fnum), Some(faces)) = (
|
||||
fnum_str.parse::<u64>(),
|
||||
frame_data.get("faces").and_then(|v| v.as_array()),
|
||||
) {
|
||||
for (idx, face) in faces.iter().enumerate() {
|
||||
if let Some(tid) = face.get("trace_id").and_then(|v| v.as_i64()) {
|
||||
frame_face_to_trace.insert((fnum, idx), tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut trace_to_cluster: HashMap<i64, String> = HashMap::new();
|
||||
for frame_data in &result.frames {
|
||||
let frame = frame_data.frame;
|
||||
if let Some(trace_ids) = frame_to_traces.get(&frame) {
|
||||
for (idx, face) in frame_data.faces.iter().enumerate() {
|
||||
if idx < trace_ids.len() {
|
||||
trace_to_cluster.insert(trace_ids[idx], face.cluster_id.clone());
|
||||
}
|
||||
for (idx, face) in frame_data.faces.iter().enumerate() {
|
||||
if let Some(&tid) = frame_face_to_trace.get(&(frame_data.frame, idx)) {
|
||||
trace_to_cluster.insert(tid, face.cluster_id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
for (trace_id, cluster_id) in &trace_to_cluster {
|
||||
let external_id = format!("trace_{}", trace_id);
|
||||
let label = cluster_id.clone();
|
||||
@@ -212,7 +265,6 @@ async fn update_trace_labels_from_cluster(
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Sync name to trace_profiles
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
@@ -224,8 +276,34 @@ async fn update_trace_labels_from_cluster(
|
||||
.await;
|
||||
}
|
||||
|
||||
// Reset unclustered traces (not found in any cluster) to default Person_N
|
||||
if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) {
|
||||
let mut updated_count = 0u64;
|
||||
for tid in &all_trace_ids {
|
||||
if !trace_to_cluster.contains_key(tid) {
|
||||
let name = format!("Person_{}", tid);
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
))
|
||||
.bind(&name)
|
||||
.bind(file_uuid)
|
||||
.bind(tid)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
updated_count += 1;
|
||||
}
|
||||
}
|
||||
if updated_count > 0 {
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Updated {} unclustered trace names for {}",
|
||||
updated_count, file_uuid
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"[ClusterAgent] Updated {} trace labels for {}",
|
||||
"[ClusterAgent] Updated {} trace labels from clustering for {}",
|
||||
trace_to_cluster.len(),
|
||||
file_uuid
|
||||
);
|
||||
@@ -233,6 +311,21 @@ async fn update_trace_labels_from_cluster(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_all_trace_ids(file_uuid: &str) -> Option<Vec<i64>> {
|
||||
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
|
||||
.join(format!("{}.face_traced.json", file_uuid));
|
||||
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")?;
|
||||
if let Some(obj) = traces.as_object() {
|
||||
Some(obj.keys().filter_map(|k| k.parse::<i64>().ok()).collect())
|
||||
} else if let Some(arr) = traces.as_array() {
|
||||
Some(arr.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result<usize> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let count: (i64,) = sqlx::query_as(&format!(
|
||||
|
||||
+39
-26
@@ -1088,6 +1088,17 @@ fn delete_output_files(uuid: &str) -> u64 {
|
||||
tracing::info!("[UNREGISTER] Deleted workspace SQLite: {}", path.display());
|
||||
}
|
||||
}
|
||||
tracing::info!(
|
||||
"[UNREGISTER] Deleted {} output files for {}",
|
||||
deleted_count,
|
||||
uuid
|
||||
);
|
||||
if deleted_count == 0 {
|
||||
tracing::warn!(
|
||||
"[UNREGISTER] No output files found to delete for {}",
|
||||
uuid
|
||||
);
|
||||
}
|
||||
deleted_count
|
||||
}
|
||||
|
||||
@@ -1637,6 +1648,7 @@ async fn sync_file_status(
|
||||
use crate::core::config::OUTPUT_DIR;
|
||||
|
||||
let output_dir = OUTPUT_DIR.as_str();
|
||||
let videos_table = schema::table_name("videos");
|
||||
let chunk_table = schema::table_name("chunk");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let tkg_nodes_table = schema::table_name("tkg_nodes");
|
||||
@@ -1692,12 +1704,9 @@ async fn sync_file_status(
|
||||
(json_count as i64) == db_count
|
||||
}
|
||||
"ocr" => {
|
||||
let json_count = json_data.get("frames").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'ocr'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
(json_count as i64) == db_count
|
||||
// pre_chunks 存的是 grouped chunks (zone + proximity grouping),
|
||||
// 不等於 frame count,只要 JSON 存在就視為一致
|
||||
true
|
||||
}
|
||||
"cut" => {
|
||||
let json_count = json_data.get("scenes").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
@@ -1708,13 +1717,8 @@ async fn sync_file_status(
|
||||
(json_count as i64) == db_count
|
||||
}
|
||||
"face" => {
|
||||
let json_frame_count = json_data.get("frames").and_then(|f| f.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let is_no_faces = json_data.get("status").and_then(|s| s.as_str()) == Some("no_faces");
|
||||
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'face'", pre_table
|
||||
))
|
||||
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
|
||||
is_no_faces || json_frame_count == (db_count as usize)
|
||||
// face 已遷移至 Qdrant,不再比對 pre_chunks
|
||||
true
|
||||
}
|
||||
"face_cluster" => {
|
||||
// cluster 數量可能不等於 trace 數量,只要 JSON 存在就視為一致
|
||||
@@ -1742,10 +1746,11 @@ async fn sync_file_status(
|
||||
consistent = false;
|
||||
}
|
||||
}
|
||||
|
||||
if !consistent {
|
||||
all_consistent = false;
|
||||
}
|
||||
}
|
||||
|
||||
// JSON not existing also counts as inconsistent
|
||||
if !consistent {
|
||||
all_consistent = false;
|
||||
}
|
||||
|
||||
processor_status.insert(name.to_string(), serde_json::json!({
|
||||
@@ -1792,24 +1797,32 @@ async fn sync_file_status(
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(0) > 0;
|
||||
|
||||
// 查詢 processing_status phase
|
||||
let phase: String = sqlx::query_scalar(&format!(
|
||||
"SELECT COALESCE(processing_status->>'phase', '') FROM {} WHERE file_uuid = $1",
|
||||
videos_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
|
||||
let phase_completed = phase == "COMPLETED";
|
||||
|
||||
// 狀態判斷
|
||||
let new_status = if all_consistent && any_json_exists {
|
||||
// 所有 JSON 都存在且與 DB 一致
|
||||
if has_tkg_edges {
|
||||
"agent_ready"
|
||||
} else {
|
||||
"completed" // 即使 0 筆也算完成
|
||||
}
|
||||
"completed"
|
||||
} else if any_json_exists {
|
||||
// 部分 JSON 存在但不一致 → 入庫中
|
||||
// 部分 JSON 存在或不一致 → 入庫中
|
||||
"scanning"
|
||||
} else {
|
||||
// 無 JSON → 未開始
|
||||
"registered"
|
||||
};
|
||||
|
||||
|
||||
// 更新 DB status
|
||||
let videos_table = schema::table_name("videos");
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {} SET status = $1, updated_at = NOW() WHERE file_uuid = $2",
|
||||
videos_table
|
||||
|
||||
@@ -447,11 +447,11 @@ async fn list_unassigned_traces(
|
||||
let page_size = std::cmp::min(query.page_size.unwrap_or(20), 100);
|
||||
let offset = (page - 1) * page_size;
|
||||
|
||||
// Query Qdrant _faces for unbound traces (identity_id IS NULL, trace_id > 0)
|
||||
// Query Qdrant _faces for unbound traces (identity_id IS NULL, trace_id >= 0)
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
let mut filter_must: Vec<serde_json::Value> = vec![
|
||||
serde_json::json!({"is_null": {"key": "identity_id"}}),
|
||||
serde_json::json!({"key": "trace_id", "range": {"gt": 0}}),
|
||||
serde_json::json!({"key": "trace_id", "range": {"gte": 0}}),
|
||||
];
|
||||
if let Some(ref file_uuid) = query.file_uuid {
|
||||
filter_must.push(serde_json::json!({"key": "file_uuid", "match": {"value": file_uuid}}));
|
||||
@@ -489,7 +489,7 @@ async fn list_unassigned_traces(
|
||||
None => continue,
|
||||
};
|
||||
let trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32;
|
||||
if trace_id <= 0 {
|
||||
if trace_id < 0 {
|
||||
continue;
|
||||
}
|
||||
let frame = payload["frame"].as_i64().unwrap_or(0);
|
||||
|
||||
@@ -719,7 +719,7 @@ async fn stream_video(
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.unwrap_or(24.0);
|
||||
(sf / _fps, (ef - sf) / _fps)
|
||||
(sf / _fps, ((ef - sf).max(0.0) + 1.0) / _fps)
|
||||
} else if let (Some(st), Some(et)) = (start_time_param, end_time_param) {
|
||||
(st, et - st)
|
||||
} else if let (Some(s), Some(e)) = (start_legacy, end_legacy) {
|
||||
|
||||
+705
-51
@@ -11,20 +11,34 @@ use crate::api::middleware::UserAuth;
|
||||
use crate::api::types::AppState;
|
||||
use crate::core::db::schema;
|
||||
|
||||
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
|
||||
if a.len() != b.len() || a.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
|
||||
let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
if na == 0.0 || nb == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
dot / (na * nb)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Trace Profile ───
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TraceProfileQuery {
|
||||
pub file_uuid: String,
|
||||
pub trace_id: i64,
|
||||
pub trace_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct TraceProfile {
|
||||
pub file_uuid: String,
|
||||
pub trace_id: i64,
|
||||
pub trace_id: i32,
|
||||
pub name: String,
|
||||
pub key_frame: Option<i64>,
|
||||
pub key_frame: Option<String>,
|
||||
pub key_face: Option<String>,
|
||||
pub aliases: Option<serde_json::Value>,
|
||||
pub bbox: Option<serde_json::Value>,
|
||||
@@ -34,9 +48,9 @@ pub struct TraceProfile {
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateTraceProfileRequest {
|
||||
pub file_uuid: String,
|
||||
pub trace_id: i64,
|
||||
pub trace_id: i32,
|
||||
pub name: Option<String>,
|
||||
pub key_frame: Option<i64>,
|
||||
pub key_frame: Option<String>,
|
||||
pub key_face: Option<String>,
|
||||
pub aliases: Option<serde_json::Value>,
|
||||
pub properties: Option<serde_json::Value>,
|
||||
@@ -45,7 +59,7 @@ pub struct UpdateTraceProfileRequest {
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateTraceProfileGroupRequest {
|
||||
pub file_uuid: String,
|
||||
pub trace_ids: Vec<i64>,
|
||||
pub trace_ids: Vec<i32>,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
@@ -66,19 +80,54 @@ pub struct MergeGroupsResponse {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub async fn save_trace_operation_snapshot(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
operation: &str,
|
||||
before_snapshot: serde_json::Value,
|
||||
after_snapshot: Option<serde_json::Value>,
|
||||
user_id: Option<&str>,
|
||||
) -> Result<(), ()> {
|
||||
let table = schema::table_name("trace_operation_history");
|
||||
let result = sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, operation, before_snapshot, after_snapshot, user_id) VALUES ($1, $2, $3, $4, $5)",
|
||||
table
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(operation)
|
||||
.bind(&before_snapshot)
|
||||
.bind(&after_snapshot)
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await;
|
||||
match result {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
tracing::error!("[TraceOpHistory] Failed to save snapshot: {}", e);
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_trace_profile_handler(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Query(params): Query<TraceProfileQuery>,
|
||||
) -> Result<Json<TraceProfile>, StatusCode> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let external_id_face = format!("face_track_{}", params.trace_id);
|
||||
let external_id_trace = format!("trace_{}", params.trace_id);
|
||||
|
||||
let row: Option<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT label, external_id, properties FROM {} \
|
||||
WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
|
||||
tkg_table
|
||||
let row: Option<(String, String, serde_json::Value, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
|
||||
tp.properties, tn.properties \
|
||||
FROM {} tn \
|
||||
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::int \
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
|
||||
AND (tn.external_id = $2 OR tn.external_id = $3)",
|
||||
tkg_table, tp_table
|
||||
))
|
||||
.bind(¶ms.file_uuid)
|
||||
.bind(&external_id_face)
|
||||
@@ -90,9 +139,21 @@ pub async fn get_trace_profile_handler(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let (label, _ext_id, properties) = row.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let key_frame = properties.get("key_frame").and_then(|v| v.as_i64());
|
||||
// Merge properties: tp_props takes precedence, tn_props as fallback
|
||||
let mut properties = tn_props.clone();
|
||||
if let Some(tp_obj) = tp_props.as_object() {
|
||||
if let Some(props_obj) = properties.as_object_mut() {
|
||||
for (k, v) in tp_obj {
|
||||
if !v.is_null() {
|
||||
props_obj.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let key_frame = properties.get("key_frame").and_then(|v| v.as_str()).map(|s| s.to_string());
|
||||
let key_face = properties
|
||||
.get("key_face")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -103,7 +164,7 @@ pub async fn get_trace_profile_handler(
|
||||
Ok(Json(TraceProfile {
|
||||
file_uuid: params.file_uuid,
|
||||
trace_id: params.trace_id,
|
||||
name: label,
|
||||
name,
|
||||
key_frame,
|
||||
key_face,
|
||||
aliases,
|
||||
@@ -180,6 +241,9 @@ pub async fn update_trace_profile_handler(
|
||||
})));
|
||||
}
|
||||
|
||||
let new_name_val = req.name.as_deref();
|
||||
let before_name = current_name.clone().unwrap_or_default();
|
||||
|
||||
let props_json = serde_json::to_string(¤t_props).unwrap();
|
||||
|
||||
let mut query = format!(
|
||||
@@ -195,19 +259,34 @@ pub async fn update_trace_profile_handler(
|
||||
let mut sql_query = sqlx::query(&query)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&props_json)
|
||||
.bind(req.trace_id);
|
||||
.bind(req.trace_id as i32);
|
||||
|
||||
if let Some(ref new_name) = req.name {
|
||||
sql_query = sql_query.bind(new_name);
|
||||
}
|
||||
|
||||
match sql_query.execute(state.db.pool()).await {
|
||||
Ok(res) if res.rows_affected() > 0 => Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "Trace profile updated",
|
||||
"file_uuid": req.file_uuid,
|
||||
"trace_id": req.trace_id
|
||||
}))),
|
||||
Ok(res) if res.rows_affected() > 0 => {
|
||||
let after_name = new_name_val.unwrap_or(&before_name);
|
||||
let _ = save_trace_operation_snapshot(
|
||||
state.db.pool(),
|
||||
&req.file_uuid,
|
||||
"rename_single",
|
||||
serde_json::json!({
|
||||
"traces": { req.trace_id.to_string(): before_name }
|
||||
}),
|
||||
Some(serde_json::json!({
|
||||
"traces": { req.trace_id.to_string(): after_name }
|
||||
})),
|
||||
None,
|
||||
).await;
|
||||
Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "Trace profile updated",
|
||||
"file_uuid": req.file_uuid,
|
||||
"trace_id": req.trace_id
|
||||
})))
|
||||
}
|
||||
Ok(_) => Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("[TraceProfile] Update failed: {}", e);
|
||||
@@ -223,6 +302,26 @@ pub async fn update_trace_profile_group_handler(
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
// Snapshot current names before update
|
||||
let mut before_names: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
|
||||
for trace_id in &req.trace_ids {
|
||||
let current: Option<(String,)> = sqlx::query_as(&format!(
|
||||
"SELECT name FROM {} WHERE file_uuid = $1 AND trace_id = $2",
|
||||
tp_table
|
||||
))
|
||||
.bind(&req.file_uuid)
|
||||
.bind(trace_id)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[TraceProfileGroup] DB error: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
if let Some((name,)) = current {
|
||||
before_names.insert(trace_id.to_string(), serde_json::json!(name));
|
||||
}
|
||||
}
|
||||
|
||||
let mut updated = 0;
|
||||
for trace_id in &req.trace_ids {
|
||||
let result = sqlx::query(&format!(
|
||||
@@ -240,6 +339,17 @@ pub async fn update_trace_profile_group_handler(
|
||||
}
|
||||
}
|
||||
|
||||
let _ = save_trace_operation_snapshot(
|
||||
state.db.pool(),
|
||||
&req.file_uuid,
|
||||
"rename_batch",
|
||||
serde_json::json!({ "traces": before_names }),
|
||||
Some(serde_json::json!({
|
||||
"traces": req.trace_ids.iter().map(|tid| (tid.to_string(), serde_json::json!(req.name))).collect::<serde_json::Map<_,_>>()
|
||||
})),
|
||||
None,
|
||||
).await;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": format!("Updated {} traces in group", updated),
|
||||
@@ -275,17 +385,31 @@ pub async fn merge_groups_handler(
|
||||
));
|
||||
}
|
||||
|
||||
// Update trace_profiles.name for all matching traces
|
||||
// Snapshot current names before merge
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let before_names: Vec<(i32, String)> = sqlx::query_as(&format!(
|
||||
"SELECT trace_id, name FROM {} WHERE file_uuid = $1 AND name = ANY($2)",
|
||||
tp_table
|
||||
))
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&req.source_groups)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[MergeGroups] Snapshot error: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Update trace_profiles.name AND tkg_nodes.label for all matching traces
|
||||
let nodes_table = schema::table_name("tkg_nodes");
|
||||
|
||||
let result = sqlx::query(&format!(
|
||||
"UPDATE {} tp SET name = $1 \
|
||||
WHERE tp.file_uuid = $2 AND tp.trace_id IN (\
|
||||
SELECT REPLACE(n.external_id, 'trace_', '')::int \
|
||||
FROM {} n WHERE n.file_uuid = $2 AND n.node_type = 'face_track' AND n.label = ANY($3)\
|
||||
)",
|
||||
tp_table, nodes_table
|
||||
// First update tkg_nodes.label
|
||||
let nodes_result = sqlx::query(&format!(
|
||||
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND label = ANY($3)",
|
||||
nodes_table
|
||||
))
|
||||
.bind(&req.target_group_name)
|
||||
.bind(&req.file_uuid)
|
||||
@@ -293,21 +417,50 @@ pub async fn merge_groups_handler(
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(res) => {
|
||||
let updated = res.rows_affected();
|
||||
// Then update trace_profiles.name
|
||||
let tp_result = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND name = ANY($3)",
|
||||
tp_table
|
||||
))
|
||||
.bind(&req.target_group_name)
|
||||
.bind(&req.file_uuid)
|
||||
.bind(&req.source_groups)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
match (nodes_result, tp_result) {
|
||||
(Ok(nodes_res), Ok(tp_res)) => {
|
||||
let updated = tp_res.rows_affected();
|
||||
let nodes_updated = nodes_res.rows_affected();
|
||||
let group_count = req.source_groups.len();
|
||||
let target_name = req.target_group_name.clone();
|
||||
|
||||
let before_map: serde_json::Map<String, serde_json::Value> = before_names
|
||||
.iter()
|
||||
.map(|(tid, name)| (tid.to_string(), serde_json::json!(name)))
|
||||
.collect();
|
||||
let _ = save_trace_operation_snapshot(
|
||||
state.db.pool(),
|
||||
&req.file_uuid,
|
||||
"merge_groups",
|
||||
serde_json::json!({ "traces": before_map, "target": &target_name, "sources": &req.source_groups }),
|
||||
Some(serde_json::json!({
|
||||
"traces": before_names.iter().map(|(tid, _)| (tid.to_string(), serde_json::json!(&target_name))).collect::<serde_json::Map<_,_>>(),
|
||||
"target": &target_name,
|
||||
})),
|
||||
None,
|
||||
).await;
|
||||
|
||||
Ok(Json(MergeGroupsResponse {
|
||||
success: true,
|
||||
file_uuid: req.file_uuid,
|
||||
source_groups: req.source_groups,
|
||||
target_group_name: req.target_group_name,
|
||||
target_group_name: target_name.clone(),
|
||||
traces_merged: updated,
|
||||
message: format!("Merged {} group(s) into '{}'", group_count, target_name),
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
(Err(e), _) | (_, Err(e)) => {
|
||||
tracing::error!("[MergeGroups] DB error: {}", e);
|
||||
Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -320,6 +473,299 @@ pub async fn merge_groups_handler(
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct UndoFaceOperationResponse {
|
||||
pub success: bool,
|
||||
pub file_uuid: String,
|
||||
pub operation: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub async fn undo_face_operation_handler(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<UndoFaceOperationResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let table = schema::table_name("trace_operation_history");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
|
||||
// Find latest undoable operation for this file
|
||||
let record: Option<(i64, String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT id, operation, before_snapshot FROM {} WHERE file_uuid = $1 AND is_undone = false ORDER BY created_at DESC LIMIT 1",
|
||||
table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[UndoFaceOp] DB error: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
|
||||
let (history_id, operation, before_snapshot) = record.ok_or_else(|| {
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "No undoable operations found for this file"})),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Handle merge_trace specially (Qdrant point restore)
|
||||
if operation == "merge_trace" {
|
||||
return undo_merge_trace(state, file_uuid, history_id, before_snapshot).await;
|
||||
}
|
||||
|
||||
// Handle hard_delete (restore from _faces_trash)
|
||||
if operation == "hard_delete" {
|
||||
return undo_hard_delete_trace(state, file_uuid, history_id, before_snapshot).await;
|
||||
}
|
||||
|
||||
// Handle operations with traces name mapping
|
||||
let traces = before_snapshot.get("traces").and_then(|v| v.as_object()).ok_or_else(|| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": "Invalid snapshot: missing traces"})),
|
||||
)
|
||||
})?;
|
||||
|
||||
for (trace_id_str, name_val) in traces {
|
||||
let name = name_val.as_str().unwrap_or("Person_0");
|
||||
let trace_id: i32 = trace_id_str.parse().unwrap_or(0);
|
||||
|
||||
// Restore trace_profiles.name
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
))
|
||||
.bind(name)
|
||||
.bind(&file_uuid)
|
||||
.bind(trace_id)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
// For merge_groups, also restore tkg_nodes.label
|
||||
if operation == "merge_groups" {
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3",
|
||||
tkg_table
|
||||
))
|
||||
.bind(name)
|
||||
.bind(&file_uuid)
|
||||
.bind(format!("trace_{}", trace_id))
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark as undone
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1",
|
||||
table
|
||||
))
|
||||
.bind(history_id)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[UndoFaceOp] Failed to mark as undone: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Json(UndoFaceOperationResponse {
|
||||
success: true,
|
||||
file_uuid,
|
||||
operation,
|
||||
message: "Operation undone successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn undo_merge_trace(
|
||||
state: AppState,
|
||||
file_uuid: String,
|
||||
history_id: i64,
|
||||
before_snapshot: serde_json::Value,
|
||||
) -> Result<Json<UndoFaceOperationResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let table = schema::table_name("trace_operation_history");
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
|
||||
let source_trace_id = before_snapshot["source_trace_id"].as_i64().unwrap_or(0);
|
||||
let target_trace_id = before_snapshot["target_trace_id"].as_i64().unwrap_or(0);
|
||||
|
||||
// 1. Delete merged points from target trace (those with merged_from marker)
|
||||
let delete_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": &file_uuid}},
|
||||
{"key": "trace_id", "match": {"value": target_trace_id}},
|
||||
{"key": "merged_from", "match": {"value": source_trace_id}}
|
||||
]
|
||||
});
|
||||
let _ = state.qdrant.delete_points_by_filter("_faces", delete_filter).await;
|
||||
|
||||
// 2. Re-insert original points
|
||||
if let Some(qdrant_points) = before_snapshot["qdrant_points"].as_array() {
|
||||
let owned_batch: Vec<(u64, Vec<f32>, Option<serde_json::Value>)> = qdrant_points
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let id = p["id"].as_u64()?;
|
||||
let vec_arr = p["vector"].as_array()?;
|
||||
let vector: Vec<f32> = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
|
||||
let payload = p["payload"].clone();
|
||||
Some((id, vector, Some(payload)))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let ref_batch: Vec<(u64, &[f32], Option<serde_json::Value>)> = owned_batch
|
||||
.iter()
|
||||
.map(|(id, vec, pl)| (*id, vec.as_slice(), pl.clone()))
|
||||
.collect();
|
||||
|
||||
if !ref_batch.is_empty() {
|
||||
if let Err(e) = state.qdrant.upsert_vectors_batch("_faces", &ref_batch).await {
|
||||
tracing::error!("[UndoMergeTrace] Failed to restore Qdrant points: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Re-insert TKG nodes
|
||||
if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() {
|
||||
for node in tkg_nodes {
|
||||
let ext_id = node["external_id"].as_str().unwrap_or("");
|
||||
let label = node["label"].as_str().unwrap_or("Person_0");
|
||||
let props = node.get("properties").cloned().unwrap_or(serde_json::json!({"trace_id": source_trace_id}));
|
||||
|
||||
let _ = sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING",
|
||||
tkg_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(ext_id)
|
||||
.bind(label)
|
||||
.bind(&props)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark as undone
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1",
|
||||
table
|
||||
))
|
||||
.bind(history_id)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
Ok(Json(UndoFaceOperationResponse {
|
||||
success: true,
|
||||
file_uuid,
|
||||
operation: "merge_trace".to_string(),
|
||||
message: "Trace merge undone successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn undo_hard_delete_trace(
|
||||
state: AppState,
|
||||
file_uuid: String,
|
||||
history_id: i64,
|
||||
before_snapshot: serde_json::Value,
|
||||
) -> Result<Json<UndoFaceOperationResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let table = schema::table_name("trace_operation_history");
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
|
||||
let trace_id = before_snapshot["trace_id"].as_i64().unwrap_or(0);
|
||||
|
||||
// 1. Scroll points from _faces_trash
|
||||
let trash_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": &file_uuid}},
|
||||
{"key": "trace_id", "match": {"value": trace_id}}
|
||||
]
|
||||
});
|
||||
let trash_points = state.qdrant
|
||||
.scroll_all_points_with_vectors("_faces_trash", trash_filter.clone(), 1000)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("Failed to read trash: {}", e)})),
|
||||
)
|
||||
})?;
|
||||
|
||||
if trash_points.is_empty() {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "No trashed points found for this trace"})),
|
||||
));
|
||||
}
|
||||
|
||||
// 2. Copy back to _faces
|
||||
let restore_batch: Vec<(u64, Vec<f32>, serde_json::Value)> = trash_points
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let id = p["id"].as_u64()?;
|
||||
let vec_arr = p["vector"].as_array()?;
|
||||
let vector: Vec<f32> = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
|
||||
let mut payload = p["payload"].clone();
|
||||
if let Some(obj) = payload.as_object_mut() {
|
||||
obj.remove("trashed_at");
|
||||
}
|
||||
Some((id, vector, payload))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let ref_batch: Vec<(u64, &[f32], Option<serde_json::Value>)> = restore_batch
|
||||
.iter()
|
||||
.map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone())))
|
||||
.collect();
|
||||
|
||||
if let Err(e) = state.qdrant.upsert_vectors_batch("_faces", &ref_batch).await {
|
||||
tracing::error!("[UndoHardDelete] Failed to restore points: {}", e);
|
||||
}
|
||||
|
||||
// 3. Delete from _faces_trash
|
||||
let _ = state.qdrant.delete_points_by_filter("_faces_trash", trash_filter).await;
|
||||
|
||||
// 4. Re-insert TKG nodes
|
||||
if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() {
|
||||
for node in tkg_nodes {
|
||||
let ext_id = node["external_id"].as_str().unwrap_or("");
|
||||
let label = node["label"].as_str().unwrap_or("Person_0");
|
||||
let props = node.get("properties").cloned().unwrap_or(serde_json::json!({"trace_id": trace_id}));
|
||||
let _ = sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING",
|
||||
tkg_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(ext_id)
|
||||
.bind(label)
|
||||
.bind(&props)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Mark as undone
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1",
|
||||
table
|
||||
))
|
||||
.bind(history_id)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
Ok(Json(UndoFaceOperationResponse {
|
||||
success: true,
|
||||
file_uuid,
|
||||
operation: "hard_delete".to_string(),
|
||||
message: "Trace restored from trash successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// ─── File Profile ───
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -439,11 +885,11 @@ pub async fn update_file_profile_handler(
|
||||
let mut updates: Vec<String> = Vec::new();
|
||||
let mut param_idx: i32 = 1;
|
||||
|
||||
if req.file_path.is_some() {
|
||||
if req.file_path.as_ref().is_some_and(|s| !s.is_empty()) {
|
||||
updates.push(format!("file_path = ${}", param_idx));
|
||||
param_idx += 1;
|
||||
}
|
||||
if req.file_name.is_some() {
|
||||
if req.file_name.as_ref().is_some_and(|s| !s.is_empty()) {
|
||||
updates.push(format!("file_name = ${}", param_idx));
|
||||
param_idx += 1;
|
||||
}
|
||||
@@ -465,30 +911,35 @@ pub async fn update_file_profile_handler(
|
||||
);
|
||||
|
||||
// Build the SQL and execute with correct bind order
|
||||
let result = match (&req.file_path, &req.file_name) {
|
||||
(Some(fp), Some(fn_)) => {
|
||||
let has_path = req.file_path.as_ref().is_some_and(|s| !s.is_empty());
|
||||
let has_name = req.file_name.as_ref().is_some_and(|s| !s.is_empty());
|
||||
let clean_path = req.file_path.as_ref().filter(|s| !s.is_empty());
|
||||
let clean_name = req.file_name.as_ref().filter(|s| !s.is_empty());
|
||||
|
||||
let result = match (has_path, has_name) {
|
||||
(true, true) => {
|
||||
sqlx::query(&sql)
|
||||
.bind(fp)
|
||||
.bind(fn_)
|
||||
.bind(clean_path.unwrap())
|
||||
.bind(clean_name.unwrap())
|
||||
.bind(&req.file_uuid)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
}
|
||||
(Some(fp), None) => {
|
||||
(true, false) => {
|
||||
sqlx::query(&sql)
|
||||
.bind(fp)
|
||||
.bind(clean_path.unwrap())
|
||||
.bind(&req.file_uuid)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
}
|
||||
(None, Some(fn_)) => {
|
||||
(false, true) => {
|
||||
sqlx::query(&sql)
|
||||
.bind(fn_)
|
||||
.bind(clean_name.unwrap())
|
||||
.bind(&req.file_uuid)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
}
|
||||
(None, None) => unreachable!(),
|
||||
(false, false) => unreachable!(),
|
||||
};
|
||||
|
||||
match result {
|
||||
@@ -534,9 +985,9 @@ pub async fn update_file_profile_handler(
|
||||
pub struct FaceGroup {
|
||||
pub group_id: i32,
|
||||
pub name: String,
|
||||
pub trace_ids: Vec<i64>,
|
||||
pub trace_ids: Vec<i32>,
|
||||
pub trace_count: i32,
|
||||
pub representative_trace: i64,
|
||||
pub representative_trace: i32,
|
||||
pub editable: bool,
|
||||
}
|
||||
|
||||
@@ -546,7 +997,7 @@ pub struct FaceGroupsResponse {
|
||||
pub file_uuid: String,
|
||||
pub face_groups: Vec<FaceGroup>,
|
||||
pub total_groups: i32,
|
||||
pub unassigned_traces: Vec<i64>,
|
||||
pub unassigned_traces: Vec<i32>,
|
||||
}
|
||||
|
||||
pub async fn get_face_groups_handler(
|
||||
@@ -558,12 +1009,13 @@ pub async fn get_face_groups_handler(
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
|
||||
let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, tn.properties \
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, \
|
||||
COALESCE(tp.properties, tn.properties) as properties \
|
||||
FROM {} tn \
|
||||
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::int \
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
|
||||
ORDER BY (tn.properties->>'trace_id')::int",
|
||||
ORDER BY (COALESCE(tp.properties, tn.properties)->>'trace_id')::int",
|
||||
tkg_table, tp_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
@@ -574,13 +1026,14 @@ pub async fn get_face_groups_handler(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let mut groups: HashMap<String, Vec<i64>> = HashMap::new();
|
||||
let mut unassigned: Vec<i64> = Vec::new();
|
||||
let mut groups: HashMap<String, Vec<i32>> = HashMap::new();
|
||||
let mut unassigned: Vec<i32> = Vec::new();
|
||||
|
||||
for (name, properties) in rows {
|
||||
let trace_id = properties
|
||||
.get("trace_id")
|
||||
.and_then(|v| v.as_i64())
|
||||
.map(|v| v as i32)
|
||||
.unwrap_or(0);
|
||||
|
||||
if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
|
||||
@@ -612,6 +1065,199 @@ pub async fn get_face_groups_handler(
|
||||
}))
|
||||
}
|
||||
|
||||
// ─── Similar Group Suggestion ───
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SimilarGroupQuery {
|
||||
pub trace_ids: String,
|
||||
pub top_k: Option<usize>,
|
||||
pub min_score: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SimilarGroupSuggestion {
|
||||
pub group_name: String,
|
||||
pub score: f64,
|
||||
pub matched_trace_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SimilarGroupResponse {
|
||||
pub success: bool,
|
||||
pub file_uuid: String,
|
||||
pub suggestions: Vec<SimilarGroupSuggestion>,
|
||||
}
|
||||
|
||||
pub async fn get_similar_group_handler(
|
||||
State(state): State<AppState>,
|
||||
Extension(_auth): Extension<UserAuth>,
|
||||
Path(file_uuid): Path<String>,
|
||||
Query(params): Query<SimilarGroupQuery>,
|
||||
) -> Result<Json<SimilarGroupResponse>, StatusCode> {
|
||||
let source_trace_ids: Vec<i64> = params
|
||||
.trace_ids
|
||||
.split(',')
|
||||
.filter_map(|s| s.trim().parse().ok())
|
||||
.collect();
|
||||
|
||||
if source_trace_ids.is_empty() {
|
||||
return Ok(Json(SimilarGroupResponse {
|
||||
success: false,
|
||||
file_uuid,
|
||||
suggestions: vec![],
|
||||
}));
|
||||
}
|
||||
|
||||
let top_k = params.top_k.unwrap_or(1);
|
||||
let min_score = params.min_score.unwrap_or(0.6);
|
||||
|
||||
// 1. Scroll all face points for the file with vectors
|
||||
let face_filter = serde_json::json!({
|
||||
"must": [{"key": "file_uuid", "match": {"value": &file_uuid}}]
|
||||
});
|
||||
let all_points = match state
|
||||
.qdrant
|
||||
.scroll_all_points_with_vectors("_faces", face_filter, 1000)
|
||||
.await
|
||||
{
|
||||
Ok(pts) => pts,
|
||||
Err(e) => {
|
||||
tracing::error!("[SimilarGroup] Qdrant scroll error: {}", e);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Group face vectors by trace_id
|
||||
let mut trace_vectors: HashMap<i64, Vec<Vec<f32>>> = HashMap::new();
|
||||
for point in &all_points {
|
||||
let tid = point["payload"]["trace_id"].as_i64().unwrap_or(0);
|
||||
if tid <= 0 {
|
||||
continue;
|
||||
}
|
||||
let vector: Vec<f32> = point["vector"]
|
||||
.as_array()
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_f64().map(|f| f as f32))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if vector.len() == 512 {
|
||||
trace_vectors.entry(tid).or_default().push(vector);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Compute source centroid
|
||||
let mut source_vectors: Vec<Vec<f32>> = Vec::new();
|
||||
for tid in &source_trace_ids {
|
||||
if let Some(vectors) = trace_vectors.get(tid) {
|
||||
source_vectors.extend(vectors.clone());
|
||||
}
|
||||
}
|
||||
if source_vectors.is_empty() {
|
||||
return Ok(Json(SimilarGroupResponse {
|
||||
success: true,
|
||||
file_uuid,
|
||||
suggestions: vec![],
|
||||
}));
|
||||
}
|
||||
|
||||
let dim = source_vectors[0].len();
|
||||
let mut centroid = vec![0.0f32; dim];
|
||||
for vec in &source_vectors {
|
||||
for (i, &v) in vec.iter().enumerate() {
|
||||
centroid[i] += v;
|
||||
}
|
||||
}
|
||||
let count = source_vectors.len() as f32;
|
||||
for v in &mut centroid {
|
||||
*v /= count;
|
||||
}
|
||||
|
||||
// 4. Build trace_id → group_name mapping from DB
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let tp_table = schema::table_name("trace_profiles");
|
||||
let db_rows: Vec<(String, i64)> = sqlx::query_as(&format!(
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, (tn.properties->>'trace_id')::bigint as trace_id \
|
||||
FROM {} tn \
|
||||
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
|
||||
AND tp.trace_id = (tn.properties->>'trace_id')::bigint \
|
||||
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'",
|
||||
tkg_table, tp_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[SimilarGroup] DB error: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let mut trace_group: HashMap<i64, String> = HashMap::new();
|
||||
let mut group_traces: HashMap<String, Vec<i64>> = HashMap::new();
|
||||
for (name, trace_id) in &db_rows {
|
||||
if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
|
||||
continue;
|
||||
}
|
||||
trace_group.insert(*trace_id, name.clone());
|
||||
group_traces.entry(name.clone()).or_default().push(*trace_id);
|
||||
}
|
||||
|
||||
let source_group_names: Vec<String> = db_rows
|
||||
.iter()
|
||||
.filter(|(_, tid)| source_trace_ids.contains(tid))
|
||||
.map(|(name, _)| name.clone())
|
||||
.collect();
|
||||
|
||||
// 5. For each non-source trace, compute cosine similarity with centroid
|
||||
// Use the best face per trace for the similarity score
|
||||
let mut trace_scores: Vec<(i64, f64)> = Vec::new();
|
||||
for (&tid, vectors) in &trace_vectors {
|
||||
if source_trace_ids.contains(&tid) {
|
||||
continue;
|
||||
}
|
||||
let best_score: f64 = vectors
|
||||
.iter()
|
||||
.map(|v| cosine_similarity(¢roid, v) as f64)
|
||||
.fold(0.0f64, f64::max);
|
||||
if best_score >= min_score {
|
||||
trace_scores.push((tid, best_score));
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Aggregate by group name, keep best score
|
||||
let mut group_scores: HashMap<String, (f64, i64)> = HashMap::new();
|
||||
for (tid, score) in &trace_scores {
|
||||
if let Some(gname) = trace_group.get(tid) {
|
||||
if source_group_names.contains(gname) {
|
||||
continue;
|
||||
}
|
||||
let entry = group_scores.entry(gname.clone()).or_insert((0.0, *tid));
|
||||
if *score > entry.0 {
|
||||
*entry = (*score, *tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Sort by score descending, take top_k
|
||||
let mut suggestions: Vec<SimilarGroupSuggestion> = group_scores
|
||||
.into_iter()
|
||||
.map(|(group_name, (score, matched_trace_id))| SimilarGroupSuggestion {
|
||||
group_name,
|
||||
score,
|
||||
matched_trace_id: matched_trace_id as i32,
|
||||
})
|
||||
.collect();
|
||||
suggestions.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
|
||||
suggestions.truncate(top_k);
|
||||
|
||||
Ok(Json(SimilarGroupResponse {
|
||||
success: true,
|
||||
file_uuid,
|
||||
suggestions,
|
||||
}))
|
||||
}
|
||||
|
||||
// ─── Routes ───
|
||||
|
||||
pub fn profile_routes() -> axum::Router<AppState> {
|
||||
@@ -629,8 +1275,16 @@ pub fn profile_routes() -> axum::Router<AppState> {
|
||||
"/api/v1/file/:file_uuid/face-groups",
|
||||
get(get_face_groups_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/face-groups/similar",
|
||||
get(get_similar_group_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/groups/merge",
|
||||
post(merge_groups_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/face-operations/undo",
|
||||
post(undo_face_operation_handler),
|
||||
)
|
||||
}
|
||||
|
||||
+69
-13
@@ -64,6 +64,37 @@ struct MergedResult {
|
||||
source: String,
|
||||
}
|
||||
|
||||
/// Parse /ocr, /asr, /asrx suffix from the end of a query string.
|
||||
/// Returns (clean_query, optional_source_filter).
|
||||
/// The filter value is in source_type terms ("ocr" / "asrx") for result filtering,
|
||||
/// not chunk_type terms ("ocr" / "sentence").
|
||||
fn parse_source_filter(query: &str) -> (String, Option<String>) {
|
||||
let trimmed = query.trim();
|
||||
if let Some(rest) = trimmed
|
||||
.strip_suffix("/ocr")
|
||||
.or_else(|| trimmed.strip_suffix("/OCR"))
|
||||
{
|
||||
(rest.trim().to_string(), Some("ocr".to_string()))
|
||||
} else if let Some(rest) = trimmed
|
||||
.strip_suffix("/asr")
|
||||
.or_else(|| trimmed.strip_suffix("/ASR"))
|
||||
.or_else(|| trimmed.strip_suffix("/asrx"))
|
||||
.or_else(|| trimmed.strip_suffix("/ASRX"))
|
||||
{
|
||||
(rest.trim().to_string(), Some("asrx".to_string()))
|
||||
} else {
|
||||
(query.to_string(), None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a source_type filter ("ocr" / "asrx") to chunk_type for DB queries.
|
||||
fn source_filter_to_chunk_type(filter: &str) -> &str {
|
||||
match filter {
|
||||
"ocr" => "ocr",
|
||||
_ => "sentence", // "asrx" → "sentence"
|
||||
}
|
||||
}
|
||||
|
||||
fn map_chunk_type_to_source(chunk_type: &str) -> String {
|
||||
match chunk_type.to_lowercase().as_str() {
|
||||
"ocr" => "ocr".to_string(),
|
||||
@@ -151,9 +182,14 @@ pub async fn smart_search(
|
||||
let hard_limit = req.limit.unwrap_or(usize::MAX);
|
||||
let limit = hard_limit.min(page_size);
|
||||
|
||||
// 1. Generate embedding
|
||||
let (clean_query, source_filter) = parse_source_filter(&req.query);
|
||||
let chunk_type_filter = source_filter
|
||||
.as_deref()
|
||||
.map(source_filter_to_chunk_type);
|
||||
|
||||
// 1. Generate embedding from clean query
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
let embedding = embedder.embed_query(&req.query).await.map_err(
|
||||
let embedding = embedder.embed_query(&clean_query).await.map_err(
|
||||
|e| -> (StatusCode, Json<serde_json::Value>) {
|
||||
tracing::error!("Embedding failed: {}", e);
|
||||
(
|
||||
@@ -199,7 +235,7 @@ pub async fn smart_search(
|
||||
|
||||
// 3. Keyword search via PG ILIKE
|
||||
let keyword_results: Vec<(String, String, f64)> = match db
|
||||
.search_bm25(&req.query, req.file_uuid.as_deref(), fetch_limit as i64)
|
||||
.search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, fetch_limit as i64)
|
||||
.await
|
||||
{
|
||||
Ok(rows) => {
|
||||
@@ -221,14 +257,14 @@ pub async fn smart_search(
|
||||
// 3b. Video title search: if query matches a video title, get its chunks
|
||||
const TITLE_MATCH_SCORE: f64 = 0.75; // Lower than semantic max (0.85-0.9), but higher than keyword
|
||||
let title_results: Vec<(String, String, f64)> = {
|
||||
let clean_query = req.query.replace('\'', "''");
|
||||
let clean_query_escaped = clean_query.replace('\'', "''");
|
||||
let v_table = crate::core::db::schema::table_name("videos");
|
||||
let c_table = crate::core::db::schema::table_name("chunk");
|
||||
let video_rows: Vec<(String,)> = sqlx::query_as(&format!(
|
||||
"SELECT file_uuid::text FROM {} WHERE file_name ILIKE $1 LIMIT 5",
|
||||
v_table
|
||||
))
|
||||
.bind(format!("%{}%", clean_query))
|
||||
.bind(format!("%{}%", clean_query_escaped))
|
||||
.fetch_all(db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
@@ -261,12 +297,12 @@ pub async fn smart_search(
|
||||
// 4. Identity search: if query matches a person name, get their chunks
|
||||
let identity_results: Vec<(String, String, f64)> = {
|
||||
let id_table = crate::core::db::schema::table_name("identities");
|
||||
let clean_query = req.query.replace('\'', "''");
|
||||
let clean_query_escaped = clean_query.replace('\'', "''");
|
||||
let id_rows: Vec<(i32, String, String)> = sqlx::query_as(&format!(
|
||||
"SELECT id, name, uuid::text FROM {} WHERE name ILIKE $1 LIMIT 5",
|
||||
id_table
|
||||
))
|
||||
.bind(format!("%{}%", clean_query))
|
||||
.bind(format!("%{}%", clean_query_escaped))
|
||||
.fetch_all(db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
@@ -407,7 +443,7 @@ pub async fn smart_search(
|
||||
);
|
||||
|
||||
// 6. Enrich top results from PG and build final response
|
||||
let query_lower = req.query.to_lowercase();
|
||||
let query_lower = clean_query.to_lowercase();
|
||||
let mut final_results = Vec::new();
|
||||
// Take all merged results to ensure keyword results are processed
|
||||
// (keyword results often have low scores and rank last)
|
||||
@@ -423,6 +459,14 @@ pub async fn smart_search(
|
||||
.await
|
||||
};
|
||||
if let Some(pg) = pg_opt.ok().flatten() {
|
||||
// Apply source filter (/ocr /asr /asrx)
|
||||
if let Some(ref filter) = source_filter {
|
||||
let st = map_chunk_type_to_source(&pg.chunk_type);
|
||||
if st != *filter {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 關鍵字結果跳過 text_match 過濾(search_bm25 已經匹配過)
|
||||
// Semantic-only results 也跳過 text_match(語意匹配不需要詞彙匹配)
|
||||
let is_keyword_only = mr.keyword_score.is_some() && mr.semantic_score.is_none();
|
||||
@@ -583,9 +627,14 @@ pub async fn keyword_search(
|
||||
let page_size = req.page_size.unwrap_or(5).max(1);
|
||||
let limit = page_size;
|
||||
|
||||
let (clean_query, source_filter) = parse_source_filter(&req.query);
|
||||
let chunk_type_filter = source_filter
|
||||
.as_deref()
|
||||
.map(source_filter_to_chunk_type);
|
||||
|
||||
// Keyword search via PG BM25
|
||||
let keyword_results = db
|
||||
.search_bm25(&req.query, req.file_uuid.as_deref(), limit as i64)
|
||||
.search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, limit as i64)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("Keyword search failed: {}", e);
|
||||
@@ -650,9 +699,11 @@ pub async fn semantic_search(
|
||||
let page_size = req.page_size.unwrap_or(5).max(1);
|
||||
let limit = page_size;
|
||||
|
||||
// Generate embedding
|
||||
let (clean_query, source_filter) = parse_source_filter(&req.query);
|
||||
|
||||
// Generate embedding from clean query
|
||||
let embedder = Embedder::new("embeddinggemma-300m".to_string());
|
||||
let embedding = embedder.embed_query(&req.query).await.map_err(|e| {
|
||||
let embedding = embedder.embed_query(&clean_query).await.map_err(|e| {
|
||||
tracing::error!("Embedding failed: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -660,7 +711,7 @@ pub async fn semantic_search(
|
||||
)
|
||||
})?;
|
||||
|
||||
// Semantic search via Qdrant
|
||||
// Semantic search via Qdrant (only has sentence vectors, so /ocr returns empty)
|
||||
let semantic_results = if let Some(file_uuid) = &req.file_uuid {
|
||||
qdrant
|
||||
.search_in_uuid(&embedding, file_uuid, limit)
|
||||
@@ -673,12 +724,17 @@ pub async fn semantic_search(
|
||||
tracing::info!(
|
||||
"Semantic search: {} hits for '{}'",
|
||||
semantic_results.len(),
|
||||
req.query
|
||||
clean_query
|
||||
);
|
||||
|
||||
let mut results = Vec::new();
|
||||
for hit in semantic_results.iter() {
|
||||
if let Some(p) = enrich_from_pg(db, &hit.uuid, &hit.chunk_id, hit.score).await {
|
||||
if let Some(ref filter) = source_filter {
|
||||
if p.source_type.as_deref() != Some(filter.as_str()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
results.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +97,12 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
let api_state = super::middleware::ApiState { db: db.clone() };
|
||||
|
||||
let qdrant = std::sync::Arc::new(QdrantDb::new());
|
||||
|
||||
// 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,
|
||||
|
||||
+119
-38
@@ -1714,41 +1714,67 @@ async fn delete_trace(
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
|
||||
if hard_delete {
|
||||
// Hard delete: actually remove from Qdrant and TKG
|
||||
// Hard delete: move to _faces_trash, then remove from _faces and TKG
|
||||
let filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": file_uuid}},
|
||||
{"key": "file_uuid", "match": {"value": &file_uuid}},
|
||||
{"key": "trace_id", "match": {"value": trace_id}}
|
||||
]
|
||||
});
|
||||
|
||||
let deleted_count = match qdrant
|
||||
.delete_points_by_filter("_faces", filter.clone())
|
||||
// 0. Scroll points with vectors for trash backup
|
||||
let trashed_points = qdrant
|
||||
.scroll_all_points_with_vectors("_faces", filter.clone(), 1000)
|
||||
.await
|
||||
{
|
||||
Ok(count) => {
|
||||
tracing::info!(
|
||||
"[delete_trace] Hard deleted {} face points from Qdrant for trace {} in {}",
|
||||
count,
|
||||
trace_id,
|
||||
file_uuid
|
||||
);
|
||||
count
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[delete_trace] Failed to delete Qdrant points: {}", e);
|
||||
return Json(serde_json::json!({
|
||||
"success": false,
|
||||
"error": format!("Failed to delete Qdrant points: {}", e)
|
||||
}));
|
||||
}
|
||||
};
|
||||
.unwrap_or_default();
|
||||
|
||||
// 1. Copy to _faces_trash
|
||||
if !trashed_points.is_empty() {
|
||||
let trash_batch: Vec<(u64, Vec<f32>, serde_json::Value)> = trashed_points
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let id = p["id"].as_u64()?;
|
||||
let vec_arr = p["vector"].as_array()?;
|
||||
let vector: Vec<f32> = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
|
||||
let mut payload = p["payload"].clone();
|
||||
if let Some(obj) = payload.as_object_mut() {
|
||||
obj.insert("trashed_at".to_string(), serde_json::json!(chrono::Utc::now().to_rfc3339()));
|
||||
}
|
||||
Some((id, vector, payload))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let ref_batch: Vec<(u64, &[f32], Option<serde_json::Value>)> = trash_batch
|
||||
.iter()
|
||||
.map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone())))
|
||||
.collect();
|
||||
|
||||
if let Err(e) = qdrant.upsert_vectors_batch("_faces_trash", &ref_batch).await {
|
||||
tracing::error!("[delete_trace] Failed to copy to trash: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Save TKG nodes before deleting
|
||||
let nodes_table = crate::core::db::schema::table_name("tkg_nodes");
|
||||
let ext_id_face = format!("face_track_{}", trace_id);
|
||||
let ext_id_trace = format!("trace_{}", trace_id);
|
||||
|
||||
let tkg_result = sqlx::query(&format!(
|
||||
let tkg_snapshot: Vec<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT external_id, label, properties FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
|
||||
nodes_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&ext_id_face)
|
||||
.bind(&ext_id_trace)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
// 3. Delete from _faces
|
||||
let _ = qdrant.delete_points_by_filter("_faces", filter.clone()).await;
|
||||
|
||||
// 4. Delete TKG nodes
|
||||
let _ = sqlx::query(&format!(
|
||||
"DELETE FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
|
||||
nodes_table
|
||||
))
|
||||
@@ -1758,21 +1784,33 @@ async fn delete_trace(
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
let tkg_deleted = match tkg_result {
|
||||
Ok(r) => r.rows_affected(),
|
||||
Err(e) => {
|
||||
tracing::error!("[delete_trace] Failed to delete TKG nodes: {}", e);
|
||||
0
|
||||
}
|
||||
};
|
||||
// 5. Save operation snapshot
|
||||
let op_table = crate::core::db::schema::table_name("trace_operation_history");
|
||||
let before_snapshot = serde_json::json!({
|
||||
"trace_id": trace_id,
|
||||
"tkg_nodes": tkg_snapshot.iter().map(|(ext_id, label, props)| {
|
||||
serde_json::json!({
|
||||
"external_id": ext_id,
|
||||
"label": label,
|
||||
"properties": props,
|
||||
})
|
||||
}).collect::<Vec<_>>(),
|
||||
});
|
||||
let _ = sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, operation, before_snapshot) VALUES ($1, 'hard_delete', $2)",
|
||||
op_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&before_snapshot)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
Json(serde_json::json!({
|
||||
"success": true,
|
||||
"file_uuid": file_uuid,
|
||||
"trace_id": trace_id,
|
||||
"hard_delete": true,
|
||||
"deleted_face_points": deleted_count,
|
||||
"deleted_tkg_nodes": tkg_deleted
|
||||
"trashed_points": trashed_points.len(),
|
||||
}))
|
||||
} else {
|
||||
// Soft delete: mark as deleted in Qdrant and TKG
|
||||
@@ -1860,6 +1898,45 @@ async fn merge_trace(
|
||||
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
|
||||
// Step 0: Snapshot source trace state before merge
|
||||
let src_filter_all = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": &file_uuid}},
|
||||
{"key": "trace_id", "match": {"value": trace_id}}
|
||||
]
|
||||
});
|
||||
let qdrant_points = qdrant
|
||||
.scroll_all_points_with_vectors("_faces", src_filter_all.clone(), 1000)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let nodes_table = crate::core::db::schema::table_name("tkg_nodes");
|
||||
let ext_id_face = format!("face_track_{}", trace_id);
|
||||
let ext_id_trace = format!("trace_{}", trace_id);
|
||||
let tkg_nodes: Vec<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
|
||||
"SELECT external_id, label, properties FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
|
||||
nodes_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&ext_id_face)
|
||||
.bind(&ext_id_trace)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let before_snapshot = serde_json::json!({
|
||||
"source_trace_id": trace_id,
|
||||
"target_trace_id": target_trace_id,
|
||||
"qdrant_points": qdrant_points,
|
||||
"tkg_nodes": tkg_nodes.iter().map(|(ext_id, label, props)| {
|
||||
serde_json::json!({
|
||||
"external_id": ext_id,
|
||||
"label": label,
|
||||
"properties": props,
|
||||
})
|
||||
}).collect::<Vec<_>>(),
|
||||
});
|
||||
|
||||
// Step 1: Update all face points from source trace to target trace
|
||||
let src_filter = serde_json::json!({
|
||||
"must": [
|
||||
@@ -1895,10 +1972,6 @@ async fn merge_trace(
|
||||
};
|
||||
|
||||
// Step 2: Delete source TKG nodes
|
||||
let nodes_table = crate::core::db::schema::table_name("tkg_nodes");
|
||||
let ext_id_face = format!("face_track_{}", trace_id);
|
||||
let ext_id_trace = format!("trace_{}", trace_id);
|
||||
|
||||
let tkg_result = sqlx::query(&format!(
|
||||
"DELETE FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
|
||||
nodes_table
|
||||
@@ -1917,8 +1990,16 @@ async fn merge_trace(
|
||||
}
|
||||
};
|
||||
|
||||
// Step 3: Rebuild TKG for the target trace
|
||||
// (The TKG rebuild will pick up the merged points automatically)
|
||||
// Step 3: Save operation snapshot for undo
|
||||
let op_table = crate::core::db::schema::table_name("trace_operation_history");
|
||||
let _ = sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, operation, before_snapshot) VALUES ($1, 'merge_trace', $2)",
|
||||
op_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&before_snapshot)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
Json(serde_json::json!({
|
||||
"success": true,
|
||||
|
||||
Reference in New Issue
Block a user