feat: P5 VLM Summary pipeline integration + trace_profile vlm_summary field

- Add src/core/processor/vlm_summary.rs: VLM + Embedding pipeline stage
  * Reads key_frame.jpg → Ollama llava:7b → vlm_description
  * Writes DB (vlm_description, vlm_model, vlm_embedding) + on-disk JSON
  * EmbeddingGemma → Qdrant upsert (chunk_type=vlm_summary)
  * Non-blocking: errors logged, does not prevent job completion
  * Redis progress tracking: vlm_summary stage N/M traces

- Add src/bin/backfill_trace_vlm.rs: manual backfill binary
  * Supports --file-uuid, --force, --limit flags
  * Concurrency: 2 parallel VLM calls

- Add vlm_embedding JSONB column to trace_profiles (schema + migration)
- Add vlm_summary field to FaceTraceProfile struct
- Add P5 trigger in job_worker.rs (has_face + no-face paths)
- Add VLM monitoring to ingestion_complete() (non-blocking)
- Update .env / .env.development: VISION_URL → Ollama 11434
This commit is contained in:
Accusys
2026-08-22 09:52:04 +08:00
parent 6d7b477b31
commit 476a31ecc6
8 changed files with 800 additions and 174 deletions
+306 -165
View File
@@ -21,9 +21,7 @@ static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSe
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
use crate::core::chunk::rule1_ingest;
use crate::core::config::{
FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR,
};
use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR};
use crate::core::db::qdrant_db::QdrantDb;
use crate::core::db::{
schema, MonitorJobStatus, PostgresDb, ProcessorJobStatus, RedisClient, VectorPayload,
@@ -31,6 +29,7 @@ use crate::core::db::{
};
use crate::core::embedding::Embedder;
use crate::core::processor::heuristic_scene::generate_scene_meta;
use crate::core::processor::vlm_summary;
use crate::core::progress::{publish_pipeline_progress, PipelineProgress};
use crate::worker::config::WorkerConfig;
use crate::worker::processor::{ProcessorPool, ProcessorTask};
@@ -148,7 +147,8 @@ impl JobWorker {
.await
.unwrap_or_default()
.len();
self.processor_pool.set_active_jobs(active_running + active_pending);
self.processor_pool
.set_active_jobs(active_running + active_pending);
}
// Reset stale running jobs: jobs stuck in 'running' with no active processor results
@@ -757,6 +757,17 @@ impl JobWorker {
// Load output file and store to pre_chunks
// Also dual-write to workspace if available
let workspace = WorkspaceDb::open(&job.uuid).await.ok();
// A3 guard: if this processor already wrote pre_chunks on a previous
// dispatch, skip re-appending. Combined with the dedup index +
// INSERT OR IGNORE (A1) this prevents the 11s re-dispatch loop from
// ballooning workspace.sqlite with duplicate rows.
let ws_skip_append = if let Some(ref ws) = workspace {
ws.has_pre_chunks(processor_type.as_str())
.await
.unwrap_or(false)
} else {
false
};
if let Ok(json_str) = std::fs::read_to_string(&output_path) {
let store_result: Result<()> = 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<crate::core::db::workspace_sqlite::SpeakerDetectionBatchItem> = 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<crate::core::db::workspace_sqlite::SpeakerDetectionBatchItem> = 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<crate::core::db::workspace_sqlite::FaceDetectionBatchItem> = 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<crate::core::db::workspace_sqlite::FaceDetectionBatchItem> = 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<i64>, Option<i64>) = 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::<crate::core::processor::FaceClusterResult>(
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::<serde_json::Value>(&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<i64> = 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::<HashSet<_>>()
.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);
}
});
});
}
}