feat: rebuild embeddings endpoint + standalone tool (API + binary), clear collection before rebuild, fix upsert_scene_embedding args
This commit is contained in:
@@ -1085,6 +1085,7 @@ pub fn router() -> axum::Router<AppState> {
|
||||
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<AppState>,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> Result<Json<serde_json::Value>, 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.
|
||||
|
||||
Reference in New Issue
Block a user