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
+10 -3
View File
@@ -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::<Option<Vec<String>>, _>(13).unwrap_or_default(),
failed_processors: r.get::<Option<Vec<String>>, _>(14).unwrap_or_default(),
video_id: r.get(15),
face_settings: r.get::<Option<String>, _>(16).and_then(|s| serde_json::from_str(&s).ok()),
face_settings: r
.get::<Option<String>, _>(16)
.and_then(|s| serde_json::from_str(&s).ok()),
}))
} else {
Ok(None)
@@ -2209,7 +2214,9 @@ impl PostgresDb {
completed_processors: r.get::<Option<Vec<String>>, _>(13).unwrap_or_default(),
failed_processors: r.get::<Option<Vec<String>>, _>(14).unwrap_or_default(),
video_id: r.get(15),
face_settings: r.get::<Option<String>, _>(16).and_then(|s| serde_json::from_str(&s).ok()),
face_settings: r
.get::<Option<String>, _>(16)
.and_then(|s| serde_json::from_str(&s).ok()),
}
})
.collect();
+5 -3
View File
@@ -399,6 +399,8 @@ pub struct FaceTraceProfile {
pub key_frame: Option<String>, // filename: key_frame.jpg
pub key_face: Option<String>, // filename: key_face.jpg
pub status: String, // pending / bound / merged
#[serde(default)]
pub vlm_summary: Option<String>, // 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()))?;
+1
View File
@@ -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};
+279
View File
@@ -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))
}