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:
+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),
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user