Files
momentry_core/src/bin/rebuild_embeddings.rs
T
Accusys 75cbaa3302
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
feat: rebuild embeddings endpoint + standalone tool (API + binary), clear collection before rebuild, fix upsert_scene_embedding args
2026-11-16 21:56:43 +08:00

268 lines
9.7 KiB
Rust

//! 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<String>,
/// 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(())
}