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
+3 -3
View File
@@ -77,9 +77,9 @@ MOMENTRY_TMDB_PROBE_ENABLED=true
MOMENTRY_LLM_CHAT_URL=http://localhost:11434/v1/chat/completions MOMENTRY_LLM_CHAT_URL=http://localhost:11434/v1/chat/completions
MOMENTRY_LLM_CHAT_MODEL=llama3.1:8b MOMENTRY_LLM_CHAT_MODEL=llama3.1:8b
# VLM uses llama.cpp (llava-v1.6-vicuna-13b) # VLM uses Ollama (llava:7b) - OpenAI-compatible endpoint
MOMENTRY_LLM_VISION_URL=http://localhost:8091/v1/chat/completions MOMENTRY_LLM_VISION_URL=http://localhost:11434/v1/chat/completions
MOMENTRY_LLM_VISION_MODEL=llava-v1.6-vicuna-13b MOMENTRY_LLM_VISION_MODEL=llava:7b
# Summary LLM uses Ollama # Summary LLM uses Ollama
MOMENTRY_LLM_SUMMARY_URL=http://localhost:11434/v1/chat/completions MOMENTRY_LLM_SUMMARY_URL=http://localhost:11434/v1/chat/completions
+4
View File
@@ -159,3 +159,7 @@ path = "src/bin/backfill_trace_profiles.rs"
[[bin]] [[bin]]
name = "rebuild_trace_thumbs" name = "rebuild_trace_thumbs"
path = "src/bin/rebuild_trace_thumbs.rs" path = "src/bin/rebuild_trace_thumbs.rs"
[[bin]]
name = "backfill_trace_vlm"
path = "src/bin/backfill_trace_vlm.rs"
+192
View File
@@ -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)
}
+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?; 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) ── // ── 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) // Migration: add new fields to existing trace_profiles tables (safe no-op if columns exist)
sqlx::query( sqlx::query(
"ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_confidence DOUBLE PRECISION", "ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS best_confidence DOUBLE PRECISION",
@@ -1302,6 +1302,9 @@ impl PostgresDb {
.execute(pool) .execute(pool)
.await?; .await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_tags ON trace_profiles USING GIN(vlm_tags)").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 ── // ── 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?; 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(), completed_processors: r.get::<Option<Vec<String>>, _>(13).unwrap_or_default(),
failed_processors: r.get::<Option<Vec<String>>, _>(14).unwrap_or_default(), failed_processors: r.get::<Option<Vec<String>>, _>(14).unwrap_or_default(),
video_id: r.get(15), 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 { } else {
Ok(None) Ok(None)
@@ -2209,7 +2214,9 @@ impl PostgresDb {
completed_processors: r.get::<Option<Vec<String>>, _>(13).unwrap_or_default(), completed_processors: r.get::<Option<Vec<String>>, _>(13).unwrap_or_default(),
failed_processors: r.get::<Option<Vec<String>>, _>(14).unwrap_or_default(), failed_processors: r.get::<Option<Vec<String>>, _>(14).unwrap_or_default(),
video_id: r.get(15), 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(); .collect();
+4 -2
View File
@@ -399,6 +399,8 @@ pub struct FaceTraceProfile {
pub key_frame: Option<String>, // filename: key_frame.jpg pub key_frame: Option<String>, // filename: key_frame.jpg
pub key_face: Option<String>, // filename: key_face.jpg pub key_face: Option<String>, // filename: key_face.jpg
pub status: String, // pending / bound / merged 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. /// Recursively round float numbers in a JSON value to 2 decimal places.
@@ -477,6 +479,7 @@ impl FaceTraceProfile {
key_frame: None, key_frame: None,
key_face: None, key_face: None,
status: "pending".to_string(), status: "pending".to_string(),
vlm_summary: None,
} }
} }
@@ -515,8 +518,7 @@ impl FaceTraceProfile {
} }
// Write trace_profile.json // Write trace_profile.json
let json = let json = serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?))
serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?))
.context("Failed to serialize FaceTraceProfile")?; .context("Failed to serialize FaceTraceProfile")?;
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id); let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
std::fs::write(&profile_path, json) std::fs::write(&profile_path, json)
+1
View File
@@ -15,6 +15,7 @@ pub mod ocr;
pub mod pose; pub mod pose;
pub mod scene_classification; pub mod scene_classification;
pub mod tkg; pub mod tkg;
pub mod vlm_summary;
pub mod yolo; pub mod yolo;
use serde::{Deserialize, Serialize}; 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))
}
+182 -41
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())); LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
use crate::core::chunk::rule1_ingest; use crate::core::chunk::rule1_ingest;
use crate::core::config::{ use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR};
FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR,
};
use crate::core::db::qdrant_db::QdrantDb; use crate::core::db::qdrant_db::QdrantDb;
use crate::core::db::{ use crate::core::db::{
schema, MonitorJobStatus, PostgresDb, ProcessorJobStatus, RedisClient, VectorPayload, schema, MonitorJobStatus, PostgresDb, ProcessorJobStatus, RedisClient, VectorPayload,
@@ -31,6 +29,7 @@ use crate::core::db::{
}; };
use crate::core::embedding::Embedder; use crate::core::embedding::Embedder;
use crate::core::processor::heuristic_scene::generate_scene_meta; 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::core::progress::{publish_pipeline_progress, PipelineProgress};
use crate::worker::config::WorkerConfig; use crate::worker::config::WorkerConfig;
use crate::worker::processor::{ProcessorPool, ProcessorTask}; use crate::worker::processor::{ProcessorPool, ProcessorTask};
@@ -148,7 +147,8 @@ impl JobWorker {
.await .await
.unwrap_or_default() .unwrap_or_default()
.len(); .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 // 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 // Load output file and store to pre_chunks
// Also dual-write to workspace if available // Also dual-write to workspace if available
let workspace = WorkspaceDb::open(&job.uuid).await.ok(); 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) { if let Ok(json_str) = std::fs::read_to_string(&output_path) {
let store_result: Result<()> = match processor_type { let store_result: Result<()> = match processor_type {
crate::core::db::ProcessorType::Asr => { crate::core::db::ProcessorType::Asr => {
@@ -770,6 +781,7 @@ impl JobWorker {
error!("Failed to store ASR chunks: {}", e); error!("Failed to store ASR chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
for segment in &result.segments { for segment in &result.segments {
let data = serde_json::json!({ let data = serde_json::json!({
"text": segment.text, "text": segment.text,
@@ -789,6 +801,7 @@ impl JobWorker {
.await; .await;
} }
} }
}
Ok(()) Ok(())
} else { } else {
error!( error!(
@@ -811,6 +824,7 @@ impl JobWorker {
error!("Failed to store ASRX chunks: {}", e); error!("Failed to store ASRX chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
for segment in &result.segments { for segment in &result.segments {
let data = serde_json::json!({"text": segment.text, "speaker_id": segment.speaker_id, "end_time": segment.end_time}); let data = serde_json::json!({"text": segment.text, "speaker_id": segment.speaker_id, "end_time": segment.end_time});
let _ = ws let _ = ws
@@ -838,6 +852,7 @@ impl JobWorker {
}).collect(); }).collect();
let _ = ws.store_speaker_detections_batch(&spk_dets).await; let _ = ws.store_speaker_detections_batch(&spk_dets).await;
} }
}
Ok(()) Ok(())
} else { } else {
error!( error!(
@@ -859,6 +874,7 @@ impl JobWorker {
error!("Failed to store CUT chunks: {}", e); error!("Failed to store CUT chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
for scene in &result.scenes { for scene in &result.scenes {
let _ = ws let _ = ws
.store_pre_chunk( .store_pre_chunk(
@@ -874,22 +890,9 @@ impl JobWorker {
.await; .await;
} }
} }
}
// Extract key frames from each scene for VLM analysis // Scene key frame extraction removed — unnecessary I/O overhead
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);
}
}
Ok(()) Ok(())
} else { } else {
@@ -913,8 +916,10 @@ impl JobWorker {
error!("Failed to store YOLO chunks: {}", e); error!("Failed to store YOLO chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
for frame in &result.frames { for frame in &result.frames {
let data = serde_json::json!({"objects": frame.objects}); let data =
serde_json::json!({"objects": frame.objects});
let _ = ws let _ = ws
.store_pre_chunk( .store_pre_chunk(
"yolo", "yolo",
@@ -929,6 +934,7 @@ impl JobWorker {
.await; .await;
} }
} }
}
Ok(()) Ok(())
} else { } else {
error!( error!(
@@ -950,6 +956,7 @@ impl JobWorker {
error!("Failed to store OCR chunks: {}", e); error!("Failed to store OCR chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
for frame in &result.frames { for frame in &result.frames {
let data = serde_json::json!({"texts": frame.texts}); let data = serde_json::json!({"texts": frame.texts});
let _ = ws let _ = ws
@@ -966,6 +973,7 @@ impl JobWorker {
.await; .await;
} }
} }
}
Ok(()) Ok(())
} else { } else {
error!( error!(
@@ -988,6 +996,7 @@ impl JobWorker {
error!("Failed to store FACE chunks: {}", e); error!("Failed to store FACE chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
let dets: Vec<crate::core::db::workspace_sqlite::FaceDetectionBatchItem> = result.frames.iter().flat_map(|frame| { 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 { frame.faces.iter().map(|face| crate::core::db::workspace_sqlite::FaceDetectionBatchItem {
face_id: face.face_id.clone(), face_id: face.face_id.clone(),
@@ -1019,6 +1028,7 @@ impl JobWorker {
.await; .await;
} }
} }
}
Ok(()) Ok(())
} else { } else {
error!( error!(
@@ -1063,8 +1073,10 @@ impl JobWorker {
error!("Failed to store POSE chunks: {}", e); error!("Failed to store POSE chunks: {}", e);
} }
if let Some(ref ws) = workspace { if let Some(ref ws) = workspace {
if !ws_skip_append {
for frame in &result.frames { for frame in &result.frames {
let data = serde_json::json!({"persons": frame.persons}); let data =
serde_json::json!({"persons": frame.persons});
let _ = ws let _ = ws
.store_pre_chunk( .store_pre_chunk(
"pose", "pose",
@@ -1079,6 +1091,7 @@ impl JobWorker {
.await; .await;
} }
} }
}
Ok(()) Ok(())
} else { } else {
error!( error!(
@@ -1361,7 +1374,9 @@ impl JobWorker {
if *processor_type == crate::core::db::ProcessorType::FaceCluster { if *processor_type == crate::core::db::ProcessorType::FaceCluster {
let traced_path = format!( let traced_path = format!(
"{}/{}.face_traced.json", "{}/{}.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 job.uuid
); );
if !std::path::Path::new(&traced_path).exists() { if !std::path::Path::new(&traced_path).exists() {
@@ -1585,8 +1600,16 @@ impl JobWorker {
} }
tracing::info!( tracing::info!(
"[WORKER] Restored FACE_MIN_CONFIDENCE={:?}, FACE_MIN_SIZE={:?} after job {}", "[WORKER] Restored FACE_MIN_CONFIDENCE={:?}, FACE_MIN_SIZE={:?} after job {}",
if conf_backup.is_empty() { None } else { Some(&conf_backup) }, if conf_backup.is_empty() {
if size_backup.is_empty() { None } else { Some(&size_backup) }, None
} else {
Some(&conf_backup)
},
if size_backup.is_empty() {
None
} else {
Some(&size_backup)
},
job.uuid job.uuid
); );
} }
@@ -1810,6 +1833,33 @@ impl JobWorker {
true 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; let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done;
tracing::info!( tracing::info!(
@@ -2587,9 +2637,9 @@ impl JobWorker {
uuid, cluster_count, face_track_count uuid, cluster_count, face_track_count
); );
if let Ok(result) = if let Ok(result) =
serde_json::from_value::<crate::core::processor::FaceClusterResult>( serde_json::from_value::<
cluster_data.clone() crate::core::processor::FaceClusterResult,
) >(cluster_data.clone())
{ {
let db_clone = self.db.clone(); let db_clone = self.db.clone();
let uuid_clone = uuid.to_string(); let uuid_clone = uuid.to_string();
@@ -2694,34 +2744,64 @@ impl JobWorker {
0 0
}; };
// Wait for Qdrant to have all face points AND stable trace count // Wait for Qdrant to have all face points AND the full trace count.
// (up to 30 seconds). Point count alone isn't enough — short traces // (up to 60 seconds). Point count alone isn't enough — store_traced_faces.py
// may still be uploading. We verify trace_id stability: two consecutive // writes face_traced.json first, then uploads trace_id to Qdrant
// checks (2s apart) with the same unique trace count. // 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 qdrant = crate::core::db::qdrant_db::QdrantDb::new();
let filter = serde_json::json!({ let filter = serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}] "must": [{"key": "file_uuid", "match": {"value": uuid}}]
}); });
let mut attempts = 0; let mut attempts = 0;
let max_attempts = 30; let max_attempts = 60;
let mut stable_trace_count: Option<i64> = None; let mut stable_trace_count: Option<i64> = None;
loop { loop {
attempts += 1;
match qdrant.count_points("_faces", filter.clone()).await { match qdrant.count_points("_faces", filter.clone()).await {
Ok(count) if count >= expected_faces && expected_faces > 0 => { Ok(count) if count >= expected_faces && expected_faces > 0 => {
// Point count met — now verify trace stability // Point count met — now verify trace stability
use std::collections::HashSet; 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) => { Ok(pts) => {
let trace_count: i64 = pts.iter() let trace_count: i64 = pts
.iter()
.filter_map(|p| p["payload"]["trace_id"].as_i64()) .filter_map(|p| p["payload"]["trace_id"].as_i64())
.filter(|&t| t >= 0) .filter(|&t| t >= 0)
.collect::<HashSet<_>>() .collect::<HashSet<_>>()
.len() as i64; .len()
as i64;
if let Some(prev) = stable_trace_count { if let Some(prev) = stable_trace_count {
if trace_count == prev && trace_count > 0 { if trace_count == prev
info!("✅ TKG prerequisites met: {} faces, {} traces (stable): {}", && trace_count > 0
count, trace_count, uuid); && trace_count >= expected_traces
{
info!(
"✅ TKG prerequisites met: {} faces, {} traces (stable, expected {}): {}",
count, trace_count, expected_traces, uuid
);
break; break;
} }
} }
@@ -2736,10 +2816,9 @@ impl JobWorker {
} }
} }
Ok(count) => { Ok(count) => {
attempts += 1;
if attempts >= max_attempts { if attempts >= max_attempts {
warn!("⚠️ TKG build proceeding with {} faces (expected {}) after 30s wait: {}", warn!("⚠️ TKG build proceeding with {} faces (expected {}), {} traces after 120s wait: {}",
count, expected_faces, uuid); count, expected_faces, stable_trace_count.unwrap_or(0), uuid);
break; break;
} }
debug!( debug!(
@@ -2881,6 +2960,38 @@ impl JobWorker {
error!("❌ TKG build failed for {}: {}", uuid_clone, e) 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 { } else {
@@ -2963,6 +3074,36 @@ impl JobWorker {
} }
Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e), 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);
}
});
}); });
} }
} }