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(),
)
}
+2
View File
@@ -10,6 +10,7 @@ pub enum ChunkType {
Trace,
Story,
Relationship,
Ocr,
}
impl ChunkType {
@@ -21,6 +22,7 @@ impl ChunkType {
ChunkType::Trace => "trace",
ChunkType::Story => "story",
ChunkType::Relationship => "relationship",
ChunkType::Ocr => "ocr",
}
}
}
+75 -5
View File
@@ -195,10 +195,16 @@ pub enum VideoStatus {
Registered,
Pending,
Queued,
Scanning,
Processing,
Processed,
Indexed,
CheckedOut,
KeywordReady,
SemanticReady,
PeopleReady,
FaceMgmtReady,
AgentReady,
Completed,
Failed,
}
@@ -210,10 +216,21 @@ impl VideoStatus {
VideoStatus::Registered => "registered",
VideoStatus::Pending => "pending",
VideoStatus::Queued => "queued",
VideoStatus::Scanning => "scanning",
VideoStatus::Processing => "processing",
VideoStatus::Processed => "processed",
VideoStatus::Indexed => "indexed",
VideoStatus::CheckedOut => "checked_out",
VideoStatus::KeywordReady => "keyword_ready",
VideoStatus::SemanticReady => "semantic_ready",
VideoStatus::PeopleReady => "people_ready",
VideoStatus::FaceMgmtReady => "face_mgmt_ready",
VideoStatus::AgentReady => "agent_ready",
VideoStatus::Completed => "completed",
VideoStatus::Failed => "failed",
VideoStatus::Processed => "processed",
VideoStatus::Indexed => "indexed",
VideoStatus::CheckedOut => "checked_out",
VideoStatus::Completed => "completed",
VideoStatus::Failed => "failed",
}
@@ -225,10 +242,21 @@ impl VideoStatus {
"registered" => Some(VideoStatus::Registered),
"pending" => Some(VideoStatus::Pending),
"queued" => Some(VideoStatus::Queued),
"scanning" => Some(VideoStatus::Scanning),
"processing" => Some(VideoStatus::Processing),
"processed" => Some(VideoStatus::Processed),
"indexed" => Some(VideoStatus::Indexed),
"checked_out" => Some(VideoStatus::CheckedOut),
"keyword_ready" => Some(VideoStatus::KeywordReady),
"semantic_ready" => Some(VideoStatus::SemanticReady),
"people_ready" => Some(VideoStatus::FaceMgmtReady),
"face_mgmt_ready" => Some(VideoStatus::FaceMgmtReady),
"agent_ready" => Some(VideoStatus::AgentReady),
"completed" => Some(VideoStatus::Completed),
"failed" => Some(VideoStatus::Failed),
"processed" => Some(VideoStatus::Processed),
"indexed" => Some(VideoStatus::Indexed),
"checked_out" => Some(VideoStatus::CheckedOut),
"completed" => Some(VideoStatus::Completed),
"failed" => Some(VideoStatus::Failed),
_ => None,
@@ -264,6 +292,8 @@ pub struct VideoRow {
pub registration_time: Option<String>,
pub total_frames: Option<i64>,
pub parent_uuid: Option<String>,
pub proxy_path: Option<String>,
pub audio_track: Option<String>,
}
impl From<VideoRow> for VideoRecord {
@@ -302,6 +332,8 @@ impl From<VideoRow> for VideoRecord {
cut_max_duration: 0.0,
scene_done: false,
audio_tracks: None,
proxy_path: row.proxy_path,
audio_track: row.audio_track,
}
}
}
@@ -333,6 +365,8 @@ pub struct VideoRecord {
pub cut_max_duration: f64,
pub scene_done: bool,
pub audio_tracks: Option<serde_json::Value>,
pub proxy_path: Option<String>,
pub audio_track: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -963,6 +997,8 @@ impl PostgresDb {
"cut_count INTEGER DEFAULT 0",
"cut_max_duration DOUBLE PRECISION DEFAULT 0",
"content_hash TEXT",
"proxy_path TEXT",
"audio_track TEXT",
];
for col in &video_cols {
let (col_name, col_def) = col.split_once(' ').unwrap_or((col, ""));
@@ -1196,6 +1232,12 @@ impl PostgresDb {
// ── Strangers ──
sqlx::query("CREATE TABLE IF NOT EXISTS strangers (id SERIAL PRIMARY KEY, file_uuid TEXT, trace_id INTEGER, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
// ── Trace Profiles (VLM metadata for face traces) ──
sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_name ON trace_profiles(name)").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_tags ON trace_profiles USING GIN(vlm_tags)").execute(pool).await?;
// ── Cuts ──
sqlx::query("CREATE TABLE IF NOT EXISTS cuts (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, cut_number INTEGER NOT NULL, start_frame BIGINT NOT NULL, end_frame BIGINT NOT NULL, start_time DOUBLE PRECISION, end_time DOUBLE PRECISION, fps DOUBLE PRECISION, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, cut_number))").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_cuts_file_uuid ON cuts(file_uuid)")
@@ -1477,7 +1519,7 @@ impl PostgresDb {
let table = schema::table_name("videos");
let result = sqlx::query_as::<_, VideoRow>(
&format!(
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid FROM {} WHERE file_uuid = $1",
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid, proxy_path, audio_track FROM {} WHERE file_uuid = $1",
table
)
)
@@ -1503,7 +1545,7 @@ impl PostgresDb {
let table = schema::table_name("videos");
let result = sqlx::query_as::<_, VideoRow>(
&format!(
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid FROM {} WHERE file_name = $1 AND registration_time IS NOT NULL ORDER BY registration_time ASC LIMIT 1",
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid, proxy_path, audio_track FROM {} WHERE file_name = $1 AND registration_time IS NOT NULL ORDER BY registration_time ASC LIMIT 1",
table
)
)
@@ -1587,7 +1629,7 @@ impl PostgresDb {
.collect();
let table = schema::table_name("videos");
let sql = format!(
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, parent_uuid FROM {} WHERE file_uuid = ANY($1)",
"SELECT id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, parent_uuid, proxy_path, audio_track FROM {} WHERE file_uuid = ANY($1)",
table
);
@@ -1669,7 +1711,7 @@ impl PostgresDb {
// 2. Select Query
// Cast created_at and registration_time to text
let columns = "id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid";
let columns = "id, file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, fs_video, fs_json, psql_chunk, pobject_chunk, mobject_chunk, pvector_chunk, qvector_chunk, status, processing_status, birth_registration, user_id, job_id, created_at::text AS created_at, registration_time::text AS registration_time, total_frames, parent_uuid, proxy_path, audio_track";
// Determine parameter order for LIMIT/OFFSET
// If search is present, pattern is $1. Limit is $2. Offset is $3.
@@ -1910,7 +1952,7 @@ impl PostgresDb {
&format!(
r#"
INSERT INTO {} (uuid, video_path, status, video_id, processors)
VALUES ($1, $2, 'pending', $3, ARRAY['cut','asr','face','ocr','asrx','pose','appearance'])
VALUES ($1, $2, 'pending', $3, ARRAY['cut','asr','face','ocr','asrx','pose'])
RETURNING id, uuid, video_path, status, current_processor, progress_total, progress_current, error_count, last_error, started_at::TEXT, updated_at::TEXT, created_at::TEXT, processors, completed_processors, failed_processors, video_id
"#,
jobs_table
@@ -2721,6 +2763,32 @@ impl PostgresDb {
Ok(())
}
pub async fn update_proxy_path(&self, uuid: &str, proxy_path: &str) -> Result<()> {
let table = schema::table_name("videos");
sqlx::query(&format!(
"UPDATE {} SET proxy_path = $1, updated_at = CURRENT_TIMESTAMP WHERE file_uuid = $2",
table
))
.bind(proxy_path)
.bind(uuid)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn update_audio_track(&self, uuid: &str, audio_track: &str) -> Result<()> {
let table = schema::table_name("videos");
sqlx::query(&format!(
"UPDATE {} SET audio_track = $1, updated_at = CURRENT_TIMESTAMP WHERE file_uuid = $2",
table
))
.bind(audio_track)
.bind(uuid)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn update_processing_status_completed(
&self,
uuid: &str,
@@ -4648,6 +4716,8 @@ mod tests {
cut_max_duration: 0.0,
scene_done: false,
audio_tracks: None,
proxy_path: None,
audio_track: None,
};
let json = serde_json::to_string(&record).unwrap();
+3 -12
View File
@@ -913,15 +913,8 @@ impl QdrantDb {
Ok(all_points)
}
pub async fn count_points(
&self,
collection: &str,
filter: serde_json::Value,
) -> Result<i64> {
let url = format!(
"{}/collections/{}/points/count",
self.base_url, collection
);
pub async fn count_points(&self, collection: &str, filter: serde_json::Value) -> Result<i64> {
let url = format!("{}/collections/{}/points/count", self.base_url, collection);
let body = serde_json::json!({
"filter": filter,
@@ -942,9 +935,7 @@ impl QdrantDb {
}
let result: serde_json::Value = resp.json().await?;
let count = result["result"]["count"]
.as_i64()
.unwrap_or(0);
let count = result["result"]["count"].as_i64().unwrap_or(0);
Ok(count)
}
+703
View File
@@ -0,0 +1,703 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Version of the lifecycle schema.
const LIFECYCLE_VERSION: &str = "1.0";
// ─── Data Types ───
/// Complete lifecycle state for a file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileLifecycle {
pub version: String,
pub file_uuid: String,
pub updated_at: String, // RFC3339
pub stages: LifecycleStages,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LifecycleStages {
/// Stage 0: Registration (profile.json, probe.json, cut.json)
pub registration: StageState,
/// Stage 1: First-level processors (asr, ocr, face)
pub stage_1_processors: ProcessorGroupState,
/// Stage 2: Second-level processors (asrx, face_vector, speaker_vector)
pub stage_2_processors: ProcessorGroupState,
/// Stage 3: Third-level processors (pose, appearance)
pub stage_3_processors: ProcessorGroupState,
/// Rule 1: Text ingestion (sentence chunks → PG + Qdrant)
pub rule_1_ingestion: IngestionState,
/// Rule 2: Node ingestion (face/speaker TKG nodes)
pub rule_2_ingestion: IngestionState,
/// Rule 3: Edge ingestion (TKG edges)
pub rule_3_ingestion: IngestionState,
/// Final completion
pub completed: StageState,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageState {
pub status: String, // pending / in_progress / completed / failed / skipped
#[serde(skip_serializing_if = "Option::is_none")]
pub started_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub completed_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessorGroupState {
pub status: String, // pending / in_progress / completed / partial / failed
pub processors: HashMap<String, ProcessorState>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessorState {
pub status: String, // pending / running / completed / failed / skipped
#[serde(skip_serializing_if = "Option::is_none")]
pub started_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub completed_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub progress: Option<ProgressInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_count: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub retry_count: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressInfo {
pub current: i64,
pub total: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestionState {
pub status: String, // pending / in_progress / completed / failed / skipped
#[serde(skip_serializing_if = "Option::is_none")]
pub started_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub completed_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub items_ingested: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
// ─── Processor Definitions ───
/// Stage 1 processors (no dependencies, run in parallel)
pub const STAGE_1_PROCESSORS: &[&str] = &["asr", "ocr", "face"];
/// Stage 2 processors (depend on stage 1)
pub const STAGE_2_PROCESSORS: &[&str] = &["asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster"];
/// Stage 3 processors (depend on stage 2 or face)
pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"];
/// All processors in order
pub const ALL_PROCESSORS: &[&str] = &[
"cut", // Registration
"asr", "ocr", "face", // Stage 1
"asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster", // Stage 2
"pose", "appearance", // Stage 3
];
/// Get processor dependencies
pub fn get_dependencies(processor: &str) -> Vec<&'static str> {
match processor {
"asrx" => vec!["cut", "asr"],
"face_vector" => vec!["face"],
"face_trace" => vec!["face_vector"], // trace after vectorization
"speaker_vector" => vec!["asrx"],
"face_cluster" => vec!["face_trace"], // deduplication after trace
"pose" => vec!["face"],
"appearance" => vec!["pose"],
_ => vec![],
}
}
/// Get processor stage
pub fn get_stage(processor: &str) -> &'static str {
match processor {
"cut" => "registration",
"asr" | "ocr" | "face" => "stage_1",
"asrx" | "face_vector" | "face_trace" | "speaker_vector" | "face_cluster" => "stage_2",
"pose" | "appearance" => "stage_3",
_ => "unknown",
}
}
// ─── Construction ───
impl FileLifecycle {
/// Create a new lifecycle for a file
pub fn new(file_uuid: &str) -> Self {
let now = chrono::Utc::now().to_rfc3339();
let mut stage_1_processors = HashMap::new();
for proc in STAGE_1_PROCESSORS {
stage_1_processors.insert(proc.to_string(), ProcessorState::new("pending"));
}
let mut stage_2_processors = HashMap::new();
for proc in STAGE_2_PROCESSORS {
stage_2_processors.insert(proc.to_string(), ProcessorState::new("pending"));
}
let mut stage_3_processors = HashMap::new();
for proc in STAGE_3_PROCESSORS {
stage_3_processors.insert(proc.to_string(), ProcessorState::new("pending"));
}
Self {
version: LIFECYCLE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
updated_at: now,
stages: LifecycleStages {
registration: StageState::new("pending"),
stage_1_processors: ProcessorGroupState {
status: "pending".to_string(),
processors: stage_1_processors,
},
stage_2_processors: ProcessorGroupState {
status: "pending".to_string(),
processors: stage_2_processors,
},
stage_3_processors: ProcessorGroupState {
status: "pending".to_string(),
processors: stage_3_processors,
},
rule_1_ingestion: IngestionState::new("pending"),
rule_2_ingestion: IngestionState::new("pending"),
rule_3_ingestion: IngestionState::new("pending"),
completed: StageState::new("pending"),
},
}
}
/// Create lifecycle from existing outputs (for recovery)
pub fn from_existing_outputs(output_dir: &str, file_uuid: &str) -> Self {
let mut lifecycle = Self::new(file_uuid);
// Check registration outputs
let has_profile = Path::new(output_dir).join(format!("{}.profile.json", file_uuid)).exists();
let has_probe = Path::new(output_dir).join(format!("{}.probe.json", file_uuid)).exists();
let has_cut = Path::new(output_dir).join(format!("{}.cut.json", file_uuid)).exists();
if has_profile && has_probe && has_cut {
lifecycle.mark_stage_completed("registration");
}
// Check stage 1 processors
for proc in STAGE_1_PROCESSORS {
let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc));
if path.exists() {
lifecycle.mark_processor_completed(proc, None);
}
}
// Check stage 2 processors
let has_asrx = Path::new(output_dir).join(format!("{}.asrx.json", file_uuid)).exists();
if has_asrx {
lifecycle.mark_processor_completed("asrx", None);
// speaker_vector comes from asrx
lifecycle.mark_processor_completed("speaker_vector", None);
}
// face_vector: check if face.json exists (vectors stored in Qdrant)
let has_face = Path::new(output_dir).join(format!("{}.face.json", file_uuid)).exists();
if has_face {
lifecycle.mark_processor_completed("face_vector", None);
}
// face_trace: check face_traced.json (continuous face tracking)
let has_face_traced = Path::new(output_dir).join(format!("{}.face_traced.json", file_uuid)).exists();
if has_face_traced {
lifecycle.mark_processor_completed("face_trace", None);
}
// face_cluster: check face_cluster.json (deduplication of traces)
let has_face_cluster = Path::new(output_dir).join(format!("{}.face_cluster.json", file_uuid)).exists();
if has_face_cluster {
lifecycle.mark_processor_completed("face_cluster", None);
}
// Check stage 3 processors
for proc in STAGE_3_PROCESSORS {
let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc));
if path.exists() {
lifecycle.mark_processor_completed(proc, None);
}
}
lifecycle.update_group_status();
lifecycle
}
// ─── Persistence ───
/// Return the lifecycle file path: `{output_dir}/{file_uuid}.lifecycle.json`
pub fn lifecycle_path(output_dir: &str, file_uuid: &str) -> PathBuf {
Path::new(output_dir).join(format!("{}.lifecycle.json", file_uuid))
}
/// Save lifecycle to disk
pub fn save_to_disk(&self, output_dir: &str) -> Result<()> {
let path = Self::lifecycle_path(output_dir, &self.file_uuid);
let json = serde_json::to_string_pretty(self)
.context("Failed to serialize lifecycle")?;
std::fs::write(&path, json)
.with_context(|| format!("Failed to write lifecycle to {}", path.display()))?;
tracing::debug!("[Lifecycle] Saved for {}", self.file_uuid);
Ok(())
}
/// Load lifecycle from disk
pub fn load_from_disk(output_dir: &str, file_uuid: &str) -> Option<Self> {
let path = Self::lifecycle_path(output_dir, file_uuid);
let content = std::fs::read_to_string(&path).ok()?;
serde_json::from_str(&content).ok()
}
/// Load or create new lifecycle
pub fn load_or_create(output_dir: &str, file_uuid: &str) -> Self {
Self::load_from_disk(output_dir, file_uuid)
.unwrap_or_else(|| Self::from_existing_outputs(output_dir, file_uuid))
}
// ─── State Updates ───
/// Mark a stage as started
pub fn mark_stage_started(&mut self, stage: &str) {
let now = chrono::Utc::now().to_rfc3339();
self.updated_at = now.clone();
match stage {
"registration" => {
self.stages.registration.status = "in_progress".to_string();
self.stages.registration.started_at = Some(now);
}
"stage_1" => {
self.stages.stage_1_processors.status = "in_progress".to_string();
}
"stage_2" => {
self.stages.stage_2_processors.status = "in_progress".to_string();
}
"stage_3" => {
self.stages.stage_3_processors.status = "in_progress".to_string();
}
"rule_1" => {
self.stages.rule_1_ingestion.status = "in_progress".to_string();
self.stages.rule_1_ingestion.started_at = Some(now);
}
"rule_2" => {
self.stages.rule_2_ingestion.status = "in_progress".to_string();
self.stages.rule_2_ingestion.started_at = Some(now);
}
"rule_3" => {
self.stages.rule_3_ingestion.status = "in_progress".to_string();
self.stages.rule_3_ingestion.started_at = Some(now);
}
_ => {}
}
}
/// Mark a stage as completed
pub fn mark_stage_completed(&mut self, stage: &str) {
let now = chrono::Utc::now().to_rfc3339();
self.updated_at = now.clone();
match stage {
"registration" => {
self.stages.registration.status = "completed".to_string();
self.stages.registration.completed_at = Some(now);
}
"rule_1" => {
self.stages.rule_1_ingestion.status = "completed".to_string();
self.stages.rule_1_ingestion.completed_at = Some(now);
}
"rule_2" => {
self.stages.rule_2_ingestion.status = "completed".to_string();
self.stages.rule_2_ingestion.completed_at = Some(now);
}
"rule_3" => {
self.stages.rule_3_ingestion.status = "completed".to_string();
self.stages.rule_3_ingestion.completed_at = Some(now);
}
"completed" => {
self.stages.completed.status = "completed".to_string();
self.stages.completed.completed_at = Some(now);
}
_ => {}
}
}
/// Mark a processor as started
pub fn mark_processor_started(&mut self, processor: &str) {
let now = chrono::Utc::now().to_rfc3339();
self.updated_at = now.clone();
let stage = get_stage(processor);
let group = match stage {
"stage_1" => &mut self.stages.stage_1_processors,
"stage_2" => &mut self.stages.stage_2_processors,
"stage_3" => &mut self.stages.stage_3_processors,
_ => return,
};
if let Some(proc_state) = group.processors.get_mut(processor) {
proc_state.status = "running".to_string();
proc_state.started_at = Some(now);
}
// Update group status
group.status = "in_progress".to_string();
}
/// Mark a processor as completed
pub fn mark_processor_completed(&mut self, processor: &str, output_count: Option<i64>) {
let now = chrono::Utc::now().to_rfc3339();
self.updated_at = now.clone();
let stage = get_stage(processor);
let group = match stage {
"stage_1" => &mut self.stages.stage_1_processors,
"stage_2" => &mut self.stages.stage_2_processors,
"stage_3" => &mut self.stages.stage_3_processors,
_ => return,
};
if let Some(proc_state) = group.processors.get_mut(processor) {
proc_state.status = "completed".to_string();
proc_state.completed_at = Some(now);
proc_state.output_count = output_count;
}
self.update_group_status();
}
/// Mark a processor as failed
pub fn mark_processor_failed(&mut self, processor: &str, error: &str, retry_count: i32) {
let now = chrono::Utc::now().to_rfc3339();
self.updated_at = now.clone();
let stage = get_stage(processor);
let group = match stage {
"stage_1" => &mut self.stages.stage_1_processors,
"stage_2" => &mut self.stages.stage_2_processors,
"stage_3" => &mut self.stages.stage_3_processors,
_ => return,
};
if let Some(proc_state) = group.processors.get_mut(processor) {
proc_state.status = "failed".to_string();
proc_state.error = Some(error.to_string());
proc_state.retry_count = Some(retry_count);
}
self.update_group_status();
}
/// Update processor progress
pub fn update_processor_progress(&mut self, processor: &str, current: i64, total: i64) {
self.updated_at = chrono::Utc::now().to_rfc3339();
let stage = get_stage(processor);
let group = match stage {
"stage_1" => &mut self.stages.stage_1_processors,
"stage_2" => &mut self.stages.stage_2_processors,
"stage_3" => &mut self.stages.stage_3_processors,
_ => return,
};
if let Some(proc_state) = group.processors.get_mut(processor) {
proc_state.progress = Some(ProgressInfo { current, total });
}
}
/// Update group status based on processor states
fn update_group_status(&mut self) {
// Update stage 1
let stage_1 = &mut self.stages.stage_1_processors;
stage_1.status = compute_group_status(&stage_1.processors);
// Update stage 2
let stage_2 = &mut self.stages.stage_2_processors;
stage_2.status = compute_group_status(&stage_2.processors);
// Update stage 3
let stage_3 = &mut self.stages.stage_3_processors;
stage_3.status = compute_group_status(&stage_3.processors);
}
// ─── Queries ───
/// Check if a processor can run (dependencies met)
pub fn can_run_processor(&self, processor: &str) -> bool {
let deps = get_dependencies(processor);
if deps.is_empty() {
return true;
}
for dep in deps {
if !self.is_processor_completed(dep) {
return false;
}
}
true
}
/// Check if a processor is completed
pub fn is_processor_completed(&self, processor: &str) -> bool {
let stage = get_stage(processor);
let group = match stage {
"stage_1" => &self.stages.stage_1_processors,
"stage_2" => &self.stages.stage_2_processors,
"stage_3" => &self.stages.stage_3_processors,
_ => return processor == "cut" && self.stages.registration.status == "completed",
};
group.processors.get(processor)
.map(|p| p.status == "completed")
.unwrap_or(false)
}
/// Get next processors to run
pub fn get_next_processors(&self) -> Vec<String> {
let mut next = Vec::new();
// Check stage 1
if self.stages.registration.status != "completed" {
return next; // Registration must complete first
}
for proc in STAGE_1_PROCESSORS {
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
next.push(proc.to_string());
}
}
if !next.is_empty() {
return next;
}
// Check stage 2
for proc in STAGE_2_PROCESSORS {
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
next.push(proc.to_string());
}
}
if !next.is_empty() {
return next;
}
// Check stage 3
for proc in STAGE_3_PROCESSORS {
if !self.is_processor_completed(proc) && self.can_run_processor(proc) {
next.push(proc.to_string());
}
}
next
}
/// Check if all processors are complete
pub fn all_processors_complete(&self) -> bool {
for proc in ALL_PROCESSORS {
if !self.is_processor_completed(proc) {
return false;
}
}
true
}
/// Check if Rule 1 can run (text ingestion)
pub fn can_run_rule_1(&self) -> bool {
self.is_processor_completed("asrx")
}
/// Check if Rule 2 can run (TKG nodes)
pub fn can_run_rule_2(&self) -> bool {
self.is_processor_completed("face_trace") && self.is_processor_completed("speaker_vector")
}
/// Check if Rule 3 can run (TKG edges)
pub fn can_run_rule_3(&self) -> bool {
self.stages.rule_2_ingestion.status == "completed"
}
/// Check if file is fully complete
pub fn is_complete(&self) -> bool {
self.all_processors_complete()
&& self.stages.rule_1_ingestion.status == "completed"
&& self.stages.rule_2_ingestion.status == "completed"
&& self.stages.rule_3_ingestion.status == "completed"
}
/// Get overall progress percentage
pub fn overall_progress(&self) -> f64 {
let mut completed = 0;
let mut total = 0;
// Registration
total += 1;
if self.stages.registration.status == "completed" {
completed += 1;
}
// Stage 1
for proc in STAGE_1_PROCESSORS {
total += 1;
if self.is_processor_completed(proc) {
completed += 1;
}
}
// Stage 2
for proc in STAGE_2_PROCESSORS {
total += 1;
if self.is_processor_completed(proc) {
completed += 1;
}
}
// Stage 3
for proc in STAGE_3_PROCESSORS {
total += 1;
if self.is_processor_completed(proc) {
completed += 1;
}
}
// Rules
total += 3;
if self.stages.rule_1_ingestion.status == "completed" { completed += 1; }
if self.stages.rule_2_ingestion.status == "completed" { completed += 1; }
if self.stages.rule_3_ingestion.status == "completed" { completed += 1; }
if total == 0 { 0.0 } else { (completed as f64 / total as f64) * 100.0 }
}
}
impl StageState {
fn new(status: &str) -> Self {
Self {
status: status.to_string(),
started_at: None,
completed_at: None,
error: None,
}
}
}
impl ProcessorState {
fn new(status: &str) -> Self {
Self {
status: status.to_string(),
started_at: None,
completed_at: None,
progress: None,
output_count: None,
error: None,
retry_count: None,
}
}
}
impl IngestionState {
fn new(status: &str) -> Self {
Self {
status: status.to_string(),
started_at: None,
completed_at: None,
items_ingested: None,
error: None,
}
}
}
/// Compute group status from processor states
fn compute_group_status(processors: &HashMap<String, ProcessorState>) -> String {
let mut has_running = false;
let mut has_failed = false;
let mut has_pending = false;
let mut completed_count = 0;
for proc in processors.values() {
match proc.status.as_str() {
"running" => has_running = true,
"failed" => has_failed = true,
"pending" => has_pending = true,
"completed" => completed_count += 1,
_ => {}
}
}
if has_running {
"in_progress".to_string()
} else if has_failed {
"failed".to_string()
} else if has_pending {
if completed_count > 0 {
"partial".to_string()
} else {
"pending".to_string()
}
} else {
"completed".to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lifecycle_new() {
let lifecycle = FileLifecycle::new("test_uuid");
assert_eq!(lifecycle.file_uuid, "test_uuid");
assert_eq!(lifecycle.stages.registration.status, "pending");
assert_eq!(lifecycle.stages.stage_1_processors.status, "pending");
}
#[test]
fn test_processor_dependencies() {
assert!(get_dependencies("asr").is_empty());
assert_eq!(get_dependencies("asrx"), vec!["cut", "asr"]);
assert_eq!(get_dependencies("pose"), vec!["face"]);
}
#[test]
fn test_can_run_processor() {
let mut lifecycle = FileLifecycle::new("test");
// Initially, asrx cannot run (needs cut + asr)
assert!(!lifecycle.can_run_processor("asrx"));
// After registration, still cannot run (needs asr)
lifecycle.mark_stage_completed("registration");
assert!(!lifecycle.can_run_processor("asrx"));
// After asr completes, can run
lifecycle.mark_processor_completed("asr", Some(10));
assert!(lifecycle.can_run_processor("asrx"));
}
#[test]
fn test_overall_progress() {
let mut lifecycle = FileLifecycle::new("test");
assert_eq!(lifecycle.overall_progress(), 0.0);
lifecycle.mark_stage_completed("registration");
let progress = lifecycle.overall_progress();
assert!(progress > 0.0 && progress < 100.0);
}
}
+559
View File
@@ -0,0 +1,559 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Version of the file profile schema.
const PROFILE_VERSION: &str = "1.0";
// ─── Data Types ───
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileProfile {
pub version: String,
pub file_uuid: String,
pub file_name: String,
pub file_type: String,
pub birth: BirthInfo,
pub current: CurrentInfo,
pub history: Vec<HistoryEntry>,
pub metadata: Option<MediaMetadata>,
pub key_frame: Option<String>, // filename: {uuid}.key_frame.jpg, video only
pub proxy_path: Option<String>, // 720p proxy path for 1080p+ videos
pub audio_track: Option<String>, // audio track classification: no_audio/silent_audio/music_only/speech_only/speech_with_music
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BirthInfo {
pub mac_address: String,
pub birthday: String, // RFC3339
pub original_path: String,
pub original_filename: String,
pub canonical_path: String,
pub content_hash: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurrentInfo {
pub path: String,
pub file_name: String,
pub file_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryEntry {
pub action: String,
pub timestamp: String, // RFC3339
pub path: String,
pub file_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaMetadata {
pub duration: f64,
pub width: u32,
pub height: u32,
pub fps: f64,
pub total_frames: u64,
}
// ─── Construction ───
impl FileProfile {
/// Build a new profile from registration parameters.
#[allow(clippy::too_many_arguments)]
pub fn from_registration(
file_uuid: &str,
file_name: &str,
file_type: &str,
mac_address: &str,
birthday: &str,
canonical_path: &str,
content_hash: &str,
duration: f64,
width: u32,
height: u32,
fps: f64,
total_frames: u64,
) -> Self {
let now = chrono::Utc::now().to_rfc3339();
let parent = Path::new(canonical_path)
.parent()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
Self {
version: PROFILE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
file_name: file_name.to_string(),
file_type: file_type.to_string(),
birth: BirthInfo {
mac_address: mac_address.to_string(),
birthday: birthday.to_string(),
original_path: parent,
original_filename: file_name.to_string(),
canonical_path: canonical_path.to_string(),
content_hash: if content_hash.is_empty() {
None
} else {
Some(content_hash.to_string())
},
},
current: CurrentInfo {
path: canonical_path.to_string(),
file_name: file_name.to_string(),
file_type: file_type.to_string(),
},
history: vec![HistoryEntry {
action: "registered".to_string(),
timestamp: now,
path: canonical_path.to_string(),
file_name: file_name.to_string(),
}],
metadata: if duration > 0.0 || width > 0 || height > 0 {
Some(MediaMetadata {
duration,
width,
height,
fps,
total_frames,
})
} else {
None
},
key_frame: None,
proxy_path: None,
audio_track: None,
}
}
/// Build a minimal profile for zombie files (missing path/name in DB).
pub fn from_zombie(file_uuid: &str, file_type: &str, content_hash: &str) -> Self {
let now = chrono::Utc::now().to_rfc3339();
Self {
version: PROFILE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
file_name: String::new(),
file_type: file_type.to_string(),
birth: BirthInfo {
mac_address: String::new(),
birthday: String::new(),
original_path: String::new(),
original_filename: String::new(),
canonical_path: String::new(),
content_hash: if content_hash.is_empty() {
None
} else {
Some(content_hash.to_string())
},
},
current: CurrentInfo {
path: String::new(),
file_name: String::new(),
file_type: file_type.to_string(),
},
history: vec![HistoryEntry {
action: "recovered_zombie".to_string(),
timestamp: now,
path: String::new(),
file_name: String::new(),
}],
metadata: None,
key_frame: None,
proxy_path: None,
audio_track: None,
}
}
// ─── Persistence ───
/// Return the profile file path: `{output_dir}/{file_uuid}.profile.json`
pub fn profile_path(output_dir: &str, file_uuid: &str) -> PathBuf {
Path::new(output_dir).join(format!("{}.profile.json", file_uuid))
}
/// Save profile to disk.
pub fn save_to_disk(&self, output_dir: &str) -> Result<()> {
let path = Self::profile_path(output_dir, &self.file_uuid);
let json =
serde_json::to_string_pretty(self).context("Failed to serialize file profile")?;
std::fs::write(&path, json)
.with_context(|| format!("Failed to write profile to {}", path.display()))?;
tracing::debug!("[FileProfile] Saved profile for {}", self.file_uuid);
Ok(())
}
/// Load profile from disk. Returns `None` if file doesn't exist.
pub fn load_from_disk(output_dir: &str, file_uuid: &str) -> Option<Self> {
let path = Self::profile_path(output_dir, file_uuid);
let content = std::fs::read_to_string(&path).ok()?;
serde_json::from_str(&content).ok()
}
/// Load profile from disk, returning error if not found.
pub fn load_or_error(output_dir: &str, file_uuid: &str) -> Result<Self> {
let path = Self::profile_path(output_dir, file_uuid);
let content = std::fs::read_to_string(&path)
.with_context(|| format!("Profile not found: {}", path.display()))?;
serde_json::from_str(&content).context("Failed to parse file profile")
}
// ─── Updates ───
/// Record a path/name change. Updates `current` and appends to `history`.
pub fn update_current_path(&mut self, new_path: &str, new_name: &str) {
let now = chrono::Utc::now().to_rfc3339();
// Only record if something actually changed
if self.current.path == new_path && self.current.file_name == new_name {
return;
}
self.history.push(HistoryEntry {
action: "moved".to_string(),
timestamp: now,
path: new_path.to_string(),
file_name: new_name.to_string(),
});
self.current.path = new_path.to_string();
self.current.file_name = new_name.to_string();
}
/// Set the key_frame (base64-encoded JPEG).
pub fn set_key_frame(&mut self, key_frame: String) {
self.key_frame = Some(key_frame);
}
/// Build a profile from existing DB data (for backfilling).
#[allow(clippy::too_many_arguments)]
pub fn from_db_record(
file_uuid: &str,
file_name: &str,
file_path: &str,
file_type: &str,
content_hash: &str,
duration: f64,
width: u32,
height: u32,
fps: f64,
total_frames: u64,
) -> Self {
let now = chrono::Utc::now().to_rfc3339();
let parent = Path::new(file_path)
.parent()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
// Try to extract birthday from probe.json if available
let birthday = now.clone();
Self {
version: PROFILE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
file_name: file_name.to_string(),
file_type: file_type.to_string(),
birth: BirthInfo {
mac_address: String::new(), // Unknown for backfilled records
birthday,
original_path: parent,
original_filename: file_name.to_string(),
canonical_path: file_path.to_string(),
content_hash: if content_hash.is_empty() {
None
} else {
Some(content_hash.to_string())
},
},
current: CurrentInfo {
path: file_path.to_string(),
file_name: file_name.to_string(),
file_type: file_type.to_string(),
},
history: vec![HistoryEntry {
action: "backfilled".to_string(),
timestamp: now,
path: file_path.to_string(),
file_name: file_name.to_string(),
}],
metadata: if duration > 0.0 || width > 0 || height > 0 {
Some(MediaMetadata {
duration,
width,
height,
fps,
total_frames,
})
} else {
None
},
key_frame: None,
proxy_path: None,
audio_track: None,
}
}
// ─── Key Frame Extraction ───
/// Key frame filename: `{file_uuid}.key_frame.jpg`
pub fn key_frame_filename(file_uuid: &str) -> String {
format!("{}.key_frame.jpg", file_uuid)
}
/// Extract a representative frame from a video file using ffmpeg.
/// Saves as `{output_dir}/{file_uuid}.key_frame.jpg`. Returns filename on success.
pub fn extract_key_frame(
video_path: &str,
duration: f64,
output_dir: &str,
file_uuid: &str,
) -> Option<String> {
// Seek to 10% of duration (or 1s if duration is 0)
let seek_time = if duration > 0.0 { duration * 0.1 } else { 1.0 };
let out_path = std::path::Path::new(output_dir).join(Self::key_frame_filename(file_uuid));
let status = std::process::Command::new("ffmpeg")
.args([
"-y",
"-ss",
&format!("{:.2}", seek_time),
"-i",
video_path,
"-vframes",
"1",
"-vf",
"scale=640:-1",
"-q:v",
"5",
&out_path.to_string_lossy(),
])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.ok()?;
if status.success() && out_path.exists() {
Some(Self::key_frame_filename(file_uuid))
} else {
None
}
}
}
// ─── Face Trace Profile ───
/// Per-trace profile stored in `output/{file_uuid}/{trace_id}/trace_profile.json`.
///
/// Bbox is NOT stored here — it's already in Qdrant `_faces` per-point.
/// Original pixel values from Apple Vision are never modified.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceTraceProfile {
pub version: String,
pub file_uuid: String,
pub trace_id: i64,
pub label: String,
pub frame_count: i64,
pub start_frame: i64,
pub end_frame: i64,
pub avg_confidence: Option<f64>,
pub key_frame: Option<String>, // filename: key_frame.jpg
pub key_face: Option<String>, // filename: key_face.jpg
pub status: String, // pending / bound / merged
}
impl FaceTraceProfile {
/// Directory: `output/{file_uuid}/{trace_id}/`
pub fn trace_dir(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf {
Path::new(output_dir)
.join(file_uuid)
.join(format!("trace_{}", trace_id))
}
/// Profile file path: `output/{file_uuid}/{trace_id}/trace_profile.json`
pub fn profile_path(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf {
Self::trace_dir(output_dir, file_uuid, trace_id).join("trace_profile.json")
}
/// Build a new trace profile.
#[allow(clippy::too_many_arguments)]
pub fn new(
file_uuid: &str,
trace_id: i64,
label: &str,
frame_count: i64,
start_frame: i64,
end_frame: i64,
avg_confidence: Option<f64>,
) -> Self {
Self {
version: PROFILE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
trace_id,
label: label.to_string(),
frame_count,
start_frame,
end_frame,
avg_confidence,
key_frame: None,
key_face: None,
status: "pending".to_string(),
}
}
/// Save profile + key_frame.jpg + key_face.jpg to `output/{file_uuid}/{trace_id}/`.
/// `key_frame_jpeg` and `key_face_jpeg` are raw JPEG bytes (optional).
pub fn save(
&mut self,
output_dir: &str,
key_frame_jpeg: Option<&[u8]>,
key_face_jpeg: Option<&[u8]>,
) -> Result<()> {
let dir = Self::trace_dir(output_dir, &self.file_uuid, self.trace_id);
std::fs::create_dir_all(&dir)
.with_context(|| format!("Failed to create {}", dir.display()))?;
// Write key_frame.jpg
if let Some(jpeg) = key_frame_jpeg {
let kf_path = dir.join("key_frame.jpg");
std::fs::write(&kf_path, jpeg)
.with_context(|| format!("Failed to write {}", kf_path.display()))?;
self.key_frame = Some("key_frame.jpg".to_string());
}
// Write key_face.jpg
if let Some(jpeg) = key_face_jpeg {
let face_path = dir.join("key_face.jpg");
std::fs::write(&face_path, jpeg)
.with_context(|| format!("Failed to write {}", face_path.display()))?;
self.key_face = Some("key_face.jpg".to_string());
}
// Write trace_profile.json
let json =
serde_json::to_string_pretty(self).context("Failed to serialize FaceTraceProfile")?;
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
std::fs::write(&profile_path, json)
.with_context(|| format!("Failed to write {}", profile_path.display()))?;
Ok(())
}
/// Load profile from disk.
pub fn load(output_dir: &str, file_uuid: &str, trace_id: i64) -> Option<Self> {
let path = Self::profile_path(output_dir, file_uuid, trace_id);
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_profile_path() {
let path = FileProfile::profile_path("/output", "abc123");
assert_eq!(path, PathBuf::from("/output/abc123.profile.json"));
}
#[test]
fn test_from_registration() {
let profile = FileProfile::from_registration(
"abc123",
"test.mp4",
"video",
"aa:bb:cc:dd:ee:ff",
"2026-01-01T00:00:00Z",
"/Users/test/video.mp4",
"hash123",
120.0,
1920,
1080,
30.0,
3600,
);
assert_eq!(profile.version, "1.0");
assert_eq!(profile.file_uuid, "abc123");
assert_eq!(profile.file_name, "test.mp4");
assert_eq!(profile.current.path, "/Users/test/video.mp4");
assert_eq!(profile.history.len(), 1);
assert_eq!(profile.history[0].action, "registered");
assert!(profile.metadata.is_some());
assert!(profile.key_frame.is_none());
}
#[test]
fn test_update_current_path() {
let mut profile = FileProfile::from_registration(
"abc123",
"test.mp4",
"video",
"aa:bb:cc:dd:ee:ff",
"2026-01-01T00:00:00Z",
"/Users/test/video.mp4",
"hash123",
120.0,
1920,
1080,
30.0,
3600,
);
profile.update_current_path("/Users/test/moved.mp4", "moved.mp4");
assert_eq!(profile.current.path, "/Users/test/moved.mp4");
assert_eq!(profile.current.file_name, "moved.mp4");
assert_eq!(profile.history.len(), 2);
assert_eq!(profile.history[1].action, "moved");
}
#[test]
fn test_no_move_if_same_path() {
let mut profile = FileProfile::from_registration(
"abc123",
"test.mp4",
"video",
"aa:bb:cc:dd:ee:ff",
"2026-01-01T00:00:00Z",
"/Users/test/video.mp4",
"hash123",
120.0,
1920,
1080,
30.0,
3600,
);
profile.update_current_path("/Users/test/video.mp4", "test.mp4");
assert_eq!(profile.history.len(), 1); // No new entry
}
#[test]
fn test_zombie_profile() {
let profile = FileProfile::from_zombie("zombie123", "video", "hash");
assert_eq!(profile.file_uuid, "zombie123");
assert!(profile.file_name.is_empty());
assert!(profile.birth.canonical_path.is_empty());
assert_eq!(profile.history[0].action, "recovered_zombie");
}
#[test]
fn test_serialization_roundtrip() {
let profile = FileProfile::from_registration(
"abc123",
"test.mp4",
"video",
"aa:bb:cc:dd:ee:ff",
"2026-01-01T00:00:00Z",
"/Users/test/video.mp4",
"hash123",
120.0,
1920,
1080,
30.0,
3600,
);
let json = serde_json::to_string(&profile).unwrap();
let restored: FileProfile = serde_json::from_str(&json).unwrap();
assert_eq!(restored.file_uuid, profile.file_uuid);
assert_eq!(restored.file_name, profile.file_name);
assert_eq!(restored.history.len(), 1);
}
}
+52 -1
View File
@@ -224,8 +224,9 @@ impl IngestionService {
cut_max_duration: 0.0,
scene_done: false,
audio_tracks: None,
proxy_path: None,
audio_track: None,
};
self.db
.register_video(&record)
.await
@@ -254,6 +255,56 @@ impl IngestionService {
.await
.with_context(|| "Failed to set birth_registration")?;
// ── File Profile: write first artifact to disk ──
{
use crate::core::file_profile::FileProfile;
let has_video = probe_result.as_ref().map_or(false, |pr| {
pr.streams
.iter()
.any(|s| s.codec_type.as_deref() == Some("video"))
});
let has_audio = probe_result.as_ref().map_or(false, |pr| {
pr.streams
.iter()
.any(|s| s.codec_type.as_deref() == Some("audio"))
});
let file_type_str = if has_video {
"video"
} else if has_audio {
"audio"
} else {
"unknown"
};
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let mut profile = FileProfile::from_registration(
&uuid,
&final_name,
file_type_str,
&uuid_utils::get_mac_address(),
&birthday,
&canonical_path.to_string_lossy(),
&content_hash,
duration,
width,
height,
fps,
total_frames.unwrap_or(0),
);
if has_video {
if let Some(kf) = FileProfile::extract_key_frame(
&canonical_path.to_string_lossy(),
duration,
output_dir,
&uuid,
) {
profile.set_key_frame(kf);
}
}
if let Err(e) = profile.save_to_disk(output_dir) {
warn!("Failed to save file profile: {}", e);
}
}
Ok(Some(uuid))
}
}
+3
View File
@@ -7,6 +7,8 @@ pub mod chunk;
pub mod config;
pub mod db;
pub mod embedding;
pub mod file_lifecycle;
pub mod file_profile;
pub mod frame_cache;
pub mod health_agent;
pub mod identity;
@@ -18,6 +20,7 @@ pub mod pipeline;
pub mod probe;
pub mod processor;
pub mod progress;
pub mod proxy;
pub mod storage;
pub mod text;
pub mod thumbnail;
+78
View File
@@ -146,6 +146,84 @@ pub async fn vectorize_chunks(uuid: &str) -> Result<()> {
Ok(())
}
pub async fn reindex_embeddings(uuid: &str) -> Result<()> {
let db = PostgresDb::new(&config::DATABASE_URL).await?;
let qdrant = QdrantDb::new();
let chunk_table = schema::table_name("chunk");
let rows = sqlx::query_as::<_, (String, String, String, i64, i64, f64, f64, String, String)>(
&format!(
"SELECT chunk_id, chunk_type, text_content, start_frame, end_frame, \
start_time, end_time, content::text, embedding::text \
FROM {} WHERE file_uuid = $1 AND embedding IS NOT NULL \
ORDER BY id",
chunk_table
),
)
.bind(uuid)
.fetch_all(db.pool())
.await?;
if rows.is_empty() {
println!("No chunks with embeddings to reindex for {}", uuid);
return Ok(());
}
let total = rows.len();
let mut stored = 0usize;
for (
chunk_id,
chunk_type,
text,
start_frame,
end_frame,
start_time,
end_time,
_content_str,
embedding_text,
) in &rows
{
let vector: Vec<f32> = match serde_json::from_str(embedding_text) {
Ok(v) => v,
Err(e) => {
eprintln!("Failed to parse embedding for {}: {}", chunk_id, e);
continue;
}
};
let payload = VectorPayload {
file_uuid: uuid.to_string(),
chunk_id: chunk_id.clone(),
chunk_type: chunk_type.clone(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: if text.is_empty() {
None
} else {
Some(text.clone())
},
};
if let Err(e) = qdrant.upsert_vector(chunk_id, &vector, payload).await {
eprintln!("Qdrant upsert failed for {}: {}", chunk_id, e);
continue;
}
stored += 1;
if stored % 50 == 0 {
println!("Reindexed {}/{} chunks for {}", stored, total, uuid);
}
}
println!(
"Reindex complete: {}/{} embeddings pushed to Qdrant for {}",
stored, total, uuid
);
Ok(())
}
pub async fn run_phase1(uuid: &str) -> Result<()> {
let executor = PythonExecutor::new().context("Failed to create PythonExecutor")?;
+2
View File
@@ -54,6 +54,8 @@ pub struct AsrSegment {
pub start_frame: Option<i64>,
pub end_frame: Option<i64>,
pub text: String,
#[serde(default)]
pub confidence: f64,
}
pub async fn process_asr(
+17 -1
View File
@@ -16,7 +16,23 @@ pub struct FaceClusterResult {
pub struct FaceClusterInfo {
pub cluster_id: String,
pub face_count: usize,
pub representative_face: Option<String>,
pub representative_face: Option<RepresentativeFace>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RepresentativeFace {
pub face_id: String,
pub confidence: f64,
pub frame: u64,
pub bbox: BoundingBox,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BoundingBox {
pub x: u64,
pub y: u64,
pub width: u64,
pub height: u64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
+111 -36
View File
@@ -97,7 +97,7 @@ fn parse_face_points(points: Vec<serde_json::Value>) -> Vec<FacePoint> {
.iter()
.filter_map(|p| {
let payload = &p["payload"];
let trace_id = payload["trace_id"].as_i64().filter(|&t| t > 0);
let trace_id = payload["trace_id"].as_i64().filter(|&t| t >= 0);
if trace_id.is_none() {
no_trace_id += 1;
return None;
@@ -519,6 +519,7 @@ fn load_face_pose_data(output_dir: &str, file_uuid: &str) -> Result<Vec<FacePose
/// Match a face from face_detections (frame, x, y, w, h) to its pose in face.json
/// Uses bbox center distance to find the best match when multiple faces per frame.
/// Returns None if no pose within threshold (unreliable match).
fn get_pose_for_face(
frame: i64,
x: f64,
@@ -527,6 +528,8 @@ fn get_pose_for_face(
h: f64,
poses: &[FacePose],
) -> Option<(f64, f64, f64)> {
const MAX_CENTER_DIST: f64 = 100.0; // Max center distance for valid match (pixels)
let cx = x + w / 2.0;
let cy = y + h / 2.0;
let mut best_dist = f64::MAX;
@@ -535,7 +538,7 @@ fn get_pose_for_face(
let pcx = p.x + p.w / 2.0;
let pcy = p.y + p.h / 2.0;
let dist = (cx - pcx).abs() + (cy - pcy).abs();
if dist < best_dist {
if dist < best_dist && dist < MAX_CENTER_DIST {
best_dist = dist;
result = Some((p.yaw, p.pitch, p.roll));
}
@@ -1130,6 +1133,7 @@ async fn build_face_track_nodes_from_qdrant(
sum_y: f64,
sum_w: f64,
sum_h: f64,
sum_confidence: f64,
frames: Vec<(i64, f64, f64, f64, f64)>, // (frame, x, y, w, h)
best_frame: i64,
best_confidence: f64,
@@ -1146,6 +1150,7 @@ async fn build_face_track_nodes_from_qdrant(
sum_y: 0.0,
sum_w: 0.0,
sum_h: 0.0,
sum_confidence: 0.0,
frames: vec![],
best_frame: 0,
best_confidence: 0.0,
@@ -1158,6 +1163,7 @@ async fn build_face_track_nodes_from_qdrant(
entry.sum_y += p.y;
entry.sum_w += p.w;
entry.sum_h += p.h;
entry.sum_confidence += p.confidence;
entry.frames.push((p.frame, p.x, p.y, p.w, p.h));
// Track best face (highest confidence)
if p.confidence > entry.best_confidence {
@@ -1218,14 +1224,8 @@ async fn build_face_track_nodes_from_qdrant(
"status": "pending",
});
// Save key frame and key face JPGs
// Save key_frame.jpg + key_face.jpg + trace_profile.json
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let face_dir = std::path::PathBuf::from(output_dir)
.join(".faces").join(file_uuid).join(&external_id);
let _ = std::fs::create_dir_all(&face_dir);
let key_frame_path = face_dir.join("key_frame.jpg");
let key_face_path = face_dir.join("key_face.jpg");
// Get video path from database
let video_path: Option<String> = sqlx::query_scalar(&format!(
@@ -1238,41 +1238,116 @@ async fn build_face_track_nodes_from_qdrant(
.ok()
.flatten();
// Extract key frame using ffmpeg
if !key_frame_path.exists() {
if let Some(ref vp) = video_path {
let timestamp = agg.best_frame as f64 / 30.0;
let _ = std::process::Command::new("ffmpeg")
.args(["-y", "-v", "quiet", "-ss", &timestamp.to_string(), "-i", vp])
.args(["-frames:v", "1", "-q:v", "2"])
.arg(key_frame_path.to_str().unwrap_or(""))
.output();
// Get actual fps for timestamp calculation
let actual_fps: f64 = sqlx::query_scalar(&format!(
"SELECT fps FROM {} WHERE file_uuid = $1",
crate::core::db::schema::table_name("videos")
))
.bind(file_uuid)
.fetch_optional(pool)
.await
.ok()
.flatten()
.unwrap_or(30.0);
let avg_confidence = if agg.frame_count > 0 {
agg.sum_confidence / agg.frame_count as f64
} else {
0.0
};
let mut trace_profile = crate::core::file_profile::FaceTraceProfile::new(
file_uuid,
*tid,
&label,
agg.frame_count,
agg.start_f,
agg.end_f,
Some(avg_confidence),
);
// Extract key_frame JPEG bytes via ffmpeg pipe
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
let timestamp = agg.best_frame as f64 / actual_fps;
let output = std::process::Command::new("ffmpeg")
.args([
"-y",
"-v",
"quiet",
"-ss",
&format!("{:.3}", timestamp),
"-i",
])
.arg(vp)
.args([
"-frames:v",
"1",
"-q:v",
"2",
"-f",
"image2pipe",
"-c:v",
"mjpeg",
"pipe:1",
])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if output.status.success() && !output.stdout.is_empty() {
Some(output.stdout)
} else {
None
}
}
});
// Crop key face from key frame using bbox
if !key_face_path.exists() && key_frame_path.exists() {
let bbox = &props["avg_bbox"];
let x = bbox["x"].as_i64().unwrap_or(0) as u32;
let y = bbox["y"].as_i64().unwrap_or(0) as u32;
let w = bbox["width"].as_i64().unwrap_or(100) as u32;
let h = bbox["height"].as_i64().unwrap_or(100) as u32;
let _ = std::process::Command::new("ffmpeg")
.args(["-y", "-v", "quiet", "-i", key_frame_path.to_str().unwrap_or("")])
.args(["-vf", &format!("crop={}:{}:{}:{}", w, h, x, y)])
.args(["-q:v", "2"])
.arg(key_face_path.to_str().unwrap_or(""))
.output();
}
// Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame)
let key_face_jpeg: Option<Vec<u8>> = key_frame_jpeg.as_ref().and_then(|kf| {
// Find bbox for best_frame from trace frames
let (_, bx, by, bw, bh) = agg.frames.iter().find(|(f, _, _, _, _)| *f == agg.best_frame)?;
let crop_filter = format!(
"crop={}:{}:{}:{}",
(*bw as i64).max(1),
(*bh as i64).max(1),
(*bx as i64).max(0),
(*by as i64).max(0),
);
let mut cmd = std::process::Command::new("ffmpeg");
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
.arg(&crop_filter)
.args(["-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null());
let mut child = cmd.spawn().ok()?;
if let Some(ref mut stdin) = child.stdin {
use std::io::Write;
let _ = stdin.write_all(kf);
}
let output = child.wait_with_output().ok()?;
if output.status.success() && !output.stdout.is_empty() {
Some(output.stdout)
} else {
None
}
});
// Update props with actual file paths
// Save all three files to output/{file_uuid}/{trace_id}/
let _ = trace_profile.save(
output_dir,
key_frame_jpeg.as_deref(),
key_face_jpeg.as_deref(),
);
// Update props with actual file paths (for DB properties JSONB)
let final_props = serde_json::json!({
"trace_id": tid,
"frame_count": agg.frame_count,
"start_frame": agg.start_f,
"end_frame": agg.end_f,
"key_frame": if key_frame_path.exists() { key_frame_path.to_string_lossy().to_string() } else { serde_json::Value::Null.to_string() },
"key_face": if key_face_path.exists() { key_face_path.to_string_lossy().to_string() } else { serde_json::Value::Null.to_string() },
"key_frame": agg.best_frame,
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
"avg_bbox": props["avg_bbox"].clone(),
"avg_yaw": props["avg_yaw"].clone(),
"avg_pitch": props["avg_pitch"].clone(),
+1 -1
View File
@@ -63,7 +63,7 @@ impl PipelineProgress {
detail: None,
},
PipelineStage {
name: "identity_agent".into(),
name: "face_dedup".into(),
weight: 0.10,
progress: 0.0,
status: "pending".into(),
+263
View File
@@ -0,0 +1,263 @@
use anyhow::{Context, Result};
use std::path::PathBuf;
use std::process::Command;
use crate::core::config::{OUTPUT_DIR, PYTHON_PATH};
const PROXY_HEIGHT: u32 = 720;
const PROXY_CRF: u32 = 23;
const MIN_HEIGHT_FOR_PROXY: u32 = 1080;
pub fn needs_proxy(width: u32, height: u32) -> bool {
height >= MIN_HEIGHT_FOR_PROXY || width >= MIN_HEIGHT_FOR_PROXY
}
pub fn proxy_output_path(file_path: &str) -> Result<PathBuf> {
let src = std::path::Path::new(file_path);
let stem = src
.file_stem()
.context("Cannot get file stem")?
.to_string_lossy();
let parent = src.parent().context("Cannot get parent dir")?;
Ok(parent.join(format!("{}_720p.mp4", stem)))
}
fn ffmpeg_cmd() -> Command {
let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string());
let mut cmd = Command::new(&ffmpeg_path);
let full_lib = "/opt/homebrew/opt/ffmpeg-full/lib";
if std::path::Path::new(full_lib).exists() {
cmd.env("DYLD_LIBRARY_PATH", full_lib);
}
cmd
}
pub async fn generate_proxy(file_path: &str, file_uuid: &str) -> Result<Option<String>> {
let src = std::path::Path::new(file_path);
if !src.exists() {
tracing::warn!("[PROXY] Source file not found: {}", file_path);
return Ok(None);
}
let out = proxy_output_path(file_path)?;
if out.exists() {
tracing::info!("[PROXY] Proxy already exists: {}", out.display());
return Ok(Some(out.to_string_lossy().to_string()));
}
let out_str = out.to_string_lossy().to_string();
let file_path_owned = file_path.to_string();
let status = tokio::task::spawn_blocking(move || {
ffmpeg_cmd()
.args([
"-i", &file_path_owned,
"-vf", &format!("scale=-2:{}", PROXY_HEIGHT),
"-c:v", "libx264",
"-preset", "fast",
"-crf", &PROXY_CRF.to_string(),
"-c:a", "aac",
"-b:a", "128k",
"-movflags", "+faststart",
"-y", &out_str,
])
.status()
})
.await
.context("Spawn blocking failed")?
.context("Failed to spawn ffmpeg")?;
if !status.success() {
let _ = tokio::fs::remove_file(&out).await;
tracing::error!(
"[PROXY] ffmpeg failed for {} (exit: {:?})",
file_uuid,
status.code()
);
return Ok(None);
}
tracing::info!(
"[PROXY] Generated 720p proxy: {} -> {}",
file_uuid,
out.display()
);
Ok(Some(out.to_string_lossy().to_string()))
}
/// Audio track classification result
#[derive(Debug, Clone)]
pub struct AudioTrackResult {
pub classification: String,
pub speech_ratio: f64,
pub speech_segments: i32,
pub duration: f64,
}
/// Probe audio track and classify using VAD
pub async fn probe_audio_track(file_path: &str) -> Result<Option<AudioTrackResult>> {
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/audio_track_probe.py");
if !script.exists() {
tracing::warn!("[AUDIO_TRACK] Script not found: {}", script.display());
return Ok(None);
}
let file_path_owned = file_path.to_string();
let script_str = script.to_string_lossy().to_string();
let python_path = PYTHON_PATH.as_str().to_string();
let output = tokio::task::spawn_blocking(move || {
Command::new(&python_path)
.arg(&script_str)
.arg("--file")
.arg(&file_path_owned)
.arg("--json")
.output()
})
.await
.context("Spawn blocking failed")?
.context("Failed to spawn python")?;
if !output.status.success() {
tracing::warn!(
"[AUDIO_TRACK] Probe failed: {}",
String::from_utf8_lossy(&output.stderr)
);
return Ok(None);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = match serde_json::from_str(&stdout) {
Ok(v) => v,
Err(e) => {
tracing::warn!("[AUDIO_TRACK] JSON parse error: {}", e);
return Ok(None);
}
};
let classification = json
.get("classification")
.and_then(|v| v.as_str())
.unwrap_or("speech_only")
.to_string();
let speech_ratio = json
.get("speech_ratio")
.and_then(|v| v.as_f64())
.unwrap_or(0.5);
let speech_segments = json
.get("speech_segments")
.and_then(|v| v.as_i64())
.unwrap_or(0) as i32;
let duration = json
.get("duration")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
tracing::info!(
"[AUDIO_TRACK] {} -> {} (ratio: {:.2}, segments: {})",
file_path,
classification,
speech_ratio,
speech_segments
);
Ok(Some(AudioTrackResult {
classification,
speech_ratio,
speech_segments,
duration,
}))
}
/// Extract key frames from each scene in cut.json for VLM analysis
pub async fn extract_cut_key_frames(
file_uuid: &str,
video_path: &str,
output_dir: &str,
) -> Result<Vec<String>> {
let cut_json = PathBuf::from(output_dir)
.join(format!("{}.cut.json", file_uuid));
if !cut_json.exists() {
tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display());
return Ok(vec![]);
}
let script = std::path::Path::new("/Users/accusys/momentry_core/scripts/cut_key_frame.py");
if !script.exists() {
tracing::warn!("[CUT_KEY_FRAME] Script not found: {}", script.display());
return Ok(vec![]);
}
let file_uuid_owned = file_uuid.to_string();
let video_path_owned = video_path.to_string();
let cut_json_str = cut_json.to_string_lossy().to_string();
let output_dir_owned = output_dir.to_string();
let script_str = script.to_string_lossy().to_string();
let python_path = PYTHON_PATH.as_str().to_string();
let output = tokio::task::spawn_blocking(move || {
Command::new(&python_path)
.arg(&script_str)
.arg("--file-uuid")
.arg(&file_uuid_owned)
.arg("--video")
.arg(&video_path_owned)
.arg("--cut-json")
.arg(&cut_json_str)
.arg("--output-dir")
.arg(&output_dir_owned)
.arg("--json")
.output()
})
.await
.context("Spawn blocking failed")?
.context("Failed to spawn python")?;
if !output.status.success() {
tracing::warn!(
"[CUT_KEY_FRAME] Extraction failed: {}",
String::from_utf8_lossy(&output.stderr)
);
return Ok(vec![]);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = match serde_json::from_str(&stdout) {
Ok(v) => v,
Err(e) => {
tracing::warn!("[CUT_KEY_FRAME] JSON parse error: {}", e);
return Ok(vec![]);
}
};
let scenes: Vec<String> = json
.get("scenes")
.and_then(|s| s.as_array())
.map(|arr| {
arr.iter()
.filter_map(|s| {
if s.get("success").and_then(|b| b.as_bool()) == Some(true) {
s.get("output_path").and_then(|p| p.as_str().map(|p| p.to_string()))
} else {
None
}
})
.collect()
})
.unwrap_or_default();
tracing::info!(
"[CUT_KEY_FRAME] Extracted {} scene key frames for {}",
scenes.len(),
file_uuid
);
Ok(scenes)
}