diff --git a/.env.development b/.env.development index fcc37d1a..887132c3 100644 --- a/.env.development +++ b/.env.development @@ -77,9 +77,9 @@ MOMENTRY_TMDB_PROBE_ENABLED=true MOMENTRY_LLM_CHAT_URL=http://localhost:11434/v1/chat/completions MOMENTRY_LLM_CHAT_MODEL=llama3.1:8b -# VLM uses llama.cpp (llava-v1.6-vicuna-13b) -MOMENTRY_LLM_VISION_URL=http://localhost:8091/v1/chat/completions -MOMENTRY_LLM_VISION_MODEL=llava-v1.6-vicuna-13b +# VLM uses Ollama (llava:7b) - OpenAI-compatible endpoint +MOMENTRY_LLM_VISION_URL=http://localhost:11434/v1/chat/completions +MOMENTRY_LLM_VISION_MODEL=llava:7b # Summary LLM uses Ollama MOMENTRY_LLM_SUMMARY_URL=http://localhost:11434/v1/chat/completions diff --git a/Cargo.toml b/Cargo.toml index 3a5bdf6c..e30fdfd9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,3 +159,7 @@ path = "src/bin/backfill_trace_profiles.rs" [[bin]] name = "rebuild_trace_thumbs" path = "src/bin/rebuild_trace_thumbs.rs" + +[[bin]] +name = "backfill_trace_vlm" +path = "src/bin/backfill_trace_vlm.rs" diff --git a/src/bin/backfill_trace_vlm.rs b/src/bin/backfill_trace_vlm.rs new file mode 100644 index 00000000..3849a8cd --- /dev/null +++ b/src/bin/backfill_trace_vlm.rs @@ -0,0 +1,192 @@ +use anyhow::Result; +use base64::Engine; +use dotenv::dotenv; +use momentry_core::core::config; +use momentry_core::core::db::{schema::table_name, PostgresDb}; +use momentry_core::core::llm::function_calling::call_llm_vision; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +const SYSTEM_PROMPT: &str = + "You are a scene analysis assistant for a video surveillance/DAM system. \ +Given a video key frame, write a concise summary (2-4 sentences, in the same language as the user) \ +describing: what is happening, the people present (clothing/appearance), the setting/location, \ +and any notable objects or actions. Be factual and specific."; + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt::init(); + dotenv().ok(); + + let mut file_filter: Option = None; + let mut force = false; + let mut limit: Option = None; + + let args: Vec = std::env::args().collect(); + let mut i = 1; + while i < args.len() { + match args[i].as_str() { + "--file-uuid" => { + i += 1; + file_filter = args.get(i).cloned(); + } + "--force" => force = true, + "--limit" => { + i += 1; + limit = args.get(i).and_then(|v| v.parse().ok()); + } + "--help" | "-h" => { + println!("Usage: backfill_trace_vlm [--file-uuid ] [--force] [--limit ]"); + return Ok(()); + } + _ => {} + } + i += 1; + } + + let db = PostgresDb::new(&config::DATABASE_URL).await?; + let tp_table = table_name("trace_profiles"); + + // Find traces to process: prefer unpopulated vlm_description, unless --force + let mut sql = format!( + "SELECT file_uuid, trace_id FROM {tp_table} \ + WHERE {} \ + ORDER BY file_uuid, trace_id", + if force { + "TRUE" + } else { + "vlm_description IS NULL OR vlm_description = ''" + } + ); + if let Some(ref f) = file_filter { + sql = format!( + "SELECT file_uuid, trace_id FROM {tp_table} \ + WHERE file_uuid = '{}' {} \ + ORDER BY trace_id", + f, + if force { + "" + } else { + "AND (vlm_description IS NULL OR vlm_description = '')" + } + ); + } + if let Some(l) = limit { + sql = format!("{} LIMIT {}", sql, l); + } + + let traces: Vec<(String, i32)> = sqlx::query_as(&sql).fetch_all(db.pool()).await?; + println!("Found {} traces to process", traces.len()); + + let done = Arc::new(AtomicUsize::new(0)); + let skipped = Arc::new(AtomicUsize::new(0)); + let errors = Arc::new(AtomicUsize::new(0)); + + let mut tasks = Vec::new(); + for (file_uuid, trace_id) in traces { + let done = done.clone(); + let skipped = skipped.clone(); + let errors = errors.clone(); + + let task = tokio::spawn(async move { + match process_trace(&file_uuid, trace_id).await { + Ok(ProcessOutcome::Updated) => { + done.fetch_add(1, Ordering::Relaxed); + println!(" ✅ {} trace {} : summarized", file_uuid, trace_id); + } + Ok(ProcessOutcome::Skipped(reason)) => { + skipped.fetch_add(1, Ordering::Relaxed); + println!(" ⏭ {} trace {} : {}", file_uuid, trace_id, reason); + } + Err(e) => { + errors.fetch_add(1, Ordering::Relaxed); + eprintln!(" ❌ {} trace {} : {}", file_uuid, trace_id, e); + } + } + }); + tasks.push(task); + + // VLM is slow; keep concurrency low + if tasks.len() >= 2 { + tasks.pop().unwrap().await?; + } + } + + for task in tasks { + task.await?; + } + + println!( + "\nDone! Summarized: {}, Skipped: {}, Errors: {}", + done.load(Ordering::Relaxed), + skipped.load(Ordering::Relaxed), + errors.load(Ordering::Relaxed) + ); + Ok(()) +} + +enum ProcessOutcome { + Updated, + Skipped(String), +} + +async fn process_trace(file_uuid: &str, trace_id: i32) -> Result { + let output_dir = config::OUTPUT_DIR.as_str(); + let key_frame_path = PathBuf::from(output_dir) + .join(file_uuid) + .join(format!("trace_{}", trace_id)) + .join("key_frame.jpg"); + + if !key_frame_path.exists() { + return Ok(ProcessOutcome::Skipped("key_frame.jpg missing".to_string())); + } + + let jpeg_bytes = std::fs::read(&key_frame_path)?; + let base64_img = base64::engine::general_purpose::STANDARD.encode(&jpeg_bytes); + + let summary = call_llm_vision( + SYSTEM_PROMPT, + "Summarize this key frame.", + vec![base64_img], + 512, + 120, + ) + .await?; + + if summary.trim().is_empty() { + return Ok(ProcessOutcome::Skipped("VLM returned empty".to_string())); + } + + let db = PostgresDb::new(&config::DATABASE_URL).await?; + let tp_table = table_name("trace_profiles"); + sqlx::query(&format!( + "UPDATE {tp_table} SET vlm_description = $1, vlm_model = $2, updated_at = NOW() \ + WHERE file_uuid = $3 AND trace_id = $4" + )) + .bind(&summary) + .bind(config::llm::VISION_MODEL.as_str()) + .bind(file_uuid) + .bind(trace_id) + .execute(db.pool()) + .await?; + + // Mirror into on-disk trace_profile.json + let profile_path = momentry_core::core::file_profile::FaceTraceProfile::profile_path( + output_dir, + file_uuid, + trace_id as i64, + ); + if profile_path.exists() { + if let Some(mut profile) = momentry_core::core::file_profile::FaceTraceProfile::load( + output_dir, + file_uuid, + trace_id as i64, + ) { + profile.vlm_summary = Some(summary.clone()); + profile.save(output_dir, None, None)?; + } + } + + Ok(ProcessOutcome::Updated) +} diff --git a/src/core/db/postgres_db.rs b/src/core/db/postgres_db.rs index 24d0d759..1307542b 100644 --- a/src/core/db/postgres_db.rs +++ b/src/core/db/postgres_db.rs @@ -1270,7 +1270,7 @@ impl PostgresDb { 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, best_confidence DOUBLE PRECISION, avg_capture_quality DOUBLE PRECISION, best_capture_quality DOUBLE PRECISION, avg_bbox JSONB, best_bbox JSONB, 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 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, best_confidence DOUBLE PRECISION, avg_capture_quality DOUBLE PRECISION, best_capture_quality DOUBLE PRECISION, avg_bbox JSONB, best_bbox JSONB, 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), vlm_embedding JSONB, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?; // Migration: add new fields to existing trace_profiles tables (safe no-op if columns exist) sqlx::query( "ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_confidence DOUBLE PRECISION", @@ -1302,6 +1302,9 @@ impl PostgresDb { .execute(pool) .await?; sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_tags ON trace_profiles USING GIN(vlm_tags)").execute(pool).await?; + sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS vlm_embedding JSONB") + .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?; @@ -2160,7 +2163,9 @@ impl PostgresDb { completed_processors: r.get::>, _>(13).unwrap_or_default(), failed_processors: r.get::>, _>(14).unwrap_or_default(), video_id: r.get(15), - face_settings: r.get::, _>(16).and_then(|s| serde_json::from_str(&s).ok()), + face_settings: r + .get::, _>(16) + .and_then(|s| serde_json::from_str(&s).ok()), })) } else { Ok(None) @@ -2209,7 +2214,9 @@ impl PostgresDb { completed_processors: r.get::>, _>(13).unwrap_or_default(), failed_processors: r.get::>, _>(14).unwrap_or_default(), video_id: r.get(15), - face_settings: r.get::, _>(16).and_then(|s| serde_json::from_str(&s).ok()), + face_settings: r + .get::, _>(16) + .and_then(|s| serde_json::from_str(&s).ok()), } }) .collect(); diff --git a/src/core/file_profile.rs b/src/core/file_profile.rs index e3c4c322..18aee092 100644 --- a/src/core/file_profile.rs +++ b/src/core/file_profile.rs @@ -399,6 +399,8 @@ pub struct FaceTraceProfile { pub key_frame: Option, // filename: key_frame.jpg pub key_face: Option, // filename: key_face.jpg pub status: String, // pending / bound / merged + #[serde(default)] + pub vlm_summary: Option, // VLM free-text summary of key_frame } /// Recursively round float numbers in a JSON value to 2 decimal places. @@ -477,6 +479,7 @@ impl FaceTraceProfile { key_frame: None, key_face: None, status: "pending".to_string(), + vlm_summary: None, } } @@ -515,9 +518,8 @@ impl FaceTraceProfile { } // Write trace_profile.json - let json = - serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?)) - .context("Failed to serialize FaceTraceProfile")?; + let json = serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*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()))?; diff --git a/src/core/processor/mod.rs b/src/core/processor/mod.rs index 7e40127a..867498f7 100644 --- a/src/core/processor/mod.rs +++ b/src/core/processor/mod.rs @@ -15,6 +15,7 @@ pub mod ocr; pub mod pose; pub mod scene_classification; pub mod tkg; +pub mod vlm_summary; pub mod yolo; use serde::{Deserialize, Serialize}; diff --git a/src/core/processor/vlm_summary.rs b/src/core/processor/vlm_summary.rs new file mode 100644 index 00000000..3ec016fb --- /dev/null +++ b/src/core/processor/vlm_summary.rs @@ -0,0 +1,279 @@ +use anyhow::Result; +use base64::Engine; +use std::path::PathBuf; +use std::sync::Arc; +use tracing::{error, info, warn}; + +use crate::core::config; +use crate::core::db::redis_client::RedisClient; +use crate::core::db::schema::table_name; +use crate::core::db::{qdrant_db::QdrantDb, PostgresDb}; +use crate::core::embedding::Embedder; +use crate::core::llm::function_calling::call_llm_vision; +use crate::core::progress::{publish_pipeline_progress, PipelineProgress}; + +const SYSTEM_PROMPT: &str = + "You are a scene analysis assistant for a video surveillance/DAM system. \ +Given a video key frame, write a concise summary (2-4 sentences, in the same language as the user) \ +describing: what is happening, the people present (clothing/appearance), the setting/location, \ +and any notable objects or actions. Be factual and specific."; + +#[derive(Debug, Default)] +pub struct VlmSummaryResult { + pub total: usize, + pub summarized: usize, + pub embedded: usize, + pub skipped: usize, + pub errors: usize, +} + +/// Generate VLM summaries for all traces in a file that don't have one yet. +/// Non-blocking: errors are logged but don't prevent job completion. +pub async fn generate_vlm_summaries( + db: &PostgresDb, + file_uuid: &str, + output_dir: &str, + redis: Option>, +) -> VlmSummaryResult { + let tp_table = table_name("trace_profiles"); + + // Find traces without vlm_description + let sql = format!( + "SELECT trace_id FROM {tp_table} \ + WHERE file_uuid = $1 \ + AND (vlm_description IS NULL OR vlm_description = '') \ + ORDER BY trace_id" + ); + + let trace_ids: Vec = match sqlx::query_scalar(&sql) + .bind(file_uuid) + .fetch_all(db.pool()) + .await + { + Ok(ids) => ids, + Err(e) => { + error!("[VLM] Failed to query traces for {}: {}", file_uuid, e); + return VlmSummaryResult::default(); + } + }; + + let total = trace_ids.len(); + if total == 0 { + info!("[VLM] No traces need summarizing for {}", file_uuid); + return VlmSummaryResult::default(); + } + + info!( + "[VLM] Starting VLM summary generation for {}: {} traces", + file_uuid, total + ); + + let mut result = VlmSummaryResult { + total, + ..Default::default() + }; + + for (i, &trace_id) in trace_ids.iter().enumerate() { + let current = i + 1; + + // Update progress + if let Some(ref r) = redis { + let mut pp = PipelineProgress::new(file_uuid); + pp.update_stage( + "vlm_summary", + current as f64 / total as f64, + "running", + Some(format!("{}/{}", current, total)), + ); + let _ = publish_pipeline_progress(r.as_ref(), file_uuid, &pp).await; + } + + match process_single_trace(db, file_uuid, trace_id, output_dir, current, total).await { + Ok((summarized, embedded)) => { + if summarized { + result.summarized += 1; + } + if embedded { + result.embedded += 1; + } + } + Err(e) => { + result.errors += 1; + error!( + "[VLM] trace {}/{} (tid={}): {}", + current, total, trace_id, e + ); + } + } + } + + // Mark completed + if let Some(ref r) = redis { + let mut pp = PipelineProgress::new(file_uuid); + pp.update_stage( + "vlm_summary", + 1.0, + "completed", + Some(format!( + "{}/{} done, {} embedded", + result.summarized, result.total, result.embedded + )), + ); + let _ = publish_pipeline_progress(r.as_ref(), file_uuid, &pp).await; + } + + info!( + "[VLM] Completed for {}: {}/{} summarized, {} embedded, {} errors", + file_uuid, result.summarized, result.total, result.embedded, result.errors + ); + + result +} + +async fn process_single_trace( + db: &PostgresDb, + file_uuid: &str, + trace_id: i32, + output_dir: &str, + current: usize, + total: usize, +) -> Result<(bool, bool)> { + let trace_id_i64 = trace_id as i64; + + // Read key_frame.jpg + let key_frame_path = PathBuf::from(output_dir) + .join(file_uuid) + .join(format!("trace_{}", trace_id)) + .join("key_frame.jpg"); + + if !key_frame_path.exists() { + warn!( + "[VLM] trace {}/{} (tid={}): key_frame.jpg missing, skipping", + current, total, trace_id + ); + return Ok((false, false)); + } + + let jpeg_bytes = std::fs::read(&key_frame_path)?; + let base64_img = base64::engine::general_purpose::STANDARD.encode(&jpeg_bytes); + + // Call VLM + let summary = match call_llm_vision( + SYSTEM_PROMPT, + "Summarize this key frame.", + vec![base64_img], + 512, + 0, + ) + .await + { + Ok(s) if !s.trim().is_empty() => s, + Ok(_) => { + warn!( + "[VLM] trace {}/{} (tid={}): VLM returned empty, skipping", + current, total, trace_id + ); + return Ok((false, false)); + } + Err(e) => { + return Err(e.context("VLM call failed")); + } + }; + + info!( + "[VLM] trace {}/{} (tid={}): summarized", + current, total, trace_id + ); + + // Update DB: vlm_description + vlm_model + let tp_table = table_name("trace_profiles"); + if let Err(e) = sqlx::query(&format!( + "UPDATE {tp_table} SET vlm_description = $1, vlm_model = $2, updated_at = NOW() \ + WHERE file_uuid = $3 AND trace_id = $4" + )) + .bind(&summary) + .bind(config::llm::VISION_MODEL.as_str()) + .bind(file_uuid) + .bind(trace_id) + .execute(db.pool()) + .await + { + warn!( + "[VLM] trace {}/{} (tid={}): DB update failed: {}", + current, total, trace_id, e + ); + } + + // Update on-disk trace_profile.json + let profile_path = crate::core::file_profile::FaceTraceProfile::profile_path( + output_dir, + file_uuid, + trace_id_i64, + ); + if profile_path.exists() { + if let Some(mut profile) = + crate::core::file_profile::FaceTraceProfile::load(output_dir, file_uuid, trace_id_i64) + { + profile.vlm_summary = Some(summary.clone()); + if let Err(e) = profile.save(output_dir, None, None) { + warn!( + "[VLM] trace {}/{} (tid={}): JSON save failed: {}", + current, total, trace_id, e + ); + } + } + } + + // Embedding + let embedder = Embedder::new("embeddinggemma-300m".to_string()); + let vector = match embedder.embed_document(&summary).await { + Ok(v) => v, + Err(e) => { + warn!( + "[VLM] trace {}/{} (tid={}): embedding failed: {} (text saved)", + current, total, trace_id, e + ); + return Ok((true, false)); + } + }; + + // Store embedding in DB + if let Err(e) = sqlx::query(&format!( + "UPDATE {tp_table} SET vlm_embedding = $1 WHERE file_uuid = $2 AND trace_id = $3" + )) + .bind(&serde_json::to_value(&vector)?) + .bind(file_uuid) + .bind(trace_id) + .execute(db.pool()) + .await + { + warn!( + "[VLM] trace {}/{} (tid={}): embedding DB store failed: {}", + current, total, trace_id, e + ); + } + + // Store in Qdrant + let qdrant = QdrantDb::new(); + let point_id = format!("{}_t{}", file_uuid, trace_id); + if let Err(e) = qdrant + .upsert_chunk_embedding( + &point_id, + &vector, + "vlm_summary", + file_uuid, + &summary, + None, + 0.0, + 0.0, + ) + .await + { + warn!( + "[VLM] trace {}/{} (tid={}): Qdrant upsert failed: {} (DB saved)", + current, total, trace_id, e + ); + } + + Ok((true, true)) +} diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 7012d6a8..104178a8 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -21,9 +21,7 @@ static FACE_TRACE_INFLIGHT: LazyLock = match processor_type { crate::core::db::ProcessorType::Asr => { @@ -770,23 +781,25 @@ impl JobWorker { error!("Failed to store ASR chunks: {}", e); } if let Some(ref ws) = workspace { - for segment in &result.segments { - let data = serde_json::json!({ - "text": segment.text, - "timestamp": segment.start_time, - }); - let _ = ws - .store_pre_chunk( - "asr", - "raw", - segment.start_frame, - segment.end_frame, - Some(segment.start_time), - Some(segment.end_time), - Some(&data.to_string()), - Some(&segment.text), - ) - .await; + if !ws_skip_append { + for segment in &result.segments { + let data = serde_json::json!({ + "text": segment.text, + "timestamp": segment.start_time, + }); + let _ = ws + .store_pre_chunk( + "asr", + "raw", + segment.start_frame, + segment.end_frame, + Some(segment.start_time), + Some(segment.end_time), + Some(&data.to_string()), + Some(&segment.text), + ) + .await; + } } } Ok(()) @@ -811,32 +824,34 @@ impl JobWorker { error!("Failed to store ASRX chunks: {}", e); } if let Some(ref ws) = workspace { - for segment in &result.segments { - let data = serde_json::json!({"text": segment.text, "speaker_id": segment.speaker_id, "end_time": segment.end_time}); - let _ = ws - .store_pre_chunk( - "asrx", - "raw", - None, - None, - Some(segment.start_time), - Some(segment.end_time), - Some(&data.to_string()), - Some(&segment.text), - ) - .await; - } - let spk_dets: Vec = result.segments.iter().map(|s| { - crate::core::db::workspace_sqlite::SpeakerDetectionBatchItem { - speaker_id: s.speaker_id.clone().unwrap_or_default(), - start_time: s.start_time, - end_time: s.end_time, - text: s.text.clone(), - chunk_id: None, - confidence: 0.0, + if !ws_skip_append { + for segment in &result.segments { + let data = serde_json::json!({"text": segment.text, "speaker_id": segment.speaker_id, "end_time": segment.end_time}); + let _ = ws + .store_pre_chunk( + "asrx", + "raw", + None, + None, + Some(segment.start_time), + Some(segment.end_time), + Some(&data.to_string()), + Some(&segment.text), + ) + .await; } - }).collect(); - let _ = ws.store_speaker_detections_batch(&spk_dets).await; + let spk_dets: Vec = result.segments.iter().map(|s| { + crate::core::db::workspace_sqlite::SpeakerDetectionBatchItem { + speaker_id: s.speaker_id.clone().unwrap_or_default(), + start_time: s.start_time, + end_time: s.end_time, + text: s.text.clone(), + chunk_id: None, + confidence: 0.0, + } + }).collect(); + let _ = ws.store_speaker_detections_batch(&spk_dets).await; + } } Ok(()) } else { @@ -859,37 +874,25 @@ impl JobWorker { error!("Failed to store CUT chunks: {}", e); } if let Some(ref ws) = workspace { - for scene in &result.scenes { - let _ = ws - .store_pre_chunk( - "cut", - "cut", - Some(scene.start_frame as i64), - Some(scene.end_frame as i64), - Some(scene.start_time), - Some(scene.end_time), - None, - None, - ) - .await; + if !ws_skip_append { + for scene in &result.scenes { + let _ = ws + .store_pre_chunk( + "cut", + "cut", + Some(scene.start_frame as i64), + Some(scene.end_frame as i64), + Some(scene.start_time), + Some(scene.end_time), + None, + None, + ) + .await; + } } } - // Extract key frames from each scene for VLM analysis - if let Some(video_row) = - self.db.get_video_by_uuid(&job.uuid).await.ok().flatten() - { - let output_dir = crate::core::config::OUTPUT_DIR.as_str(); - if let Err(e) = crate::core::proxy::extract_cut_key_frames( - &job.uuid, - &video_row.file_path, - output_dir, - ) - .await - { - error!("Failed to extract cut key frames: {}", e); - } - } + // Scene key frame extraction removed — unnecessary I/O overhead Ok(()) } else { @@ -913,20 +916,23 @@ impl JobWorker { error!("Failed to store YOLO chunks: {}", e); } if let Some(ref ws) = workspace { - for frame in &result.frames { - let data = serde_json::json!({"objects": frame.objects}); - let _ = ws - .store_pre_chunk( - "yolo", - "raw", - Some(frame.frame as i64), - None, - Some(frame.timestamp), - None, - Some(&data.to_string()), - None, - ) - .await; + if !ws_skip_append { + for frame in &result.frames { + let data = + serde_json::json!({"objects": frame.objects}); + let _ = ws + .store_pre_chunk( + "yolo", + "raw", + Some(frame.frame as i64), + None, + Some(frame.timestamp), + None, + Some(&data.to_string()), + None, + ) + .await; + } } } Ok(()) @@ -950,20 +956,22 @@ impl JobWorker { error!("Failed to store OCR chunks: {}", e); } if let Some(ref ws) = workspace { - for frame in &result.frames { - let data = serde_json::json!({"texts": frame.texts}); - let _ = ws - .store_pre_chunk( - "ocr", - "raw", - Some(frame.frame as i64), - None, - Some(frame.timestamp), - None, - Some(&data.to_string()), - None, - ) - .await; + if !ws_skip_append { + for frame in &result.frames { + let data = serde_json::json!({"texts": frame.texts}); + let _ = ws + .store_pre_chunk( + "ocr", + "raw", + Some(frame.frame as i64), + None, + Some(frame.timestamp), + None, + Some(&data.to_string()), + None, + ) + .await; + } } } Ok(()) @@ -988,35 +996,37 @@ impl JobWorker { error!("Failed to store FACE chunks: {}", e); } if let Some(ref ws) = workspace { - let dets: Vec = result.frames.iter().flat_map(|frame| { - frame.faces.iter().map(|face| crate::core::db::workspace_sqlite::FaceDetectionBatchItem { - face_id: face.face_id.clone(), - frame: frame.frame as i64, - ts: frame.timestamp, - x: face.x, - y: face.y, - w: face.width, - h: face.height, - confidence: face.confidence, - }) - }).collect(); - if !dets.is_empty() { - let _ = ws.store_face_detections_batch(&dets).await; - } - for frame in &result.frames { - let data = serde_json::json!({"faces": frame.faces}); - let _ = ws - .store_pre_chunk( - "face", - "raw", - Some(frame.frame as i64), - None, - Some(frame.timestamp), - None, - Some(&data.to_string()), - None, - ) - .await; + if !ws_skip_append { + let dets: Vec = result.frames.iter().flat_map(|frame| { + frame.faces.iter().map(|face| crate::core::db::workspace_sqlite::FaceDetectionBatchItem { + face_id: face.face_id.clone(), + frame: frame.frame as i64, + ts: frame.timestamp, + x: face.x, + y: face.y, + w: face.width, + h: face.height, + confidence: face.confidence, + }) + }).collect(); + if !dets.is_empty() { + let _ = ws.store_face_detections_batch(&dets).await; + } + for frame in &result.frames { + let data = serde_json::json!({"faces": frame.faces}); + let _ = ws + .store_pre_chunk( + "face", + "raw", + Some(frame.frame as i64), + None, + Some(frame.timestamp), + None, + Some(&data.to_string()), + None, + ) + .await; + } } } Ok(()) @@ -1063,20 +1073,23 @@ impl JobWorker { error!("Failed to store POSE chunks: {}", e); } if let Some(ref ws) = workspace { - for frame in &result.frames { - let data = serde_json::json!({"persons": frame.persons}); - let _ = ws - .store_pre_chunk( - "pose", - "raw", - Some(frame.frame as i64), - None, - Some(frame.timestamp), - None, - Some(&data.to_string()), - None, - ) - .await; + if !ws_skip_append { + for frame in &result.frames { + let data = + serde_json::json!({"persons": frame.persons}); + let _ = ws + .store_pre_chunk( + "pose", + "raw", + Some(frame.frame as i64), + None, + Some(frame.timestamp), + None, + Some(&data.to_string()), + None, + ) + .await; + } } } Ok(()) @@ -1361,7 +1374,9 @@ impl JobWorker { if *processor_type == crate::core::db::ProcessorType::FaceCluster { let traced_path = format!( "{}/{}.face_traced.json", - crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), job.uuid ); if !std::path::Path::new(&traced_path).exists() { @@ -1585,8 +1600,16 @@ impl JobWorker { } tracing::info!( "[WORKER] Restored FACE_MIN_CONFIDENCE={:?}, FACE_MIN_SIZE={:?} after job {}", - if conf_backup.is_empty() { None } else { Some(&conf_backup) }, - if size_backup.is_empty() { None } else { Some(&size_backup) }, + if conf_backup.is_empty() { + None + } else { + Some(&conf_backup) + }, + if size_backup.is_empty() { + None + } else { + Some(&size_backup) + }, job.uuid ); } @@ -1810,6 +1833,33 @@ impl JobWorker { true }; + // VLM summary check (non-blocking: logged but does NOT prevent job completion) + let tp_table = schema::table_name("trace_profiles"); + let (vlm_total, vlm_done_count): (Option, Option) = if has_face { + sqlx::query_as(&format!( + "SELECT COUNT(*)::bigint, COUNT(CASE WHEN vlm_description IS NOT NULL AND vlm_description != '' THEN 1 END)::bigint \ + FROM {tp_table} WHERE file_uuid = $1" + )) + .bind(uuid) + .fetch_optional(pool) + .await + .ok() + .flatten() + .unwrap_or((None, None)) + } else { + (None, None) + }; + if let (Some(total), Some(done)) = (vlm_total, vlm_done_count) { + if total > 0 { + tracing::info!( + "[Ingestion] vlm_summary={}/{} for uuid={}", + done, + total, + uuid + ); + } + } + let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done; tracing::info!( @@ -2587,9 +2637,9 @@ impl JobWorker { uuid, cluster_count, face_track_count ); if let Ok(result) = - serde_json::from_value::( - cluster_data.clone() - ) + serde_json::from_value::< + crate::core::processor::FaceClusterResult, + >(cluster_data.clone()) { let db_clone = self.db.clone(); let uuid_clone = uuid.to_string(); @@ -2694,34 +2744,64 @@ impl JobWorker { 0 }; - // Wait for Qdrant to have all face points AND stable trace count - // (up to 30 seconds). Point count alone isn't enough — short traces - // may still be uploading. We verify trace_id stability: two consecutive - // checks (2s apart) with the same unique trace count. + // Wait for Qdrant to have all face points AND the full trace count. + // (up to 60 seconds). Point count alone isn't enough — store_traced_faces.py + // writes face_traced.json first, then uploads trace_id to Qdrant + // incrementally. Two consecutive equal polls (2s apart) can falsely look + // "stable" between upload batches. So we additionally require the Qdrant + // distinct trace count to reach the expected count from face_traced.json. + let expected_traces: i64 = + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = + serde_json::from_str::(&content) + { + traced_data + .get("traces") + .and_then(|t| t.as_object()) + .map(|o| o.len() as i64) + .unwrap_or(0) + } else { + 0 + } + } else { + 0 + }; + let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); let filter = serde_json::json!({ "must": [{"key": "file_uuid", "match": {"value": uuid}}] }); let mut attempts = 0; - let max_attempts = 30; + let max_attempts = 60; let mut stable_trace_count: Option = None; loop { + attempts += 1; match qdrant.count_points("_faces", filter.clone()).await { Ok(count) if count >= expected_faces && expected_faces > 0 => { // Point count met — now verify trace stability use std::collections::HashSet; - match qdrant.scroll_all_points("_faces", filter.clone(), 500).await { + match qdrant + .scroll_all_points("_faces", filter.clone(), 500) + .await + { Ok(pts) => { - let trace_count: i64 = pts.iter() + let trace_count: i64 = pts + .iter() .filter_map(|p| p["payload"]["trace_id"].as_i64()) .filter(|&t| t >= 0) .collect::>() - .len() as i64; + .len() + as i64; if let Some(prev) = stable_trace_count { - if trace_count == prev && trace_count > 0 { - info!("✅ TKG prerequisites met: {} faces, {} traces (stable): {}", - count, trace_count, uuid); + if trace_count == prev + && trace_count > 0 + && trace_count >= expected_traces + { + info!( + "✅ TKG prerequisites met: {} faces, {} traces (stable, expected {}): {}", + count, trace_count, expected_traces, uuid + ); break; } } @@ -2736,10 +2816,9 @@ impl JobWorker { } } Ok(count) => { - attempts += 1; if attempts >= max_attempts { - warn!("⚠️ TKG build proceeding with {} faces (expected {}) after 30s wait: {}", - count, expected_faces, uuid); + warn!("⚠️ TKG build proceeding with {} faces (expected {}), {} traces after 120s wait: {}", + count, expected_faces, stable_trace_count.unwrap_or(0), uuid); break; } debug!( @@ -2881,6 +2960,38 @@ impl JobWorker { error!("❌ TKG build failed for {}: {}", uuid_clone, e) } } + + // 🚀 P5 Trigger: VLM Summary (after TKG, key_frame exists) + let db_p5 = db_clone.clone(); + let redis_p5 = redis_clone.clone(); + let uuid_p5 = uuid_clone.clone(); + let output_dir_p5 = output_dir_clone.clone(); + tokio::spawn(async move { + // Check if this file has face traces + let tp_table = + crate::core::db::schema::table_name("trace_profiles"); + let face_count: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1" + )) + .bind(&uuid_p5) + .fetch_optional(db_p5.pool()) + .await + .ok() + .flatten() + .unwrap_or(0); + + if face_count > 0 { + vlm_summary::generate_vlm_summaries( + &db_p5, + &uuid_p5, + &output_dir_p5, + Some(redis_p5), + ) + .await; + } else { + info!("[VLM] Skipping for {} (no face traces)", uuid_p5); + } + }); }); } } else { @@ -2963,6 +3074,36 @@ impl JobWorker { } Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e), } + + // 🚀 P5 Trigger: VLM Summary (no-face TKG path) + let db_p5 = db_clone.clone(); + let redis_p5 = redis_clone.clone(); + let uuid_p5 = uuid_clone.clone(); + let output_dir_p5 = output_dir_clone.clone(); + tokio::spawn(async move { + let tp_table = crate::core::db::schema::table_name("trace_profiles"); + let face_count: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1" + )) + .bind(&uuid_p5) + .fetch_optional(db_p5.pool()) + .await + .ok() + .flatten() + .unwrap_or(0); + + if face_count > 0 { + vlm_summary::generate_vlm_summaries( + &db_p5, + &uuid_p5, + &output_dir_p5, + Some(redis_p5), + ) + .await; + } else { + info!("[VLM] Skipping for {} (no face traces)", uuid_p5); + } + }); }); } }