feat: VLM summary vector search integration
- Add vlm_point_id column to trace_profiles (stores Qdrant point ID) - Add upsert_chunk_embedding_u64 to QdrantDb (numeric ID support) - Add chunk_id to VLM payload in Qdrant for search enrichment - Update enrich_from_pg to fallback to VLM lookup when chunk not found - Add /api/v1/file/:uuid/vlm-summary endpoint for manual trigger - Fix VLM point_id: use u64 hash instead of string (Qdrant requirement) - Fix VLM timeout: was 0 (immediate timeout), now 120s Verified: semantic search returns [vlm] results with proper enrichment
This commit is contained in:
@@ -878,6 +878,73 @@ async fn verify_file_handler(
|
||||
Json(report)
|
||||
}
|
||||
|
||||
/// Manually trigger VLM summary generation for an existing file.
|
||||
/// Non-blocking: returns immediately, VLM runs in background.
|
||||
async fn trigger_vlm_summary(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let db = state.db.clone();
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.clone();
|
||||
|
||||
// Check if 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(&file_uuid)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
if face_count == 0 {
|
||||
return Json(serde_json::json!({
|
||||
"success": false,
|
||||
"message": "No face traces found for this file",
|
||||
"file_uuid": file_uuid,
|
||||
}));
|
||||
}
|
||||
|
||||
// Check how many traces already have vlm_description
|
||||
let done_count: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND vlm_description IS NOT NULL AND vlm_description != ''"
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
let pending = face_count - done_count;
|
||||
if pending == 0 {
|
||||
return Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "All traces already have VLM summaries",
|
||||
"file_uuid": file_uuid,
|
||||
"total_traces": face_count,
|
||||
"already_done": done_count,
|
||||
}));
|
||||
}
|
||||
|
||||
// Spawn VLM generation in background
|
||||
let file_uuid_clone = file_uuid.clone();
|
||||
tokio::spawn(async move {
|
||||
let redis = crate::core::db::RedisClient::new().ok();
|
||||
crate::core::processor::vlm_summary::generate_vlm_summaries(
|
||||
&db, &file_uuid_clone, &output_dir, redis.map(std::sync::Arc::new),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": format!("VLM summary generation started for {} traces", pending),
|
||||
"file_uuid": file_uuid,
|
||||
"total_traces": face_count,
|
||||
"already_done": done_count,
|
||||
"pending": pending,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn processing_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/file/:file_uuid/process", post(trigger_processing))
|
||||
@@ -903,4 +970,8 @@ pub fn processing_routes() -> Router<AppState> {
|
||||
get(get_processor_counts),
|
||||
)
|
||||
.route("/api/v1/file/:file_uuid/verify", get(verify_file_handler))
|
||||
.route(
|
||||
"/api/v1/file/:file_uuid/vlm-summary",
|
||||
post(trigger_vlm_summary),
|
||||
)
|
||||
}
|
||||
|
||||
+52
-2
@@ -103,7 +103,8 @@ fn map_chunk_type_to_source(chunk_type: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enrich a Qdrant search result with full data from PostgreSQL
|
||||
/// Enrich a Qdrant search result with full data from PostgreSQL.
|
||||
/// Falls back to trace_profiles lookup for VLM summary results (matched by vlm_point_id).
|
||||
async fn enrich_from_pg(
|
||||
db: &crate::core::db::PostgresDb,
|
||||
file_uuid: &str,
|
||||
@@ -131,7 +132,10 @@ async fn enrich_from_pg(
|
||||
thumbnail_url: None,
|
||||
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
|
||||
}),
|
||||
Ok(None) => None,
|
||||
Ok(None) => {
|
||||
// Chunk not found — try VLM summary lookup by vlm_point_id
|
||||
enrich_vlm_from_pg(db, file_uuid, chunk_id, qdrant_score).await
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("PG enrichment failed for {} {}: {}", file_uuid, chunk_id, e);
|
||||
None
|
||||
@@ -139,6 +143,52 @@ async fn enrich_from_pg(
|
||||
}
|
||||
}
|
||||
|
||||
/// Enrich a VLM summary search result from trace_profiles, looked up by vlm_point_id.
|
||||
async fn enrich_vlm_from_pg(
|
||||
db: &crate::core::db::PostgresDb,
|
||||
file_uuid: &str,
|
||||
point_id: &str,
|
||||
qdrant_score: f32,
|
||||
) -> Option<SearchResult> {
|
||||
let tp_table = crate::core::db::schema::table_name("trace_profiles");
|
||||
let rows: Vec<(i32, i64, i64, Option<String>)> = sqlx::query_as(&format!(
|
||||
"SELECT trace_id, start_frame, end_frame, vlm_description FROM {tp_table} \
|
||||
WHERE file_uuid = $1 AND vlm_point_id = $2"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(point_id)
|
||||
.fetch_all(db.pool())
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let (tid, start_frame, end_frame, vlm_desc) = rows.into_iter().next()?;
|
||||
let text = vlm_desc.unwrap_or_default();
|
||||
|
||||
Some(SearchResult {
|
||||
id: 0,
|
||||
file_uuid: Some(file_uuid.to_string()),
|
||||
parent_id: 0,
|
||||
scene_order: None,
|
||||
start_frame,
|
||||
end_frame,
|
||||
fps: 0.0,
|
||||
start_time: 0.0,
|
||||
end_time: 0.0,
|
||||
raw_text: None,
|
||||
summary: Some(format!("VLM trace_{}", tid)),
|
||||
text_content: Some(text),
|
||||
metadata: Some(serde_json::json!({
|
||||
"type": "vlm_summary",
|
||||
"trace_id": tid,
|
||||
})),
|
||||
similarity: Some(qdrant_score as f64),
|
||||
file_name: None,
|
||||
serve_url: None,
|
||||
thumbnail_url: Some(format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, tid)),
|
||||
source_type: Some("vlm".to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult {
|
||||
SearchResult {
|
||||
id: 0,
|
||||
|
||||
@@ -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), vlm_embedding JSONB, 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, vlm_point_id VARCHAR(32), 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",
|
||||
@@ -1305,6 +1305,9 @@ impl PostgresDb {
|
||||
sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS vlm_embedding JSONB")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("ALTER TABLE trace_profiles ADD COLUMN IF NOT EXISTS vlm_point_id VARCHAR(32)")
|
||||
.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?;
|
||||
|
||||
@@ -843,6 +843,50 @@ impl QdrantDb {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store embedding with u64 point ID (for VLM summaries where ID is a hash integer).
|
||||
/// Uses numeric JSON value instead of string, as Qdrant requires.
|
||||
pub async fn upsert_chunk_embedding_u64(
|
||||
&self,
|
||||
point_id: u64,
|
||||
vector: &[f32],
|
||||
chunk_type: &str,
|
||||
file_uuid: &str,
|
||||
text: &str,
|
||||
start_time: f64,
|
||||
end_time: f64,
|
||||
) -> Result<()> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points?wait=true",
|
||||
self.base_url, self.collection_name
|
||||
);
|
||||
let mut payload_map = std::collections::HashMap::new();
|
||||
payload_map.insert("file_uuid".to_string(), serde_json::json!(file_uuid));
|
||||
payload_map.insert("chunk_id".to_string(), serde_json::json!(point_id.to_string()));
|
||||
payload_map.insert("chunk_type".to_string(), serde_json::json!(chunk_type));
|
||||
payload_map.insert("text".to_string(), serde_json::json!(text));
|
||||
payload_map.insert("start_time".to_string(), serde_json::json!(start_time));
|
||||
payload_map.insert("end_time".to_string(), serde_json::json!(end_time));
|
||||
|
||||
let point = serde_json::json!({
|
||||
"points": [{
|
||||
"id": point_id,
|
||||
"vector": vector,
|
||||
"payload": payload_map
|
||||
}]
|
||||
});
|
||||
let resp = self
|
||||
.client
|
||||
.put(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.json(&point)
|
||||
.send()
|
||||
.await?;
|
||||
if !resp.status().is_success() {
|
||||
anyhow::bail!("Qdrant upsert chunk (u64) failed: {}", resp.status());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scroll points matching a filter, returning payload data (single page)
|
||||
pub async fn scroll_points(
|
||||
&self,
|
||||
|
||||
@@ -163,7 +163,7 @@ async fn process_single_trace(
|
||||
"Summarize this key frame.",
|
||||
vec![base64_img],
|
||||
512,
|
||||
0,
|
||||
120,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -237,13 +237,21 @@ async fn process_single_trace(
|
||||
}
|
||||
};
|
||||
|
||||
// Generate Qdrant point_id (unique u64 hash)
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = DefaultHasher::new();
|
||||
format!("{}_{}", file_uuid, trace_id).hash(&mut hasher);
|
||||
let point_id = hasher.finish();
|
||||
|
||||
// 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"
|
||||
"UPDATE {tp_table} SET vlm_embedding = $1, vlm_point_id = $4 WHERE file_uuid = $2 AND trace_id = $3"
|
||||
))
|
||||
.bind(&serde_json::to_value(&vector)?)
|
||||
.bind(file_uuid)
|
||||
.bind(trace_id)
|
||||
.bind(&point_id.to_string())
|
||||
.execute(db.pool())
|
||||
.await
|
||||
{
|
||||
@@ -253,17 +261,15 @@ async fn process_single_trace(
|
||||
);
|
||||
}
|
||||
|
||||
// Store in Qdrant
|
||||
// Store in Qdrant (using u64 ID)
|
||||
let qdrant = QdrantDb::new();
|
||||
let point_id = format!("{}_t{}", file_uuid, trace_id);
|
||||
if let Err(e) = qdrant
|
||||
.upsert_chunk_embedding(
|
||||
&point_id,
|
||||
.upsert_chunk_embedding_u64(
|
||||
point_id,
|
||||
&vector,
|
||||
"vlm_summary",
|
||||
file_uuid,
|
||||
&summary,
|
||||
None,
|
||||
0.0,
|
||||
0.0,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user