From 75cbaa3302b0743033174f369456119b41a1df39 Mon Sep 17 00:00:00 2001 From: Accusys Date: Mon, 16 Nov 2026 21:56:43 +0800 Subject: [PATCH] feat: rebuild embeddings endpoint + standalone tool (API + binary), clear collection before rebuild, fix upsert_scene_embedding args --- src/api/service_management.rs | 214 +++++++++++++++++++++++++++ src/bin/rebuild_embeddings.rs | 267 ++++++++++++++++++++++++++++++++++ 2 files changed, 481 insertions(+) create mode 100644 src/bin/rebuild_embeddings.rs diff --git a/src/api/service_management.rs b/src/api/service_management.rs index 34bb1b30..d02e2a19 100644 --- a/src/api/service_management.rs +++ b/src/api/service_management.rs @@ -1085,6 +1085,7 @@ pub fn router() -> axum::Router { axum::Router::new() .route("/api/v2/service/start", axum::routing::post(start_service)) .route("/api/v2/service/stop", axum::routing::post(stop_service)) + .route("/api/v1/admin/rebuild-embeddings", axum::routing::post(rebuild_embeddings)) // NOTE: /api/v1/mbe/health is already registered in server.rs (line 192) } @@ -1693,6 +1694,219 @@ pub async fn test_core( Ok(Json(result)) } +/// POST /api/v1/admin/rebuild-embeddings — rebuild text/scene embeddings +/// with the current (possibly updated) embedding model. +/// +/// Body: `{ "collection": "momentry_rule1" | "_scenes" | "all", "file_uuid": "optional" }` +/// Uses the Rust `Embedder` (same code path as production). +pub async fn rebuild_embeddings( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + use crate::core::embedding::Embedder; + use crate::core::db::{schema, QdrantDb}; + + let collection = body.get("collection").and_then(|v| v.as_str()).unwrap_or("all"); + let file_uuid = body.get("file_uuid").and_then(|v| v.as_str()); + + let embedder = Embedder::new("embeddinggemma-300m".to_string()); + let qdrant = QdrantDb::new(); + let chunk_table = schema::table_name("chunk"); + let scenes_table = schema::table_name("scenes"); + + let mut results = serde_json::json!({}); + let t0 = std::time::Instant::now(); + + // ── Rebuild text chunks (sentence) → momentry_rule1 ── + if collection == "all" || collection == "momentry_rule1" { + let mut ok = 0usize; + let mut fail = 0usize; + + // Clear existing points for this file_uuid (or all if no filter) + if let Some(uuid) = file_uuid { + let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({ + "must": [{"key": "file_uuid", "match": {"value": uuid}}] + })).await; + } else { + // Delete all in collection: use empty filter to match everything + let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({})).await; + } + + // Query chunks that need re-embedding + let query = if let Some(uuid) = file_uuid { + format!( + "SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \ + FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' AND file_uuid = $1 \ + ORDER BY id", + chunk_table + ) + } else { + format!( + "SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \ + FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' \ + ORDER BY id", + chunk_table + ) + }; + + let rows: Vec<(String, String, i64, i64, f64, f64, String, String)> = if file_uuid.is_some() { + sqlx::query_as(&query) + .bind(file_uuid.unwrap()) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default() + } else { + sqlx::query_as(&query) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default() + }; + + let total = rows.len(); + for (chunk_id, text, start_frame, end_frame, start_time, end_time, chunk_type, fuuid) in &rows { + match embedder.embed_document(text).await { + Ok(vector) => { + // Update PG embedding column + let vector_json = serde_json::to_string(&vector).unwrap_or_default(); + let _ = sqlx::query(&format!( + "UPDATE {} SET embedding = $1::vector WHERE chunk_id = $2 AND file_uuid = $3", + chunk_table + )) + .bind(&vector_json) + .bind(chunk_id) + .bind(fuuid) + .execute(state.db.pool()) + .await; + + // Upsert to Qdrant + let payload = crate::core::db::VectorPayload { + file_uuid: fuuid.clone(), + chunk_id: chunk_id.clone(), + chunk_type: chunk_type.clone(), + start_frame: *start_frame, + end_frame: *end_frame, + start_time: *start_time, + end_time: *end_time, + text: Some(text.clone()), + }; + if qdrant.upsert_vector(chunk_id, &vector, payload).await.is_ok() { + ok += 1; + } else { + fail += 1; + } + } + Err(e) => { + tracing::error!("[rebuild-embed] Failed to embed {}: {}", chunk_id, e); + fail += 1; + } + } + } + + results["momentry_rule1"] = serde_json::json!({ + "total": total, + "ok": ok, + "fail": fail, + }); + } + + // ── Rebuild scene embeddings → _scenes ── + if collection == "all" || collection == "_scenes" { + let mut ok = 0usize; + let mut fail = 0usize; + + // Clear existing scene points + if let Some(uuid) = file_uuid { + let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({ + "must": [{"key": "file_uuid", "match": {"value": uuid}}] + })).await; + } else { + // Delete all in _scenes: use empty filter to match everything + let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({})).await; + } + + // Query scenes with VLM descriptions + let query = if let Some(uuid) = file_uuid { + format!( + "SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \ + COALESCE(vlm_description_localized, vlm_description) as description \ + FROM {} WHERE file_uuid = $1 AND (vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL) \ + ORDER BY id", + scenes_table + ) + } else { + format!( + "SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \ + COALESCE(vlm_description_localized, vlm_description) as description \ + FROM {} WHERE vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL \ + ORDER BY id", + scenes_table + ) + }; + + let rows: Vec<(i64, String, i32, f64, i64, String)> = if file_uuid.is_some() { + sqlx::query_as(&query) + .bind(file_uuid.unwrap()) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default() + } else { + sqlx::query_as(&query) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default() + }; + + let total = rows.len(); + for (scene_id, fuuid, scene_index, timestamp_sec, frame_number, description) in &rows { + match embedder.embed_document(description).await { + Ok(vector) => { + let point_id_str = format!("{}_s{}", fuuid, scene_index); + let point_id = { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + let mut hasher = DefaultHasher::new(); + point_id_str.hash(&mut hasher); + hasher.finish() + }; + + if qdrant.upsert_scene_embedding( + point_id, + &vector, + fuuid, + *scene_index as usize, + *timestamp_sec, + *frame_number as u32, + description, + None, + &[], + &[], + ).await.is_ok() { + ok += 1; + } else { + fail += 1; + } + } + Err(e) => { + tracing::error!("[rebuild-embed] Failed to embed scene {}: {}", scene_id, e); + fail += 1; + } + } + } + + results["_scenes"] = serde_json::json!({ + "total": total, + "ok": ok, + "fail": fail, + }); + } + + results["elapsed_ms"] = serde_json::json!(t0.elapsed().as_millis()); + results["collection"] = serde_json::json!(collection); + results["file_uuid"] = serde_json::json!(file_uuid); + + Ok(Json(results)) +} + /// GET /api/v1/admin/components — full component registry with versions /// Returns all system components: binaries, tools, scripts, dists, externals /// Each with current file hash, size, repo mapping, and latest Gitea commit. diff --git a/src/bin/rebuild_embeddings.rs b/src/bin/rebuild_embeddings.rs new file mode 100644 index 00000000..d236276e --- /dev/null +++ b/src/bin/rebuild_embeddings.rs @@ -0,0 +1,267 @@ +//! Standalone embedding rebuild tool. +//! +//! Rebuilds text/scene embeddings with the current embedding model. +//! Uses the Rust `Embedder` (same code path as production). +//! +//! Usage: +//! cargo run --release --bin rebuild_embeddings -- --collection momentry_rule1 +//! cargo run --release --bin rebuild_embeddings -- --collection _scenes +//! cargo run --release --bin rebuild_embeddings -- --collection all +//! cargo run --release --bin rebuild_embeddings -- --collection momentry_rule1 --uuid abc123 + +use anyhow::{Context, Result}; +use dotenv::dotenv; +use momentry_core::core::config; +use momentry_core::core::db::{schema, QdrantDb, VectorPayload}; +use momentry_core::core::embedding::Embedder; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +#[derive(clap::Parser)] +#[command(name = "rebuild_embeddings", about = "Rebuild embeddings with current model")] +struct Args { + /// Collection to rebuild: momentry_rule1, _scenes, or all + #[arg(short, long, default_value = "all")] + collection: String, + + /// Optional file UUID to rebuild only one video + #[arg(short, long)] + uuid: Option, + + /// Skip PG embedding column update (only update Qdrant) + #[arg(long)] + skip_pg: bool, +} + +async fn rebuild_text_chunks(db: &momentry_core::core::db::postgres_db::PostgresDb, qdrant: &QdrantDb, embedder: &Embedder, file_uuid: Option<&str>, skip_pg: bool) -> Result<(usize, usize)> { + let chunk_table = schema::table_name("chunk"); + let mut ok = 0usize; + let mut fail = 0usize; + + // Clear existing points + if let Some(uuid) = file_uuid { + let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({ + "must": [{"key": "file_uuid", "match": {"value": uuid}}] + })).await; + println!(" Cleared points for file_uuid={}", uuid); + } else { + let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({})).await; + println!(" Cleared all points in momentry_rule1"); + } + + // Query chunks + let query = if let Some(uuid) = file_uuid { + format!( + "SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \ + FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' AND file_uuid = $1 \ + ORDER BY id", + chunk_table + ) + } else { + format!( + "SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \ + FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' \ + ORDER BY id", + chunk_table + ) + }; + + let rows: Vec<(String, String, i64, i64, f64, f64, String, String)> = if file_uuid.is_some() { + sqlx::query_as(&query) + .bind(file_uuid.unwrap()) + .fetch_all(db.pool()) + .await + .unwrap_or_default() + } else { + sqlx::query_as(&query) + .fetch_all(db.pool()) + .await + .unwrap_or_default() + }; + + let total = rows.len(); + println!(" Found {} sentence chunks to rebuild", total); + + for (i, (chunk_id, text, start_frame, end_frame, start_time, end_time, chunk_type, fuuid)) in rows.iter().enumerate() { + if text.is_empty() { + continue; + } + + match embedder.embed_document(text).await { + Ok(vector) => { + // Update PG embedding column if not skipped + if !skip_pg { + let vector_json = serde_json::to_string(&vector).unwrap_or_default(); + let _ = sqlx::query(&format!( + "UPDATE {} SET embedding = $1::vector WHERE chunk_id = $2 AND file_uuid = $3", + chunk_table + )) + .bind(&vector_json) + .bind(chunk_id) + .bind(fuuid) + .execute(db.pool()) + .await; + } + + // Upsert to Qdrant + let payload = VectorPayload { + file_uuid: fuuid.clone(), + chunk_id: chunk_id.clone(), + chunk_type: chunk_type.clone(), + start_frame: *start_frame, + end_frame: *end_frame, + start_time: *start_time, + end_time: *end_time, + text: Some(text.clone()), + }; + if qdrant.upsert_vector(chunk_id, &vector, payload).await.is_ok() { + ok += 1; + } else { + fail += 1; + } + + if (i + 1) % 50 == 0 || i + 1 == total { + println!(" Progress: {}/{} (ok={}, fail={})", i + 1, total, ok, fail); + } + } + Err(e) => { + eprintln!(" ✗ Failed to embed {}: {}", chunk_id, e); + fail += 1; + } + } + } + + Ok((ok, fail)) +} + +async fn rebuild_scenes(db: &momentry_core::core::db::postgres_db::PostgresDb, qdrant: &QdrantDb, embedder: &Embedder, file_uuid: Option<&str>) -> Result<(usize, usize)> { + let scenes_table = schema::table_name("scenes"); + let mut ok = 0usize; + let mut fail = 0usize; + + // Clear existing scene points + if let Some(uuid) = file_uuid { + let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({ + "must": [{"key": "file_uuid", "match": {"value": uuid}}] + })).await; + println!(" Cleared scene points for file_uuid={}", uuid); + } else { + let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({})).await; + println!(" Cleared all points in _scenes"); + } + + // Query scenes with VLM descriptions + let query = if let Some(uuid) = file_uuid { + format!( + "SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \ + COALESCE(vlm_description_localized, vlm_description) as description \ + FROM {} WHERE file_uuid = $1 AND (vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL) \ + ORDER BY id", + scenes_table + ) + } else { + format!( + "SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \ + COALESCE(vlm_description_localized, vlm_description) as description \ + FROM {} WHERE vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL \ + ORDER BY id", + scenes_table + ) + }; + + let rows: Vec<(i64, String, i32, f64, i64, String)> = if file_uuid.is_some() { + sqlx::query_as(&query) + .bind(file_uuid.unwrap()) + .fetch_all(db.pool()) + .await + .unwrap_or_default() + } else { + sqlx::query_as(&query) + .fetch_all(db.pool()) + .await + .unwrap_or_default() + }; + + let total = rows.len(); + println!(" Found {} scenes to rebuild", total); + + for (i, (scene_id, fuuid, scene_index, timestamp_sec, frame_number, description)) in rows.iter().enumerate() { + match embedder.embed_document(description).await { + Ok(vector) => { + let point_id_str = format!("{}_s{}", fuuid, scene_index); + let point_id = { + let mut hasher = DefaultHasher::new(); + point_id_str.hash(&mut hasher); + hasher.finish() + }; + + if qdrant.upsert_scene_embedding( + point_id, + &vector, + fuuid, + *scene_index as usize, + *timestamp_sec, + *frame_number as u32, + description, + None, + &[], + &[], + ).await.is_ok() { + ok += 1; + } else { + fail += 1; + } + + if (i + 1) % 50 == 0 || i + 1 == total { + println!(" Progress: {}/{} (ok={}, fail={})", i + 1, total, ok, fail); + } + } + Err(e) => { + eprintln!(" ✗ Failed to embed scene {}: {}", scene_id, e); + fail += 1; + } + } + } + + Ok((ok, fail)) +} + +#[tokio::main] +async fn main() -> Result<()> { + use clap::Parser; + + dotenv().ok(); + let args = Args::parse(); + + println!("═══ Embedding Rebuild Tool ═══"); + println!("Collection: {}", args.collection); + if let Some(uuid) = &args.uuid { + println!("File UUID: {}", uuid); + } + println!("Skip PG update: {}", args.skip_pg); + println!(); + + let db = momentry_core::core::db::postgres_db::PostgresDb::new(&config::DATABASE_URL).await + .context("Failed to connect to PostgreSQL")?; + let qdrant = QdrantDb::new(); + let embedder = Embedder::new("embeddinggemma-300m".to_string()); + + let t0 = std::time::Instant::now(); + + if args.collection == "all" || args.collection == "momentry_rule1" { + println!("── Rebuilding momentry_rule1 (text chunks) ──"); + let (ok, fail) = rebuild_text_chunks(&db, &qdrant, &embedder, args.uuid.as_deref(), args.skip_pg).await?; + println!(" Result: {}/{} succeeded, {} failed\n", ok, ok + fail, fail); + } + + if args.collection == "all" || args.collection == "_scenes" { + println!("── Rebuilding _scenes (scene embeddings) ──"); + let (ok, fail) = rebuild_scenes(&db, &qdrant, &embedder, args.uuid.as_deref()).await?; + println!(" Result: {}/{} succeeded, {} failed\n", ok, ok + fail, fail); + } + + let elapsed = t0.elapsed(); + println!("═══ Total time: {:.1}s ═══", elapsed.as_secs_f64()); + + Ok(()) +}