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:
@@ -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<String> = None;
|
||||
let mut force = false;
|
||||
let mut limit: Option<i64> = None;
|
||||
|
||||
let args: Vec<String> = 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 <uuid>] [--force] [--limit <N>]");
|
||||
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<ProcessOutcome> {
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user