fix: face group name read consistency, sync_file_status fix, cleanup ghost records, identity_agent replaced with face_dedup

- get_face_groups_handler: COALESCE(tp.name, tn.label) for name consistency
- sync_file_status: compare JSON vs pre_chunks (not chunk table)
- face consistency: compare frames.len() not total_faces
- cleanup 2 ghost records with NULL file_name/file_path
- replace identity_agent with face_dedup in pipeline stages
- remove identity_agent_api.rs and all references
- update required_processors to match actual processors
- update AGENTS.md with team responsibilities
- add Studio pipeline changes documentation
This commit is contained in:
Accusys
2026-07-27 02:15:51 +08:00
parent fcdeab82e6
commit 39a2cbc65b
118 changed files with 19386 additions and 2964 deletions
+437 -88
View File
@@ -4,6 +4,7 @@ use std::time::Duration;
use crate::core::db::qdrant_db::QdrantDb;
use crate::core::db::schema;
use crate::core::embedding::Embedder;
use crate::core::llm::function_calling::call_llm_vision;
use crate::core::processor::tkg::query_auto_representative_frame;
@@ -54,7 +55,12 @@ pub async fn exec_find_file(
let mut files = Vec::new();
for (u, n) in rows {
let has_data = has_faces_in_qdrant(&u).await;
files.push(serde_json::json!({"file_uuid": u, "file_name": n, "has_data": has_data}));
files.push(serde_json::json!({
"card_type": "file",
"file_uuid": u,
"file_name": n,
"has_data": has_data
}));
}
Ok(serde_json::json!({"found": true, "files": files}).to_string())
}
@@ -551,104 +557,117 @@ pub async fn exec_smart_search(
args: &serde_json::Value,
) -> Result<String, String> {
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
let file_uuid = args.get("file_uuid").and_then(|v| v.as_str());
let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(5);
let file_uuid = args
.get("file_uuid")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(5) as i64;
tracing::info!("[smart_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
let chunk_table = schema::table_name("chunk");
let videos = schema::table_name("videos");
let mut sql = format!(
"SELECT chunk_id, text_content, start_frame, end_frame, chunk_type, content \
FROM {} WHERE text_content ILIKE $1",
chunk_table
"SELECT c.chunk_id, c.text_content, c.start_frame, c.end_frame, c.chunk_type, c.content, \
c.file_uuid, v.file_name, COALESCE(v.fps, 25.0) as fps \
FROM {} c \
LEFT JOIN {} v ON v.file_uuid = c.file_uuid \
WHERE c.text_content ILIKE $1",
chunk_table, videos
);
if file_uuid.is_some() {
sql.push_str(" AND file_uuid = $2");
sql.push_str(" AND c.file_uuid = $2");
}
sql.push_str(&format!(" ORDER BY start_frame LIMIT {}", limit));
sql.push_str(&format!(" ORDER BY c.start_frame LIMIT {}", limit));
if let Some(fuid) = file_uuid {
let like = format!("%{}%", query);
let rows: Vec<(String, Option<String>, i64, i64, String, Option<serde_json::Value>)> = sqlx::query_as(&sql)
let like = format!("%{}%", query);
tracing::info!("[smart_search] SQL: {}, like: {}", sql, like);
let rows: Vec<(
String,
Option<String>,
i64,
i64,
String,
Option<serde_json::Value>,
String,
String,
f64,
)> = if let Some(fuid) = file_uuid {
sqlx::query_as(&sql)
.bind(&like)
.bind(fuid)
.fetch_all(pool)
.await
.map_err(|e| e.to_string())?;
let results: Vec<Vec<serde_json::Value>> = rows.into_iter().map(|(chunk_id, text_content, start_frame, end_frame, chunk_type, content)| {
let source_prefix = if let Some(ref content) = content {
let text = content.get("text").and_then(|t| t.as_str()).unwrap_or("");
let ocr_text = content.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
let has_asrx = !text.trim().is_empty();
let has_ocr = !ocr_text.trim().is_empty();
if has_asrx && has_ocr {
"[ASRX+OCR] "
} else if has_asrx {
"[ASRX] "
} else if has_ocr {
"[OCR] "
} else {
""
}
} else {
""
};
let prefixed_text = text_content.map(|t| format!("{}{}", source_prefix, t));
vec![
serde_json::json!(chunk_id),
serde_json::json!(prefixed_text),
serde_json::json!(start_frame),
serde_json::json!(end_frame),
serde_json::json!(chunk_type),
]
}).collect();
Ok(serde_json::json!({"results": results}).to_string())
.map_err(|e| {
tracing::error!("[smart_search] Query failed: {}", e);
e.to_string()
})?
} else {
let like = format!("%{}%", query);
let rows: Vec<(String, Option<String>, i64, i64, String, Option<serde_json::Value>)> = sqlx::query_as(&sql)
sqlx::query_as(&sql)
.bind(&like)
.fetch_all(pool)
.await
.map_err(|e| e.to_string())?;
let results: Vec<Vec<serde_json::Value>> = rows.into_iter().map(|(chunk_id, text_content, start_frame, end_frame, chunk_type, content)| {
let source_prefix = if let Some(ref content) = content {
let text = content.get("text").and_then(|t| t.as_str()).unwrap_or("");
let ocr_text = content.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
let has_asrx = !text.trim().is_empty();
let has_ocr = !ocr_text.trim().is_empty();
if has_asrx && has_ocr {
"[ASRX+OCR] "
} else if has_asrx {
"[ASRX] "
} else if has_ocr {
"[OCR] "
.map_err(|e| {
tracing::error!("[smart_search] Query failed: {}", e);
e.to_string()
})?
};
tracing::info!("[smart_search] Found {} rows", rows.len());
let cards: Vec<serde_json::Value> = rows
.into_iter()
.map(
|(chunk_id, text_content, start_frame, end_frame, chunk_type, content, fuuid, file_name, fps)| {
let source = if let Some(ref c) = content {
let text = c.get("text").and_then(|t| t.as_str()).unwrap_or("");
let ocr_text = c.get("ocr_text").and_then(|t| t.as_str()).unwrap_or("");
if !text.trim().is_empty() && !ocr_text.trim().is_empty() {
"asrx+ocr"
} else if !text.trim().is_empty() {
"asrx"
} else if !ocr_text.trim().is_empty() {
"ocr"
} else {
"unknown"
}
} else {
""
}
} else {
""
};
let prefixed_text = text_content.map(|t| format!("{}{}", source_prefix, t));
vec![
serde_json::json!(chunk_id),
serde_json::json!(prefixed_text),
serde_json::json!(start_frame),
serde_json::json!(end_frame),
serde_json::json!(chunk_type),
]
}).collect();
Ok(serde_json::json!({"results": results}).to_string())
}
"unknown"
};
let text_preview = text_content
.as_ref()
.map(|t| t.chars().take(150).collect::<String>())
.unwrap_or_default();
let start_time = if fps > 0.0 { start_frame as f64 / fps } else { 0.0 };
let end_time = if fps > 0.0 { end_frame as f64 / fps } else { 0.0 };
serde_json::json!({
"card_type": "chunk",
"file_uuid": fuuid,
"chunk_id": chunk_id,
"chunk_type": chunk_type,
"file_name": file_name,
"start_time": start_time,
"end_time": end_time,
"start_frame": start_frame,
"end_frame": end_frame,
"score": 1.0,
"text_preview": text_preview,
"source": source
})
},
)
.collect();
Ok(serde_json::json!({
"tool": "smart_search",
"query": query,
"count": cards.len(),
"cards": cards
}).to_string())
}
pub async fn exec_identity_text(
@@ -1268,14 +1287,16 @@ pub async fn exec_vlm_describe(
return Ok(serde_json::json!({"error": "file_uuid is required"}).to_string());
}
if trace_id <= 0 {
return Ok(serde_json::json!({"error": "trace_id is required and must be > 0"}).to_string());
return Ok(
serde_json::json!({"error": "trace_id is required and must be > 0"}).to_string(),
);
}
let crop_path = face_crop_path(file_uuid, trace_id)
.ok_or_else(|| format!("No face crop found for {} trace {}", file_uuid, trace_id))?;
let jpeg_bytes = std::fs::read(&crop_path)
.map_err(|e| format!("Failed to read face crop: {}", e))?;
let jpeg_bytes =
std::fs::read(&crop_path).map_err(|e| format!("Failed to read face crop: {}", e))?;
let videos = schema::table_name("videos");
let fps: f64 = sqlx::query_scalar(&format!(
@@ -1297,8 +1318,8 @@ pub async fn exec_vlm_describe(
let base64_img = BASE64.encode(&jpeg_bytes);
let ollama_url = std::env::var("OLLAMA_URL")
.unwrap_or_else(|_| "http://localhost:11434".to_string());
let ollama_url =
std::env::var("OLLAMA_URL").unwrap_or_else(|_| "http://localhost:11434".to_string());
let model = std::env::var("VLM_MODEL").unwrap_or_else(|_| "llava".to_string());
let body = serde_json::json!({
@@ -1346,3 +1367,331 @@ pub async fn exec_vlm_describe(
})
.to_string())
}
/// Search trace profiles by VLM fields (description, clothing, tags, location, setting, name)
/// Returns top N matching traces as cards with file_uuid, trace_id, name, frame_range, VLM data
pub async fn exec_trace_search(
pool: &sqlx::PgPool,
args: &serde_json::Value,
) -> Result<String, String> {
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
let file_uuid = args.get("file_uuid").and_then(|v| v.as_str());
let limit = args
.get("limit")
.and_then(|v| v.as_i64())
.unwrap_or(10)
.min(50) as i32;
if query.is_empty() {
return Err("query is required".to_string());
}
let table = schema::table_name("trace_profiles");
let videos = schema::table_name("videos");
let like_q = format!("%{}%", query.to_lowercase().replace('%', "%%"));
let sql = format!(
"SELECT tp.file_uuid, tp.trace_id, tp.name, tp.start_frame, tp.end_frame, \
tp.frame_count, tp.key_frame, tp.status, tp.avg_confidence, \
tp.vlm_description, tp.vlm_clothing, tp.vlm_tags, tp.vlm_location, \
tp.vlm_setting, tp.vlm_lighting, COALESCE(v.file_name, ''), COALESCE(v.fps, 25.0) \
FROM {} tp \
LEFT JOIN {} v ON v.file_uuid = tp.file_uuid \
WHERE ($1::text IS NULL OR tp.file_uuid = $1) \
AND (LOWER(tp.name) LIKE $2 \
OR LOWER(tp.vlm_description) LIKE $2 \
OR LOWER(tp.vlm_clothing) LIKE $2 \
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE LOWER(tag) LIKE $2) \
OR LOWER(tp.vlm_location) LIKE $2 \
OR LOWER(tp.vlm_setting) LIKE $2 \
OR LOWER(tp.vlm_background) LIKE $2) \
ORDER BY tp.frame_count DESC \
LIMIT $3",
table, videos
);
let rows = sqlx::query(&sql)
.bind(file_uuid)
.bind(&like_q)
.bind(limit)
.fetch_all(pool)
.await
.map_err(|e| format!("DB query failed: {}", e))?;
let cards: Vec<serde_json::Value> = rows
.iter()
.map(|row| {
use sqlx::Row;
let file_uuid: String = row.get(0);
let trace_id: i32 = row.get(1);
let name: Option<String> = row.get(2);
let start_frame: Option<i64> = row.get(3);
let end_frame: Option<i64> = row.get(4);
let frame_count: Option<i32> = row.get(5);
let key_frame: Option<String> = row.get(6);
let status: Option<String> = row.get(7);
let avg_confidence: Option<f64> = row.get(8);
let vlm_description: Option<String> = row.get(9);
let vlm_clothing: Option<String> = row.get(10);
let vlm_tags: Option<Vec<String>> = row.get(11);
let vlm_location: Option<String> = row.get(12);
let vlm_setting: Option<String> = row.get(13);
let vlm_lighting: Option<String> = row.get(14);
let file_name: String = row.get(15);
let fps: f64 = row.get(16);
let start_time = start_frame.map(|f| (f as f64 / fps).round() / 100.0);
let end_time = end_frame.map(|f| (f as f64 / fps).round() / 100.0);
serde_json::json!({
"card_type": "face",
"file_uuid": file_uuid,
"trace_id": trace_id,
"name": name,
"file_name": file_name,
"start_frame": start_frame,
"end_frame": end_frame,
"start_time": start_time,
"end_time": end_time,
"frame_count": frame_count,
"key_frame": key_frame,
"status": status,
"avg_confidence": avg_confidence,
"vlm_description": vlm_description,
"vlm_clothing": vlm_clothing,
"vlm_tags": vlm_tags,
"vlm_location": vlm_location,
"vlm_setting": vlm_setting,
"vlm_lighting": vlm_lighting
})
})
.collect();
Ok(
serde_json::json!({
"tool": "trace_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string(),
)
}
/// Semantic search using embedding + Qdrant
/// Returns top N chunk results with video segment info
pub async fn exec_semantic_search(
pool: &sqlx::PgPool,
args: &serde_json::Value,
) -> Result<String, String> {
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
let file_uuid = args
.get("file_uuid")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
let limit = args
.get("limit")
.and_then(|v| v.as_i64())
.unwrap_or(10)
.min(50) as usize;
tracing::info!("[exec_semantic_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
if query.is_empty() {
return Err("query is required".to_string());
}
// Generate embedding
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let embedding = embedder
.embed_query(query)
.await
.map_err(|e| {
tracing::error!("[exec_semantic_search] Embedding failed: {}", e);
format!("Embedding failed: {}", e)
})?;
tracing::info!("[exec_semantic_search] Embedding generated, dim={}", embedding.len());
// Search Qdrant
let qdrant = QdrantDb::new();
let search_results = if let Some(fuuid) = file_uuid {
tracing::info!("[exec_semantic_search] Searching in uuid: {}", fuuid);
qdrant
.search_in_uuid(&embedding, fuuid, limit)
.await
.map_err(|e| {
tracing::error!("[exec_semantic_search] Qdrant search_in_uuid failed: {}", e);
format!("Qdrant search failed: {}", e)
})?
} else {
tracing::info!("[exec_semantic_search] Searching all collections");
qdrant
.search(&embedding, limit)
.await
.map_err(|e| {
tracing::error!("[exec_semantic_search] Qdrant search failed: {}", e);
format!("Qdrant search failed: {}", e)
})?
};
tracing::info!("[exec_semantic_search] Qdrant returned {} hits", search_results.len());
// Enrich from PostgreSQL
let chunk_table = schema::table_name("chunk");
let videos = schema::table_name("videos");
let mut cards = Vec::new();
for hit in search_results.iter() {
let row: Option<(
String,
String,
f64,
f64,
f64,
Option<String>,
String,
)> = sqlx::query_as(&format!(
"SELECT c.chunk_id, c.chunk_type, c.start_time, c.end_time, c.fps, \
c.text_content, v.file_name \
FROM {} c \
JOIN {} v ON v.file_uuid = c.file_uuid \
WHERE c.file_uuid = $1 AND c.chunk_id = $2",
chunk_table, videos
))
.bind(&hit.uuid)
.bind(&hit.chunk_id)
.fetch_optional(pool)
.await
.map_err(|e| format!("PG query failed: {}", e))?;
if let Some((chunk_id, chunk_type, start_time, end_time, fps, text_content, file_name)) = row {
let start_frame = (start_time * fps) as i64;
let end_frame = (end_time * fps) as i64;
let text_preview = text_content
.as_ref()
.map(|t| t.chars().take(150).collect::<String>())
.unwrap_or_default();
cards.push(serde_json::json!({
"card_type": "chunk",
"file_uuid": hit.uuid,
"chunk_id": chunk_id,
"chunk_type": chunk_type,
"file_name": file_name,
"start_time": start_time,
"end_time": end_time,
"start_frame": start_frame,
"end_frame": end_frame,
"score": hit.score,
"text_preview": text_preview,
"source": chunk_type
}));
}
}
Ok(
serde_json::json!({
"tool": "semantic_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string(),
)
}
/// Search named face profiles by name — finds face_track TKG nodes whose label
/// matches the given name, joined with trace_profiles for frame/key-image info.
/// Returns cards with key_frame, key_face, frame_range, and time_range.
pub async fn exec_face_profile_search(
pool: &sqlx::PgPool,
args: &serde_json::Value,
) -> Result<String, String> {
let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("");
let file_uuid = args.get("file_uuid").and_then(|v| v.as_str());
let limit = args
.get("limit")
.and_then(|v| v.as_i64())
.unwrap_or(10)
.min(50) as i32;
if name.is_empty() {
return Err("name is required".to_string());
}
let tp_table = schema::table_name("trace_profiles");
let nodes_table = schema::table_name("tkg_nodes");
let like_q = format!("%{}%", name.replace('%', "%%"));
let sql = format!(
"SELECT tp.file_uuid, tp.trace_id, tp.name, \
tp.start_frame, tp.end_frame, tp.frame_count, \
tp.key_frame, tp.key_face, tp.avg_confidence, \
n.external_id \
FROM {} tp \
LEFT JOIN {} n ON n.file_uuid = tp.file_uuid \
AND n.node_type = 'face_track' \
AND REPLACE(n.external_id, 'trace_', '')::int = tp.trace_id \
WHERE tp.name IS NOT NULL AND tp.name != '' \
AND (tp.name ILIKE $1 \
OR tp.vlm_description ILIKE $1 \
OR tp.vlm_clothing ILIKE $1 \
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE tag ILIKE $1) \
OR tp.vlm_location ILIKE $1 \
OR tp.vlm_setting ILIKE $1) \
AND ($2::text IS NULL OR tp.file_uuid = $2) \
ORDER BY tp.frame_count DESC NULLS LAST \
LIMIT $3",
tp_table, nodes_table
);
let rows = sqlx::query(&sql)
.bind(&like_q)
.bind(file_uuid)
.bind(limit)
.fetch_all(pool)
.await
.map_err(|e| format!("DB query failed: {}", e))?;
let cards: Vec<serde_json::Value> = rows
.iter()
.map(|row| {
use sqlx::Row;
let file_uuid: String = row.get(0);
let trace_id: i32 = row.get(1);
let name: Option<String> = row.get(2);
let start_frame: Option<i64> = row.get(3);
let end_frame: Option<i64> = row.get(4);
let frame_count: Option<i32> = row.get(5);
let key_frame: Option<String> = row.get(6);
let key_face: Option<String> = row.get(7);
let avg_confidence: Option<f64> = row.get(8);
let external_id: Option<String> = row.get(9);
serde_json::json!({
"card_type": "face_profile",
"file_uuid": file_uuid,
"trace_id": trace_id,
"external_id": external_id.unwrap_or_else(|| format!("trace_{}", trace_id)),
"name": name,
"start_frame": start_frame,
"end_frame": end_frame,
"frame_count": frame_count,
"key_frame": key_frame,
"key_face": key_face,
"avg_confidence": avg_confidence
})
})
.collect();
Ok(
serde_json::json!({
"tool": "face_profile_search",
"query": name,
"count": cards.len(),
"cards": cards
})
.to_string(),
)
}