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:
@@ -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};
|
||||
|
||||
@@ -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<Arc<RedisClient>>,
|
||||
) -> 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<i32> = 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))
|
||||
}
|
||||
Reference in New Issue
Block a user