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
+139 -269
View File
@@ -88,13 +88,15 @@ pub enum SearchResult {
#[serde(rename = "person")]
Person {
file_uuid: Option<String>,
identity_id: i32,
identity_uuid: String,
trace_id: i32,
external_id: String,
name: Option<String>,
appearance_count: i32,
frame_count: Option<i32>,
score: f64,
first_appearance_time: Option<f64>,
last_appearance_time: Option<f64>,
start_time: Option<f64>,
end_time: Option<f64>,
key_frame: Option<String>,
key_face: Option<String>,
},
}
@@ -102,6 +104,7 @@ pub fn universal_search_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v1/search/universal", post(universal_search))
.route("/api/v1/search/frames", post(search_frames))
.route("/api/v1/search/people", get(search_people))
}
/// Unified search across all data types
@@ -154,10 +157,10 @@ pub async fn universal_search(
results.extend(frame_results);
}
// Search persons
if types.contains(&"person".to_string()) {
let person_results = search_persons_internal(&db, &req).await.unwrap_or_default();
results.extend(person_results);
// Search people
if types.contains(&"people".to_string()) || types.is_empty() {
let people_results = search_persons_internal(&db, &req).await.unwrap_or_default();
results.extend(people_results);
}
// Deduplicate by chunk_id / frame_number / person_id
@@ -168,7 +171,7 @@ pub async fn universal_search(
results.retain(|r| match r {
SearchResult::Chunk { chunk_id, .. } => seen_chunks.insert(chunk_id.clone()),
SearchResult::Frame { frame_number, .. } => seen_frames.insert(*frame_number),
SearchResult::Person { identity_id, .. } => seen_persons.insert(*identity_id),
SearchResult::Person { trace_id, .. } => seen_persons.insert(*trace_id),
});
}
@@ -236,11 +239,11 @@ pub async fn search_frames(
}))
}
/// Search persons by name or speaker_id
pub async fn search_persons(
/// Search people by name from trace_profiles (named face tracks)
pub async fn search_people(
State(_state): State<crate::api::types::AppState>,
Query(query): Query<PersonSearchQuery>,
) -> Result<Json<PersonSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
Query(query): Query<PeopleSearchQuery>,
) -> Result<Json<PeopleSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
let db = PostgresDb::init().await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
@@ -249,7 +252,7 @@ pub async fn search_persons(
})?;
let limit = query.limit.unwrap_or(20);
let persons = search_persons_by_query(
let people = search_people_by_query(
&db,
&query.file_uuid,
&query.query,
@@ -264,10 +267,10 @@ pub async fn search_persons(
)
})?;
let persons_count = persons.len();
Ok(Json(PersonSearchResponse {
persons,
total: persons_count,
let total = people.len();
Ok(Json(PeopleSearchResponse {
people,
total,
}))
}
@@ -301,27 +304,34 @@ pub struct FrameResult {
}
#[derive(Debug, Deserialize)]
pub struct PersonSearchQuery {
pub file_uuid: String,
pub struct PeopleSearchQuery {
pub file_uuid: Option<String>,
pub query: Option<String>,
pub min_appearances: Option<i32>,
pub limit: Option<usize>,
}
#[derive(Debug, Serialize)]
pub struct PersonSearchResponse {
pub persons: Vec<PersonResult>,
pub struct PeopleSearchResponse {
pub people: Vec<PeopleResult>,
pub total: usize,
}
#[derive(Debug, Serialize)]
pub struct PersonResult {
pub identity_id: i32,
pub identity_uuid: String,
pub struct PeopleResult {
pub file_uuid: String,
pub file_name: String,
pub trace_id: i32,
pub external_id: Option<String>,
pub name: Option<String>,
pub appearance_count: i32,
pub first_appearance_time: Option<f64>,
pub last_appearance_time: Option<f64>,
pub start_frame: Option<i64>,
pub end_frame: Option<i64>,
pub frame_count: Option<i32>,
pub start_time: Option<f64>,
pub end_time: Option<f64>,
pub key_frame: Option<String>,
pub key_face: Option<String>,
pub avg_confidence: Option<f64>,
}
async fn search_chunks(
@@ -590,162 +600,65 @@ async fn search_persons_internal(
db: &PostgresDb,
req: &UniversalSearchRequest,
) -> Result<Vec<SearchResult>, anyhow::Error> {
let id_table = schema::table_name("identities");
let tp_table = schema::table_name("trace_profiles");
let nodes_table = schema::table_name("tkg_nodes");
// Query matching identities from PostgreSQL
let mut id_sql = format!(
"SELECT id, uuid::text, name FROM {} WHERE name IS NOT NULL",
id_table
let mut 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 != ''",
tp_table, nodes_table
);
if !req.query.is_empty() {
let q = req.query.replace('\'', "''");
id_sql.push_str(&format!(" AND name ILIKE '%{}%'", q));
sql.push_str(&format!(
" AND (tp.name ILIKE '%{0}%' \
OR tp.vlm_description ILIKE '%{0}%' \
OR tp.vlm_clothing ILIKE '%{0}%' \
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE tag ILIKE '%{0}%') \
OR tp.vlm_location ILIKE '%{0}%' \
OR tp.vlm_setting ILIKE '%{0}%')",
q
));
}
id_sql.push_str(" ORDER BY name ASC");
let identities: Vec<(i32, String, Option<String>)> =
sqlx::query_as(&id_sql).fetch_all(db.pool()).await?;
if identities.is_empty() {
return Ok(Vec::new());
if let Some(ref fuuid) = req.file_uuid {
let safe = fuuid.replace('\'', "''");
sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe));
}
sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", req.page_size.unwrap_or(20)));
// For each identity, scroll _faces points from Qdrant and aggregate per file
let qdrant = QdrantDb::new();
let limit = req.page_size.unwrap_or(20);
let rows: Vec<(String, i32, Option<String>, Option<i64>, Option<i64>, Option<i32>,
Option<String>, Option<String>, Option<f64>, Option<String>)> =
sqlx::query_as(&sql).fetch_all(db.pool()).await?;
// Aggregate frame ranges per (identity_id, file_uuid)
use std::collections::HashMap;
let mut agg: HashMap<(i32, String), (i64, i64, i64)> = HashMap::new(); // (id, fu) -> (count, min_frame, max_frame)
for (id, _uuid, _name) in &identities {
let scroll_filter = serde_json::json!({
"must": [
{"key": "identity_id", "match": {"value": id}}
]
});
let points = match qdrant
.scroll_all_points("_faces", scroll_filter, 1000)
.await
{
Ok(p) => p,
Err(e) => {
tracing::warn!("Qdrant scroll failed for identity {}: {}", id, e);
continue;
}
};
for point in &points {
let payload = &point["payload"];
let file_uuid = match payload["file_uuid"].as_str() {
Some(f) => f.to_string(),
None => continue,
};
// Apply file_uuid filter if specified
if let Some(ref filter_fu) = req.file_uuid {
if &file_uuid != filter_fu {
continue;
}
}
let frame = payload["frame"].as_i64().unwrap_or(0);
let entry = agg
.entry((*id, file_uuid))
.or_insert((0, i64::MAX, i64::MIN));
entry.0 += 1;
if frame < entry.1 {
entry.1 = frame;
}
if frame > entry.2 {
entry.2 = frame;
}
}
}
// Cache FPS per file_uuid for frame→second conversion
use std::collections::HashSet;
let file_uuids: HashSet<&str> = agg.keys().map(|(_, fu)| fu.as_str()).collect();
let video_table = crate::core::db::schema::table_name("videos");
let mut fps_cache: HashMap<String, f64> = HashMap::new();
for fu in file_uuids {
let fps: f64 = sqlx::query_scalar(&format!(
"SELECT COALESCE(fps, 30.0) FROM {} WHERE file_uuid = $1",
video_table
))
.bind(fu)
.fetch_optional(db.pool())
.await?
.unwrap_or(30.0);
fps_cache.insert(fu.to_string(), fps);
}
// Build results
let q_lower = req.query.to_lowercase();
let mut results: Vec<SearchResult> = identities
.iter()
.flat_map(|(id, uuid, name)| {
let name_str = name.as_deref().unwrap_or("");
let name_match = !req.query.is_empty() && name_str.to_lowercase().contains(&q_lower);
let score = if name_match { 0.95 } else { 0.5 };
// Yield entries for this identity's files
let files: Vec<String> = agg
.keys()
.filter(|(iid, _)| iid == id)
.map(|(_, fu)| fu.clone())
.collect();
if files.is_empty() {
vec![]
} else {
files
.into_iter()
.map(|fu| {
let (count, min_fr, max_fr) = agg[&(*id, fu.clone())];
let fps = fps_cache.get(&fu).copied().unwrap_or(30.0);
let first = if min_fr == i64::MAX {
None
} else {
Some(min_fr as f64 / fps)
};
let last = if max_fr == i64::MIN {
None
} else {
Some(max_fr as f64 / fps)
};
SearchResult::Person {
file_uuid: Some(fu),
identity_id: *id,
identity_uuid: uuid.clone(),
name: name.clone(),
appearance_count: count as i32,
score,
first_appearance_time: first,
last_appearance_time: last,
}
})
.collect::<Vec<_>>()
}
})
.collect();
let mut results: Vec<SearchResult> = Vec::new();
for (fuuid, trace_id, name, start_frame, end_frame, frame_count,
key_frame, key_face, avg_confidence, external_id) in rows
{
let name_match = !req.query.is_empty()
&& name.as_deref().map(|n| n.to_lowercase().contains(&q_lower)).unwrap_or(false);
let score = if name_match { 0.95 } else { 0.5 };
// Sort by appearance_count descending, then limit
results.sort_by(|a, b| {
let a_count = match a {
SearchResult::Person {
appearance_count, ..
} => *appearance_count,
_ => 0,
};
let b_count = match b {
SearchResult::Person {
appearance_count, ..
} => *appearance_count,
_ => 0,
};
b_count.cmp(&a_count)
});
results.truncate(limit);
results.push(SearchResult::Person {
file_uuid: Some(fuuid),
trace_id,
external_id: external_id.unwrap_or_else(|| format!("trace_{}", trace_id)),
name,
frame_count,
score,
start_time: None,
end_time: None,
key_frame,
key_face,
});
}
Ok(results)
}
@@ -831,114 +744,71 @@ async fn search_frames_internal_v2(
Ok(results)
}
async fn search_persons_by_query(
async fn search_people_by_query(
db: &PostgresDb,
file_uuid: &str,
file_uuid: &Option<String>,
query: &Option<String>,
min_appearances: Option<i32>,
_min_appearances: Option<i32>,
limit: usize,
) -> Result<Vec<PersonResult>, anyhow::Error> {
let id_table = schema::table_name("identities");
) -> Result<Vec<PeopleResult>, anyhow::Error> {
let tp_table = schema::table_name("trace_profiles");
let nodes_table = schema::table_name("tkg_nodes");
// Query matching identities from PostgreSQL
let mut id_sql = format!(
"SELECT id, uuid::text, name FROM {} WHERE name IS NOT NULL",
id_table
let mut 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 != ''",
tp_table, nodes_table
);
if let Some(q) = query {
let safe = q.replace('\'', "''");
id_sql.push_str(&format!(" AND name ILIKE '%{}%'", safe));
sql.push_str(&format!(
" AND (tp.name ILIKE '%{0}%' \
OR tp.vlm_description ILIKE '%{0}%' \
OR tp.vlm_clothing ILIKE '%{0}%' \
OR EXISTS (SELECT 1 FROM unnest(tp.vlm_tags) tag WHERE tag ILIKE '%{0}%') \
OR tp.vlm_location ILIKE '%{0}%' \
OR tp.vlm_setting ILIKE '%{0}%')",
safe
));
}
id_sql.push_str(" ORDER BY name ASC");
let identities: Vec<(i32, String, Option<String>)> =
sqlx::query_as(&id_sql).fetch_all(db.pool()).await?;
if identities.is_empty() {
return Ok(Vec::new());
if let Some(fuuid) = file_uuid {
let safe = fuuid.replace('\'', "''");
sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe));
}
sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", limit));
// For each identity, scroll _faces points from Qdrant and aggregate
let qdrant = QdrantDb::new();
let mut results: Vec<PersonResult> = Vec::new();
let rows: Vec<(String, i32, Option<String>, Option<i64>, Option<i64>, Option<i32>,
Option<String>, Option<String>, Option<f64>, Option<String>)> =
sqlx::query_as(&sql).fetch_all(db.pool()).await?;
for (id, uuid, name) in &identities {
let scroll_filter = serde_json::json!({
"must": [
{"key": "identity_id", "match": {"value": id}},
{"key": "file_uuid", "match": {"value": file_uuid}}
]
});
let points = match qdrant
.scroll_all_points("_faces", scroll_filter, 1000)
.await
{
Ok(p) => p,
Err(e) => {
tracing::warn!("Qdrant scroll failed for identity {}: {}", id, e);
continue;
}
};
if points.is_empty() {
continue;
}
let count = points.len() as i64;
if let Some(min) = min_appearances {
if (count as i32) < min {
continue;
}
}
let min_frame = points
.iter()
.filter_map(|p| p["payload"]["frame"].as_i64())
.min()
.unwrap_or(0);
let max_frame = points
.iter()
.filter_map(|p| p["payload"]["frame"].as_i64())
.max()
.unwrap_or(0);
// Look up FPS for this file
let video_table = crate::core::db::schema::table_name("videos");
let fps: f64 = sqlx::query_scalar(&format!(
"SELECT COALESCE(fps, 30.0) FROM {} WHERE file_uuid = $1",
video_table
))
.bind(file_uuid)
.fetch_optional(db.pool())
.await?
.unwrap_or(30.0);
let first_time = if fps > 0.0 {
Some(min_frame as f64 / fps)
} else {
None
};
let last_time = if fps > 0.0 {
Some(max_frame as f64 / fps)
} else {
None
};
results.push(PersonResult {
identity_id: *id,
identity_uuid: uuid.clone(),
name: name.clone(),
appearance_count: count as i32,
first_appearance_time: first_time,
last_appearance_time: last_time,
let mut results: Vec<PeopleResult> = Vec::new();
for (fuuid, trace_id, name, start_frame, end_frame, frame_count,
key_frame, key_face, avg_confidence, external_id) in rows
{
results.push(PeopleResult {
file_uuid: fuuid,
file_name: String::new(),
trace_id,
external_id,
name,
start_frame,
end_frame,
frame_count,
start_time: None,
end_time: None,
key_frame,
key_face,
avg_confidence,
});
}
// Sort by appearance_count descending, then limit
results.sort_by(|a, b| b.appearance_count.cmp(&a.appearance_count));
results.truncate(limit);
Ok(results)
}