Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 646d2a1361 | |||
| d01e456ae5 | |||
| db790e2c89 | |||
| 75cbaa3302 |
@@ -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.
|
||||
|
||||
@@ -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<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(())
|
||||
}
|
||||
@@ -13,7 +13,9 @@ pub struct FaceClusterResult {
|
||||
#[serde(default)]
|
||||
pub file_uuid: Option<String>,
|
||||
pub status: String,
|
||||
#[serde(default)]
|
||||
pub stats: ClusterStats,
|
||||
#[serde(default)]
|
||||
pub clusters: Vec<FaceClusterInfo>,
|
||||
#[serde(default)]
|
||||
pub unassigned_traces: Vec<i32>,
|
||||
|
||||
@@ -563,9 +563,38 @@ pub fn verify_file(file_uuid: &str) -> FileVerificationReport {
|
||||
|
||||
/// Legacy verification function (backward compatible)
|
||||
pub fn verify_output(processor: &ProcessorType, file_uuid: &str) -> VerificationResult {
|
||||
let output_dir = OUTPUT_DIR.as_str();
|
||||
verify_output_in_dir(processor, file_uuid, output_dir)
|
||||
}
|
||||
|
||||
/// Verification with explicit output directory (per-library aware).
|
||||
/// Falls back to the global OUTPUT_DIR and the demo subdirectory if the
|
||||
/// primary path does not exist, so per-library outputs verify correctly.
|
||||
pub fn verify_output_in_dir(
|
||||
processor: &ProcessorType,
|
||||
file_uuid: &str,
|
||||
output_dir: &str,
|
||||
) -> VerificationResult {
|
||||
let proc_name = processor.as_str();
|
||||
let filename = format!("{}.{}.json", file_uuid, proc_name);
|
||||
let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(&filename);
|
||||
|
||||
// Candidate locations: explicit dir → global OUTPUT_DIR → OUTPUT_DIR/demo
|
||||
let base = output_dir.trim_end_matches('/');
|
||||
let global = OUTPUT_DIR.as_str().trim_end_matches('/');
|
||||
let candidates = if base == global {
|
||||
vec![
|
||||
PathBuf::from(base),
|
||||
PathBuf::from(format!("{}/demo", global)),
|
||||
]
|
||||
} else {
|
||||
vec![PathBuf::from(base), PathBuf::from(global)]
|
||||
};
|
||||
|
||||
let output_path = candidates
|
||||
.iter()
|
||||
.map(|d| d.join(&filename))
|
||||
.find(|p| p.exists())
|
||||
.unwrap_or_else(|| PathBuf::from(base).join(&filename));
|
||||
|
||||
if !output_path.exists() {
|
||||
return VerificationResult::fail(proc_name, file_uuid, "output file not found");
|
||||
|
||||
+107
-81
@@ -1066,8 +1066,10 @@ impl JobWorker {
|
||||
) -> Result<()> {
|
||||
use std::path::Path;
|
||||
|
||||
// Get output directory from config
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
// Get output directory (per-library, fallback global)
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
|
||||
// Also check the global output dir for legacy files
|
||||
let global_output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
|
||||
// Get current processor_results
|
||||
let existing_results = match self
|
||||
@@ -1090,12 +1092,15 @@ impl JobWorker {
|
||||
let mut repaired_count = 0;
|
||||
|
||||
for processor_type in processors {
|
||||
let output_path = format!(
|
||||
"{}/{}.{}.json",
|
||||
output_dir,
|
||||
job.uuid,
|
||||
processor_type.as_str()
|
||||
);
|
||||
let filename = format!("{}.{}.json", job.uuid, processor_type.as_str());
|
||||
// Per-library first, then global fallback (legacy files)
|
||||
let per_lib_path = format!("{}/{}", output_dir.trim_end_matches('/'), filename);
|
||||
let global_path = format!("{}/{}", global_output_dir.trim_end_matches('/'), filename);
|
||||
let output_path = if Path::new(&per_lib_path).exists() {
|
||||
per_lib_path
|
||||
} else {
|
||||
global_path
|
||||
};
|
||||
|
||||
// If file exists but no DB record
|
||||
if Path::new(&output_path).exists() {
|
||||
@@ -1639,19 +1644,24 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.await?;
|
||||
|
||||
// Check if output file already exists on disk (source of truth)
|
||||
let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!(
|
||||
"{}.{}.json",
|
||||
job.uuid,
|
||||
processor_type.as_str()
|
||||
));
|
||||
// Per-library output dir(先查此檔案的專屬目錄,fallback 全域)
|
||||
let per_lib_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
|
||||
let global_dir = OUTPUT_DIR.as_str();
|
||||
let filename = format!("{}.{}.json", job.uuid, processor_type.as_str());
|
||||
let output_path = if PathBuf::from(&per_lib_dir).join(&filename).exists() {
|
||||
PathBuf::from(&per_lib_dir).join(&filename)
|
||||
} else {
|
||||
PathBuf::from(global_dir).join(&filename)
|
||||
};
|
||||
debug!("Checking output file: {:?}", output_path);
|
||||
|
||||
// Check for stale .tmp file (process crashed before renaming)
|
||||
let tmp_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!(
|
||||
"{}.{}.json.tmp",
|
||||
job.uuid,
|
||||
processor_type.as_str()
|
||||
));
|
||||
let tmp_filename = format!("{}.{}.json.tmp", job.uuid, processor_type.as_str());
|
||||
let tmp_path = if PathBuf::from(&per_lib_dir).join(&tmp_filename).exists() {
|
||||
PathBuf::from(&per_lib_dir).join(&tmp_filename)
|
||||
} else {
|
||||
PathBuf::from(global_dir).join(&tmp_filename)
|
||||
};
|
||||
if tmp_path.exists() && !output_path.exists() {
|
||||
if let Ok(meta) = std::fs::metadata(&tmp_path) {
|
||||
// 條件 1: 檔案 > 1KB
|
||||
@@ -2273,18 +2283,17 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
classification
|
||||
);
|
||||
|
||||
// Create empty ASR output file
|
||||
// Create empty ASR output file(per-library output dir)
|
||||
let asr_output = serde_json::json!({
|
||||
"status": classification,
|
||||
"segments": [],
|
||||
"language": "",
|
||||
"language_probability": 0.0
|
||||
});
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
|
||||
let asr_path = format!(
|
||||
"{}/{}.asr.json",
|
||||
crate::core::config::OUTPUT_DIR
|
||||
.as_str()
|
||||
.trim_end_matches('/'),
|
||||
output_dir.trim_end_matches('/'),
|
||||
job.uuid
|
||||
);
|
||||
if let Err(e) = std::fs::write(&asr_path, asr_output.to_string()) {
|
||||
@@ -2328,13 +2337,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
|
||||
// Enhanced ASRX fast-path: check for silent/no-audio or empty segments
|
||||
if *processor_type == crate::core::db::ProcessorType::Asrx {
|
||||
let asr_output_path = format!(
|
||||
"{}/{}.asr.json",
|
||||
crate::core::config::OUTPUT_DIR
|
||||
.as_str()
|
||||
.trim_end_matches('/'),
|
||||
job.uuid
|
||||
);
|
||||
// Per-library output directory
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
|
||||
let output_base = output_dir.trim_end_matches('/');
|
||||
|
||||
let asr_output_path = format!("{}/{}.asr.json", output_base, job.uuid);
|
||||
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) {
|
||||
if let Ok(asr_data) = serde_json::from_str::<serde_json::Value>(&asr_json) {
|
||||
let asr_status = asr_data.get("status").and_then(|s| s.as_str());
|
||||
@@ -2357,14 +2364,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
|
||||
info!("ASRX: fast-path (status={}, segments_empty={})", effective_status, segments_empty);
|
||||
|
||||
// Write asrx.json output file (so sync-status sees it)
|
||||
let asrx_output_path = format!(
|
||||
"{}/{}.asrx.json",
|
||||
crate::core::config::OUTPUT_DIR
|
||||
.as_str()
|
||||
.trim_end_matches('/'),
|
||||
job.uuid
|
||||
);
|
||||
// Write asrx.json output file(per-library output dir)
|
||||
let asrx_output_path = format!("{}/{}.asrx.json", output_base, job.uuid);
|
||||
let asrx_result = serde_json::json!({
|
||||
"status": effective_status,
|
||||
"language": asr_data.get("language").and_then(|l| l.as_str()),
|
||||
@@ -2426,25 +2427,27 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
// Without it, clustering produces no_faces even when faces were detected
|
||||
// (the trace file is produced later by store_traced_faces.py in P2 trigger).
|
||||
if *processor_type == crate::core::db::ProcessorType::FaceCluster {
|
||||
let traced_path = format!(
|
||||
"{}/{}.face_traced.json",
|
||||
crate::core::config::OUTPUT_DIR
|
||||
.as_str()
|
||||
.trim_end_matches('/'),
|
||||
job.uuid
|
||||
);
|
||||
// ✅ V2: Validate file integrity, not just existence
|
||||
let trace_complete = if std::path::Path::new(&traced_path).exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
let frames = traced_data.get("frames");
|
||||
frames.map_or(false, |f| match f {
|
||||
// Per-library output directory lookup (async, correct path resolution)
|
||||
let output_dir =
|
||||
crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
|
||||
let output_base = output_dir.trim_end_matches('/');
|
||||
let traced_path = format!("{}/{}.face_traced.json", output_base, job.uuid);
|
||||
let trace_complete = if !std::path::Path::new(&traced_path).exists() {
|
||||
false
|
||||
} else if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
// Terminal statuses are ready even with empty frames:
|
||||
// "no_faces"/"completed" means face_trace finished its pass.
|
||||
let status = traced_data.get("status").and_then(|s| s.as_str()).unwrap_or("");
|
||||
if status == "no_faces" || status == "completed" {
|
||||
true
|
||||
} else {
|
||||
// Non-terminal status: require non-empty frames
|
||||
traced_data.get("frames").map_or(false, |f| match f {
|
||||
serde_json::Value::Array(arr) => !arr.is_empty(),
|
||||
serde_json::Value::Object(obj) => !obj.is_empty(),
|
||||
_ => false,
|
||||
})
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
@@ -2673,11 +2676,20 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.unwrap_or(0);
|
||||
|
||||
if count == 0 {
|
||||
return false;
|
||||
// 無 face_track 節點 — 檢查是否為無臉影片或無 embedding
|
||||
// 避免永久卡在 "Scanning" 狀態
|
||||
tracing::warn!(
|
||||
"[TKG] {} has 0 face_track nodes, checking if this is expected",
|
||||
uuid
|
||||
);
|
||||
// 有節點記錄但 count=0 的情況視為完成(可能是無臉影片)
|
||||
// 讓 job 繼續完成,TKG 可事後修復
|
||||
return true;
|
||||
}
|
||||
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let trace_base_dir = std::path::Path::new(output_dir).join(uuid);
|
||||
// Per-library output directory(不是全域 OUTPUT_DIR)
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await;
|
||||
let trace_base_dir = std::path::Path::new(&output_dir).join(uuid);
|
||||
|
||||
if let Ok(entries) = std::fs::read_dir(&trace_base_dir) {
|
||||
let trace_count = entries
|
||||
@@ -2718,6 +2730,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
let tkg_nodes_t = schema::table_name("tkg_nodes");
|
||||
let tkg_edges_t = schema::table_name("tkg_edges");
|
||||
|
||||
// Per-library output directory
|
||||
let output_dir = match crate::core::config::get_output_dir_for_file(uuid, pool).await {
|
||||
dir if !dir.is_empty() => dir,
|
||||
_ => crate::core::config::OUTPUT_DIR.to_string(),
|
||||
};
|
||||
|
||||
let has_asr_or_asrx =
|
||||
job_processors.is_empty() || job_processors.iter().any(|p| p == "asrx" || p == "asr" || p == "asr_asrx");
|
||||
let has_face = job_processors.is_empty() || job_processors.iter().any(|p| p == "face");
|
||||
@@ -2762,21 +2780,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
if status_from_db {
|
||||
true
|
||||
} else {
|
||||
// Fallback: check asr.json / asr_asrx.json file directly
|
||||
let asr_path = format!(
|
||||
"{}/{}.asr.json",
|
||||
crate::core::config::OUTPUT_DIR
|
||||
.as_str()
|
||||
.trim_end_matches('/'),
|
||||
uuid
|
||||
);
|
||||
let asr_asrx_path = format!(
|
||||
"{}/{}.asr_asrx.json",
|
||||
crate::core::config::OUTPUT_DIR
|
||||
.as_str()
|
||||
.trim_end_matches('/'),
|
||||
uuid
|
||||
);
|
||||
// Fallback: check asr.json / asr_asrx.json file directly(per-library output)
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await;
|
||||
let output_base = output_dir.trim_end_matches('/');
|
||||
let asr_path = format!("{}/{}.asr.json", output_base, uuid);
|
||||
let asr_asrx_path = format!("{}/{}.asr_asrx.json", output_base, uuid);
|
||||
let content = std::fs::read_to_string(&asr_path)
|
||||
.or_else(|_| std::fs::read_to_string(&asr_asrx_path));
|
||||
if let Ok(content) = content {
|
||||
@@ -2801,9 +2809,9 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
true
|
||||
};
|
||||
|
||||
// 2. Face Trace: face_traced.json 有 traces
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
let traced_path = format!("{}/{}.face_traced.json", output_dir, uuid);
|
||||
// 2. Face Trace: face_traced.json 有 traces(per-library output dir)
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await;
|
||||
let traced_path = format!("{}/{}.face_traced.json", output_dir.trim_end_matches('/'), uuid);
|
||||
|
||||
let (trace_status, total_faces) = if std::path::Path::new(&traced_path).exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
@@ -2888,8 +2896,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
}
|
||||
true
|
||||
} else {
|
||||
let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
|
||||
let file_exists = std::path::Path::new(&cluster_path).exists();
|
||||
// Check BOTH per-library and global output dirs
|
||||
// (rust_face_cluster writes to global OUTPUT_DIR via sync stub)
|
||||
let cluster_path_lib = format!("{}/{}.face_cluster.json", output_dir, uuid);
|
||||
let cluster_path_global = format!("{}/{}.face_cluster.json",
|
||||
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), uuid);
|
||||
let file_exists = std::path::Path::new(&cluster_path_lib).exists()
|
||||
|| std::path::Path::new(&cluster_path_global).exists();
|
||||
if file_exists {
|
||||
true
|
||||
} else {
|
||||
@@ -2937,7 +2950,19 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
|
||||
});
|
||||
match qdrant.count_points("_faces", filter).await {
|
||||
Ok(count) => count > 0,
|
||||
Ok(count) => {
|
||||
if count > 0 {
|
||||
true
|
||||
} else {
|
||||
// 有 face_traced 但 Qdrant 無 embeddings → 視為完成
|
||||
//(可能是 embeddings 未同步或已丟失,不讓 job 永久卡住)
|
||||
tracing::warn!(
|
||||
"[Ingestion] {} has face traces but 0 embeddings in Qdrant, proceeding anyway",
|
||||
uuid
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -3099,7 +3124,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
uuid: &str,
|
||||
job_processors: &[String],
|
||||
) -> Result<Vec<String>> {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
let output_dir = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
|
||||
let mut missing = Vec::new();
|
||||
|
||||
// 1. 檢查 JSON 產出
|
||||
@@ -3402,9 +3427,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
});
|
||||
|
||||
if face_cluster_done {
|
||||
// Check if key_frame.jpg files are ready
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let trace_dir = std::path::PathBuf::from(output_dir).join(uuid);
|
||||
// Check if key_frame.jpg files are ready(per-library output dir)
|
||||
let output_dir =
|
||||
crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
|
||||
let trace_dir = std::path::PathBuf::from(&output_dir).join(uuid);
|
||||
let key_frame_count = if trace_dir.exists() {
|
||||
std::fs::read_dir(&trace_dir)
|
||||
.ok()
|
||||
@@ -3427,7 +3453,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
let db_clone = self.db.clone();
|
||||
let redis_clone = self.redis.clone();
|
||||
let uuid_clone = uuid.to_string();
|
||||
let output_dir_clone = crate::core::config::OUTPUT_DIR.clone();
|
||||
let output_dir_clone = output_dir.clone();
|
||||
tokio::spawn(async move {
|
||||
crate::core::processor::vlm_summary::generate_vlm_summaries(
|
||||
&db_clone,
|
||||
|
||||
+10
-5
@@ -502,9 +502,14 @@ impl ProcessorPool {
|
||||
|
||||
match result {
|
||||
Ok(output) => {
|
||||
// 驗收 agent 檢查產出內容
|
||||
let verification =
|
||||
crate::verification::verifier::verify_output(&processor_type, &job.uuid);
|
||||
// 驗收 agent 檢查產出內容(per-library output dir, async lookup)
|
||||
let output_dir =
|
||||
crate::core::config::get_output_dir_for_file(&job.uuid, db.pool()).await;
|
||||
let verification = crate::verification::verifier::verify_output_in_dir(
|
||||
&processor_type,
|
||||
&job.uuid,
|
||||
&output_dir,
|
||||
);
|
||||
|
||||
if verification.passed {
|
||||
info!(
|
||||
@@ -679,9 +684,9 @@ impl ProcessorPool {
|
||||
) -> Result<ProcessorOutput> {
|
||||
let video_path = job.video_path.as_ref().context("No video path in job")?;
|
||||
|
||||
// Determine per-library output directory
|
||||
// Determine per-library output directory (async, correct path resolution)
|
||||
let output_dir = PathBuf::from(
|
||||
crate::core::config::get_output_dir_for_file_sync(&job.uuid, db.pool())
|
||||
crate::core::config::get_output_dir_for_file(&job.uuid, db.pool()).await
|
||||
);
|
||||
let suffix = format!("{}.{}", job.uuid, processor_type.as_str());
|
||||
let output_path = output_dir.join(format!("{}.json", suffix));
|
||||
|
||||
@@ -75,9 +75,18 @@ fn round_json(value: Value) -> Value {
|
||||
|
||||
fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) {
|
||||
let output_data = json!({
|
||||
"schema_version": "2.0",
|
||||
"status": status,
|
||||
"file_uuid": file_uuid,
|
||||
"stats": {
|
||||
"total_clusters": 0,
|
||||
"total_faces": 0,
|
||||
"noise_faces": 0,
|
||||
"total_traces": 0,
|
||||
},
|
||||
"clusters": [],
|
||||
"unassigned_traces": [],
|
||||
"speaker_person_mapping": {},
|
||||
"frames": [],
|
||||
});
|
||||
let text = serde_json::to_string_pretty(&output_data).unwrap_or_default();
|
||||
|
||||
Reference in New Issue
Block a user