7 Commits

Author SHA1 Message Date
Accusys 7fd7df2913 fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts'); embedding port 11436→11437
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 08:41:34 +08:00
Accusys eac827d932 fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts') → ~/momentry/scripts/ 2026-11-17 04:31:03 +08:00
Accusys a85e31ff16 fix: embedding default port 11436 → 11437 (llama-server GGUF) 2026-11-17 04:26:33 +08:00
Accusys 646d2a1361 fix(P0): face_cluster_done 雙路徑檢查 + run_processor 改用 async get_output_dir_for_file; 補 ingestion_complete output_dir
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 03:03:16 +08:00
Accusys d01e456ae5 fix(P0): per-library output dir for worker ingestion/verification (face_cluster guard, verifier, TKG, qdrant_face, ASR/ASRX); fix face_cluster serde default for empty output; fix face_cluster dependencies in pipeline_flows.json
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 02:46:57 +08:00
Accusys db790e2c89 fix: face_cluster guard checks both global OUTPUT_DIR and demo subdirectory for face_traced.json
Cross-Project Integration / integration (push) Has been cancelled
Core Test / lint-and-test (push) Has been cancelled
2026-11-17 01:29:28 +08:00
Accusys 75cbaa3302 feat: rebuild embeddings endpoint + standalone tool (API + binary), clear collection before rebuild, fix upsert_scene_embedding args
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-16 21:56:43 +08:00
11 changed files with 1718 additions and 92 deletions
+217
View File
@@ -0,0 +1,217 @@
use std::time::Duration;
use axum::{Json, Router};
use serde_json::json;
use tokio::time::timeout;
use tower_http::cors::{Any, CorsLayer};
use tower_http::services::ServeDir;
use crate::core::cache::{MongoCache, RedisCache};
use crate::core::db::{Database, PostgresDb, QdrantDb};
use crate::Embedder;
use super::admin_config;
use super::agent_api;
use super::agent_search;
use super::auth;
use super::billing;
use super::checkin_api;
use super::clip_api;
use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::file_progress;
use super::files;
use super::health;
use super::health::{health, health_consistency, health_detailed, health_queue};
use super::identities;
use super::identity_api;
use super::identity_binding;
use super::llm_search;
use super::markbase_compat;
use super::media_api;
use super::middleware::unified_auth;
use super::pipeline;
use super::processing;
use super::profile;
use super::scan;
use super::search::search_routes;
use super::service_management;
use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::monitor;
use super::universal_search::universal_search_routes;
use super::vlm_search;
use super::job_management;
pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
health::init_server_state(host, port);
let embedder = std::sync::Arc::new(Embedder::new("embeddinggemma-300m".to_string()));
// ── ⚠️ WARNING: DO NOT move MongoCache::init() back to critical path ──
//
// MongoDB is ONLY a cache layer — if unavailable, the server MUST still
// start with Redis cache alone. This keeps 3002 bootable on machines
// without MongoDB installed. If you add a new dependency here, ask:
// "Can this service degrade gracefully if the dependant is missing?"
//
// See also: MongoCache::disabled() in mongo_cache.rs
let mongo_cache = match timeout(Duration::from_secs(5), MongoCache::init()).await {
Ok(Ok(cache)) => cache,
Ok(Err(e)) => {
tracing::warn!("MongoDB cache unavailable (continuing without): {e}");
MongoCache::disabled().await
}
Err(_) => {
tracing::warn!("MongoDB init timed out (continuing without cache)");
MongoCache::disabled().await
}
};
let redis_cache = RedisCache::new()?;
let db = PostgresDb::init().await?;
// Run migrations (create identity_history table if not exists)
PostgresDb::run_migrations(db.pool()).await?;
let schema_health = health::check_schema_migrations(db.pool()).await;
if schema_health.ok {
tracing::info!(
"[SCHEMA] All {}/{} required migrations applied ✓",
schema_health.required.len(),
schema_health.required.len()
);
} else if !schema_health.table_exists {
tracing::warn!("[SCHEMA] schema_migrations table not found!");
} else {
let missing: Vec<&str> = schema_health
.required
.iter()
.filter(|req| {
!schema_health
.applied
.iter()
.any(|app| app.filename == req.filename && app.checksum == req.checksum)
})
.map(|m| m.filename.as_str())
.collect();
tracing::warn!(
"[SCHEMA] {}/{} migrations match. Missing: {}",
schema_health.applied.len(),
schema_health.required.len(),
missing.join(", ")
);
}
let db = std::sync::Arc::new(db);
let api_state = super::middleware::ApiState { db: db.clone() };
let qdrant = std::sync::Arc::new(QdrantDb::new());
// Initialize AdminConfigManager
let admin_config_manager = std::sync::Arc::new(
crate::core::admin_config::AdminConfigManager::new(
&crate::core::admin_config::get_default_config_path(),
)
.expect("Failed to initialize AdminConfigManager"),
);
// Ensure trash collection exists for trace hard-delete undo
if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await {
tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e);
}
let state = AppState {
db,
qdrant,
embedder,
embedder_model: "nomic-embed-text-v2-moe:latest".to_string(),
mongo_cache,
redis_cache,
api_state,
admin_config_manager,
};
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(markbase_compat::markbase_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
.merge(tmdb_api::tmdb_routes())
.merge(identity_api::identity_routes())
.merge(agent_api::agent_routes())
.merge(agent_search::agent_search_routes())
.merge(processing::processing_routes())
.merge(file_progress::file_progress_routes())
.merge(media_api::bbox_routes())
.merge(media_api::media_proxy_routes())
.merge(media_api::pose_appearance_routes())
.merge(trace_agent_api::trace_agent_routes())
.merge(clip_api::clip_routes())
.merge(search_routes())
.merge(llm_search::llm_smart_routes())
.merge(universal_search_routes())
.merge(pipeline::pipeline_routes())
.merge(checkin_api::checkin_routes())
.merge(cluster_agent::cluster_agent_routes())
.merge(profile::profile_routes())
.merge(face_filter::face_filter_routes())
.merge(admin_config::admin_config_routes())
.merge(vlm_search::vlm_search_routes())
.merge(billing::billing_routes())
.merge(job_management::job_management_routes())
.merge(service_management::router())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
))
.with_state(state.clone());
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let public_health_routes = Router::new()
.route("/api/v1/health", axum::routing::get(health))
.route(
"/api/v1/health/detailed",
axum::routing::get(health_detailed),
)
.route(
"/api/v1/health/consistency",
axum::routing::get(health_consistency),
)
.route(
"/api/v1/health/queue",
axum::routing::get(health_queue),
)
.route(
"/api/v1/mbe/health",
axum::routing::get(service_management::mbe_health),
);
let app = Router::new()
.merge(auth::auth_routes())
.merge(public_health_routes)
.merge(docs::doc_routes())
.merge(monitor::monitor_routes())
.nest_service("/monitor", ServeDir::new("static/monitor"))
.merge(protected_routes)
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.layer(axum::middleware::from_fn(
super::middleware::concurrency_limit,
))
.with_state(state);
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap();
tracing::info!("Starting API server at http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
+215 -1
View File
@@ -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)
}
@@ -1098,7 +1099,7 @@ pub async fn test_embedding(
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let url = std::env::var("MOMENTRY_EMBED_URL")
.unwrap_or_else(|_| "http://localhost:11436".to_string());
.unwrap_or_else(|_| "http://localhost:11437".to_string());
// Detect server type from URL port
let server_type = if url.contains("11437") {
@@ -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.
+267
View File
@@ -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(())
}
+1 -1
View File
@@ -43,7 +43,7 @@ impl Embedder {
}
fn default_url() -> String {
std::env::var("MOMENTRY_EMBED_URL").unwrap_or_else(|_| "http://localhost:11436".to_string())
std::env::var("MOMENTRY_EMBED_URL").unwrap_or_else(|_| "http://localhost:11437".to_string())
}
pub async fn embed_text(&self, text: &str) -> Result<Vec<f32>> {
+1 -3
View File
@@ -73,9 +73,7 @@ pub fn demo_dir() -> PathBuf {
/// Get scripts directory
pub fn scripts_dir() -> PathBuf {
env::var("MOMENTRY_SCRIPTS_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| momentry_core_dir().join("tools/script"))
resolve_asset_path("MOMENTRY_SCRIPTS_DIR", "scripts")
}
/// Get CLI tools directory
+2
View File
@@ -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>,
@@ -0,0 +1,859 @@
use anyhow::{Context, Result};
use futures_util::future::join_all;
use std::collections::HashMap;
use std::path::Path;
use tokio::process::Command;
use crate::core::file_profile::{
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
};
pub struct SceneVlmProcessor {
samples_per_interval: usize,
use_cuts: bool,
max_workers: usize,
}
impl SceneVlmProcessor {
pub fn new(samples_per_interval: usize, use_cuts: bool, max_workers: usize) -> Self {
Self {
samples_per_interval,
use_cuts,
max_workers,
}
}
pub fn compute_sample_frames(
interval_start_sec: f64,
interval_sec: f64,
fps: f64,
samples: usize,
) -> Vec<u32> {
if samples == 0 {
return vec![];
}
let sample_interval = interval_sec / samples as f64;
let frames: Vec<u32> = (0..samples)
.map(|i| {
let time = interval_start_sec + (i as f64 + 0.5) * sample_interval;
(time * fps).round() as u32
})
.collect();
// Ensure at least frame 0 is included for short videos
if frames.is_empty() || frames.iter().all(|&f| f > 0) {
let mut result = vec![0u32];
result.extend(frames.into_iter().filter(|&f| f > 0));
result
} else {
frames
}
}
pub async fn calculate_blur_single(video_path: &str, frame: u32, fps: f64) -> Result<f64> {
let time_sec = frame as f64 / fps;
let output = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-vf",
"blurdetect",
"-f",
"null",
"-",
])
.output()
.await
.context("FFmpeg blurdetect failed")?;
let stderr = String::from_utf8_lossy(&output.stderr);
for line in stderr.lines() {
if let Some(blur_str) = line.split("blur mean: ").nth(1) {
if let Ok(blur) = blur_str.trim().parse::<f64>() {
return Ok(blur);
}
}
}
Ok(f64::NAN)
}
pub async fn calculate_blur_parallel(
video_path: &str,
frames: &[u32],
fps: f64,
max_workers: usize,
) -> Result<Vec<(u32, f64)>> {
let tasks: Vec<_> = frames
.iter()
.map(|frame| Self::calculate_blur_single(video_path, *frame, fps))
.collect();
let results = join_all(tasks).await;
let mut combined = Vec::new();
for (frame, result) in frames.iter().zip(results.into_iter()) {
if let Ok(blur) = result {
combined.push((*frame, blur));
} else {
combined.push((*frame, f64::NAN));
}
}
Ok(combined)
}
pub fn select_best_frame(blur_scores: &[(u32, f64)]) -> Option<(u32, f64)> {
blur_scores
.iter()
.filter(|(_, blur)| !blur.is_nan())
.min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.map(|(frame, blur)| (*frame, *blur))
}
pub fn find_cuts_in_interval(
interval_start: f64,
interval_end: f64,
cut_data: &serde_json::Value,
) -> Vec<serde_json::Value> {
let mut cuts = Vec::new();
if let Some(scenes) = cut_data.get("scenes").and_then(|s| s.as_array()) {
for scene in scenes {
if let Some(start_time) = scene.get("start_time").and_then(|t| t.as_f64()) {
if start_time > interval_start && start_time < interval_end {
cuts.push(scene.clone());
}
}
}
}
cuts
}
pub async fn process_interval(
video_path: &str,
interval_start: f64,
interval_sec: f64,
fps: f64,
cut_data: &serde_json::Value,
samples_per_interval: usize,
max_workers: usize,
) -> Result<Vec<SceneFrame>> {
let sample_frames =
Self::compute_sample_frames(interval_start, interval_sec, fps, samples_per_interval);
let blur_scores =
Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?;
let cuts =
Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
let mut selected_frames = Vec::new();
if cuts.is_empty() {
if let Some((frame, blur)) = Self::select_best_frame(&blur_scores) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::BestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
} else if let Some(&frame) = sample_frames.first() {
// Fallback: use first sample frame when blur detection yields no scores
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::Default,
quality_score: None,
quality_source: None,
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
} else {
let cut = &cuts[0];
let cut_time = cut
.get("start_time")
.and_then(|t| t.as_f64())
.unwrap_or(interval_start);
let cut_frame = (cut_time * fps).round() as u32;
let pre_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f < cut_frame)
.cloned()
.collect();
let post_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f >= cut_frame)
.cloned()
.collect();
if !pre_frames.is_empty() {
let pre_blur =
Self::calculate_blur_parallel(video_path, &pre_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&pre_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PreCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
if !post_frames.is_empty() {
let post_blur =
Self::calculate_blur_parallel(video_path, &post_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&post_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PostCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
}
for (i, frame) in selected_frames.iter_mut().enumerate() {
frame.index = i;
}
Ok(selected_frames)
}
pub async fn generate_scene_profile(
&self,
video_path: &str,
file_uuid: &str,
output_dir: &str,
interval_sec: u32,
cut_data: &serde_json::Value,
fps: f64,
duration: f64,
width: u32,
height: u32,
total_frames: u32,
) -> Result<SceneProfile> {
let config = SceneConfig {
interval_sec,
use_cuts: true,
use_faces: false,
quality_metric: "ffmpeg_blurdetect".to_string(),
samples_per_interval: self.samples_per_interval,
};
let video_info = VideoInfo {
duration_sec: duration,
fps,
width,
height,
total_frames,
};
let mut profile = SceneProfile::new(file_uuid, video_info, config);
let mut all_frames = Vec::new();
let total_intervals = (duration / interval_sec as f64).ceil() as usize;
for i in 0..total_intervals {
let interval_start = i as f64 * interval_sec as f64;
let interval_end = (interval_start + interval_sec as f64).min(duration);
let actual_interval_sec = interval_end - interval_start;
let frames = Self::process_interval(
video_path,
interval_start,
actual_interval_sec,
fps,
cut_data,
self.samples_per_interval,
self.max_workers,
)
.await?;
all_frames.extend(frames);
}
// Fix indices
for (i, frame) in all_frames.iter_mut().enumerate() {
frame.index = i;
frame.filename = format!("scene_{:03}.jpg", i);
}
profile.scenes = all_frames;
profile.total_scenes = profile.scenes.len();
profile.status = SceneStatus::Ready;
profile.updated_at = chrono::Utc::now();
Ok(profile)
}
pub fn save_scene_profile(profile: &SceneProfile, output_dir: &str) -> Result<()> {
let path = SceneProfile::scenes_path(output_dir, &profile.file_uuid);
let json =
serde_json::to_string_pretty(profile).context("Failed to serialize SceneProfile")?;
std::fs::write(&path, json).context("Failed to write scenes.json")?;
Ok(())
}
pub fn load_scene_profile(output_dir: &str, file_uuid: &str) -> Result<SceneProfile> {
let path = SceneProfile::scenes_path(output_dir, file_uuid);
let json = std::fs::read_to_string(&path).context("Failed to read scenes.json")?;
let profile: SceneProfile =
serde_json::from_str(&json).context("Failed to parse scenes.json")?;
Ok(profile)
}
pub async fn extract_scene_frames(
video_path: &str,
output_dir: &str,
file_uuid: &str,
scenes: &[SceneFrame],
) -> Result<Vec<std::path::PathBuf>> {
let scenes_dir = SceneProfile::scenes_dir(output_dir, file_uuid);
std::fs::create_dir_all(&scenes_dir).context("Failed to create scenes directory")?;
let mut extracted_paths = Vec::new();
for scene in scenes {
let output_path =
SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
let time_sec = scene.timestamp_sec;
let status = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-y",
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-q:v",
"5",
&output_path.to_string_lossy(),
])
.status()
.await
.context("FFmpeg frame extraction failed")?;
if status.success() && output_path.exists() {
extracted_paths.push(output_path);
}
}
Ok(extracted_paths)
}
/// Helper function to extract scene info from parsed JSON
fn extract_scene_info(
parsed: &serde_json::Value,
fallback: &str,
) -> (String, Vec<String>, Vec<String>) {
let desc = parsed
.get("description")
.and_then(|d| d.as_str())
.unwrap_or(fallback)
.to_string();
let objs = parsed
.get("objects")
.and_then(|o| o.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let tgs = parsed
.get("tags")
.and_then(|t| t.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
(desc, objs, tgs)
}
/// Extract objects from text (simple keyword matching)
fn extract_objects_from_text(text: &str) -> Vec<String> {
let keywords = [
"river", "tree", "forest", "mountain", "building", "person", "text", "water", "sky",
"cloud", "road", "car", "house", "flower", "grass", "rock", "bridge", "boat", "animal",
"bird",
];
keywords
.iter()
.filter(|&k| text.to_lowercase().contains(k))
.map(|k| k.to_string())
.collect()
}
/// Extract tags from text (category inference)
fn extract_tags_from_text(text: &str) -> Vec<String> {
let mut tags = vec![];
let lower = text.to_lowercase();
if lower.contains("landscape") || lower.contains("nature") {
tags.push("nature".to_string());
}
if lower.contains("indoor") || lower.contains("room") {
tags.push("indoor".to_string());
}
if lower.contains("outdoor") {
tags.push("outdoor".to_string());
}
if lower.contains("presentation") || lower.contains("slide") {
tags.push("presentation".to_string());
}
if lower.contains("text") || lower.contains("title") {
tags.push("text".to_string());
}
if lower.contains("water") || lower.contains("river") {
tags.push("water".to_string());
}
tags
}
fn language_display_name(language: &str) -> &'static str {
match language {
"zh-TW" => "Traditional Chinese (zh-TW)",
"zh-CN" => "Simplified Chinese (zh-CN)",
"ja" => "Japanese (ja)",
"ko" => "Korean (ko)",
"es" => "Spanish (es)",
"fr" => "French (fr)",
"de" => "German (de)",
_ => "English (en)",
}
}
/// Build the structured scene analysis prompt.
fn build_scene_prompt(local_language: &str) -> String {
let local_name = Self::language_display_name(local_language);
format!(
r#"You are an expert visual analyst for a multimodal video search system.
Analyze the attached image frame and return ONLY valid JSON with NO markdown, NO explanations, NO reasoning, NO thinking.
Use this exact schema:
{{
"summary": "Concise English summary of the core content (1-2 sentences). Factual, avoid superlatives like beautiful/stunning/amazing.",
"category": "Single highest-level category. Choose ONE from: landscape|architecture|interior|people|event|nature|urban|transport|food|animal|product|other",
"scene_type": "Environment/background. Choose ONE from: indoor|outdoor|city street|resort|nature|mountain|beach|forest|building exterior|building interior|road|park|unknown",
"objects": ["3-5 most prominent objects or subjects in English. Concrete and specific."],
"actions": ["Main actions/events or static state if no motion. Use English (e.g. 'static scene', 'driving', 'walking')."],
"visual_attributes": {{
"lighting": "e.g. natural daylight, golden hour, overcast, artificial, backlit, mixed lighting",
"composition": "e.g. aerial view, wide angle, eye level, low angle, close-up, drone shot, street level",
"color_palette": ["3-5 dominant colors in English (e.g. gray, green, blue, orange)"]
}},
"detected_text": ["Exact visible signs, logos, plaques, or printed text. Only if legible. Empty array if none."],
"tags": [
{{"en": "english_tag", "local": "localized_tag"}}
]
}}
Rules:
- summary must be English only
- objects, actions, visual_attributes must use concrete English terms. Avoid generic words like "photo", "image", "view", "scene"
- tags: 5-10 items. Each item MUST be an object with both "en" and "local" keys
- Use {local_name} for "local". If the preferred language is English, set "local" equal to "en" but keep both keys
- Prioritize search-relevant terms (environment type, key structures/objects). Do NOT just copy the full summary into tags
- Do NOT duplicate objects 1:1 unless genuinely useful as search tags
- Keep tags concise (1-3 words). Avoid redundancy between tags
- detected_text: only extract text actually visible, do not guess or infer
- Output ONLY the JSON object"#
)
}
/// Extract the first JSON object from a VLM response (tolerates markdown fences).
fn extract_json_object(content: &str) -> Option<&str> {
let start = content.find('{')?;
let end = content.rfind('}')?;
if end <= start {
return None;
}
Some(&content[start..=end])
}
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
let Some(arr) = value.and_then(|v| v.as_array()) else {
return Vec::new();
};
arr.iter()
.filter_map(|tag| {
if let Some(en) = tag.get("en").and_then(|v| v.as_str()) {
let local = tag
.get("local")
.and_then(|v| v.as_str())
.unwrap_or(en)
.to_string();
Some(VlmTagValue::Structured(VlmTag {
en: en.to_string(),
local,
}))
} else {
tag.as_str().map(|s| VlmTagValue::String(s.to_string()))
}
})
.collect()
}
/// Call VLM API to generate structured scene info.
/// Returns (english_description, objects, bilingual_tags).
pub async fn generate_scene_description(
image_path: &std::path::Path,
local_language: &str,
) -> Result<(String, Vec<String>, Vec<VlmTagValue>)> {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use std::time::Duration;
// Read image
let jpeg_bytes = std::fs::read(image_path)
.with_context(|| format!("Failed to read image: {:?}", image_path))?;
let base64_img = BASE64.encode(&jpeg_bytes);
// VLM API config
let vlm_url = crate::core::config::llm::VISION_URL.clone();
let vlm_model = crate::core::config::llm::VISION_MODEL.clone();
let prompt = Self::build_scene_prompt(local_language);
tracing::debug!(
"[VLM API] Calling {} with model {} (local language: {})",
vlm_url,
vlm_model,
local_language
);
let body = serde_json::json!({
"model": vlm_model,
"messages": [{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": format!("data:image/jpeg;base64,{}", base64_img)
}
}
]
}],
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(120))
.build()
.context("Failed to create HTTP client")?;
let resp = client
.post(&vlm_url)
.json(&body)
.send()
.await
.context("VLM API request failed")?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("VLM API returned {}: {}", status, body);
}
let resp_json: serde_json::Value = resp
.json()
.await
.context("Failed to parse VLM API response")?;
// Parse response
let choice = resp_json
.get("choices")
.and_then(|c| c.get(0))
.context("Invalid VLM API response structure")?;
if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") {
anyhow::bail!("VLM returned truncated response (finish_reason=length)");
}
let message = choice.get("message").context("Invalid VLM API response structure")?;
let content = match message
.get("content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => s.trim().to_string(),
None => anyhow::bail!("VLM returned empty content"),
};
tracing::debug!(
"[Scene VLM] VLM response content (first 500 chars): {}",
&content[..content.len().min(500)]
);
// Parse structured JSON; fall back to heuristic extraction if it fails.
if let Some(json_str) = Self::extract_json_object(&content) {
tracing::debug!("[Scene VLM] Extracted JSON object ({} chars)", json_str.len());
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json_str) {
tracing::debug!("[Scene VLM] Successfully parsed JSON");
let description = parsed
.get("summary")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
if let Some(description) = description {
let objects = parsed
.get("objects")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect::<Vec<_>>()
})
.unwrap_or_default();
let tags = Self::parse_tags(parsed.get("tags"));
tracing::info!(
"[Scene VLM] Parsed {} objects, {} tags from JSON",
objects.len(),
tags.len()
);
return Ok((description, objects, tags));
} else {
tracing::warn!("[Scene VLM] JSON missing 'summary' field or summary is empty");
}
} else {
tracing::warn!("[Scene VLM] Failed to parse extracted JSON: {}", json_str);
}
} else {
tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response");
}
tracing::warn!(
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
);
let objects = Self::extract_objects_from_text(&content);
let tags = Self::extract_tags_from_text(&content)
.into_iter()
.map(VlmTagValue::String)
.collect();
Ok((content, objects, tags))
}
/// Generate VLM descriptions for all scene frames
pub async fn generate_vlm_descriptions(
output_dir: &str,
file_uuid: &str,
scenes: &mut [SceneFrame],
max_workers: usize,
) -> Result<()> {
tracing::info!(
"[Scene VLM] Generating descriptions for {} scenes",
scenes.len()
);
// Get preferred language from admin config
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
.get_full_config()
.await
.search
.vlm_output_language
.clone();
crate::core::config::set_preferred_language(preferred_language.clone());
tracing::info!("[Scene VLM] Preferred language: {}", preferred_language);
// Process scenes sequentially to avoid issues
for (idx, scene) in scenes.iter_mut().enumerate() {
let frame_path = SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
// Generate English description (for indexing)
match Self::generate_scene_description(&frame_path, &preferred_language).await {
Ok((description_en, objects, tags)) => {
scene.vlm_description = Some(description_en.clone());
scene.vlm_objects = objects.clone();
scene.vlm_tags = tags.clone();
tracing::info!(
"[Scene VLM] Scene {}: Generated {} tags: {:?}",
idx,
tags.len(),
tags
);
// Generate localized description by translation if needed
if preferred_language != "en" {
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
let body = serde_json::json!({
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
"stream": false,
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
Ok(resp) => {
if resp.status().is_success() {
if let Ok(v) = resp.json::<serde_json::Value>().await {
if let Some(choice) = v["choices"].get(0) {
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
if let Some(tr) = choice["message"]["content"].as_str() {
let tr = tr.trim();
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
scene.vlm_description_localized = Some(tr.to_string());
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
scene.vlm_status = VlmStatus::Completed;
continue;
}
}
}
}
}
}
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
}
Err(e) => {
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
}
}
} else {
tracing::info!("[Scene VLM] ✅ Scene {}: EN only", idx);
}
scene.vlm_status = VlmStatus::Completed;
}
Err(e) => {
tracing::error!("[Scene VLM] ❌ Scene {}: {}", idx, e);
scene.vlm_status = VlmStatus::Failed;
}
}
}
let success_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Completed)
.count();
let fail_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Failed)
.count();
tracing::info!(
"[Scene VLM] ✅ Generated {} descriptions, {} failed",
success_count,
fail_count
);
Ok(())
}
}
+30 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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();