feat: face fix deployment + trace_* regeneration + executor stderr filter fix

- swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64
- trace_* directories regenerated for KOBA (37 traces, start_frame 5307)
- executor.rs: stderr filter now logs all non-empty stderr (was discarding)
- VAD not skippable in ASRX (main_fixed.py Step 2 always runs)
- Step 2.5 sentence boundary refinement added
- Cluster agent async endpoints + similarity transparency
- Keyword search: relationship text extraction, priority ordering
- Face fix handoff doc for Studio team
This commit is contained in:
Accusys
2026-08-05 00:13:50 +08:00
parent 36a704e3d3
commit 3d13a06bd9
42 changed files with 3447 additions and 778 deletions
+85 -67
View File
@@ -563,7 +563,12 @@ pub async fn exec_smart_search(
.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);
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");
@@ -619,7 +624,17 @@ pub async fn exec_smart_search(
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)| {
|(
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("");
@@ -641,8 +656,16 @@ pub async fn exec_smart_search(
.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 };
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",
@@ -667,7 +690,8 @@ pub async fn exec_smart_search(
"query": query,
"count": cards.len(),
"cards": cards
}).to_string())
})
.to_string())
}
pub async fn exec_identity_text(
@@ -1467,15 +1491,13 @@ pub async fn exec_trace_search(
})
.collect();
Ok(
serde_json::json!({
"tool": "trace_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string(),
)
Ok(serde_json::json!({
"tool": "trace_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string())
}
/// Semantic search using embedding + Qdrant
@@ -1495,7 +1517,12 @@ pub async fn exec_semantic_search(
.unwrap_or(10)
.min(50) as usize;
tracing::info!("[exec_semantic_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit);
tracing::info!(
"[exec_semantic_search] query='{}', file_uuid={:?}, limit={}",
query,
file_uuid,
limit
);
if query.is_empty() {
return Err("query is required".to_string());
@@ -1503,15 +1530,15 @@ pub async fn exec_semantic_search(
// 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)
})?;
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());
tracing::info!(
"[exec_semantic_search] Embedding generated, dim={}",
embedding.len()
);
// Search Qdrant
let qdrant = QdrantDb::new();
@@ -1526,16 +1553,16 @@ pub async fn exec_semantic_search(
})?
} 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)
})?
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());
tracing::info!(
"[exec_semantic_search] Qdrant returned {} hits",
search_results.len()
);
// Enrich from PostgreSQL
let chunk_table = schema::table_name("chunk");
@@ -1543,29 +1570,24 @@ pub async fn exec_semantic_search(
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, \
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))?;
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 {
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
@@ -1590,15 +1612,13 @@ pub async fn exec_semantic_search(
}
}
Ok(
serde_json::json!({
"tool": "semantic_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string(),
)
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
@@ -1685,13 +1705,11 @@ pub async fn exec_face_profile_search(
})
.collect();
Ok(
serde_json::json!({
"tool": "face_profile_search",
"query": name,
"count": cards.len(),
"cards": cards
})
.to_string(),
)
Ok(serde_json::json!({
"tool": "face_profile_search",
"query": name,
"count": cards.len(),
"cards": cards
})
.to_string())
}
+80 -17
View File
@@ -891,6 +891,34 @@ pub struct ChildChunkResult {
pub speaker_ids: Vec<String>,
}
/// Extract actual text content from a relationship chunk's content JSON.
/// Returns the related sentence text if found, otherwise falls back to empty string.
fn extract_relationship_text(content_json: &str) -> String {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(content_json) {
if let Some(target) = json.get("target_node") {
if let Some(label) = target.get("label").and_then(|v| v.as_str()) {
if let Some(pos) = label.find(':') {
let text_part = label[pos + 1..].trim();
if !text_part.is_empty() {
return text_part.to_string();
}
}
}
}
if let Some(source) = json.get("source_node") {
if let Some(label) = source.get("label").and_then(|v| v.as_str()) {
if let Some(pos) = label.find(':') {
let text_part = label[pos + 1..].trim();
if !text_part.is_empty() {
return text_part.to_string();
}
}
}
}
}
String::new()
}
impl PostgresDb {
pub fn from_pool(pool: PgPool) -> Self {
Self {
@@ -1240,8 +1268,14 @@ impl PostgresDb {
// ── 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_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 ──
@@ -3508,7 +3542,10 @@ impl PostgresDb {
use sqlx::Row;
// Build WHERE clauses dynamically to handle optional params
let mut clauses = vec!["text_content ILIKE $2".to_string(), "text_content != ''".to_string()];
let mut clauses = vec![
"(text_content ILIKE $2 OR content::text ILIKE $2)".to_string(),
"COALESCE(text_content, content::text, '') != ''".to_string(),
];
let mut next_idx = 3;
if file_uuid.is_some() {
next_idx += 1;
@@ -3522,11 +3559,22 @@ impl PostgresDb {
let where_sql = clauses.join(" AND ");
let sql = format!(
"SELECT chunk_id, file_uuid, chunk_type, text_content, start_time, end_time, \
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8))::float8 as score \
"SELECT chunk_id, file_uuid, chunk_type, text_content, content::text as content_text, start_time, end_time, \
CASE \
WHEN text_content ILIKE $2 THEN \
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8)) \
ELSE \
(1.0 - (POSITION(LOWER($1) IN LOWER(content::text))::float8 / NULLIF(LENGTH(content::text), 0)::float8)) \
END::float8 as score, \
CASE chunk_type \
WHEN 'sentence' THEN 1 \
WHEN 'ocr' THEN 2 \
WHEN 'cut' THEN 3 \
ELSE 4 \
END as priority \
FROM {} \
WHERE {} \
ORDER BY score DESC \
ORDER BY priority ASC, score DESC \
LIMIT $3",
table, where_sql
);
@@ -3542,17 +3590,32 @@ impl PostgresDb {
Ok(rows
.into_iter()
.map(|r| Bm25Result {
file_uuid: r.get("file_uuid"),
chunk_id: r.get("chunk_id"),
chunk_type: r.get("chunk_type"),
uuid: r.get("file_uuid"),
text: r.get("text_content"),
start_time: r.get("start_time"),
end_time: r.get("end_time"),
bm25_score: r.get("score"),
vector_score: 0.0,
combined_score: r.get("score"),
.map(|r| {
let chunk_type: String = r.get("chunk_type");
let text: Option<String> = if chunk_type == "relationship" {
let content_text: String = r.get("content_text");
let extracted = extract_relationship_text(&content_text);
if extracted.is_empty() {
r.get("text_content")
} else {
Some(extracted)
}
} else {
r.get("text_content")
};
Bm25Result {
file_uuid: r.get("file_uuid"),
chunk_id: r.get("chunk_id"),
chunk_type: r.get("chunk_type"),
uuid: r.get("file_uuid"),
text,
start_time: r.get("start_time"),
end_time: r.get("end_time"),
bm25_score: r.get("score"),
vector_score: 0.0,
combined_score: r.get("score"),
}
})
.collect())
}
+105 -67
View File
@@ -96,7 +96,13 @@ pub struct IngestionState {
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"];
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"];
@@ -104,9 +110,16 @@ 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
"asr",
"ocr",
"face", // Stage 1
"asrx",
"face_vector",
"face_trace",
"speaker_vector",
"face_cluster", // Stage 2
"pose",
"appearance", // Stage 3
];
/// Get processor dependencies
@@ -140,22 +153,22 @@ 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(),
@@ -185,16 +198,22 @@ impl FileLifecycle {
/// 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();
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));
@@ -202,33 +221,41 @@ impl FileLifecycle {
lifecycle.mark_processor_completed(proc, None);
}
}
// Check stage 2 processors
let has_asrx = Path::new(output_dir).join(format!("{}.asrx.json", file_uuid)).exists();
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();
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();
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();
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));
@@ -236,7 +263,7 @@ impl FileLifecycle {
lifecycle.mark_processor_completed(proc, None);
}
}
lifecycle.update_group_status();
lifecycle
}
@@ -251,8 +278,7 @@ impl FileLifecycle {
/// 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")?;
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);
@@ -278,7 +304,7 @@ impl FileLifecycle {
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();
@@ -313,7 +339,7 @@ impl FileLifecycle {
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();
@@ -343,7 +369,7 @@ impl FileLifecycle {
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,
@@ -351,12 +377,12 @@ impl FileLifecycle {
"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();
}
@@ -365,7 +391,7 @@ impl FileLifecycle {
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,
@@ -373,13 +399,13 @@ impl FileLifecycle {
"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();
}
@@ -387,7 +413,7 @@ impl FileLifecycle {
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,
@@ -395,20 +421,20 @@ impl FileLifecycle {
"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,
@@ -416,7 +442,7 @@ impl FileLifecycle {
"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 });
}
@@ -427,11 +453,11 @@ impl FileLifecycle {
// 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);
@@ -445,7 +471,7 @@ impl FileLifecycle {
if deps.is_empty() {
return true;
}
for dep in deps {
if !self.is_processor_completed(dep) {
return false;
@@ -463,8 +489,10 @@ impl FileLifecycle {
"stage_3" => &self.stages.stage_3_processors,
_ => return processor == "cut" && self.stages.registration.status == "completed",
};
group.processors.get(processor)
group
.processors
.get(processor)
.map(|p| p.status == "completed")
.unwrap_or(false)
}
@@ -472,40 +500,40 @@ impl FileLifecycle {
/// 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
}
@@ -546,13 +574,13 @@ impl FileLifecycle {
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;
@@ -560,7 +588,7 @@ impl FileLifecycle {
completed += 1;
}
}
// Stage 2
for proc in STAGE_2_PROCESSORS {
total += 1;
@@ -568,7 +596,7 @@ impl FileLifecycle {
completed += 1;
}
}
// Stage 3
for proc in STAGE_3_PROCESSORS {
total += 1;
@@ -576,14 +604,24 @@ impl FileLifecycle {
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 }
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
}
}
}
@@ -630,7 +668,7 @@ fn compute_group_status(processors: &HashMap<String, ProcessorState>) -> String
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,
@@ -640,7 +678,7 @@ fn compute_group_status(processors: &HashMap<String, ProcessorState>) -> String
_ => {}
}
}
if has_running {
"in_progress".to_string()
} else if has_failed {
@@ -678,14 +716,14 @@ mod tests {
#[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"));
@@ -695,7 +733,7 @@ mod tests {
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);
+6
View File
@@ -418,6 +418,9 @@ impl FaceTraceProfile {
std::fs::write(&kf_path, jpeg)
.with_context(|| format!("Failed to write {}", kf_path.display()))?;
self.key_frame = Some("key_frame.jpg".to_string());
} else if dir.join("key_frame.jpg").exists() {
// Extraction failed but file already exists on disk: preserve reference
self.key_frame = Some("key_frame.jpg".to_string());
}
// Write key_face.jpg
@@ -426,6 +429,9 @@ impl FaceTraceProfile {
std::fs::write(&face_path, jpeg)
.with_context(|| format!("Failed to write {}", face_path.display()))?;
self.key_face = Some("key_face.jpg".to_string());
} else if dir.join("key_face.jpg").exists() {
// Crop failed but file already exists on disk: preserve reference
self.key_face = Some("key_face.jpg".to_string());
}
// Write trace_profile.json
+21 -1
View File
@@ -123,17 +123,37 @@ impl IngestionService {
let mut width = 0u32;
let mut height = 0u32;
let mut fps = 0.0;
let mut nb_frames: Option<u64> = None;
if let Some(ref probe) = probe_result {
for stream in &probe.streams {
if stream.codec_type.as_deref() == Some("video") {
width = stream.width.unwrap_or(0);
height = stream.height.unwrap_or(0);
if let Some(fps_str) = &stream.r_frame_rate {
// Get nb_frames first (needed for actual fps calculation)
if let Some(nb_frames_str) = &stream.nb_frames {
if let Ok(n) = nb_frames_str.parse::<u64>() {
nb_frames = Some(n);
}
}
// Calculate actual fps from nb_frames / duration (more accurate than r_frame_rate)
if let Some(frames) = nb_frames {
if duration > 0.0 {
fps = frames as f64 / duration;
info!(
"Using actual fps from nb_frames/duration: {} / {} = {:.2} fps",
frames, duration, fps
);
}
} else if let Some(fps_str) = &stream.r_frame_rate {
// Fallback to r_frame_rate if nb_frames or duration unavailable
if let Some((num, den)) = fps_str.split_once('/') {
if let (Ok(n), Ok(d)) = (num.parse::<f64>(), den.parse::<f64>()) {
if d > 0.0 {
fps = n / d;
info!("Using r_frame_rate as fps: {} fps", fps);
}
}
}
+200
View File
@@ -535,6 +535,8 @@ impl PythonExecutor {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
} else if !line.trim().is_empty() {
tracing::warn!("[{} stderr] {}", log_prefix, line);
}
}
Ok(None) => stderr_done = true,
@@ -738,6 +740,8 @@ impl PythonExecutor {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
} else if !line.trim().is_empty() {
tracing::warn!("[{} stderr] {}", log_prefix, line);
}
}
Ok(None) => stderr_done = true,
@@ -825,6 +829,202 @@ impl PythonExecutor {
Ok(())
}
/// Like `run_with_output_idx_and_frames` but accepts a `CancellationToken` so the caller
/// can cleanly abort the Python subprocess without leaking processes.
pub async fn run_with_output_idx_and_frames_with_cancel(
&self,
script_name: &str,
args: &[&str],
uuid: Option<&str>,
log_prefix: &str,
timeout_duration: Option<Duration>,
output_idx: Option<usize>,
frames: Option<&[i64]>,
cancel: tokio_util::sync::CancellationToken,
) -> Result<()> {
let script_path = self.scripts_dir.join(script_name);
if !script_path.exists() {
anyhow::bail!("Script not found: {:?}", script_path);
}
self.verify_script_integrity(script_name).context(
"Pre-execution integrity check failed — possible version mismatch or corruption",
)?;
let output_path =
output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p)));
let tmp_path = output_path.as_ref().map(|p| {
let mut tmp = p.to_path_buf();
tmp.set_extension("json.tmp");
tmp
});
let mut cmd = Command::new(&self.python_path);
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
if let Ok(qdrant_url) = std::env::var("QDRANT_URL") {
cmd.env("QDRANT_URL", qdrant_url);
}
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
if Some(i) == output_idx {
if let Some(ref tmp) = tmp_path {
cmd.arg(tmp);
continue;
}
}
cmd.arg(arg);
}
if let Some(u) = uuid {
cmd.arg("--uuid").arg(u);
}
// Append extra args (e.g. --threshold) after --uuid
// Pass frame list for 8Hz sampling
if let Some(frames) = frames {
if !frames.is_empty() {
let frames_str = Self::format_frames_arg(frames);
cmd.arg("--frames").arg(&frames_str);
}
}
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
cmd.kill_on_drop(true);
cmd.process_group(0);
tracing::info!("[{}] Starting: {:?}", log_prefix, script_name);
let mut child = cmd
.spawn()
.with_context(|| format!("Failed to run {}", script_name))?;
let child_pid = child.id();
let stdout = child.stdout.take().context("Failed to capture stdout")?;
let stderr = child.stderr.take().context("Failed to capture stderr")?;
let mut stdout_reader = BufReader::new(stdout).lines();
let mut stderr_reader = BufReader::new(stderr).lines();
let run_future = async {
let mut stdout_done = false;
let mut stderr_done = false;
loop {
tokio::select! {
line = stdout_reader.next_line(), if !stdout_done => {
match line {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
}
}
Ok(None) => stdout_done = true,
Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e),
}
}
line = stderr_reader.next_line(), if !stderr_done => {
match line {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
} else if !line.trim().is_empty() {
tracing::warn!("[{} stderr] {}", log_prefix, line);
}
}
Ok(None) => stderr_done = true,
Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e),
}
}
_ = cancel.cancelled() => {
tracing::info!("[{}] Cancelled by caller", log_prefix);
if let Some(pid) = child_pid {
unsafe { libc::killpg(pid as i32, libc::SIGTERM); }
}
return Err(anyhow::anyhow!("{} cancelled by caller", script_name));
}
status = child.wait() => {
match status {
Ok(status) => {
if !status.success() {
tracing::error!("[{}] Process failed: {}", log_prefix, status);
return Err(anyhow::anyhow!("{} exited with: {}", script_name, status));
}
tracing::info!("[{}] Completed successfully", log_prefix);
}
Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e),
}
break;
}
}
}
Ok(())
};
let mark_failed = || {
if let Some(tmp) = &tmp_path {
if tmp.exists() {
if let Some(out) = &output_path {
let is_valid = std::fs::read_to_string(tmp)
.ok()
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
.is_some();
if is_valid {
let mut partial_path = out.to_path_buf();
partial_path.set_extension("json.partial");
let _ = std::fs::rename(tmp, &partial_path);
tracing::warn!("[Executor] Partial output preserved: {:?}", partial_path);
} else {
let mut err_path = out.to_path_buf();
err_path.set_extension("json.err");
let _ = std::fs::rename(tmp, &err_path);
}
}
}
}
};
if let Some(duration) = timeout_duration {
match timeout(duration, run_future).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
mark_failed();
return Err(e);
}
Err(_) => {
mark_failed();
if let Some(pid) = child_pid {
unsafe { libc::killpg(pid as i32, libc::SIGKILL); }
}
child.kill().await.context("Failed to kill process")?;
anyhow::bail!("{} timed out after {:?}", script_name, duration);
}
}
} else {
if let Err(e) = run_future.await {
mark_failed();
return Err(e);
}
}
if let Some(tmp) = &tmp_path {
if tmp.exists() {
if let Some(out) = &output_path {
let _ = std::fs::rename(tmp, out);
}
}
}
Ok(())
}
pub async fn run_with_output(
&self,
script_name: &str,
+26 -2
View File
@@ -17,6 +17,14 @@ pub struct FaceClusterInfo {
pub cluster_id: String,
pub face_count: usize,
pub representative_face: Option<RepresentativeFace>,
pub similarity: Option<ClusterSimilarity>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClusterSimilarity {
pub min: f64,
pub avg: f64,
pub threshold: f64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -55,6 +63,7 @@ pub async fn process_face_cluster(
output_path: &str,
uuid: Option<&str>,
frames: Option<&[i64]>,
similarity_threshold: Option<f64>,
) -> Result<FaceClusterResult> {
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("fast_face_clustering_processor.py");
@@ -69,13 +78,28 @@ pub async fn process_face_cluster(
});
}
// Build args with optional --threshold
let distance = similarity_threshold.map(|s| 1.0 - s);
let mut args = vec![video_path, output_path];
if let Some(d) = distance {
let threshold_str = format!("{:.4}", d);
args.push("--threshold");
args.push(Box::leak(threshold_str.into_boxed_str()) as &str);
tracing::info!(
"[FACE_CLUSTER] similarity={:.2} → distance={:.4}",
similarity_threshold.unwrap_or(0.65),
d
);
}
executor
.run_with_frames(
.run_with_output_idx_and_frames(
"fast_face_clustering_processor.py",
&[video_path, output_path],
&args,
uuid,
"FACE_CLUSTER",
Some(FACE_CLUSTER_TIMEOUT),
Some(1),
frames,
)
.await
+1 -2
View File
@@ -96,8 +96,7 @@ pub fn group_ocr_texts_by_zone_and_proximity(
for frame in frames {
// Rule 2: Frame difference detection
let current_texts: HashSet<String> =
frame.texts.iter().map(|t| t.text.clone()).collect();
let current_texts: HashSet<String> = frame.texts.iter().map(|t| t.text.clone()).collect();
let similarity = jaccard_similarity(&last_texts, &current_texts);
if !last_texts.is_empty() && similarity < TEXT_SIMILARITY_THRESHOLD {
+177 -8
View File
@@ -1304,13 +1304,31 @@ async fn build_face_track_nodes_from_qdrant(
// 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 (bf, bx, by, bw, bh) = agg
.frames
.iter()
.find(|(f, _, _, _, _)| *f == agg.best_frame)?;
let (bx, by, bw, bh) = (*bx, *by, *bw, *bh);
// Validate bbox: must have positive dimensions
if bw < 2.0 || bh < 2.0 {
tracing::warn!(
"[TKG] trace {}: invalid bbox {}x{} at ({},{}), skipping key_face",
tid,
bw,
bh,
bx,
by
);
return None;
}
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),
(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"])
@@ -1336,7 +1354,7 @@ async fn build_face_track_nodes_from_qdrant(
// Save all three files to output/{file_uuid}/{trace_id}/
let mut key_frame_file = agg.best_frame.to_string();
let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string();
match trace_profile.save(
output_dir,
key_frame_jpeg.as_deref(),
@@ -1347,7 +1365,154 @@ async fn build_face_track_nodes_from_qdrant(
key_face_file = "key_face.jpg".to_string();
}
Err(e) => {
tracing::error!("[TKG] Failed to save trace_profile for trace {}: {}", tid, e);
tracing::error!(
"[TKG] Failed to save trace_profile for trace {}: {}",
tid,
e
);
}
}
// Validate all three outputs exist: key_frame.jpg, key_face.jpg, trace_profile.json
// If missing, retry extraction on the spot
let trace_dir =
crate::core::file_profile::FaceTraceProfile::trace_dir(output_dir, file_uuid, *tid);
let kf_path = trace_dir.join("key_frame.jpg");
let kface_path = trace_dir.join("key_face.jpg");
let tp_path =
crate::core::file_profile::FaceTraceProfile::profile_path(output_dir, file_uuid, *tid);
let mut need_retry = false;
if !kf_path.exists() {
tracing::warn!(
"[TKG-VERIFY] trace {}: key_frame.jpg missing, retrying",
tid
);
need_retry = true;
}
if !kface_path.exists() {
tracing::warn!("[TKG-VERIFY] trace {}: key_face.jpg missing, retrying", tid);
need_retry = true;
}
if !tp_path.exists() {
tracing::warn!(
"[TKG-VERIFY] trace {}: trace_profile.json missing, retrying",
tid
);
need_retry = true;
}
if need_retry {
if let Some(ref vp) = video_path {
let timestamp = agg.best_frame as f64 / actual_fps;
// Retry key_frame extraction
if !kf_path.exists() {
if let Ok(output) = std::process::Command::new("ffmpeg")
.args([
"-y",
"-v",
"quiet",
"-ss",
&format!("{:.3}", timestamp),
"-i",
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()
{
if output.status.success() && !output.stdout.is_empty() {
let _ = std::fs::write(&kf_path, &output.stdout);
if kf_path.exists() {
tracing::info!(
"[TKG-VERIFY] trace {}: key_frame.jpg recovered",
tid
);
key_frame_file = "key_frame.jpg".to_string();
}
}
}
}
// Retry key_face crop
if !kface_path.exists() && kf_path.exists() {
let (_, bx, by, bw, bh) = agg
.frames
.iter()
.find(|(f, _, _, _, _)| *f == agg.best_frame)
.cloned()
.unwrap_or((0, 0.0, 0.0, 100.0, 100.0));
// Validate bbox
if bw < 2.0 || bh < 2.0 {
tracing::warn!(
"[TKG-VERIFY] trace {}: invalid bbox {}x{}, skipping key_face retry",
tid,
bw,
bh
);
} else {
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),
);
if let Ok(kf_bytes) = std::fs::read(&kf_path) {
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());
if let Ok(mut child) = cmd.spawn() {
if let Some(ref mut stdin) = child.stdin {
use std::io::Write;
let _ = stdin.write_all(&kf_bytes);
}
if let Ok(output) = child.wait_with_output() {
if output.status.success() && !output.stdout.is_empty() {
let _ = std::fs::write(&kface_path, &output.stdout);
if kface_path.exists() {
tracing::info!(
"[TKG-VERIFY] trace {}: key_face.jpg recovered",
tid
);
key_face_file = "key_face.jpg".to_string();
}
}
}
}
}
}
}
// Update trace_profile with recovered file paths, then rewrite profile
// (even if it already exists — it may have stale null key_frame/key_face)
if kf_path.exists() {
trace_profile.key_frame = Some("key_frame.jpg".to_string());
}
if kface_path.exists() {
trace_profile.key_face = Some("key_face.jpg".to_string());
}
if let Ok(json) = serde_json::to_string_pretty(&trace_profile) {
let _ = std::fs::write(&tp_path, json);
if tp_path.exists() {
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
}
}
}
}
@@ -1399,7 +1564,11 @@ async fn build_face_track_nodes_from_qdrant(
count += 1;
}
tracing::info!("[TKG-face_track] built {} face_track nodes for {}", count, file_uuid);
tracing::info!(
"[TKG-face_track] built {} face_track nodes for {}",
count,
file_uuid
);
Ok(count)
}
+24 -19
View File
@@ -23,8 +23,7 @@ pub fn proxy_output_path(file_path: &str) -> Result<PathBuf> {
}
fn ffmpeg_cmd() -> Command {
let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string());
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() {
@@ -52,15 +51,24 @@ pub async fn generate_proxy(file_path: &str, file_uuid: &str) -> Result<Option<S
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,
"-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()
})
@@ -153,10 +161,7 @@ pub async fn probe_audio_track(file_path: &str) -> Result<Option<AudioTrackResul
.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);
let duration = json.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0);
tracing::info!(
"[AUDIO_TRACK] {} -> {} (ratio: {:.2}, segments: {})",
@@ -180,8 +185,7 @@ pub async fn extract_cut_key_frames(
video_path: &str,
output_dir: &str,
) -> Result<Vec<String>> {
let cut_json = PathBuf::from(output_dir)
.join(format!("{}.cut.json", file_uuid));
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());
@@ -244,7 +248,8 @@ pub async fn extract_cut_key_frames(
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()))
s.get("output_path")
.and_then(|p| p.as_str().map(|p| p.to_string()))
} else {
None
}
@@ -260,4 +265,4 @@ pub async fn extract_cut_key_frames(
);
Ok(scenes)
}
}