feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering

This commit is contained in:
Accusys
2026-11-02 14:34:02 +08:00
parent 2fca49b120
commit 5d18183d82
566 changed files with 321788 additions and 1662 deletions
+3
View File
@@ -622,6 +622,9 @@ impl AdminConfigManager {
if let Some(search) = partial.search {
config.search = search;
}
if let Some(pipeline) = partial.pipeline {
config.pipeline = pipeline;
}
config.updated_at = chrono::Utc::now().to_rfc3339();
config.updated_by = "admin".to_string();
+1 -1
View File
@@ -685,7 +685,7 @@ impl ProcessorType {
ProcessorType::Pose => vec![ProcessorType::Face],
ProcessorType::Appearance => vec![ProcessorType::Pose],
ProcessorType::FaceTrace => vec![ProcessorType::Face],
ProcessorType::FaceCluster => vec![ProcessorType::FaceTrace],
ProcessorType::FaceCluster => vec![ProcessorType::Tkg],
ProcessorType::Tkg => vec![ProcessorType::FaceTrace],
_ => vec![],
}
+36 -23
View File
@@ -432,6 +432,10 @@ impl RedisClient {
fields.push(("error", err.to_string()));
}
// Set TTL for job key (24 hours)
let _: bool = conn.expire(&key, 86400).await?;
let field_refs: Vec<(&str, &str)> = fields.iter().map(|(k, v)| (*k, v.as_str())).collect();
let _: Option<String> = conn.hset_multiple(&key, &field_refs).await?;
@@ -471,31 +475,40 @@ impl RedisClient {
pub async fn delete_worker_job(&self, uuid: &str) -> Result<()> {
let mut conn = self.get_conn_internal().await?;
let prefix = REDIS_KEY_PREFIX.as_str();
let key = format!("{}job:{}", prefix, uuid);
let _: i32 = conn.del(&key).await?;
let processor_types = [
"appearance",
"asr",
"cut",
"ocr",
"face",
"pose",
"asrx",
"visual_chunk",
"story",
"tmdb_probe",
"embedding",
];
for ptype in processor_types {
let proc_key = format!("{}job:{}:processor:{}", prefix, uuid, ptype);
let _: i32 = conn.del(&proc_key).await?;
// 1. Find all related keys using SCAN (better performance than KEYS)
let pattern = format!("{}job:{}*", prefix, uuid);
let mut cursor: u64 = 0;
let mut keys_to_delete = Vec::new();
loop {
let result: (u64, Vec<String>) = redis::cmd("SCAN")
.arg(&[&cursor.to_string(), "MATCH", &pattern, "COUNT", "100"])
.query_async(&mut conn)
.await?;
let (new_cursor, keys) = result;
keys_to_delete.extend(keys);
cursor = new_cursor;
if cursor == 0 {
break;
}
}
// 2. Batch delete all keys
if !keys_to_delete.is_empty() {
let field_refs: Vec<&str> = keys_to_delete.iter().map(|s| s.as_str()).collect();
let _: () = redis::cmd("DEL")
.arg(&field_refs)
.query_async(&mut conn)
.await?;
}
// 3. Delete progress keys
let progress_key = format!("{}progress:{}", prefix, uuid);
let _: i32 = conn.del(&progress_key).await?;
let _: () = conn.del(&progress_key).await?;
Ok(())
}
+1
View File
@@ -1,3 +1,4 @@
pub mod client;
pub mod function_calling;
pub mod prompts;
pub mod rerank;
+227
View File
@@ -0,0 +1,227 @@
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptTemplate {
pub system_prompt: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_prompt: Option<String>,
#[serde(default = "default_max_tokens")]
pub max_tokens: u32,
}
fn default_max_tokens() -> u32 {
300
}
static PROMPT_TEMPLATES: Lazy<HashMap<String, HashMap<String, PromptTemplate>>> = Lazy::new(|| {
let mut templates = HashMap::new();
templates.insert("agent_search".to_string(), {
let mut lang_map = HashMap::new();
lang_map.insert("en".to_string(), PromptTemplate {
system_prompt: "You are a professional video analysis assistant for a digital asset management system. Respond concisely in English.".to_string(),
user_prompt: None,
max_tokens: 1024,
});
lang_map.insert("zh-TW".to_string(), PromptTemplate {
system_prompt: "你是一個專業的影片分析助手,服務於數位資產管理系統。請用繁體中文簡潔回答。".to_string(),
user_prompt: None,
max_tokens: 1024,
});
lang_map.insert("ja".to_string(), PromptTemplate {
system_prompt: "あなたはデジタルアセット管理システムのプロフェッショナルなビデオ分析アシスタントです。日本語で簡潔に回答してください。".to_string(),
user_prompt: None,
max_tokens: 1024,
});
lang_map
});
templates.insert("vlm_summary".to_string(), {
let mut lang_map = HashMap::new();
lang_map.insert("en".to_string(), PromptTemplate {
system_prompt: "You are a scene analysis assistant for a video surveillance/DAM system. Given a video key frame, write a concise summary (2-4 sentences, in English) describing: what is happening, the people present (clothing/appearance), the setting/location, and any notable objects or actions. Be factual and specific.".to_string(),
user_prompt: Some("Summarize this key frame.".to_string()),
max_tokens: 900,
});
lang_map.insert("zh-TW".to_string(), PromptTemplate {
system_prompt: "你是影片監控/數位資產管理系統的場景分析助手。請根據影片關鍵幀,撰寫簡潔摘要(2-4句,使用繁體中文),描述:發生的事情、人物(衣著/外觀)、場景/地點、以及任何顯著的物體或動作。請具體且準確。".to_string(),
user_prompt: Some("總結這個關鍵幀。".to_string()),
max_tokens: 900,
});
lang_map.insert("ja".to_string(), PromptTemplate {
system_prompt: "あなたはビデオ監視/DAMシステムのシーン分析アシスタントです。ビデオのキーフレームを分析し、簡潔な要約(2-4文、日本語)を作成してください:何が起きているか、登場人物(服装/外見)、場所/設定、目立つ物体や動作について説明してください。具体的かつ正確に記述してください。".to_string(),
user_prompt: Some("このキーフレームを要約してください。".to_string()),
max_tokens: 900,
});
lang_map
});
templates.insert("scene_vlm".to_string(), {
let mut lang_map = HashMap::new();
lang_map.insert("en".to_string(), PromptTemplate {
system_prompt: "You are a professional scene analyzer. Describe the scene in English, including the main subjects, actions, setting, and notable objects. Be concise (2-3 sentences).".to_string(),
user_prompt: Some("Describe this scene.".to_string()),
max_tokens: 300,
});
lang_map.insert("zh-TW".to_string(), PromptTemplate {
system_prompt: "你是專業的場景分析師。請用繁體中文描述場景,包括主要對象、動作、場景設置和顯著物體。請簡潔(2-3句)。".to_string(),
user_prompt: Some("描述這個場景。".to_string()),
max_tokens: 300,
});
lang_map.insert("ja".to_string(), PromptTemplate {
system_prompt: "あなたはプロフェッショナルなシーンアナライザーです。日本語でシーンを説明し、主要な被写体、アクション、設定、目立つ物体を含めてください。簡潔に(2-3文)記述してください。".to_string(),
user_prompt: Some("このシーンを説明してください。".to_string()),
max_tokens: 300,
});
lang_map
});
templates.insert("analyze_frame".to_string(), {
let mut lang_map = HashMap::new();
lang_map.insert("en".to_string(), PromptTemplate {
system_prompt: "You are a professional video frame analyst. Describe what you see in this frame in English, including people, objects, actions, and the scene setting. Be detailed but concise.".to_string(),
user_prompt: None,
max_tokens: 1024,
});
lang_map.insert("zh-TW".to_string(), PromptTemplate {
system_prompt: "你是專業的影片畫面分析師。請用繁體中文描述畫面中的內容,包括人物、物體、動作和場景設置。請詳細但簡潔。".to_string(),
user_prompt: None,
max_tokens: 1024,
});
lang_map.insert("ja".to_string(), PromptTemplate {
system_prompt: "あなたはプロフェッショナルなビデオフレームアナリストです。日本語でこのフレームに見えるものを説明してください。人物、物体、アクション、シーン設定を含めてください。詳細かつ簡潔に記述してください。".to_string(),
user_prompt: None,
max_tokens: 1024,
});
lang_map
});
templates
});
pub fn get_system_prompt(module: &str, language: &str) -> String {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get(language))
.or_else(|| {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get("en"))
})
.map(|template| template.system_prompt.clone())
.unwrap_or_else(|| {
tracing::warn!(
"No prompt template found for module '{}' with language '{}', using default",
module,
language
);
format!(
"You are a helpful assistant. Respond in {}.",
match language {
"zh-TW" => "Traditional Chinese",
"ja" => "Japanese",
_ => "English",
}
)
})
}
pub fn get_user_prompt(module: &str, language: &str) -> Option<String> {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get(language))
.or_else(|| {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get("en"))
})
.and_then(|template| template.user_prompt.clone())
}
pub fn get_max_tokens(module: &str, language: &str) -> u32 {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get(language))
.or_else(|| {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get("en"))
})
.map(|template| template.max_tokens)
.unwrap_or(300)
}
pub fn get_prompt_template(module: &str, language: &str) -> Option<PromptTemplate> {
PROMPT_TEMPLATES
.get(module)
.and_then(|lang_map| lang_map.get(language))
.cloned()
}
pub fn list_available_modules() -> Vec<String> {
PROMPT_TEMPLATES.keys().cloned().collect()
}
pub fn list_available_languages(module: &str) -> Vec<String> {
PROMPT_TEMPLATES
.get(module)
.map(|lang_map| lang_map.keys().cloned().collect())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_system_prompt() {
let prompt = get_system_prompt("agent_search", "en");
assert!(prompt.contains("professional video analysis assistant"));
let prompt_zh = get_system_prompt("agent_search", "zh-TW");
assert!(prompt_zh.contains("專業的影片分析助手"));
let prompt_ja = get_system_prompt("agent_search", "ja");
assert!(prompt_ja.contains("プロフェッショナルなビデオ分析アシスタント"));
}
#[test]
fn test_fallback_to_english() {
let prompt = get_system_prompt("agent_search", "unknown");
assert!(prompt.contains("professional video analysis assistant"));
}
#[test]
fn test_get_max_tokens() {
let tokens = get_max_tokens("agent_search", "en");
assert_eq!(tokens, 1024);
let tokens_vlm = get_max_tokens("vlm_summary", "en");
assert_eq!(tokens_vlm, 900);
}
#[test]
fn test_list_modules() {
let modules = list_available_modules();
assert!(modules.contains(&"agent_search".to_string()));
assert!(modules.contains(&"vlm_summary".to_string()));
}
}
+40 -21
View File
@@ -39,6 +39,8 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FaceResult {
#[serde(default = "default_schema_version")]
pub schema_version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ProcessorMetadata>,
#[serde(default)]
@@ -50,6 +52,10 @@ pub struct FaceResult {
pub total_faces: usize,
}
fn default_schema_version() -> String {
"2.0".to_string()
}
impl FaceResult {
pub fn compute_status(&mut self) {
for frame in &mut self.frames {
@@ -100,6 +106,7 @@ impl FaceResult {
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
FaceResult {
schema_version: "2.0".to_string(),
metadata: None,
status: Some(FaceStatus::NoFaces),
frame_count,
@@ -128,9 +135,18 @@ pub struct Face {
pub width: i32,
#[serde(default)]
pub height: i32,
#[serde(default)]
pub x2: i32,
#[serde(default)]
pub y2: i32,
#[serde(default)]
pub center_x: i32,
#[serde(default)]
pub center_y: i32,
pub confidence: f32,
#[serde(default, rename = "captureQuality", alias = "capture_quality")]
pub capture_quality: Option<f32>,
#[serde(default)]
pub embedding: Option<Vec<f32>>,
pub landmarks: Option<serde_json::Value>,
pub pose_angle: Option<serde_json::Value>,
@@ -161,6 +177,12 @@ impl Face {
self.width = bbox.width;
self.height = bbox.height;
}
// Calculate derived bbox fields
self.x2 = self.x + self.width;
self.y2 = self.y + self.height;
self.center_x = self.x + self.width / 2;
self.center_y = self.y + self.height / 2;
if let Some(pose) = &self.pose {
self.pose_angle = Some(pose.clone());
}
@@ -583,6 +605,7 @@ mod tests {
#[test]
fn test_face_result_serialization() {
let result = FaceResult {
schema_version: "2.0".to_string(),
metadata: None,
status: None,
frame_count: 100,
@@ -682,6 +705,7 @@ mod tests {
#[test]
fn test_face_result_empty_frames() {
let result = FaceResult {
schema_version: "2.0".to_string(),
status: None,
frame_count: 0,
fps: 0.0,
@@ -777,15 +801,24 @@ pub async fn store_face_embeddings_to_qdrant(
let payload = serde_json::json!({
"file_uuid": file_uuid,
"frame": frame_num,
"timestamp_secs": timestamp_secs,
"timestamp": timestamp_secs,
"face_id": face_id,
"confidence": face.confidence,
"x": face.x,
"y": face.y,
"width": face.width,
"height": face.height,
"capture_quality": face.capture_quality.unwrap_or(0.0),
"bbox": {
"x": face.x,
"y": face.y,
"width": face.width,
"height": face.height,
"x2": face.x2,
"y2": face.y2,
"center_x": face.center_x,
"center_y": face.center_y
},
"pose": face.pose_angle.clone().unwrap_or(serde_json::json!({})),
"landmarks": face.landmarks.clone().unwrap_or(serde_json::json!({})),
"trace_id": -1i32, // Will be updated by face tracing
"identity_id": null
});
points.push((point_id, embedding.clone(), payload));
@@ -829,22 +862,8 @@ pub async fn store_face_embeddings_to_qdrant(
tracing::info!("[FACE] Stored {} embeddings to Qdrant", total_points);
// Remove embeddings from in-memory result
for frame in &mut face_result.frames {
for face in &mut frame.faces {
face.embedding = None;
}
}
// Save cleaned JSON back
let json_str = serde_json::to_string_pretty(&face_result)
.context("Failed to serialize cleaned face result")?;
std::fs::write(output_path, &json_str).context("Failed to write cleaned face.json")?;
tracing::info!(
"[FACE] Removed embeddings from JSON, saved to {}",
output_path
);
// Keep embeddings in JSON (JSON is source of truth)
// No longer remove embeddings from JSON
Ok(total_points)
}
+89 -7
View File
@@ -8,15 +8,54 @@ const FACE_CLUSTER_TIMEOUT: Duration = Duration::from_secs(3600);
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FaceClusterResult {
#[serde(default = "default_schema_version")]
pub schema_version: String,
#[serde(default)]
pub file_uuid: Option<String>,
pub status: String,
pub stats: ClusterStats,
pub clusters: Vec<FaceClusterInfo>,
#[serde(default)]
pub unassigned_traces: Vec<i32>,
#[serde(default)]
pub speaker_person_mapping: serde_json::Value,
#[serde(default)]
pub frames: Vec<FaceClusterFrame>,
}
fn default_schema_version() -> String {
"2.0".to_string()
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ClusterStats {
#[serde(default)]
pub total_clusters: usize,
#[serde(default)]
pub unassigned_traces: usize,
#[serde(default)]
pub total_traces: usize,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FaceClusterInfo {
pub cluster_id: String,
pub cluster_id: i32,
pub group_name: String,
#[serde(default)]
pub trace_ids: Vec<i32>,
#[serde(default)]
pub total_faces: usize,
#[serde(default)]
pub representative_trace: Option<i32>,
#[serde(default)]
pub confidence: f64,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub face_count: usize,
#[serde(default)]
pub representative_face: Option<RepresentativeFace>,
#[serde(default)]
pub similarity: Option<ClusterSimilarity>,
}
@@ -37,10 +76,18 @@ pub struct RepresentativeFace {
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BoundingBox {
pub x: u64,
pub y: u64,
pub width: u64,
pub height: u64,
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
#[serde(default)]
pub x2: i32,
#[serde(default)]
pub y2: i32,
#[serde(default)]
pub center_x: i32,
#[serde(default)]
pub center_y: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -58,6 +105,22 @@ pub struct ClusteredFace {
pub confidence: f32,
}
impl FaceClusterResult {
pub fn add_metadata(&mut self, file_uuid: &str) {
self.file_uuid = Some(file_uuid.to_string());
self.status = "completed".to_string();
self.stats.total_clusters = self.clusters.len();
self.stats.total_traces = self.clusters.iter().map(|c| c.trace_ids.len()).sum();
self.stats.unassigned_traces = self.unassigned_traces.len();
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face_cluster.json")?;
Ok(())
}
}
pub async fn process_face_cluster(
video_path: &str,
output_path: &str,
@@ -73,7 +136,13 @@ pub async fn process_face_cluster(
if !script_path.exists() {
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
return Ok(FaceClusterResult {
schema_version: "2.0".to_string(),
file_uuid: None,
status: "no_faces".to_string(),
stats: ClusterStats::default(),
clusters: vec![],
unassigned_traces: vec![],
speaker_person_mapping: serde_json::json!({}),
frames: vec![],
});
}
@@ -116,8 +185,15 @@ pub async fn process_face_cluster(
Ok(_) => {
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read FACE_CLUSTER output")?;
let result: FaceClusterResult = serde_json::from_str(&json_str)
let mut result: FaceClusterResult = serde_json::from_str(&json_str)
.context("Failed to parse FACE_CLUSTER output")?;
if let Some(uuid) = uuid {
result.add_metadata(uuid);
}
result.status = "completed".to_string();
result.save_to_file(output_path)?;
tracing::info!(
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
result.clusters.len(),
@@ -151,8 +227,14 @@ pub async fn process_face_cluster(
let json_str =
std::fs::read_to_string(output_path).context("Failed to read FACE_CLUSTER output")?;
let result: FaceClusterResult =
let mut result: FaceClusterResult =
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
if let Some(uuid) = uuid {
result.add_metadata(uuid);
}
result.status = "completed".to_string();
result.save_to_file(output_path)?;
tracing::info!(
"[FACE_CLUSTER] Result: {} clusters, {} frames",