fix: Face processor now saves status and total_faces to face.json

This commit is contained in:
Accusys
2026-09-26 23:06:11 +08:00
parent 8a736a4103
commit 357e585399
99 changed files with 13881 additions and 1065 deletions
+20 -15
View File
@@ -2,14 +2,14 @@ use axum::{
extract::State,
http::StatusCode,
response::Json,
Router,
routing::{get, post, put},
Router,
};
use serde_json::{json, Value};
use std::sync::Arc;
use crate::core::admin_config::{VlmPrompt, PartialAdminConfig};
use crate::api::types::AppState;
use crate::core::admin_config::{PartialAdminConfig, VlmPrompt};
pub fn admin_config_routes() -> Router<AppState> {
Router::new()
@@ -17,13 +17,14 @@ pub fn admin_config_routes() -> Router<AppState> {
.route("/api/v1/admin/config", post(update_config))
.route("/api/v1/admin/config/vlm_prompts", get(get_vlm_prompts))
.route("/api/v1/admin/config/vlm_prompts/:key", get(get_vlm_prompt))
.route("/api/v1/admin/config/vlm_prompts/:key", put(update_vlm_prompt))
.route(
"/api/v1/admin/config/vlm_prompts/:key",
put(update_vlm_prompt),
)
.route("/api/v1/admin/config/reload", post(reload_config))
}
pub async fn get_config(
State(state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
pub async fn get_config(State(state): State<AppState>) -> Result<Json<Value>, StatusCode> {
let config = state.admin_config_manager.get_full_config().await;
Ok(Json(serde_json::to_value(config).unwrap_or_default()))
}
@@ -32,7 +33,11 @@ pub async fn update_config(
State(state): State<AppState>,
Json(partial): Json<PartialAdminConfig>,
) -> Result<Json<Value>, StatusCode> {
match state.admin_config_manager.update_partial_config(partial).await {
match state
.admin_config_manager
.update_partial_config(partial)
.await
{
Ok(_) => Ok(Json(json!({
"success": true,
"message": "Config updated"
@@ -41,9 +46,7 @@ pub async fn update_config(
}
}
pub async fn get_vlm_prompts(
State(state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
pub async fn get_vlm_prompts(State(state): State<AppState>) -> Result<Json<Value>, StatusCode> {
let prompts = state.admin_config_manager.get_all_vlm_prompts().await;
Ok(Json(serde_json::to_value(prompts).unwrap_or_default()))
}
@@ -63,7 +66,11 @@ pub async fn update_vlm_prompt(
axum::extract::Path(key): axum::extract::Path<String>,
Json(prompt): Json<VlmPrompt>,
) -> Result<Json<Value>, StatusCode> {
match state.admin_config_manager.update_vlm_prompt(&key, prompt).await {
match state
.admin_config_manager
.update_vlm_prompt(&key, prompt)
.await
{
Ok(_) => Ok(Json(json!({
"success": true,
"message": format!("Prompt '{}' updated", key)
@@ -72,9 +79,7 @@ pub async fn update_vlm_prompt(
}
}
pub async fn reload_config(
State(state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
pub async fn reload_config(State(state): State<AppState>) -> Result<Json<Value>, StatusCode> {
match state.admin_config_manager.reload().await {
Ok(_) => Ok(Json(json!({
"success": true,
@@ -82,4 +87,4 @@ pub async fn reload_config(
}))),
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
}
+38 -4
View File
@@ -102,10 +102,22 @@ const SYSTEM_PROMPT: &str = r#"你是 Momentry 影片分析助手。回答用戶
## 搜尋工具選擇策略(重要:根據問題類型選擇正確工具)
### 優先順序(按此順序選擇工具)
1. **semantic_search** - 語意搜尋 → **優先使用(適合大多數查詢)**
2. **smart_search** - 精確關鍵字匹配(僅在需要精確匹配時使用)
3. **trace_search** - 人物外貌、衣著、地點
4. **find_file** - 僅搜尋片名(不搜尋內容)
1. **vlm_search** - VLM 統一視覺搜尋(Scene + Trace 向量一次搜)→ **畫面/場景/人物視覺查詢優先使用,一查即涵蓋場景與人物**
2. **scene_search** - 場景功能搜尋(Scene VLM 向量優先)→ **只查畫面場景時使用**
3. **semantic_search** - 語意搜尋 → 適合文字內容(台詞、概念)
4. **smart_search** - 精確關鍵字匹配(僅在需要精確匹配時使用)
5. **trace_search** - 人物外貌、衣著、地點
6. **find_file** - 僅搜尋片名(不搜尋內容)
### vlm_search(VLM 統一視覺搜尋)- 視覺查詢優先使用
- **使用時機**:查詢畫面/場景/人物視覺內容(「廚房」、「公園」、「穿白外套的女人」、「有人在跑步」、「室內場景」),一次同時搜 Scene VLM 與 Trace VLM 向量,最全面
- **範例**:「廚房場景」、「公園裡的男人」、「穿白外套的女人在哪」、「室內場景」、「某人的外貌特徵」
- **回傳**:混合卡片(card_type: scene 或 face),scene 含 scene_index/thumbnail_url/vlm_tags,face 含 trace_id/identity_name/vlm_clothing/vlm_tags
### scene_search(場景功能搜尋)- 畫面查詢優先使用
- **使用時機**:查詢畫面/場景內容(「廚房」、「公園」、「室內裝潢」、「有人在跑步」),優先於文字搜尋
- **範例**:「廚房場景」、「公園裡的男人」、「穿白外套的女人在哪個畫面」、「室內場景」
- **回傳**:符合的場景卡片(file_uuid, scene_index, thumbnail_url, vlm_description, vlm_tags, score, timestamp)
### semantic_search(語意搜尋)- 優先使用
- **使用時機**:大多數查詢(理解意圖、概念性問題、一般話題)
@@ -200,6 +212,26 @@ fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
}),
vec!["query"],
),
function_calling::make_tool(
"vlm_search",
"VLM 視覺統一搜尋(Scene VLM 場景向量 + Trace VLM 人物向量,一次查兩邊)。用一段描述同時搜尋影片的畫面場景與人物,兩者皆為視覺向量搜尋(embedding),非文字關鍵字。適合回答「哪個畫面/場景出現OOO」、「穿OO的人」、「影片的視覺內容」。可用 file_uuid 限制搜尋範圍。回傳混合卡片(card_type: scene 或 face)。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字(會轉為 embedding,同時搜 scene + trace VLM 向量)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"scene_search",
"場景功能搜尋(Scene VLM, Qdrant 向量優先)。搜尋影片中的畫面場景,如「廚房」、「公園」、「室內」、「有人在跑步」、「穿白外套的女人在廚房」。回傳場景卡片(含縮圖 URL、時間點、VLM 描述、tags)。適合回答「哪個畫面/場景出現OOO」、「場景外觀長什麼樣」。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字(會轉為 embedding)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"trace_search",
"搜尋人物軌跡的 VLM 註記(外貌描述、衣著、標籤、地點、場景)。輸入關鍵字,回傳符合的 face trace 卡片。適合回答「穿藍色衣服的人」、「在展場出現的人」。",
@@ -353,6 +385,8 @@ async fn execute_tool(pool: &sqlx::PgPool, tool_call: &ToolCall) -> (String, Str
"tkg_node_detail" => tools::exec_tkg_node_detail(pool, &args).await,
"smart_search" => tools::exec_smart_search(pool, &args).await,
"semantic_search" => tools::exec_semantic_search(pool, &args).await,
"scene_search" => tools::exec_scene_search(pool, &args).await,
"vlm_search" => tools::exec_vlm_search(pool, &args).await,
"trace_search" => tools::exec_trace_search(pool, &args).await,
"identity_text" => tools::exec_identity_text(pool, &args).await,
"identities_search" => tools::exec_identities_search(pool, &args).await,
+88
View File
@@ -0,0 +1,88 @@
use axum::{
extract::{Query, State},
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use crate::api::types::AppState;
#[derive(Debug, Deserialize)]
pub struct UsageQuery {
pub period: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct HistoryQuery {
pub months: Option<i32>,
}
pub fn billing_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/billing/usage", get(get_usage))
.route("/api/v1/billing/history", get(get_history))
}
async fn get_usage(
State(state): State<AppState>,
Query(query): Query<UsageQuery>,
) -> Result<Json<crate::core::billing::UsageResponse>, StatusCode> {
let period_month = query
.period
.unwrap_or_else(|| format!("{}", chrono::Utc::now().format("%Y-%m")));
let period = state
.db
.get_billing_usage(None, &period_month)
.await
.map_err(|e| {
tracing::error!("[BILLING] Failed to get usage: {:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let response = if let Some(p) = period {
crate::core::billing::UsageResponse {
key_id: p.key_id,
period: p.period_month,
tokens: crate::core::billing::TokenStats {
input: p.total_input_tokens,
output: p.total_output_tokens,
total: p.total_tokens,
},
services: p.service_breakdown,
}
} else {
crate::core::billing::UsageResponse {
key_id: None,
period: period_month,
tokens: crate::core::billing::TokenStats {
input: 0,
output: 0,
total: 0,
},
services: serde_json::json!({}),
}
};
Ok(Json(response))
}
async fn get_history(
State(state): State<AppState>,
Query(query): Query<HistoryQuery>,
) -> Result<Json<crate::core::billing::HistoryResponse>, StatusCode> {
let months = query.months.unwrap_or(12);
let periods = state
.db
.get_billing_history(None, months)
.await
.map_err(|e| {
tracing::error!("[BILLING] Failed to get history: {:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(crate::core::billing::HistoryResponse { periods }))
}
+269 -542
View File
@@ -12,7 +12,7 @@ use std::collections::HashMap;
use super::types::AppState;
use crate::core::config;
use crate::core::db::schema;
use crate::core::db::{Database, PostgresDb, QdrantDb, QdrantWorkspace, RedisClient};
use crate::core::db::{CommandJob, Database, PostgresDb, QdrantDb, QdrantWorkspace, RedisClient};
use crate::core::storage::content_hash;
use crate::FileManager;
@@ -133,22 +133,28 @@ async fn lookup_file_by_name(
}
#[derive(Debug, Serialize)]
struct RegisterFileResponse {
success: bool,
file_uuid: String,
file_name: String,
file_path: String,
file_type: Option<String>,
duration: f64,
width: u32,
height: u32,
fps: f64,
total_frames: u64,
registration_time: Option<String>,
already_exists: bool,
message: String,
pub struct RegisterFileResponse {
pub success: bool,
pub file_uuid: String,
pub file_name: String,
pub file_path: String,
pub file_type: Option<String>,
pub duration: f64,
pub width: u32,
pub height: u32,
pub fps: f64,
pub total_frames: u64,
pub registration_time: Option<String>,
pub already_exists: bool,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
warning: Option<String>,
pub warning: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub command_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub command_ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -198,8 +204,9 @@ async fn resolve_filename(db: &PostgresDb, file_name: &str, content_hash: &str)
}
}
async fn register_single_file(
state: &AppState,
#[allow(clippy::too_many_arguments)]
pub(crate) async fn register_single_file(
db: &PostgresDb,
file_path: &str,
_user_id: Option<i64>,
provided_hash: Option<String>,
@@ -224,6 +231,9 @@ async fn register_single_file(
already_exists: false,
message: format!("File not found: {}", file_path),
warning: None,
command_id: None,
command_ids: None,
status: None,
};
}
@@ -237,29 +247,6 @@ async fn register_single_file(
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let db = match PostgresDb::init().await {
Ok(db) => db,
Err(e) => {
tracing::error!("[REGISTER] DB init failed: {}", e);
return RegisterFileResponse {
success: false,
file_uuid: String::new(),
file_name,
file_path: canonical_path,
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!("DB init failed: {}", e),
warning: None,
};
}
};
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string());
@@ -349,7 +336,7 @@ async fn register_single_file(
"[REGISTER] Force mode: async unregistering existing file {}",
existing_uuid
);
if let Err(e) = unregister_internal(&state, &existing_uuid).await {
if let Err(e) = unregister_internal(&db, &existing_uuid).await {
tracing::error!(
"[REGISTER] Force unregister failed for {}: {:?}",
existing_uuid,
@@ -381,6 +368,9 @@ async fn register_single_file(
already_exists: true,
message: format!("Content already registered: {}", epath),
warning: None,
command_id: None,
command_ids: None,
status: None,
};
}
return RegisterFileResponse {
@@ -398,6 +388,9 @@ async fn register_single_file(
already_exists: true,
message: "Content already registered (identical file)".to_string(),
warning: None,
command_id: None,
command_ids: None,
status: None,
};
}
}
@@ -635,6 +628,9 @@ async fn register_single_file(
already_exists: false,
message: "File registered successfully".to_string(),
warning: None,
command_id: None,
command_ids: None,
status: None,
}
}
@@ -653,9 +649,9 @@ async fn register_file(
};
let file_path = req.file_path.clone();
let pattern = req.pattern;
let pattern = req.pattern.clone();
if let Some(ref pat) = pattern {
let target_files: Vec<String> = if let Some(ref pat) = pattern {
let dir = std::path::Path::new(&file_path);
if !dir.is_dir() {
return Ok(Json(RegisterFileResponse {
@@ -676,6 +672,9 @@ async fn register_file(
file_path
),
warning: None,
command_id: None,
command_ids: None,
status: None,
}));
}
let re = regex::Regex::new(pat).map_err(|e| {
@@ -683,10 +682,7 @@ async fn register_file(
StatusCode::BAD_REQUEST
})?;
let mut registered = 0u32;
let mut failed = 0u32;
let mut skipped = 0u32;
let mut files = Vec::new();
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let entry_path = entry.path();
@@ -700,166 +696,151 @@ async fn register_file(
if !re.is_match(fname) {
continue;
}
let result = register_single_file(
&state,
&entry_path.to_string_lossy().to_string(),
req.user_id,
None,
req.force,
)
.await;
if result.success {
registered += 1;
} else if result.already_exists {
skipped += 1;
} else {
failed += 1;
}
files.push(entry_path.to_string_lossy().to_string());
}
}
return Ok(Json(RegisterFileResponse {
success: true,
file_uuid: format!("batch_{}_registered_{}_failed", registered, failed),
file_name: format!(
"{} files registered, {} skipped, {} failed",
registered, skipped, failed
),
file_path: file_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!(
"Batch register: {} registered, {} skipped, {} failed",
registered, skipped, failed
),
warning: worker_warning.clone(),
}));
}
// If force=true and file already exists, unregister first
if req.force {
let videos_table = schema::table_name("videos");
// Check by file_path first
if let Ok(Some(existing_uuid)) = sqlx::query_scalar::<_, String>(&format!(
"SELECT file_uuid FROM {} WHERE file_path = $1 LIMIT 1",
videos_table
))
.bind(&file_path)
.fetch_optional(state.db.pool())
.await
{
tracing::info!(
"[REGISTER] Force mode: unregistering existing file {}",
existing_uuid
);
if let Err(e) = unregister_internal(&state, &existing_uuid).await {
tracing::error!(
"[REGISTER] Force unregister failed for {}: {:?}",
existing_uuid,
e
);
}
if files.is_empty() {
return Ok(Json(RegisterFileResponse {
success: false,
file_uuid: String::new(),
file_name: String::new(),
file_path: file_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: "No files match pattern".to_string(),
warning: None,
command_id: None,
command_ids: None,
status: None,
}));
}
// Also check by content_hash if provided
if let Some(ref content_hash) = req.content_hash {
files
} else {
if !std::path::Path::new(&file_path).exists() {
return Ok(Json(RegisterFileResponse {
success: false,
file_uuid: String::new(),
file_name: String::new(),
file_path: file_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!("File not found: {}", file_path),
warning: None,
command_id: None,
command_ids: None,
status: None,
}));
}
vec![file_path.clone()]
};
let videos_table = schema::table_name("videos");
let mut command_ids: Vec<String> = Vec::new();
for fp in &target_files {
if req.force {
if let Ok(Some(existing_uuid)) = sqlx::query_scalar::<_, String>(&format!(
"SELECT file_uuid FROM {} WHERE content_hash = $1 LIMIT 1",
"SELECT file_uuid FROM {} WHERE file_path = $1 LIMIT 1",
videos_table
))
.bind(content_hash)
.bind(fp)
.fetch_optional(state.db.pool())
.await
{
tracing::info!(
"[REGISTER] Force mode: unregistering by content_hash {}",
"[REGISTER] Force mode: enqueuing unregister command for {}",
existing_uuid
);
if let Err(e) = unregister_internal(&state, &existing_uuid).await {
tracing::error!(
"[REGISTER] Force unregister failed for {}: {:?}",
existing_uuid,
e
);
let unregister_payload = serde_json::json!({});
if let Ok(cmd) = state
.db
.create_command(
"unregister",
None,
Some(&existing_uuid),
req.user_id,
&unregister_payload,
1,
)
.await
{
tracing::info!("[REGISTER] Unregister command {} enqueued", cmd.command_id);
}
}
}
let payload = serde_json::json!({
"content_hash": req.content_hash,
"force": req.force,
"face_settings": req.face_settings.as_ref().map(|fs| {
serde_json::json!({
"min_confidence": fs.min_confidence,
"min_size": fs.min_size
})
}),
});
match state
.db
.create_command("register", Some(fp), None, req.user_id, &payload, 0)
.await
{
Ok(cmd) => {
tracing::info!("[REGISTER] Command {} enqueued for {}", cmd.command_id, fp);
command_ids.push(cmd.command_id);
}
Err(e) => {
tracing::error!("[REGISTER] Failed to enqueue command for {}: {:?}", fp, e);
}
}
}
let mut resp =
register_single_file(&state, &file_path, req.user_id, req.content_hash, req.force).await;
let (message, command_id, command_ids_opt) = if command_ids.len() == 1 {
(
format!("Register queued (command_id={})", command_ids[0]),
Some(command_ids[0].clone()),
None,
)
} else {
(
format!("Batch register {} files queued", command_ids.len()),
None,
Some(command_ids.clone()),
)
};
if worker_warning.is_some() {
resp.warning = worker_warning;
}
if resp.success
&& !resp.already_exists
&& resp.file_type.as_deref() == Some("video")
&& crate::core::config::get_auto_pipeline_enabled()
{
let auto_uuid = resp.file_uuid.clone();
let auto_state = state.clone();
// Convert face_settings to serde_json::Value for create_monitor_job
let face_settings_json = req.face_settings.as_ref().map(|fs| {
serde_json::json!({
"min_confidence": fs.min_confidence.unwrap_or(config::FACE_MIN_CONFIDENCE_DEFAULT),
"min_size": fs.min_size.unwrap_or(config::FACE_MIN_SIZE_DEFAULT)
})
});
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
let video_path: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_path FROM {} WHERE file_uuid = $1",
schema::table_name("videos")
))
.bind(&auto_uuid)
.fetch_optional(auto_state.db.pool())
.await
.ok()
.flatten();
if let Some(ref vp) = video_path {
if let Ok(job) = auto_state
.db
.create_monitor_job(&auto_uuid, Some(vp), face_settings_json.as_ref())
.await
{
tracing::info!("[AUTO-PIPELINE] Job {} created for {}", job.id, auto_uuid);
let all_procs: Vec<&str> =
vec!["cut", "asr", "asrx", "ocr", "face", "pose", "appearance"];
let total = sqlx::query_scalar::<_, i64>(&format!(
"SELECT COALESCE(total_frames, 0) FROM {} WHERE file_uuid = $1",
schema::table_name("videos")
))
.bind(&auto_uuid)
.fetch_one(auto_state.db.pool())
.await
.unwrap_or(0);
let _ = auto_state
.db
.init_processing_status(&auto_uuid, all_procs, total as u64)
.await;
let _ = sqlx::query(&format!(
"UPDATE {} SET status = 'scanning' WHERE file_uuid = $1",
schema::table_name("videos")
))
.bind(&auto_uuid)
.execute(auto_state.db.pool())
.await;
tracing::info!("[AUTO-PIPELINE] Pipeline triggered for {}", auto_uuid);
}
}
});
}
Ok(Json(resp))
Ok(Json(RegisterFileResponse {
success: true,
file_uuid: String::new(),
file_name: String::new(),
file_path: file_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message,
warning: worker_warning,
command_id,
command_ids: command_ids_opt,
status: Some("queued".to_string()),
}))
}
async fn probe_by_uuid(
@@ -1040,6 +1021,8 @@ struct UnregisterResponse {
message: String,
file_uuid: String,
job_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
command_id: Option<String>,
deleted_face_detections: u64,
deleted_processor_results: u64,
deleted_chunks: u64,
@@ -1087,7 +1070,8 @@ fn delete_output_files(uuid: &str) -> u64 {
let is_pipeline_log = name.starts_with("pipeline_")
&& name.contains(uuid)
&& name.ends_with(".log");
if is_uuid_file || is_pipeline_log {
let is_scenes_json = name == &format!("{}.scenes.json", uuid);
if is_uuid_file || is_pipeline_log || is_scenes_json {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
tracing::info!("[UNREGISTER] Deleted output file: {}", name);
@@ -1141,352 +1125,57 @@ async fn unregister(
let reason = req.reason.as_deref().unwrap_or("unspecified");
tracing::info!(
"[UNREGISTER] Trigger: source={}, reason={}. Unregistering file: {} (async_mode={})",
source,
reason,
"[UNREGISTER] Enqueuing unregister command for {} (source={}, reason={})",
uuid,
req.async_mode
source,
reason
);
// Async mode: spawn background task and return immediately
if req.async_mode {
let job_id = format!("unregister_{}", uuid);
let state_clone = state.clone();
let uuid_clone = uuid.clone();
let source_clone = source.to_string();
let reason_clone = reason.to_string();
tokio::spawn(async move {
tracing::info!(
"[ASYNC_UNREGISTER] Starting background unregister for {} (source={}, reason={})",
uuid_clone,
source_clone,
reason_clone
);
match unregister_internal(&state_clone, &uuid_clone).await {
Ok(()) => {
tracing::info!("[ASYNC_UNREGISTER] Completed for {}", uuid_clone);
}
Err(e) => {
tracing::error!(
"[ASYNC_UNREGISTER] FAILED for {} (source={}, reason={}): {:?}",
uuid_clone,
source_clone,
reason_clone,
e
);
}
}
});
let payload = serde_json::json!({
"trigger_source": source,
"reason": reason,
});
return Ok(Json(UnregisterResponse {
success: true,
message: format!("Unregister started in background for {}", uuid),
file_uuid: uuid,
job_id: Some(job_id),
deleted_face_detections: 0,
deleted_processor_results: 0,
deleted_chunks: 0,
deleted_tkg_nodes: 0,
deleted_qdrant_vectors: None,
deleted_qdrant_workspace: None,
deleted_redis_keys: None,
deleted_output_files: 0,
deleted_file_identities: 0,
deleted_speaker_detections: 0,
deleted_face_clusters: 0,
deleted_face_recognition_results: 0,
deleted_characters: 0,
deleted_chunks_rule1: 0,
deleted_processor_alerts: 0,
deleted_processor_versions: 0,
}));
}
// Synchronous mode (existing code follows)
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
let chunks_table = schema::table_name("chunk");
let parent_chunks_table = schema::table_name("parent_chunks");
let pre_chunks_table = schema::table_name("pre_chunks");
let tkg_nodes_table = schema::table_name("tkg_nodes");
let cuts_table = schema::table_name("cuts");
let strangers_table = schema::table_name("strangers");
let chunk_vectors_table = schema::table_name("chunk_vectors");
let monitor_jobs_table = schema::table_name("monitor_jobs");
let frames_table = schema::table_name("frames");
let file_identities_table = schema::table_name("file_identities");
let speaker_detections_table = schema::table_name("speaker_detections");
let face_clusters_table = schema::table_name("face_clusters");
let face_recognition_results_table = schema::table_name("face_recognition_results");
let characters_table = schema::table_name("characters");
let chunks_rule1_table = schema::table_name("chunks_rule1");
let processor_alerts_table = schema::table_name("processor_alerts");
let trace_profiles_table = schema::table_name("trace_profiles");
let mut tx = state.db.pool().begin().await.map_err(|e| {
tracing::error!("[unregister] Failed to start transaction: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
macro_rules! delete_safe {
($table:expr, $where:expr, $bind:expr, $label:expr) => {{
sqlx::query(&format!("DELETE FROM {} WHERE {}", $table, $where))
.bind($bind)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed to delete {}: {}", $label, e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.rows_affected() as i64
}};
}
let deleted_faces = 0i64; // Deprecated: face_detections table removed
let deleted_processors = delete_safe!(processor_table, "file_uuid = $1", &uuid, "processors");
let deleted_parent_chunks =
delete_safe!(parent_chunks_table, "uuid = $1", &uuid, "parent chunks");
let deleted_chunks = delete_safe!(chunks_table, "file_uuid = $1", &uuid, "chunks");
let deleted_pre_chunks = delete_safe!(pre_chunks_table, "file_uuid = $1", &uuid, "pre_chunks");
let deleted_tkg_nodes = delete_safe!(tkg_nodes_table, "file_uuid = $1", &uuid, "TKG nodes");
let deleted_cuts = delete_safe!(cuts_table, "file_uuid = $1", &uuid, "cuts");
let deleted_strangers = delete_safe!(strangers_table, "file_uuid = $1", &uuid, "strangers");
let deleted_chunk_vectors =
delete_safe!(chunk_vectors_table, "uuid = $1", &uuid, "chunk vectors");
let deleted_monitor_jobs = delete_safe!(monitor_jobs_table, "uuid = $1", &uuid, "monitor jobs");
let deleted_frames: i64 = sqlx::query(&format!(
"DELETE FROM {} WHERE file_id = (SELECT id FROM {} WHERE file_uuid = $1)",
frames_table, videos_table
))
.bind(&uuid)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed to delete frames: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.rows_affected() as i64;
let deleted_file_identities = delete_safe!(
file_identities_table,
"file_uuid = $1",
&uuid,
"file identities"
);
let deleted_speaker_detections = delete_safe!(
speaker_detections_table,
"file_uuid = $1",
&uuid,
"speaker detections"
);
let deleted_face_clusters = delete_safe!(
face_clusters_table,
"file_uuid = $1",
&uuid,
"face clusters"
);
let deleted_face_recognition = delete_safe!(
face_recognition_results_table,
"file_uuid = $1",
&uuid,
"face recognition results"
);
let deleted_characters = delete_safe!(characters_table, "file_uuid = $1", &uuid, "characters");
let deleted_chunks_rule1 = delete_safe!(chunks_rule1_table, "uuid = $1", &uuid, "chunks rule1");
let deleted_processor_alerts = delete_safe!(
processor_alerts_table,
"file_uuid = $1",
&uuid,
"processor alerts"
);
let deleted_processor_versions = delete_safe!(
"processor_versions",
"file_uuid = $1",
&uuid,
"processor versions"
);
let deleted_trace_profiles = delete_safe!(
trace_profiles_table,
"file_uuid = $1",
&uuid,
"trace profiles"
);
sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&uuid)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tx.commit().await.map_err(|e| {
tracing::error!(
"[UNREGISTER] FAILED to commit transaction for {} (source={}, reason={}): {}",
uuid,
source,
reason,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tracing::info!(
"[UNREGISTER] Deleted: {} faces, {} processors, {} parent_chunks, {} chunks, {} pre_chunks, {} tkg_nodes, {} cuts, {} strangers, {} chunk_vectors, {} monitor_jobs, {} frames, {} file_identities, {} speaker_detections, {} face_clusters, {} face_recognition_results, {} characters, {} chunks_rule1, {} processor_alerts, {} processor_versions, {} trace_profiles",
deleted_faces, deleted_processors, deleted_parent_chunks, deleted_chunks,
deleted_pre_chunks, deleted_tkg_nodes, deleted_cuts, deleted_strangers,
deleted_chunk_vectors, deleted_monitor_jobs, deleted_frames,
deleted_file_identities, deleted_speaker_detections, deleted_face_clusters,
deleted_face_recognition, deleted_characters, deleted_chunks_rule1,
deleted_processor_alerts, deleted_processor_versions, deleted_trace_profiles
);
let deleted_output_files = delete_output_files(&uuid);
let deleted_qdrant_vectors = {
let qdrant = QdrantDb::new();
let mut total = 0u64;
if qdrant.delete_by_uuid(&uuid).await.is_ok() {
tracing::info!("[UNREGISTER] Deleted Qdrant vectors from main collection");
total += 1;
} else {
let cmd = state
.db
.create_command("unregister", None, Some(&uuid), None, &payload, 1)
.await
.map_err(|e| {
tracing::error!(
"[UNREGISTER] FAILED to delete Qdrant vectors from main collection for {} (source={})",
uuid, source
"[UNREGISTER] Failed to enqueue command for {}: {:?}",
uuid,
e
);
}
let additional_collections = [
"_faces", // Python store_traced_faces.py
&format!("{}_voice", uuid), // Per-file voice embeddings
];
for coll in &additional_collections {
if QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
coll,
&uuid,
)
.await
.is_ok()
{
tracing::info!(
"[UNREGISTER] Deleted Qdrant vectors from collection: {}",
coll
);
total += 1;
} else {
tracing::debug!("[UNREGISTER] No vectors or collection not found: {}", coll);
}
}
Some(total)
};
let deleted_redis_keys = {
match RedisClient::new() {
Ok(redis) => {
let mut deleted = 0;
// Delete worker job keys
if redis.delete_worker_job(&uuid).await.is_ok() {
tracing::info!("[UNREGISTER] Deleted Redis worker job keys for {}", uuid);
deleted += 1;
}
// Delete PipelineProgress keys (all variants)
let progress_patterns = [
format!(
"{}progress:{}:pipeline",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
),
format!(
"{}progress:{}:agent",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
),
format!(
"{}progress:{}:tkg",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
),
];
if let Ok(mut conn) = redis.get_conn().await {
for key in &progress_patterns {
let _: Option<String> =
redis::cmd("DEL").arg(key).query_async(&mut conn).await.ok();
}
tracing::info!(
"[UNREGISTER] Deleted Redis PipelineProgress keys for {}",
uuid
);
deleted += progress_patterns.len() as u64;
}
Some(deleted)
}
Err(e) => {
tracing::error!(
"[UNREGISTER] FAILED to create Redis client for {} (source={}): {}",
uuid,
source,
e
);
None
}
}
};
let deleted_qdrant_workspace = {
let workspace = QdrantWorkspace::new();
match workspace.delete_by_file_uuid(&uuid).await {
Ok(_) => {
tracing::info!("[UNREGISTER] Deleted Qdrant workspace vectors for {}", uuid);
Some(1)
}
Err(e) => {
tracing::warn!(
"[UNREGISTER] Failed to delete Qdrant workspace vectors: {}",
e
);
None
}
}
};
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(UnregisterResponse {
success: true,
message: format!("File {} unregistered successfully.", uuid),
message: format!("Unregister queued (command_id={})", cmd.command_id),
file_uuid: uuid,
job_id: None,
deleted_face_detections: deleted_faces as u64,
deleted_processor_results: deleted_processors as u64,
deleted_chunks: (deleted_chunks + deleted_parent_chunks + deleted_pre_chunks) as u64,
deleted_tkg_nodes: deleted_tkg_nodes as u64,
deleted_qdrant_vectors,
deleted_qdrant_workspace,
deleted_redis_keys,
deleted_output_files,
deleted_file_identities: deleted_file_identities as u64,
deleted_speaker_detections: deleted_speaker_detections as u64,
deleted_face_clusters: deleted_face_clusters as u64,
deleted_face_recognition_results: deleted_face_recognition as u64,
deleted_characters: deleted_characters as u64,
deleted_chunks_rule1: deleted_chunks_rule1 as u64,
deleted_processor_alerts: deleted_processor_alerts as u64,
deleted_processor_versions: deleted_processor_versions as u64,
command_id: Some(cmd.command_id),
deleted_face_detections: 0,
deleted_processor_results: 0,
deleted_chunks: 0,
deleted_tkg_nodes: 0,
deleted_qdrant_vectors: None,
deleted_qdrant_workspace: None,
deleted_redis_keys: None,
deleted_output_files: 0,
deleted_file_identities: 0,
deleted_speaker_detections: 0,
deleted_face_clusters: 0,
deleted_face_recognition_results: 0,
deleted_characters: 0,
deleted_chunks_rule1: 0,
deleted_processor_alerts: 0,
deleted_processor_versions: 0,
}))
}
/// Internal unregister function - can be called from both API and register
async fn unregister_internal(state: &AppState, uuid: &str) -> Result<(), StatusCode> {
pub(crate) async fn unregister_internal(db: &PostgresDb, uuid: &str) -> Result<(), StatusCode> {
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
let chunks_table = schema::table_name("chunk");
@@ -1507,7 +1196,7 @@ async fn unregister_internal(state: &AppState, uuid: &str) -> Result<(), StatusC
let processor_alerts_table = schema::table_name("processor_alerts");
let trace_profiles_table = schema::table_name("trace_profiles");
let mut tx = state.db.pool().begin().await.map_err(|e| {
let mut tx = db.pool().begin().await.map_err(|e| {
tracing::error!("[unregister] Failed to start transaction: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
@@ -1614,32 +1303,54 @@ async fn unregister_internal(state: &AppState, uuid: &str) -> Result<(), StatusC
// Delete output files
delete_output_files(uuid);
// Delete Qdrant vectors
// Delete Qdrant vectors — iterate all collections that carry per-file points.
// The main collection holds text/trace chunks (incl. vlm_summary); `_faces` (face
// embeddings, trace_id/bbox), `_scenes` (Scene VLM), `_vlm` (legacy trace VLM),
// `_seeds` (TMDb identity seeds), `{schema}_face_embeddings` (legacy 512D face
// storage) and the speaker collection must be cleaned too or orphan vectors are left
// behind (previously `_scenes` was missed, causing orphan residue like a0ae64...).
let qdrant = QdrantDb::new();
let _ = qdrant.delete_by_uuid(uuid).await;
let _ = QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
"_faces",
uuid,
)
.await;
// Delete from speaker collection
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string());
let speaker_collection = if schema == "public" {
"momentry_public_speaker"
"momentry_public_speaker".to_string()
} else {
&format!("momentry_{}_speaker", schema)
format!("momentry_{}_speaker", schema)
};
let _ = QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
let face_embeddings_collection = format!("{}_face_embeddings", schema);
let collections: Vec<String> = vec![
qdrant.collection_name.clone(),
"_faces".to_string(),
"_scenes".to_string(),
"_vlm".to_string(),
"_seeds".to_string(),
face_embeddings_collection,
speaker_collection,
uuid,
)
.await;
];
for collection in collections {
match QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
&collection,
uuid,
)
.await
{
Ok(_) => tracing::info!(
"[unregister] Deleted {} vectors from Qdrant `{}`",
uuid,
collection
),
Err(e) => tracing::warn!(
"[unregister] Failed to delete {} from Qdrant `{}`: {:?}",
uuid,
collection,
e
),
}
}
// Delete Qdrant workspace
let workspace = QdrantWorkspace::new();
@@ -1756,11 +1467,27 @@ async fn update_file_metadata(
}
}
async fn get_command_status(
Path(command_id): Path<String>,
State(state): State<AppState>,
) -> Result<Json<CommandJob>, StatusCode> {
let job = state.db.get_command_by_id(&command_id).await.map_err(|e| {
tracing::error!("Failed to fetch command {}: {:?}", command_id, e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
match job {
Some(j) => Ok(Json(j)),
None => Err(StatusCode::NOT_FOUND),
}
}
pub fn file_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/files/register", post(register_file))
.route("/api/v1/files/lookup", get(lookup_file_by_name))
.route("/api/v1/unregister", post(unregister))
.route("/api/v1/command/:command_id", get(get_command_status))
.route("/api/v1/file/:file_uuid/probe", get(probe_by_uuid))
.route(
"/api/v1/file/:file_uuid/metadata",
+20 -18
View File
@@ -9,8 +9,8 @@ use axum::{
use serde::{Deserialize, Serialize};
use std::process::Command;
use crate::core::db::{Database, PostgresDb};
use crate::api::types::AppState;
use crate::core::db::{Database, PostgresDb};
#[derive(Debug, Deserialize)]
pub struct CreateIdentityRequest {
@@ -450,22 +450,24 @@ async fn list_unassigned_traces(
let page = query.page.unwrap_or(1);
let page_size = std::cmp::min(query.page_size.unwrap_or(20), 100);
let offset = (page - 1) * page_size;
// Read face_filter settings if file_uuid is provided
let settings: Option<crate::core::file_profile::FaceFilterSettings> = if let Some(ref file_uuid) = query.file_uuid {
let v_table = crate::core::db::schema::table_name("videos");
sqlx::query_scalar(&format!(
"SELECT face_filter FROM {} WHERE file_uuid = $1", v_table
))
.bind(file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten()
.and_then(|v| serde_json::from_value(v).ok())
} else {
None
};
let settings: Option<crate::core::file_profile::FaceFilterSettings> =
if let Some(ref file_uuid) = query.file_uuid {
let v_table = crate::core::db::schema::table_name("videos");
sqlx::query_scalar(&format!(
"SELECT face_filter FROM {} WHERE file_uuid = $1",
v_table
))
.bind(file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten()
.and_then(|v| serde_json::from_value(v).ok())
} else {
None
};
// Query Qdrant _faces for unbound traces (identity_id IS NULL, trace_id >= 0)
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
@@ -549,7 +551,7 @@ async fn list_unassigned_traces(
// Sort by frame_count DESC, paginate
let mut sorted_traces: Vec<((String, i32), TraceAgg)> = trace_map.into_iter().collect();
sorted_traces.sort_by(|a, b| b.1.frame_count.cmp(&a.1.frame_count));
// Filter single frame traces if disabled
let settings = settings.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
let sorted_traces: Vec<_> = sorted_traces
@@ -566,7 +568,7 @@ async fn list_unassigned_traces(
true
})
.collect();
let paginated: Vec<_> = sorted_traces
.into_iter()
.skip(offset)
+57
View File
@@ -87,6 +87,10 @@ pub fn bbox_routes() -> Router<crate::api::types::AppState> {
"/api/v1/file/:file_uuid/chunk/:chunk_id/thumbnail",
get(chunk_thumbnail),
)
.route(
"/api/v1/file/:file_uuid/scenes/:filename",
get(scene_thumbnail),
)
.route("/api/v1/file/:file_uuid/clip", get(video_clip))
}
@@ -955,6 +959,59 @@ async fn trace_thumbnail(
.unwrap())
}
/// Serve a scene frame image (`scene_*.jpg`) directly from the output dir.
/// Path mirrors `thumbnail_url` produced by the VLM scene search API.
/// e.g. /api/v1/file/{file_uuid}/scenes/scene_000.jpg
async fn scene_thumbnail(
State(_state): State<crate::api::types::AppState>,
Path((file_uuid, filename)): Path<(String, String)>,
) -> Result<impl IntoResponse, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
// Security: only allow scene_*.jpg filenames (no path traversal)
let safe_name = filename
.strip_prefix("scene_")
.and_then(|rest| rest.strip_suffix(".jpg"))
.filter(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()))
.map(|_| filename.clone())
.ok_or(StatusCode::NOT_FOUND)?;
let file_path = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
.join("scenes")
.join(&safe_name);
if !file_path.exists() {
return Err(StatusCode::NOT_FOUND);
}
let bytes = tokio::fs::read(&file_path).await.map_err(|e| {
tracing::warn!(
"[scene-thumb] Failed to read {}: {}",
file_path.display(),
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| {
tracing::warn!("[scene-thumb] JPEG validation failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
// Generate ETag from file content (first 16 chars of sha256)
use sha2::{Digest, Sha256};
let etag = format!("\"{}\"", hex::encode(&Sha256::digest(&bytes)[..8]));
Ok(Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "image/jpeg")
.header(header::CACHE_CONTROL, "no-cache, must-revalidate")
.header(header::ETAG, etag)
.body(Body::from(bytes))
.unwrap())
}
async fn face_thumbnail(
State(state): State<crate::api::types::AppState>,
Path(file_uuid): Path<String>,
+9 -1
View File
@@ -8,6 +8,7 @@ use sha2::{Digest, Sha256};
use std::sync::Arc;
use crate::core::auth::jwt;
use crate::core::billing::set_request_context;
use crate::core::db::postgres_db::ApiKeyRecord;
use crate::core::db::PostgresDb;
@@ -182,6 +183,8 @@ pub async fn unified_auth(
jwt_exp: exp,
};
request.extensions_mut().insert(auth);
let request_id = uuid::Uuid::new_v4().to_string().replace('-', "");
set_request_context(request_id, Some(claims.sub.clone()));
return next.run(request).await;
}
}
@@ -212,10 +215,12 @@ pub async fn unified_auth(
user_id: 0,
role: "user".to_string(),
source: AuthSource::ApiKey,
key_id: api_key,
key_id: api_key.clone(),
jwt_jti: None,
jwt_exp: None,
});
let request_id = uuid::Uuid::new_v4().to_string().replace('-', "");
set_request_context(request_id, Some(api_key));
return next.run(request).await;
}
@@ -256,6 +261,9 @@ pub async fn unified_auth(
tracing::warn!("[AUTH] Failed to update key usage: {}", e);
}
let request_id = uuid::Uuid::new_v4().to_string().replace('-', "");
set_request_context(request_id, Some(record.key_id.clone()));
request.extensions_mut().insert(auth);
next.run(request).await
}
+2
View File
@@ -2,6 +2,7 @@ pub mod admin_config;
pub mod agent_api;
pub mod agent_search;
pub mod auth;
pub mod billing;
pub mod checkin_api;
pub mod cluster_agent;
pub mod docs;
@@ -24,5 +25,6 @@ pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
pub mod universal_search;
pub mod vlm_search;
pub use server::start_server;
+11 -7
View File
@@ -30,9 +30,8 @@ fn delete_output_files_for_uuid(uuid: &str, output_dir: &str) -> u64 {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let is_uuid_file = name.starts_with(uuid) && !path.is_dir();
let is_pipeline_log = name.starts_with("pipeline_")
&& name.contains(uuid)
&& name.ends_with(".log");
let is_pipeline_log =
name.starts_with("pipeline_") && name.contains(uuid) && name.ends_with(".log");
if is_uuid_file || is_pipeline_log {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
@@ -907,6 +906,9 @@ async fn verify_file_handler(
Json(report)
}
/// [DISABLED] FS VLM Summary removed from pipeline (2026-09-22)
/// Scene VLM (moment chunk VLM) remains active
/*
/// Manually trigger VLM summary generation for an existing file.
/// Non-blocking: returns immediately, VLM runs in background.
async fn trigger_vlm_summary(
@@ -975,6 +977,7 @@ async fn trigger_vlm_summary(
"pending": pending,
}))
}
*/
pub fn processing_routes() -> Router<AppState> {
Router::new()
@@ -1001,8 +1004,9 @@ pub fn processing_routes() -> Router<AppState> {
get(get_processor_counts),
)
.route("/api/v1/file/:file_uuid/verify", get(verify_file_handler))
.route(
"/api/v1/file/:file_uuid/vlm-summary",
post(trigger_vlm_summary),
)
// [DISABLED] FS VLM Summary API removed (2026-09-22)
// .route(
// "/api/v1/file/:file_uuid/vlm-summary",
// post(trigger_vlm_summary),
// )
}
+17 -14
View File
@@ -1219,7 +1219,7 @@ pub async fn get_face_groups_handler(
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
let v_table = schema::table_name("videos");
// Read face_filter settings
let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!(
"SELECT face_filter FROM {v_table} WHERE file_uuid = $1"
@@ -1257,14 +1257,19 @@ pub async fn get_face_groups_handler(
for (name, trace_id, frame_count) in rows {
// Filter single frame traces if disabled
if frame_count == Some(1) {
if !settings.single_frame_trace_group_enabled && !name.starts_with("Face Trace ") && !name.starts_with("Trace ") {
if !settings.single_frame_trace_group_enabled
&& !name.starts_with("Face Trace ")
&& !name.starts_with("Trace ")
{
continue;
}
if !settings.single_frame_trace_unassigned_enabled && (name.starts_with("Face Trace ") || name.starts_with("Trace ")) {
if !settings.single_frame_trace_unassigned_enabled
&& (name.starts_with("Face Trace ") || name.starts_with("Trace "))
{
continue;
}
}
if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
unassigned.push(trace_id);
} else {
@@ -1276,10 +1281,9 @@ pub async fn get_face_groups_handler(
let mut filtered_groups: HashMap<String, Vec<i32>> = HashMap::new();
for (name, trace_ids) in groups {
let is_auto_name = name.starts_with("Person_");
let should_filter = settings.single_trace_group_filter_enabled
&& trace_ids.len() == 1
&& is_auto_name;
let should_filter =
settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name;
if !should_filter {
filtered_groups.insert(name, trace_ids);
}
@@ -1369,7 +1373,7 @@ pub async fn get_cluster_results_handler(
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
let v_table = schema::table_name("videos");
// Read face_filter settings
let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!(
"SELECT face_filter FROM {v_table} WHERE file_uuid = $1"
@@ -1408,7 +1412,7 @@ pub async fn get_cluster_results_handler(
if frame_count == Some(1) && !settings.single_frame_trace_group_enabled {
continue;
}
if !(name.starts_with("Face Trace ") || name.starts_with("Trace ")) {
groups.entry(name).or_default().push(trace_id);
}
@@ -1419,10 +1423,9 @@ pub async fn get_cluster_results_handler(
let mut filtered_groups: HashMap<String, Vec<i32>> = HashMap::new();
for (name, trace_ids) in groups {
let is_auto_name = name.starts_with("Person_");
let should_filter = settings.single_trace_group_filter_enabled
&& trace_ids.len() == 1
&& is_auto_name;
let should_filter =
settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name;
if !should_filter {
filtered_groups.insert(name, trace_ids);
}
+113 -20
View File
@@ -18,6 +18,10 @@ struct FileStatsResponse {
file_uuid: String,
file_name: Option<String>,
status: Option<String>,
// Timestamps
created_at: Option<String>,
updated_at: Option<String>,
processing_completed_at: Option<String>,
// Processor status
processors: Vec<ProcessorStatus>,
// PostgreSQL counts
@@ -30,6 +34,8 @@ struct FileStatsResponse {
face_dedup: FaceDedupStats,
// VLM Summary progress
vlm_summary: VlmSummaryStats,
// Scene VLM stats
scene_vlm: SceneVlmStats,
// On-disk face artifact counts (vs expected)
face_artifacts: FaceArtifactsCounts,
}
@@ -95,6 +101,14 @@ struct VlmSummaryStats {
done: i64,
}
#[derive(Debug, Serialize, Default)]
struct SceneVlmStats {
total_scenes: i64,
status: String,
vlm_done: i64,
vlm_total: i64,
}
#[derive(Debug, Serialize, Deserialize)]
struct ScannedFileInfo {
file_name: String,
@@ -106,6 +120,7 @@ struct ScannedFileInfo {
file_uuid: Option<String>,
status: Option<String>,
registration_time: Option<String>,
status_updated_at: Option<String>,
job_id: Option<i32>,
}
@@ -140,7 +155,7 @@ fn scan_directory_recursive(
allowed_extensions: &[&str],
registered_paths: &std::collections::HashMap<
String,
(String, String, Option<String>, Option<i32>),
(String, String, Option<String>, Option<String>, Option<i32>),
>,
files: &mut Vec<ScannedFileInfo>,
) {
@@ -181,7 +196,9 @@ fn scan_directory_recursive(
.unwrap_or_default();
match registered_paths.get(&abs_path) {
Some((uuid, status, reg_time, jid)) if status != "unregistered" => {
Some((uuid, status, reg_time, updated_at, jid))
if status != "unregistered" =>
{
files.push(ScannedFileInfo {
file_name,
relative_path: rel_path,
@@ -192,6 +209,7 @@ fn scan_directory_recursive(
file_uuid: Some(uuid.clone()),
status: Some(status.clone()),
registration_time: reg_time.clone(),
status_updated_at: updated_at.clone(),
job_id: *jid,
});
}
@@ -206,6 +224,7 @@ fn scan_directory_recursive(
file_uuid: None,
status: Some("unregistered".to_string()),
registration_time: None,
status_updated_at: None,
job_id: None,
});
}
@@ -232,27 +251,37 @@ async fn scan_files(
let table = schema::table_name("videos");
let mj_table = schema::table_name("monitor_jobs");
let registered_db: Vec<(String, String, String, String, Option<String>, Option<i32>)> =
sqlx::query_as(&format!(
"SELECT v.file_path, v.file_name, v.file_uuid, v.status, v.registration_time::text, \
let registered_db: Vec<(
String,
String,
String,
String,
Option<String>,
Option<String>,
Option<i32>,
)> = sqlx::query_as(&format!(
"SELECT v.file_path, v.file_name, v.file_uuid, v.status, v.registration_time::text, \
v.updated_at::text, \
latest_job.id as job_id \
FROM {} v \
LEFT JOIN LATERAL ( \
SELECT id FROM {} WHERE uuid = v.file_uuid ORDER BY id DESC LIMIT 1 \
) latest_job ON true \
ORDER BY v.id",
table, mj_table
))
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
table, mj_table
))
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let registered_paths: std::collections::HashMap<
String,
(String, String, Option<String>, Option<i32>),
(String, String, Option<String>, Option<String>, Option<i32>),
> = registered_db
.into_iter()
.map(|(path, _name, uuid, status, reg_time, jid)| (path, (uuid, status, reg_time, jid)))
.map(|(path, _name, uuid, status, reg_time, updated_at, jid)| {
(path, (uuid, status, reg_time, updated_at, jid))
})
.collect();
let mut result_files = Vec::new();
@@ -785,8 +814,8 @@ async fn get_file_stats(
// 1. Get file info from PostgreSQL
let videos_table = schema::table_name("videos");
let file_info: Option<(String, String, String)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_name, status FROM {} WHERE file_uuid = $1",
let file_info: Option<(String, String, String, Option<String>, Option<String>)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_name, status, created_at::text, updated_at::text FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
@@ -794,9 +823,15 @@ async fn get_file_stats(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (file_uuid_str, file_name, status) = file_info
.map(|(uuid, name, s)| (uuid, Some(name), Some(s)))
.unwrap_or_else(|| (file_uuid.clone(), None, None));
let (file_uuid_str, file_name, status, created_at, updated_at) =
file_info.unwrap_or_else(|| (file_uuid.clone(), String::new(), String::new(), None, None));
// Determine processing_completed_at based on status
let processing_completed_at = if status == "completed" {
updated_at.clone()
} else {
None
};
// 2. Get processor status from processing_status JSONB
let processing_status: serde_json::Value = sqlx::query_scalar(&format!(
@@ -1101,16 +1136,70 @@ async fn get_file_stats(
done: vlm_done,
};
// 9. Scene VLM stats
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
let scene_vlm = if std::path::Path::new(&scenes_path).exists() {
if let Ok(scenes_json) = std::fs::read_to_string(&scenes_path) {
if let Ok(scenes_data) = serde_json::from_str::<serde_json::Value>(&scenes_json) {
let total_scenes = scenes_data
.get("total_scenes")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let status = scenes_data
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("pending")
.to_string();
let scenes_array = scenes_data
.get("scenes")
.and_then(|v| v.as_array())
.map(|arr| arr.len() as i64)
.unwrap_or(0);
let vlm_done = scenes_data
.get("scenes")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter(|s| {
let status = s.get("vlm_status").and_then(|v| v.as_str());
status == Some("completed") || status == Some("done")
})
.count() as i64
})
.unwrap_or(0);
SceneVlmStats {
total_scenes: total_scenes.max(scenes_array),
status,
vlm_done,
vlm_total: total_scenes.max(scenes_array),
}
} else {
SceneVlmStats::default()
}
} else {
SceneVlmStats::default()
}
} else {
SceneVlmStats::default()
};
Ok(Json(FileStatsResponse {
file_uuid: file_uuid_str,
file_name,
status,
file_name: Some(file_name).filter(|s| !s.is_empty()),
status: Some(status).filter(|s| !s.is_empty()),
created_at,
updated_at,
processing_completed_at,
processors,
postgres,
qdrant: qdrant_stats,
tkg,
face_dedup,
vlm_summary,
scene_vlm,
face_artifacts,
}))
}
@@ -1326,7 +1415,11 @@ async fn get_pipeline_progress_handler(
} else {
0.0
};
let status = if vlm_done == vlm_total { "completed" } else { "running" };
let status = if vlm_done == vlm_total {
"completed"
} else {
"running"
};
pp.update_stage(
"vlm_summary",
vlm_progress,
+4 -1
View File
@@ -196,7 +196,10 @@ async fn enrich_vlm_from_pg(
similarity: Some(qdrant_score as f64),
file_name: None,
serve_url: None,
thumbnail_url: Some(format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, trace_id)),
thumbnail_url: Some(format!(
"/api/v1/file/{}/trace/{}/thumbnail",
file_uuid, trace_id
)),
source_type: Some("vlm".to_string()),
})
}
+6 -2
View File
@@ -13,6 +13,7 @@ use super::admin_config;
use super::agent_api;
use super::agent_search;
use super::auth;
use super::billing;
use super::checkin_api;
use super::cluster_agent;
use super::docs;
@@ -35,6 +36,7 @@ use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::universal_search::universal_search_routes;
use super::vlm_search;
pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
health::init_server_state(host, port);
@@ -103,9 +105,9 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
// Initialize AdminConfigManager
let admin_config_manager = std::sync::Arc::new(
crate::core::admin_config::AdminConfigManager::new(
&crate::core::admin_config::get_default_config_path()
&crate::core::admin_config::get_default_config_path(),
)
.expect("Failed to initialize AdminConfigManager")
.expect("Failed to initialize AdminConfigManager"),
);
// Ensure trash collection exists for trace hard-delete undo
@@ -147,6 +149,8 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
.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())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
+665
View File
@@ -0,0 +1,665 @@
use axum::{extract::State, http::StatusCode, Json};
use serde::{Deserialize, Serialize};
use crate::api::types::AppState;
use crate::core::admin_config::SearchConfig;
#[derive(Debug, Deserialize)]
pub struct SceneSearchRequest {
pub query: String,
pub file_uuid: Option<String>,
pub filters: Option<SceneSearchFilters>,
#[serde(default = "default_page")]
pub page: usize,
#[serde(default = "default_page_size")]
pub page_size: usize,
#[serde(default = "default_min_score")]
pub min_score: f64,
}
fn default_page() -> usize {
1
}
fn default_page_size() -> usize {
20
}
fn default_min_score() -> f64 {
0.0
}
#[derive(Debug, Deserialize)]
pub struct SceneSearchFilters {
pub vlm_objects: Option<Vec<String>>,
pub vlm_tags: Option<Vec<String>>,
pub time_range: Option<TimeRange>,
}
#[derive(Debug, Deserialize)]
pub struct TimeRange {
pub start_sec: f64,
pub end_sec: f64,
}
#[derive(Debug, Serialize)]
pub struct SceneSearchResponse {
pub results: Vec<SceneSearchResult>,
pub total: usize,
pub page: usize,
pub page_size: usize,
}
#[derive(Debug, Serialize)]
pub struct SceneSearchResult {
pub file_uuid: String,
pub file_name: String,
pub scene_index: usize,
pub timestamp_sec: f64,
pub frame_number: u32,
pub thumbnail_url: String,
pub vlm_description: String,
pub vlm_objects: Vec<String>,
pub vlm_tags: Vec<String>,
pub score: f64,
pub source: String,
}
#[derive(Debug, Deserialize)]
pub struct TraceSearchRequest {
pub query: String,
pub file_uuid: Option<String>,
pub filters: Option<TraceSearchFilters>,
#[serde(default = "default_page")]
pub page: usize,
#[serde(default = "default_page_size")]
pub page_size: usize,
#[serde(default = "default_min_score")]
pub min_score: f64,
}
#[derive(Debug, Deserialize)]
pub struct TraceSearchFilters {
pub vlm_clothing: Option<String>,
pub vlm_location: Option<String>,
pub vlm_tags: Option<Vec<String>>,
}
#[derive(Debug, Serialize)]
pub struct TraceSearchResponse {
pub results: Vec<TraceSearchResult>,
pub total: usize,
pub page: usize,
pub page_size: usize,
}
#[derive(Debug, Serialize)]
pub struct TraceSearchResult {
pub file_uuid: String,
pub file_name: String,
pub trace_id: i32,
pub identity_uuid: Option<String>,
pub identity_name: Option<String>,
pub vlm_description: String,
pub vlm_clothing: Option<String>,
pub vlm_tags: Vec<String>,
pub vlm_location: Option<String>,
pub thumbnail_url: String,
pub score: f64,
pub source: String,
}
pub async fn search_vlm_scenes(
State(state): State<AppState>,
Json(req): Json<SceneSearchRequest>,
) -> Result<Json<SceneSearchResponse>, StatusCode> {
let pool = state.db.pool();
let qdrant = &state.qdrant;
let embedder = &state.embedder;
// Get config min_score (request can override)
let config: SearchConfig = state.admin_config_manager.get_search().await;
let min_score = if req.min_score > 0.0 {
req.min_score
} else {
config.vlm_min_score
};
let active_files = state
.db
.get_active_file_uuids()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 1. Generate query embedding
let query_embedding = embedder
.embed_query(&req.query)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 2. Vector search in Qdrant
let search_results = qdrant
.search_scenes(
&query_embedding,
req.file_uuid.as_deref(),
req.page_size * 2,
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 3. Post-filter and build results
let mut results = Vec::new();
for point in search_results {
let payload = match point.get("payload") {
Some(p) => p,
None => continue,
};
// Skip orphaned points from unregistered files (no longer in videos table)
let hit_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("");
if !active_files.contains(hit_uuid) {
continue;
}
// Apply filters
if let Some(ref filters) = req.filters {
// Filter by vlm_objects
if let Some(ref objects) = filters.vlm_objects {
let empty_vec = Vec::new();
let payload_objects = payload
.get("vlm_objects")
.and_then(|v| v.as_array())
.unwrap_or(&empty_vec);
let all_match = objects
.iter()
.all(|obj| payload_objects.contains(&serde_json::json!(obj)));
if !all_match {
continue;
}
}
// Filter by vlm_tags
if let Some(ref tags) = filters.vlm_tags {
let empty_vec = Vec::new();
let payload_tags = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
.unwrap_or(&empty_vec);
let all_match = tags
.iter()
.all(|tag| payload_tags.contains(&serde_json::json!(tag)));
if !all_match {
continue;
}
}
// Filter by time_range
if let Some(ref time_range) = filters.time_range {
let timestamp = payload
.get("timestamp_sec")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
if timestamp < time_range.start_sec || timestamp > time_range.end_sec {
continue;
}
}
}
// Build result
let file_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let scene_index = payload
.get("scene_index")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
// Query file name
let file_name =
sqlx::query_scalar::<_, String>("SELECT file_name FROM videos WHERE file_uuid = $1")
.bind(&file_uuid)
.fetch_optional(pool)
.await
.ok()
.flatten()
.unwrap_or_default();
let timestamp_sec = payload
.get("timestamp_sec")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
let frame_number = payload
.get("frame_number")
.and_then(|v| v.as_u64())
.unwrap_or(0) as u32;
let vlm_description = payload
.get("vlm_description")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_objects = payload
.get("vlm_objects")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let vlm_tags = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
// Apply min_score filter
if score < min_score {
continue;
}
results.push(SceneSearchResult {
file_uuid: file_uuid.clone(),
file_name,
scene_index,
timestamp_sec,
frame_number,
thumbnail_url: format!(
"/api/v1/file/{}/scenes/scene_{:03}.jpg",
file_uuid, scene_index
),
vlm_description,
vlm_objects,
vlm_tags,
score,
source: "vector".to_string(),
});
// Stop if we have enough results
if results.len() >= req.page_size {
break;
}
}
let total = results.len();
Ok(Json(SceneSearchResponse {
results,
total,
page: req.page,
page_size: req.page_size,
}))
}
pub fn vlm_search_routes() -> axum::Router<AppState> {
axum::Router::new()
.route(
"/api/v1/search/vlm/scenes",
axum::routing::post(search_vlm_scenes),
)
.route(
"/api/v1/search/vlm/traces",
axum::routing::post(search_vlm_traces),
)
.route(
"/api/v1/search/vlm/debug",
axum::routing::post(vlm_debug_search),
)
}
pub async fn search_vlm_traces(
State(state): State<AppState>,
Json(req): Json<TraceSearchRequest>,
) -> Result<Json<TraceSearchResponse>, StatusCode> {
let pool = state.db.pool();
let qdrant = &state.qdrant;
let embedder = &state.embedder;
// Get config min_score (request can override)
let config: SearchConfig = state.admin_config_manager.get_search().await;
let min_score = if req.min_score > 0.0 {
req.min_score
} else {
config.vlm_min_score
};
let active_files = state
.db
.get_active_file_uuids()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 1. Generate query embedding (vector-first)
let query_embedding = embedder
.embed_query(&req.query)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 2. Vector search in Qdrant main collection (chunk_type = vlm_summary)
let search_results = qdrant
.search_trace_vlm(
&query_embedding,
req.file_uuid.as_deref(),
req.page_size * 3,
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 3. Post-filter + enrich from trace_profiles
let mut results = Vec::new();
for point in search_results {
let payload = match point.get("payload") {
Some(p) => p,
None => continue,
};
let file_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if !active_files.contains(&file_uuid) {
continue;
}
let trace_id = payload
.get("trace_id")
.and_then(|v| v.as_i64())
.unwrap_or(0) as i32;
let vlm_description = payload
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if trace_id <= 0 || file_uuid.is_empty() {
continue;
}
// Apply structured filters via trace_profiles
if let Some(ref filters) = req.filters {
let tp = sqlx::query_as::<_, (Option<String>, Option<String>, Option<Vec<String>>)>(
"SELECT vlm_clothing, vlm_location, vlm_tags FROM trace_profiles \
WHERE file_uuid = $1 AND trace_id = $2",
)
.bind(&file_uuid)
.bind(trace_id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (clothing, location, tags) = tp.unwrap_or((None, None, None));
if let Some(ref c) = filters.vlm_clothing {
if !clothing
.as_deref()
.map_or(false, |s| s.to_lowercase().contains(&c.to_lowercase()))
{
continue;
}
}
if let Some(ref l) = filters.vlm_location {
if !location
.as_deref()
.map_or(false, |s| s.to_lowercase().contains(&l.to_lowercase()))
{
continue;
}
}
if let Some(ref required_tags) = filters.vlm_tags {
let all_match = required_tags.iter().all(|t| {
tags.as_ref()
.map_or(false, |v| v.iter().any(|x| x.eq_ignore_ascii_case(t)))
});
if !all_match {
continue;
}
}
}
// Query file name + profile enrichment
let (file_name, vlm_clothing, vlm_location, vlm_tags_arr, identity_uuid, identity_name) =
sqlx::query_as::<
_,
(
String,
Option<String>,
Option<String>,
Option<Vec<String>>,
Option<String>,
Option<String>,
),
>(
"SELECT COALESCE(v.file_name, ''), tp.vlm_clothing, tp.vlm_location, tp.vlm_tags, \
i.uuid, i.name \
FROM trace_profiles tp \
LEFT JOIN videos v ON v.file_uuid = tp.file_uuid \
LEFT JOIN identity_bindings ib ON ib.identity_type = 'trace' \
AND ib.identity_value = tp.trace_id::text \
LEFT JOIN identities i ON i.id = ib.identity_id \
WHERE tp.file_uuid = $1 AND tp.trace_id = $2",
)
.bind(&file_uuid)
.bind(trace_id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.unwrap_or_default();
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
// Apply min_score filter
if score < min_score {
continue;
}
results.push(TraceSearchResult {
file_uuid: file_uuid.clone(),
file_name,
trace_id,
identity_uuid,
identity_name,
vlm_description,
vlm_clothing,
vlm_tags: vlm_tags_arr.unwrap_or_default(),
vlm_location,
thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id),
score,
source: "vector".to_string(),
});
if results.len() >= req.page_size {
break;
}
}
let total = results.len();
Ok(Json(TraceSearchResponse {
results,
total,
page: req.page,
page_size: req.page_size,
}))
}
// ── Combined VLM Debug Search (scenes + traces, raw) ──────────────
#[derive(Debug, Deserialize)]
pub struct VlmDebugSearchRequest {
pub query: String,
pub file_uuid: Option<String>,
#[serde(default = "default_page_size")]
pub limit: usize,
#[serde(default = "default_min_score")]
pub min_score: f64,
}
#[derive(Debug, Serialize)]
pub struct VlmDebugSearchResponse {
pub query: String,
pub file_uuid: Option<String>,
pub limit: usize,
pub total: usize,
pub scenes: Vec<VlmDebugHit>,
pub traces: Vec<VlmDebugHit>,
pub filtered_orphan_points: usize,
}
#[derive(Debug, Serialize)]
pub struct VlmDebugHit {
pub collection: String,
pub point_id: String,
pub score: f64,
pub file_uuid: String,
pub payload: serde_json::Value,
}
/// Standalone combined VLM debug search. Embeds the query once, then searches
/// BOTH `_scenes` (scene VLM) and the main collection (trace VLM summaries,
/// chunk_type = vlm_summary) in parallel. Returns raw Qdrant hits (payload +
/// score + point id) for inspection/debugging. Orphaned points from
/// unregistered files (not present in the `videos` table) are filtered out;
/// the count of dropped orphans is reported in `filtered_orphan_points`.
pub async fn vlm_debug_search(
State(state): State<AppState>,
Json(req): Json<VlmDebugSearchRequest>,
) -> Result<Json<VlmDebugSearchResponse>, StatusCode> {
let qdrant = &state.qdrant;
let embedder = &state.embedder;
// Get config min_score (request can override)
let config: SearchConfig = state.admin_config_manager.get_search().await;
let min_score = if req.min_score > 0.0 {
req.min_score
} else {
config.vlm_min_score
};
let limit = req.limit.max(1).min(100);
if req.query.trim().is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
// 1. Generate query embedding once
let query_embedding = embedder
.embed_query(&req.query)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 2. Parallel search scenes (_scenes) + traces (main collection)
let (scene_res, trace_res) = tokio::join!(
qdrant.search_scenes(&query_embedding, req.file_uuid.as_deref(), limit),
qdrant.search_trace_vlm(&query_embedding, req.file_uuid.as_deref(), limit)
);
let mut scenes = Vec::new();
let mut traces = Vec::new();
let mut filtered_orphan_points = 0usize;
let active_files = state
.db
.get_active_file_uuids()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if let Ok(hits) = scene_res {
for point in hits {
let payload = point.get("payload").cloned().unwrap_or_default();
let point_id = if let Some(pid) = point.get("id") {
if pid.is_i64() {
format!("{:x}", pid.as_i64().unwrap_or(0) as u64)
} else {
pid.to_string()
}
} else {
String::new()
};
let file_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if !active_files.contains(&file_uuid) {
filtered_orphan_points += 1;
continue;
}
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
if score < min_score {
continue;
}
scenes.push(VlmDebugHit {
collection: "_scenes".to_string(),
point_id,
score,
file_uuid,
payload,
});
}
}
if let Ok(hits) = trace_res {
for point in hits {
let payload = point.get("payload").cloned().unwrap_or_default();
let point_id = if let Some(pid) = point.get("id") {
if pid.is_i64() {
format!("{:x}", pid.as_i64().unwrap_or(0) as u64)
} else {
pid.to_string()
}
} else {
String::new()
};
let file_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if !active_files.contains(&file_uuid) {
filtered_orphan_points += 1;
continue;
}
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
if score < min_score {
continue;
}
traces.push(VlmDebugHit {
collection: "main (vlm_summary)".to_string(),
point_id,
score,
file_uuid,
payload,
});
}
}
let total = scenes.len() + traces.len();
Ok(Json(VlmDebugSearchResponse {
query: req.query,
file_uuid: req.file_uuid,
limit,
total,
scenes,
traces,
filtered_orphan_points,
}))
}
+67
View File
@@ -0,0 +1,67 @@
use anyhow::Result;
use dotenv::dotenv;
use momentry_core::core::config;
use momentry_core::core::db::PostgresDb;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
dotenv().ok();
let db = PostgresDb::new(&config::DATABASE_URL).await?;
println!("Creating scenes table...");
sqlx::query(
"CREATE TABLE IF NOT EXISTS scenes (
id BIGSERIAL PRIMARY KEY,
file_uuid VARCHAR(32) NOT NULL,
scene_index INTEGER NOT NULL,
timestamp_sec DOUBLE PRECISION NOT NULL,
frame_number BIGINT NOT NULL,
filename VARCHAR(255) NOT NULL,
selection_reason VARCHAR(50),
quality_score DOUBLE PRECISION,
quality_source VARCHAR(100),
vlm_status VARCHAR(20) DEFAULT 'pending',
vlm_description TEXT,
vlm_scene_type VARCHAR(100),
vlm_location VARCHAR(255),
vlm_objects JSONB DEFAULT '[]',
vlm_tags JSONB DEFAULT '[]',
vlm_attributes JSONB,
face_count INTEGER DEFAULT 0,
person_traces JSONB DEFAULT '[]',
has_cut BOOLEAN DEFAULT false,
cut_count INTEGER DEFAULT 0,
scene_info JSONB,
embedding_status VARCHAR(20) DEFAULT 'pending',
embedding_point_id VARCHAR(64),
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(file_uuid, scene_index)
)",
)
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_file_uuid ON scenes(file_uuid)")
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_tags ON scenes USING GIN(vlm_tags)")
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_objects ON scenes USING GIN(vlm_objects)")
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_timestamp ON scenes(timestamp_sec)")
.execute(db.pool())
.await?;
println!("✅ Scenes table created successfully");
Ok(())
}
+215
View File
@@ -0,0 +1,215 @@
use anyhow::{Context, Result};
use dotenv::dotenv;
use momentry_core::core::config;
use momentry_core::core::db::{schema::table_name, PostgresDb, QdrantDb, SCENES_COLLECTION};
use momentry_core::core::embedding::comic_embed::Embedder;
use momentry_core::core::file_profile::SceneProfile;
use std::path::PathBuf;
fn hash_string(s: &str) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
s.hash(&mut hasher);
hasher.finish()
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
dotenv().ok();
let output_dir = config::OUTPUT_DIR.clone();
let mut dry_run = false;
let mut generate_embeddings = true;
let args: Vec<String> = std::env::args().collect();
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
"--dry-run" => dry_run = true,
"--skip-embeddings" => generate_embeddings = false,
"--help" | "-h" => {
println!("Usage: migrate_scenes [--dry-run] [--skip-embeddings]");
println!(" --dry-run: Only scan files, don't import");
println!(" --skip-embeddings: Don't generate vector embeddings");
return Ok(());
}
_ => {}
}
i += 1;
}
println!("=== Scene Data Migration ===\n");
println!("Output directory: {}", output_dir);
println!("Dry run: {}", dry_run);
println!("Generate embeddings: {}\n", generate_embeddings);
// 1. Scan .scenes.json files
let output_path = std::path::Path::new(&output_dir);
let mut scene_files: Vec<PathBuf> = Vec::new();
if output_path.exists() {
for entry in std::fs::read_dir(output_path)? {
let entry = entry?;
let path = entry.path();
if path.extension().map(|e| e == "json").unwrap_or(false) {
if let Some(filename) = path.file_name() {
if filename.to_string_lossy().ends_with(".scenes.json") {
scene_files.push(path);
}
}
}
}
}
println!("Found {} scene files\n", scene_files.len());
if dry_run {
for file in &scene_files {
println!(" {}", file.display());
}
return Ok(());
}
// 2. Connect to databases
let db = PostgresDb::new(&config::DATABASE_URL).await?;
let qdrant = QdrantDb::new();
let embedder = Embedder::new(config::EMBED_URL.clone());
// 3. Ensure Qdrant collection exists
if generate_embeddings {
println!(
"Ensuring Qdrant collection '{}' exists...",
SCENES_COLLECTION
);
qdrant.ensure_collection(SCENES_COLLECTION, 768).await?;
}
let scenes_table = table_name("scenes");
// 4. Process each file
let mut total_scenes = 0;
let mut total_imported = 0;
let mut total_embeddings = 0;
for file in &scene_files {
let json_content =
std::fs::read_to_string(file).context(format!("Failed to read {}", file.display()))?;
let profile: SceneProfile = serde_json::from_str(&json_content)
.context(format!("Failed to parse {}", file.display()))?;
println!(
"\nProcessing: {} ({} scenes)",
profile.file_uuid,
profile.scenes.len()
);
total_scenes += profile.scenes.len();
// Insert into PostgreSQL
for scene in &profile.scenes {
if scene.vlm_status != momentry_core::core::file_profile::VlmStatus::Completed {
continue;
}
let vlm_objects_json = serde_json::to_string(&scene.vlm_objects)?;
let vlm_tags_json = serde_json::to_string(&scene.vlm_tags)?;
let person_traces_json = serde_json::to_string(&scene.person_traces)?;
sqlx::query(&format!(
"INSERT INTO {} (file_uuid, scene_index, timestamp_sec, frame_number, filename,
selection_reason, quality_score, quality_source, vlm_status, vlm_description,
vlm_objects, vlm_tags, face_count, person_traces, has_cut, cut_count,
embedding_status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12::jsonb, $13, $14::jsonb, $15, $16, $17)
ON CONFLICT (file_uuid, scene_index) DO UPDATE SET
timestamp_sec = EXCLUDED.timestamp_sec,
frame_number = EXCLUDED.frame_number,
vlm_description = EXCLUDED.vlm_description,
vlm_objects = EXCLUDED.vlm_objects,
vlm_tags = EXCLUDED.vlm_tags",
scenes_table
))
.bind(&profile.file_uuid)
.bind(scene.index as i32)
.bind(scene.timestamp_sec)
.bind(scene.frame_number as i64)
.bind(&scene.filename)
.bind(format!("{:?}", scene.selection_reason))
.bind(scene.quality_score)
.bind(&scene.quality_source)
.bind("completed")
.bind(&scene.vlm_description)
.bind(&vlm_objects_json)
.bind(&vlm_tags_json)
.bind(scene.face_count as i32)
.bind(&person_traces_json)
.bind(scene.has_cut)
.bind(scene.cut_count as i32)
.bind("pending")
.execute(db.pool())
.await
.context("Failed to insert scene")?;
total_imported += 1;
}
// Generate embeddings
if generate_embeddings {
println!(" Generating embeddings...");
for scene in &profile.scenes {
if scene.vlm_status != momentry_core::core::file_profile::VlmStatus::Completed {
continue;
}
if let Some(ref desc) = scene.vlm_description {
// Generate embedding
let embedding = embedder.embed_document(desc).await?;
// Generate point ID
let point_id_str = format!("{}_s{}", profile.file_uuid, scene.index);
let point_id = hash_string(&point_id_str);
// Upsert to Qdrant
qdrant
.upsert_scene_embedding(
point_id,
&embedding,
&profile.file_uuid,
scene.index,
scene.timestamp_sec,
scene.frame_number,
desc,
&scene.vlm_objects,
&scene.vlm_tags,
)
.await?;
// Update PostgreSQL
sqlx::query(&format!(
"UPDATE {} SET embedding_status = 'completed', embedding_point_id = $1
WHERE file_uuid = $2 AND scene_index = $3",
scenes_table
))
.bind(format!("{:x}", point_id))
.bind(&profile.file_uuid)
.bind(scene.index as i32)
.execute(db.pool())
.await?;
total_embeddings += 1;
}
}
}
}
println!("\n=== Migration Summary ===");
println!("Total scene files: {}", scene_files.len());
println!("Total scenes: {}", total_scenes);
println!("Scenes imported: {}", total_imported);
println!("Embeddings generated: {}", total_embeddings);
Ok(())
}
+203
View File
@@ -0,0 +1,203 @@
// Standalone Scene VLM Test Tool
// This tool manually triggers Scene VLM processing for testing
use anyhow::Result;
use momentry_core::core::db::PostgresDb;
use momentry_core::core::processor::scene_vlm::SceneVlmProcessor;
use momentry_core::Database;
use sqlx::postgres::PgPoolOptions;
#[tokio::main]
async fn main() -> Result<()> {
// Initialize tracing
tracing_subscriber::fmt::init();
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <file_uuid>", args[0]);
std::process::exit(1);
}
let uuid = &args[1];
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string());
println!("=== Scene VLM Test Tool ===");
println!("UUID: {}", uuid);
println!("Output: {}", output_dir);
println!();
// Load config
let (enabled, interval_sec, samples, use_cuts, max_workers) =
momentry_core::core::config::get_scene_vlm_config();
println!("Config:");
println!(" Enabled: {}", enabled);
println!(" Interval: {}s", interval_sec);
println!(" Samples: {}", samples);
println!(" Use CUTs: {}", use_cuts);
println!(" Max Workers: {}", max_workers);
println!();
if !enabled {
println!("❌ Scene VLM is disabled");
println!("Set MOMENTRY_SCENE_VLM_ENABLED=true to enable");
return Ok(());
}
// Load video metadata
println!("Loading video metadata...");
let db_url = momentry_core::core::config::DATABASE_URL.clone();
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&db_url)
.await?;
let db = PostgresDb::from_pool(pool);
let video = db
.get_video_by_uuid(uuid)
.await?
.ok_or_else(|| anyhow::anyhow!("Video not found: {}", uuid))?;
let fps = video.fps;
let duration = video.duration;
let width = video.width;
let height = video.height;
let total_frames = video.total_frames as u32;
let video_path = video.file_path.clone();
println!("Video:");
println!(" Path: {}", video_path);
println!(" Duration: {}s", duration);
println!(" FPS: {}", fps);
println!(" Resolution: {}x{}", width, height);
println!(" Total frames: {}", total_frames);
println!();
// Load CUT data
println!("Loading CUT data...");
let cut_path = format!("{}/{}.cut.json", output_dir, uuid);
let cut_data = if std::path::Path::new(&cut_path).exists() {
let json = std::fs::read_to_string(&cut_path)?;
let data: serde_json::Value = serde_json::from_str(&json)?;
let scene_count = data
.get("scenes")
.and_then(|s| s.as_array())
.map(|a| a.len())
.unwrap_or(0);
println!(" Scenes: {}", scene_count);
data
} else {
println!(" ⚠️ No CUT data, using empty");
serde_json::json!({"scenes": []})
};
println!();
// Create processor
let processor = SceneVlmProcessor::new(samples, use_cuts, max_workers);
// Generate profile
println!("Generating scene profile...");
let start = std::time::Instant::now();
let profile = processor
.generate_scene_profile(
&video_path,
uuid,
&output_dir,
interval_sec,
&cut_data,
fps,
duration,
width,
height,
total_frames,
)
.await?;
let elapsed = start.elapsed();
println!(" ✅ Generated in {:.2}s", elapsed.as_secs_f64());
println!(" Total scenes: {}", profile.total_scenes);
println!();
// Extract frames
println!("Extracting frames...");
let start = std::time::Instant::now();
let extracted =
SceneVlmProcessor::extract_scene_frames(&video_path, &output_dir, uuid, &profile.scenes)
.await?;
let elapsed = start.elapsed();
println!(
" ✅ Extracted {} frames in {:.2}s",
extracted.len(),
elapsed.as_secs_f64()
);
println!();
// Generate VLM descriptions
println!("Generating VLM descriptions...");
let start = std::time::Instant::now();
let mut profile = profile;
match SceneVlmProcessor::generate_vlm_descriptions(
&output_dir,
uuid,
&mut profile.scenes,
max_workers,
)
.await
{
Ok(_) => {
let elapsed = start.elapsed();
println!(
" ✅ Generated VLM descriptions in {:.2}s",
elapsed.as_secs_f64()
);
}
Err(e) => {
println!(" ⚠️ VLM generation failed: {}", e);
}
}
println!();
// Save profile
println!("Saving profile...");
SceneVlmProcessor::save_scene_profile(&profile, &output_dir)?;
println!(" ✅ Saved to {}/{}.scenes.json", output_dir, uuid);
println!();
// Print summary
println!("=== Summary ===");
println!("Total frames: {}", profile.total_scenes);
println!("Processing time: {:.2}s", elapsed.as_secs_f64());
println!();
// Print first 5 scenes with VLM status
println!("First 5 scenes:");
for scene in profile.scenes.iter().take(5) {
let vlm_desc = scene.vlm_description.as_deref().unwrap_or("N/A");
let vlm_status = match scene.vlm_status {
momentry_core::core::file_profile::VlmStatus::Pending => "pending",
momentry_core::core::file_profile::VlmStatus::Processing => "processing",
momentry_core::core::file_profile::VlmStatus::Completed => "completed",
momentry_core::core::file_profile::VlmStatus::Failed => "failed",
};
println!(
" {}: {}s (frame {}, blur={:.2}) [VLM: {}]",
scene.index,
scene.timestamp_sec,
scene.frame_number,
scene.quality_score.unwrap_or(0.0),
vlm_status
);
if scene.vlm_description.is_some() {
println!(
" Description: {}...",
&vlm_desc[..vlm_desc.len().min(80)]
);
}
}
Ok(())
}
+107 -50
View File
@@ -88,8 +88,7 @@ fn default_python_path() -> String {
}
fn default_ffmpeg_path() -> String {
std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string())
std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -160,9 +159,32 @@ pub struct AdminSettings {
pub api_key_expiry_days: u32,
#[serde(default = "default_system_stats_refresh_sec")]
pub system_stats_refresh_sec: u32,
#[serde(default = "default_preferred_language")]
pub preferred_language: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchConfig {
#[serde(default = "default_vlm_min_score")]
pub vlm_min_score: f64,
}
impl Default for SearchConfig {
fn default() -> Self {
Self {
vlm_min_score: default_vlm_min_score(),
}
}
}
fn default_vlm_min_score() -> f64 {
std::env::var("MOMENTRY_VLM_MIN_SCORE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.0)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceFilterDefaults {
#[serde(default = "default_min_confidence")]
pub min_confidence: f64,
@@ -172,9 +194,25 @@ pub struct FaceFilterDefaults {
pub min_capture_quality: f64,
}
fn default_min_confidence() -> f64 { crate::core::config::FACE_MIN_CONFIDENCE_DEFAULT }
fn default_min_size() -> i32 { crate::core::config::FACE_MIN_SIZE_DEFAULT }
fn default_min_capture_quality() -> f64 { 0.25 }
impl Default for FaceFilterDefaults {
fn default() -> Self {
Self {
min_confidence: default_min_confidence(),
min_size: default_min_size(),
min_capture_quality: default_min_capture_quality(),
}
}
}
fn default_min_confidence() -> f64 {
crate::core::config::FACE_FILTER_CONFIDENCE_PCT_DEFAULT
}
fn default_min_size() -> i32 {
crate::core::config::FACE_MIN_SIZE_DEFAULT
}
fn default_min_capture_quality() -> f64 {
0.25
}
fn default_session_timeout() -> u32 {
3600
@@ -195,6 +233,11 @@ fn default_system_stats_refresh_sec() -> u32 {
.unwrap_or(5)
}
fn default_preferred_language() -> String {
std::env::var("MOMENTRY_PREFERRED_LANGUAGE")
.unwrap_or_else(|_| "zh-TW".to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ServerConfig {
#[serde(default = "default_server_port")]
@@ -253,6 +296,8 @@ pub struct AdminConfig {
pub server: ServerConfig,
#[serde(default)]
pub admin_settings: AdminSettings,
#[serde(default)]
pub search: SearchConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -277,6 +322,8 @@ pub struct PartialAdminConfig {
pub server: Option<ServerConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub admin_settings: Option<AdminSettings>,
#[serde(skip_serializing_if = "Option::is_none")]
pub search: Option<SearchConfig>,
}
pub struct AdminConfigManager {
@@ -293,86 +340,91 @@ impl AdminConfigManager {
config_path: config_path.to_string(),
})
}
fn load_config(path: &str) -> Result<AdminConfig> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path))?;
let config: AdminConfig = serde_json::from_str(&content)
.with_context(|| "Failed to parse config JSON")?;
let config: AdminConfig =
serde_json::from_str(&content).with_context(|| "Failed to parse config JSON")?;
Ok(config)
}
pub async fn get_vlm_prompt(&self, key: &str) -> Option<VlmPrompt> {
let config = self.config.read().await;
config.vlm_prompts.get(key).cloned()
}
pub async fn get_all_vlm_prompts(&self) -> HashMap<String, VlmPrompt> {
let config = self.config.read().await;
config.vlm_prompts.clone()
}
pub async fn get_llm_config(&self, key: &str) -> Option<LlmConfig> {
let config = self.config.read().await;
config.llm_config.get(key).cloned()
}
pub async fn get_processor_config(&self, key: &str) -> Option<ProcessorConfig> {
let config = self.config.read().await;
config.processor_config.get(key).cloned()
}
pub async fn get_filter_config(&self, key: &str) -> Option<FilterConfig> {
let config = self.config.read().await;
config.filter_config.get(key).cloned()
}
pub async fn get_paths(&self) -> PathsConfig {
let config = self.config.read().await;
config.paths.clone()
}
pub async fn get_concurrency(&self) -> ConcurrencyConfig {
let config = self.config.read().await;
config.concurrency.clone()
}
pub async fn get_feature_flags(&self) -> FeatureFlags {
let config = self.config.read().await;
config.feature_flags.clone()
}
pub async fn get_server(&self) -> ServerConfig {
let config = self.config.read().await;
config.server.clone()
}
pub async fn get_admin_settings(&self) -> AdminSettings {
let config = self.config.read().await;
config.admin_settings.clone()
}
pub async fn get_search(&self) -> SearchConfig {
let config = self.config.read().await;
config.search.clone()
}
pub async fn get_full_config(&self) -> AdminConfig {
let config = self.config.read().await;
config.clone()
}
pub async fn update_vlm_prompt(&self, key: &str, prompt: VlmPrompt) -> Result<()> {
let mut config = self.config.write().await;
config.vlm_prompts.insert(key.to_string(), prompt);
config.updated_at = chrono::Utc::now().to_rfc3339();
config.updated_by = "admin".to_string();
self.save_config(&config)?;
tracing::info!("[AdminConfig] Updated VLM prompt: {}", key);
Ok(())
}
pub async fn update_partial_config(&self, partial: PartialAdminConfig) -> Result<()> {
let mut config = self.config.write().await;
if let Some(vlm_prompts) = partial.vlm_prompts {
config.vlm_prompts.extend(vlm_prompts);
}
@@ -403,28 +455,31 @@ impl AdminConfigManager {
if let Some(admin_settings) = partial.admin_settings {
config.admin_settings = admin_settings;
}
if let Some(search) = partial.search {
config.search = search;
}
config.updated_at = chrono::Utc::now().to_rfc3339();
config.updated_by = "admin".to_string();
self.save_config(&config)?;
tracing::info!("[AdminConfig] Updated partial config");
Ok(())
}
pub async fn reload(&self) -> Result<()> {
let new_config = Self::load_config(&self.config_path)?;
let mut config = self.config.write().await;
*config = new_config;
tracing::info!("[AdminConfig] Reloaded config from {}", self.config_path);
Ok(())
}
fn save_config(&self, config: &AdminConfig) -> Result<()> {
let content = serde_json::to_string_pretty(config)
.with_context(|| "Failed to serialize config")?;
let content =
serde_json::to_string_pretty(config).with_context(|| "Failed to serialize config")?;
std::fs::write(&self.config_path, content)
.with_context(|| format!("Failed to write config file: {}", self.config_path))?;
Ok(())
@@ -435,19 +490,22 @@ pub fn get_default_config_path() -> String {
let mut path = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
path.push("config");
path.push("admin_config.json");
path.to_str().unwrap_or("config/admin_config.json").to_string()
path.to_str()
.unwrap_or("config/admin_config.json")
.to_string()
}
pub static ADMIN_CONFIG: once_cell::sync::Lazy<Arc<AdminConfigManager>> = once_cell::sync::Lazy::new(|| {
let config_path = get_default_config_path();
match AdminConfigManager::new(&config_path) {
Ok(manager) => Arc::new(manager),
Err(e) => {
error!("[AdminConfig] Failed to initialize: {}", e);
panic!("Failed to initialize AdminConfigManager: {}", e);
pub static ADMIN_CONFIG: once_cell::sync::Lazy<Arc<AdminConfigManager>> =
once_cell::sync::Lazy::new(|| {
let config_path = get_default_config_path();
match AdminConfigManager::new(&config_path) {
Ok(manager) => Arc::new(manager),
Err(e) => {
error!("[AdminConfig] Failed to initialize: {}", e);
panic!("Failed to initialize AdminConfigManager: {}", e);
}
}
}
});
});
pub async fn get_vlm_prompt(key: &str) -> Option<VlmPrompt> {
ADMIN_CONFIG.get_vlm_prompt(key).await
@@ -471,7 +529,7 @@ pub fn get_face_filter_defaults() -> (f64, i32, f64) {
// Try to read without blocking - use try_read for non-blocking access
// If config is locked, fall back to hardcoded defaults
let config = ADMIN_CONFIG.config.try_read();
match config {
Ok(cfg) => (
cfg.face_filter_defaults.min_confidence,
@@ -481,9 +539,9 @@ pub fn get_face_filter_defaults() -> (f64, i32, f64) {
Err(_) => {
// Config locked, use hardcoded defaults
(
crate::core::config::FACE_MIN_CONFIDENCE_DEFAULT,
crate::core::config::FACE_FILTER_CONFIDENCE_PCT_DEFAULT,
crate::core::config::FACE_MIN_SIZE_DEFAULT,
0.25, // min_capture_quality default
0.25, // min_capture_quality default
)
}
}
@@ -515,8 +573,7 @@ pub fn get_paths_sync() -> PathsConfig {
.unwrap_or_else(|_| "/Users/accusys/momentry_core_0.1/scripts".to_string()),
python_path: std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()),
ffmpeg_path: std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string()),
ffmpeg_path: std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string()),
}
}
@@ -559,4 +616,4 @@ pub fn get_concurrency_sync() -> ConcurrencyConfig {
.and_then(|v| v.parse().ok())
.unwrap_or(3600),
}
}
}
+353
View File
@@ -1629,6 +1629,359 @@ pub async fn exec_semantic_search(
.to_string())
}
/// Scene VLM semantic search — vector-first. Embeds the query and searches the
/// Qdrant `_scenes` collection (768-dim, cosine). Returns scene cards with
/// thumbnail_url, timestamp, and VLM description.
pub async fn exec_scene_search(
pool: &sqlx::PgPool,
args: &serde_json::Value,
) -> Result<String, String> {
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
let file_uuid = args
.get("file_uuid")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
let limit = args
.get("limit")
.and_then(|v| v.as_i64())
.unwrap_or(10)
.min(50) as usize;
tracing::info!(
"[exec_scene_search] query='{}', file_uuid={:?}, limit={}",
query,
file_uuid,
limit
);
if query.is_empty() {
return Err("query is required".to_string());
}
// Generate query embedding (vector-first)
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let embedding = embedder.embed_query(query).await.map_err(|e| {
tracing::error!("[exec_scene_search] Embedding failed: {}", e);
format!("Embedding failed: {}", e)
})?;
// Search Qdrant _scenes
let qdrant = QdrantDb::new();
let search_results = qdrant
.search_scenes(&embedding, file_uuid, limit)
.await
.map_err(|e| {
tracing::error!("[exec_scene_search] Qdrant search_scenes failed: {}", e);
format!("Qdrant search failed: {}", e)
})?;
tracing::info!(
"[exec_scene_search] Qdrant returned {} hits",
search_results.len()
);
// Fetch file names for hits
let videos = schema::table_name("videos");
let mut cards = Vec::new();
for point in search_results.iter() {
let payload = match point.get("payload") {
Some(p) => p,
None => continue,
};
let hit_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let scene_index = payload
.get("scene_index")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
let timestamp_sec = payload
.get("timestamp_sec")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
let vlm_description = payload
.get("vlm_description")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_tags: Vec<String> = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
let file_name: String = sqlx::query_scalar(&format!(
"SELECT COALESCE(v.file_name, '') FROM {} v WHERE v.file_uuid = $1",
videos
))
.bind(&hit_uuid)
.fetch_optional(pool)
.await
.map_err(|e| format!("PG query failed: {}", e))?
.unwrap_or_default();
let description_preview = vlm_description.chars().take(150).collect::<String>();
cards.push(serde_json::json!({
"card_type": "scene",
"file_uuid": hit_uuid,
"file_name": file_name,
"scene_index": scene_index,
"timestamp_sec": timestamp_sec,
"thumbnail_url": format!(
"/api/v1/file/{}/scenes/scene_{:03}.jpg",
hit_uuid, scene_index
),
"score": score,
"vlm_tags": vlm_tags,
"vlm_description": description_preview,
"source": "vlm_scene"
}));
}
Ok(serde_json::json!({
"tool": "scene_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string())
}
/// Unified VLM search — searches BOTH scene VLM vectors (_scenes collection)
/// and trace VLM summary vectors (main collection, chunk_type = vlm_summary)
/// in a single call using one query embedding. Returns merged cards with a
/// `card_type` field ("scene" | "face") so the agent can distinguish sources.
pub async fn exec_vlm_search(
pool: &sqlx::PgPool,
args: &serde_json::Value,
) -> Result<String, String> {
let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
let file_uuid = args
.get("file_uuid")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty() && *s != "<nil>" && *s != "null");
let limit = args
.get("limit")
.and_then(|v| v.as_i64())
.unwrap_or(10)
.min(50) as usize;
tracing::info!(
"[exec_vlm_search] query='{}', file_uuid={:?}, limit={}",
query,
file_uuid,
limit
);
if query.is_empty() {
return Err("query is required".to_string());
}
// Generate query embedding (vector-first, shared by scenes + traces)
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let embedding = embedder.embed_query(query).await.map_err(|e| {
tracing::error!("[exec_vlm_search] Embedding failed: {}", e);
format!("Embedding failed: {}", e)
})?;
// Search both VLM collections in parallel
let qdrant = QdrantDb::new();
let (scene_hits, trace_hits) = tokio::join!(
qdrant.search_scenes(&embedding, file_uuid, limit),
qdrant.search_trace_vlm(&embedding, file_uuid, limit)
);
let scene_results = scene_hits.map_err(|e| {
tracing::error!("[exec_vlm_search] Qdrant search_scenes failed: {}", e);
format!("Qdrant scene search failed: {}", e)
})?;
let trace_results = trace_hits.map_err(|e| {
tracing::error!("[exec_vlm_search] Qdrant search_trace_vlm failed: {}", e);
format!("Qdrant trace search failed: {}", e)
})?;
let videos = schema::table_name("videos");
let mut cards = Vec::new();
let active_files: std::collections::HashSet<String> =
sqlx::query_scalar(&format!("SELECT file_uuid FROM {}", videos))
.fetch_all(pool)
.await
.map_err(|e| format!("PG query failed: {}", e))?
.into_iter()
.collect();
// Scene cards (_scenes collection)
for point in scene_results.iter() {
let payload = match point.get("payload") {
Some(p) => p,
None => continue,
};
let hit_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if !active_files.contains(&hit_uuid) {
continue;
}
let scene_index = payload
.get("scene_index")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
let timestamp_sec = payload
.get("timestamp_sec")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
let vlm_description = payload
.get("vlm_description")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_tags: Vec<String> = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
let file_name: String = sqlx::query_scalar(&format!(
"SELECT COALESCE(v.file_name, '') FROM {} v WHERE v.file_uuid = $1",
videos
))
.bind(&hit_uuid)
.fetch_optional(pool)
.await
.map_err(|e| format!("PG query failed: {}", e))?
.unwrap_or_default();
cards.push(serde_json::json!({
"card_type": "scene",
"vlm_type": "scene",
"file_uuid": hit_uuid,
"file_name": file_name,
"scene_index": scene_index,
"timestamp_sec": timestamp_sec,
"thumbnail_url": format!(
"/api/v1/file/{}/scenes/scene_{:03}.jpg",
hit_uuid, scene_index
),
"score": score,
"vlm_tags": vlm_tags,
"vlm_description": vlm_description.chars().take(150).collect::<String>(),
"source": "vlm_scene"
}));
}
// Trace cards (main collection, chunk_type = vlm_summary)
for point in trace_results.iter() {
let payload = match point.get("payload") {
Some(p) => p,
None => continue,
};
let hit_uuid = payload
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if !active_files.contains(&hit_uuid) {
continue;
}
let trace_id = payload
.get("trace_id")
.and_then(|v| v.as_i64())
.unwrap_or(0) as i32;
let vlm_description = payload
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if trace_id <= 0 || hit_uuid.is_empty() {
continue;
}
// Enrich with profile fields + identity via identity_bindings
let (file_name, vlm_clothing, vlm_location, vlm_tags_arr, identity_name) =
sqlx::query_as::<
_,
(
String,
Option<String>,
Option<String>,
Option<Vec<String>>,
Option<String>,
),
>(
"SELECT COALESCE(v.file_name, ''), tp.vlm_clothing, tp.vlm_location, tp.vlm_tags, \
i.name \
FROM trace_profiles tp \
LEFT JOIN videos v ON v.file_uuid = tp.file_uuid \
LEFT JOIN identity_bindings ib ON ib.identity_type = 'trace' \
AND ib.identity_value = tp.trace_id::text \
LEFT JOIN identities i ON i.id = ib.identity_id \
WHERE tp.file_uuid = $1 AND tp.trace_id = $2",
)
.bind(&hit_uuid)
.bind(trace_id)
.fetch_optional(pool)
.await
.map_err(|e| format!("PG query failed: {}", e))?
.unwrap_or_default();
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
cards.push(serde_json::json!({
"card_type": "face",
"vlm_type": "trace",
"file_uuid": hit_uuid,
"file_name": file_name,
"trace_id": trace_id,
"identity_name": identity_name,
"start_frame": payload.get("start_frame").and_then(|v| v.as_i64()).unwrap_or(0),
"end_frame": payload.get("end_frame").and_then(|v| v.as_i64()).unwrap_or(0),
"timestamp_sec": payload.get("timestamp_sec").and_then(|v| v.as_f64()).unwrap_or(0.0),
"thumbnail_url": format!("/api/v1/trace-thumb/{}/{}", hit_uuid, trace_id),
"score": score,
"vlm_clothing": vlm_clothing,
"vlm_location": vlm_location,
"vlm_tags": vlm_tags_arr.unwrap_or_default(),
"vlm_description": vlm_description.chars().take(150).collect::<String>(),
"source": "vlm_trace"
}));
}
// Sort merged cards by score desc, cap at limit
cards.sort_by(|a, b| {
let sa = a.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
let sb = b.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal)
});
cards.truncate(limit);
Ok(serde_json::json!({
"tool": "vlm_search",
"query": query,
"count": cards.len(),
"cards": cards
})
.to_string())
}
/// Search named face profiles by name — finds face_track TKG nodes whose label
/// matches the given name, joined with trace_profiles for frame/key-image info.
/// Returns cards with key_frame, key_face, frame_range, and time_range.
+24
View File
@@ -0,0 +1,24 @@
use std::cell::RefCell;
thread_local! {
pub static CURRENT_REQUEST_ID: RefCell<Option<String>> = RefCell::new(None);
pub static CURRENT_API_KEY_ID: RefCell<Option<String>> = RefCell::new(None);
}
pub fn set_request_context(request_id: String, key_id: Option<String>) {
CURRENT_REQUEST_ID.with(|cell| *cell.borrow_mut() = Some(request_id));
CURRENT_API_KEY_ID.with(|cell| *cell.borrow_mut() = key_id);
}
pub fn get_request_id() -> Option<String> {
CURRENT_REQUEST_ID.with(|cell| cell.borrow().clone())
}
pub fn get_key_id() -> Option<String> {
CURRENT_API_KEY_ID.with(|cell| cell.borrow().clone())
}
pub fn clear_request_context() {
CURRENT_REQUEST_ID.with(|cell| *cell.borrow_mut() = None);
CURRENT_API_KEY_ID.with(|cell| *cell.borrow_mut() = None);
}
+76
View File
@@ -0,0 +1,76 @@
use anyhow::Result;
use tracing::error;
use crate::core::db::PostgresDb;
use super::context::{get_key_id, get_request_id};
use super::models::{LogTokenUsage, TokenUsage};
pub struct TokenLogger;
impl TokenLogger {
pub async fn log(
db: &PostgresDb,
service: &str,
model: Option<&str>,
usage: TokenUsage,
endpoint: Option<&str>,
duration_ms: Option<i32>,
) -> Result<()> {
let request_id =
get_request_id().unwrap_or_else(|| uuid::Uuid::new_v4().to_string().replace('-', ""));
let key_id = get_key_id();
let log = LogTokenUsage {
request_id,
key_id,
service: service.to_string(),
model: model.map(|s| s.to_string()),
endpoint: endpoint.map(|s| s.to_string()),
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
total_tokens: usage.total_tokens,
duration_ms,
status_code: Some(200),
error_message: None,
};
if let Err(e) = db.log_token_usage(&log).await {
error!("[BILLING] Failed to log token usage: {:?}", e);
}
Ok(())
}
pub async fn log_error(
db: &PostgresDb,
service: &str,
model: Option<&str>,
endpoint: Option<&str>,
error_message: &str,
) -> Result<()> {
let request_id =
get_request_id().unwrap_or_else(|| uuid::Uuid::new_v4().to_string().replace('-', ""));
let key_id = get_key_id();
let log = LogTokenUsage {
request_id,
key_id,
service: service.to_string(),
model: model.map(|s| s.to_string()),
endpoint: endpoint.map(|s| s.to_string()),
input_tokens: 0,
output_tokens: 0,
total_tokens: 0,
duration_ms: None,
status_code: Some(500),
error_message: Some(error_message.to_string()),
};
if let Err(e) = db.log_token_usage(&log).await {
error!("[BILLING] Failed to log error: {:?}", e);
}
Ok(())
}
}
+10
View File
@@ -0,0 +1,10 @@
pub mod context;
pub mod logger;
pub mod models;
pub use context::{clear_request_context, get_key_id, get_request_id, set_request_context};
pub use logger::TokenLogger;
pub use models::{
BillingPeriod, HistoryResponse, LogTokenUsage, PeriodSummary, TokenStats, TokenUsage,
UsageResponse,
};
+68
View File
@@ -0,0 +1,68 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenUsage {
pub input_tokens: u32,
pub output_tokens: u32,
pub total_tokens: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogTokenUsage {
pub request_id: String,
pub key_id: Option<String>,
pub service: String,
pub model: Option<String>,
pub endpoint: Option<String>,
pub input_tokens: u32,
pub output_tokens: u32,
pub total_tokens: u32,
pub duration_ms: Option<i32>,
pub status_code: Option<i32>,
pub error_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingPeriod {
pub id: i32,
pub key_id: Option<String>,
pub period_month: String,
pub total_input_tokens: i64,
pub total_output_tokens: i64,
pub total_tokens: i64,
pub request_count: i64,
pub error_count: i64,
pub service_breakdown: serde_json::Value,
pub model_breakdown: serde_json::Value,
pub avg_duration_ms: Option<i32>,
pub total_duration_ms: Option<i64>,
pub period_start: String,
pub period_end: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageResponse {
pub key_id: Option<String>,
pub period: String,
pub tokens: TokenStats,
pub services: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenStats {
pub input: i64,
pub output: i64,
pub total: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryResponse {
pub periods: Vec<PeriodSummary>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeriodSummary {
pub period: String,
pub total_tokens: i64,
pub request_count: i64,
}
+20 -17
View File
@@ -103,7 +103,11 @@ pub async fn execute_rule3_moment(db: &PostgresDb, file_uuid: &str) -> Result<us
moments.push(window);
if moments.len() % 100 == 0 {
info!("[Rule3-Moment] Processed {}/{} windows", moments.len(), total_windows);
info!(
"[Rule3-Moment] Processed {}/{} windows",
moments.len(),
total_windows
);
}
}
@@ -126,11 +130,7 @@ pub async fn execute_rule3_moment(db: &PostgresDb, file_uuid: &str) -> Result<us
})
.collect();
let trace_ids: Vec<i64> = moment
.selected_traces
.iter()
.map(|t| t.trace_id)
.collect();
let trace_ids: Vec<i64> = moment.selected_traces.iter().map(|t| t.trace_id).collect();
let metadata = serde_json::json!({
"window_index": moment.window_index,
@@ -159,7 +159,10 @@ pub async fn execute_rule3_moment(db: &PostgresDb, file_uuid: &str) -> Result<us
// Store chunk directly (not in tx — store_chunk uses its own tx)
if let Err(e) = db.store_chunk(&chunk).await {
warn!("[Rule3-Moment] Failed to store moment_{}: {}", moment.window_index, e);
warn!(
"[Rule3-Moment] Failed to store moment_{}: {}",
moment.window_index, e
);
} else {
count += 1;
}
@@ -198,13 +201,16 @@ pub async fn execute_rule3_moment(db: &PostgresDb, file_uuid: &str) -> Result<us
if let Err(e) = qdrant
.upsert_vector_to_collection(
&qdrant.collection_name,
moment.window_index as u64,
&vec,
Some(payload),
)
.await
moment.window_index as u64,
&vec,
Some(payload),
)
.await
{
warn!("[Rule3-Moment] Failed to embed moment_{}: {}", moment.window_index, e);
warn!(
"[Rule3-Moment] Failed to embed moment_{}: {}",
moment.window_index, e
);
} else {
embedded += 1;
}
@@ -268,10 +274,7 @@ fn select_key_frames(
}
// Filter traces with valid key_frame
let valid: Vec<&TraceProfileLite> = traces
.iter()
.filter(|t| t.key_frame.is_some())
.collect();
let valid: Vec<&TraceProfileLite> = traces.iter().filter(|t| t.key_frame.is_some()).collect();
if valid.is_empty() {
return MomentWindow {
+65 -16
View File
@@ -44,6 +44,21 @@ pub fn set_auto_pipeline_enabled(enabled: bool) {
tracing::info!("Auto-pipeline enabled set to: {}", enabled);
}
pub static RUNTIME_PREFERRED_LANGUAGE: Lazy<RwLock<String>> = Lazy::new(|| {
let initial = env::var("MOMENTRY_PREFERRED_LANGUAGE")
.unwrap_or_else(|_| "zh-TW".to_string());
RwLock::new(initial)
});
pub fn get_preferred_language() -> String {
RUNTIME_PREFERRED_LANGUAGE.read().unwrap().clone()
}
pub fn set_preferred_language(language: String) {
*RUNTIME_PREFERRED_LANGUAGE.write().unwrap() = language.clone();
tracing::info!("Preferred language set to: {}", language);
}
// ─────────────────────────────────────────────────────────────
// Sensitive configs (always from ENV, never in JSON)
// ─────────────────────────────────────────────────────────────
@@ -124,31 +139,65 @@ pub static EMBED_URL: Lazy<String> = Lazy::new(|| {
});
pub static LLM_HEALTH_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_HEALTH_URL").unwrap_or_else(|_| {
"http://127.0.0.1:8080/health".to_string()
})
env::var("MOMENTRY_LLM_HEALTH_URL")
.unwrap_or_else(|_| "http://127.0.0.1:8080/health".to_string())
});
pub static SCENE_VLM_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_ENABLED")
.map(|v| v == "true" || v == "1")
.unwrap_or(true) // Default: true (Scene VLM is mandatory, not optional)
});
pub static SCENE_VLM_INTERVAL: Lazy<u32> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_INTERVAL")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
pub static SCENE_VLM_SAMPLES: Lazy<usize> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_SAMPLES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
pub static SCENE_VLM_USE_CUTS: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_USE_CUTS")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
pub static SCENE_VLM_MAX_WORKERS: Lazy<usize> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_MAX_WORKERS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
(
*SCENE_VLM_ENABLED,
*SCENE_VLM_INTERVAL,
*SCENE_VLM_SAMPLES,
*SCENE_VLM_USE_CUTS,
*SCENE_VLM_MAX_WORKERS,
)
}
// ─────────────────────────────────────────────────────────────
// JSON-backed configs (paths, concurrency, feature flags)
// These read from admin_config.json with ENV fallback
// ─────────────────────────────────────────────────────────────
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| {
crate::core::admin_config::get_output_dir()
});
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_output_dir());
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| {
crate::core::admin_config::get_backup_dir()
});
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_backup_dir());
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| {
crate::core::admin_config::get_scripts_dir()
});
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_scripts_dir());
pub static PYTHON_PATH: Lazy<String> = Lazy::new(|| {
crate::core::admin_config::get_python_path()
});
pub static PYTHON_PATH: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_python_path());
pub static MEDIA_BASE_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_MEDIA_BASE_URL")
@@ -347,4 +396,4 @@ pub mod processor {
.map(|v| v == "true" || v == "1")
.unwrap_or(false)
});
}
}
+6 -5
View File
@@ -45,12 +45,13 @@ pub use identity_merge_history::{
};
pub use mongodb_db::MongoDb;
pub use postgres_db::{
Bm25Result, CandidateRecord, CreateApiKeyConfig, FileFaceRecord, FileIdentityRecord,
FileRecord, HybridSearchResult, IdentityChunkRecord, IdentityDetailRecord, IdentityFaceRecord,
IdentityFileRecord, MonitorJob, MonitorJobStats, MonitorJobStatus, PipelineType, PostgresDb,
ProcessorJobStatus, ProcessorResult, ProcessorType, ResourceRecord, VideoRecord, VideoStatus,
Bm25Result, CandidateRecord, CommandJob, CommandJobStatus, CreateApiKeyConfig, FileFaceRecord,
FileIdentityRecord, FileRecord, HybridSearchResult, IdentityChunkRecord, IdentityDetailRecord,
IdentityFaceRecord, IdentityFileRecord, MonitorJob, MonitorJobStats, MonitorJobStatus,
PipelineType, PostgresDb, ProcessorJobStatus, ProcessorResult, ProcessorType, ResourceRecord,
VideoRecord, VideoStatus,
};
pub use qdrant_db::{QdrantDb, VectorPayload};
pub use qdrant_db::{QdrantDb, VectorPayload, SCENES_COLLECTION};
pub use redis_client::{
JobErrorMessage, MonitorJobRedis, ProcessorStatus as RedisProcessorStatus, ProgressData,
ProgressMessage, RedisClient,
+622 -33
View File
@@ -22,17 +22,18 @@ fn calculate_ocr_quality(text: &str) -> f64 {
if text.len() < 10 {
return 0.0;
}
let special_chars = text.chars()
let special_chars = text
.chars()
.filter(|c| !c.is_alphanumeric() && !c.is_whitespace())
.count();
let special_ratio = special_chars as f64 / text.len() as f64;
let has_gibberish = text.contains("toogunme")
let has_gibberish = text.contains("toogunme")
|| text.contains("ine coRe")
|| text.contains("sali mal")
|| text.contains("Long toogunme");
if has_gibberish {
0.3
} else if special_ratio > 0.3 {
@@ -489,6 +490,59 @@ pub struct MonitorJob {
pub face_settings: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CommandJobStatus {
Pending,
Running,
Completed,
Failed,
Cancelled,
}
impl CommandJobStatus {
pub fn as_str(&self) -> &'static str {
match self {
CommandJobStatus::Pending => "pending",
CommandJobStatus::Running => "running",
CommandJobStatus::Completed => "completed",
CommandJobStatus::Failed => "failed",
CommandJobStatus::Cancelled => "cancelled",
}
}
pub fn from_db_str(s: &str) -> Option<Self> {
match s {
"pending" => Some(CommandJobStatus::Pending),
"running" => Some(CommandJobStatus::Running),
"completed" => Some(CommandJobStatus::Completed),
"failed" => Some(CommandJobStatus::Failed),
"cancelled" => Some(CommandJobStatus::Cancelled),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandJob {
pub id: i32,
pub command_id: String,
pub job_type: String,
pub file_path: Option<String>,
pub file_uuid: Option<String>,
pub user_id: Option<i64>,
pub payload: serde_json::Value,
pub status: CommandJobStatus,
pub priority: i32,
pub error_count: i32,
pub last_error: Option<String>,
pub retry_count: i32,
pub started_at: Option<String>,
pub completed_at: Option<String>,
pub updated_at: Option<String>,
pub created_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitorJobStats {
pub pending: i32,
@@ -497,6 +551,29 @@ pub struct MonitorJobStats {
pub failed: i32,
}
pub fn parse_command_job(row: sqlx::postgres::PgRow) -> CommandJob {
let status_str: String = row.get(7);
let status = CommandJobStatus::from_db_str(&status_str).unwrap_or(CommandJobStatus::Pending);
CommandJob {
id: row.get::<i32, _>(0),
command_id: row.get(1),
job_type: row.get(2),
file_path: row.get(3),
file_uuid: row.get(4),
user_id: row.get(5),
payload: row.get::<serde_json::Value, _>(6),
status,
priority: row.get(8),
error_count: row.get(9),
last_error: row.get(10),
retry_count: row.get(11),
started_at: row.get(12),
completed_at: row.get(13),
updated_at: row.get(14),
created_at: row.get(15),
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PipelineType {
@@ -1178,6 +1255,47 @@ impl PostgresDb {
.execute(pool)
.await?;
// ── Command Queue (register/unregister async commands) ──
sqlx::query("CREATE TABLE IF NOT EXISTS command_queue (id SERIAL PRIMARY KEY, command_id VARCHAR(36) NOT NULL DEFAULT replace(gen_random_uuid()::text, '-', ''), job_type VARCHAR(20) NOT NULL, file_path VARCHAR(512), file_uuid VARCHAR(32), user_id BIGINT, payload JSONB DEFAULT '{}', status VARCHAR(20) NOT NULL DEFAULT 'pending', priority INT DEFAULT 0, error_count INT DEFAULT 0, last_error TEXT, retry_count INT DEFAULT 0, started_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP)").execute(pool).await?;
sqlx::query("CREATE UNIQUE INDEX IF NOT EXISTS idx_command_queue_command_id ON command_queue(command_id)")
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_command_queue_status_created ON command_queue(status, created_at)")
.execute(pool)
.await?;
// ── Token Usage Logs (billing monitoring) ──
sqlx::query("CREATE TABLE IF NOT EXISTS token_usage_logs (id BIGSERIAL PRIMARY KEY, request_id VARCHAR(36) NOT NULL, key_id VARCHAR(48), service VARCHAR(32) NOT NULL, model VARCHAR(64), endpoint VARCHAR(255), input_tokens INT DEFAULT 0, output_tokens INT DEFAULT 0, total_tokens INT DEFAULT 0, duration_ms INT, status_code INT DEFAULT 200, error_message TEXT, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP)").execute(pool).await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_token_usage_request ON token_usage_logs(request_id)",
)
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_token_usage_key_date ON token_usage_logs(key_id, created_at)")
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_token_usage_service ON token_usage_logs(service, created_at)")
.execute(pool)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_token_usage_created ON token_usage_logs(created_at)",
)
.execute(pool)
.await?;
// ── Billing Periods (monthly aggregates) ──
sqlx::query("CREATE TABLE IF NOT EXISTS billing_periods (id SERIAL PRIMARY KEY, key_id VARCHAR(48), period_month VARCHAR(7) NOT NULL, total_input_tokens BIGINT DEFAULT 0, total_output_tokens BIGINT DEFAULT 0, total_tokens BIGINT DEFAULT 0, request_count BIGINT DEFAULT 0, error_count BIGINT DEFAULT 0, service_breakdown JSONB DEFAULT '{}', model_breakdown JSONB DEFAULT '{}', avg_duration_ms INT, total_duration_ms BIGINT, period_start DATE NOT NULL, period_end DATE NOT NULL, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, UNIQUE(key_id, period_month))").execute(pool).await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_billing_periods_key ON billing_periods(key_id)",
)
.execute(pool)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_billing_periods_month ON billing_periods(period_month)",
)
.execute(pool)
.await?;
// ── Processor Results ──
sqlx::query("CREATE TABLE IF NOT EXISTS processor_results (id SERIAL PRIMARY KEY, job_id INTEGER, file_uuid VARCHAR(255), processor VARCHAR(64), processor_type VARCHAR(64), status VARCHAR(32) DEFAULT 'pending', result JSONB, error_message TEXT, started_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, duration_secs DOUBLE PRECISION, chunks_produced INTEGER DEFAULT 0, frames_processed INTEGER DEFAULT 0, output_size_bytes BIGINT DEFAULT 0, output_path TEXT, progress_total INTEGER DEFAULT 0, progress_current INTEGER DEFAULT 0, last_checkpoint JSONB, retry_count INTEGER DEFAULT 0, output_data JSONB, uuid VARCHAR(255))").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_pr_uuid ON processor_results(file_uuid)")
@@ -1332,6 +1450,23 @@ impl PostgresDb {
.execute(pool)
.await?;
// ── Scenes ──
sqlx::query("CREATE TABLE IF NOT EXISTS scenes (id BIGSERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, scene_index INTEGER NOT NULL, timestamp_sec DOUBLE PRECISION NOT NULL, frame_number BIGINT NOT NULL, filename VARCHAR(255) NOT NULL, selection_reason VARCHAR(50), quality_score DOUBLE PRECISION, quality_source VARCHAR(100), vlm_status VARCHAR(20) DEFAULT 'pending', vlm_description TEXT, vlm_scene_type VARCHAR(100), vlm_location VARCHAR(255), vlm_objects JSONB DEFAULT '[]', vlm_tags JSONB DEFAULT '[]', vlm_attributes JSONB, face_count INTEGER DEFAULT 0, person_traces JSONB DEFAULT '[]', has_cut BOOLEAN DEFAULT false, cut_count INTEGER DEFAULT 0, scene_info JSONB, embedding_status VARCHAR(20) DEFAULT 'pending', embedding_point_id VARCHAR(64), created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, UNIQUE(file_uuid, scene_index))").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_file_uuid ON scenes(file_uuid)")
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_tags ON scenes USING GIN(vlm_tags)")
.execute(pool)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_scenes_objects ON scenes USING GIN(vlm_objects)",
)
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_timestamp ON scenes(timestamp_sec)")
.execute(pool)
.await?;
// ── Cuts ──
sqlx::query("CREATE TABLE IF NOT EXISTS cuts (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, cut_number INTEGER NOT NULL, start_frame BIGINT NOT NULL, end_frame BIGINT NOT NULL, start_time DOUBLE PRECISION, end_time DOUBLE PRECISION, fps DOUBLE PRECISION, metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, cut_number))").execute(pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_cuts_file_uuid ON cuts(file_uuid)")
@@ -1542,23 +1677,74 @@ impl PostgresDb {
// ── Record migrations in schema_migrations table ──
let migrations = [
("migrate_add_content_hash.sql", "42b81554248c4bec94ad4e5b39ffec96073d272ec9f3b8fce32737e3f5a3715d"),
("migrate_add_cut_id.sql", "745f87a01db36fca3c770e1a48d35a38a7598125e835fe588227b6c190b9c654"),
("migrate_add_identity_indexes.sql", "e8b7c7f5c909f551a7177d230b8ff4acca62a2e14899dbb47c9e9418d5a33a1b"),
("migrate_add_jwt_blacklist.sql", "545c997465b4143df913562999afe6437400e2c4c94123f9ff1492522c37e4ca"),
("migrate_add_registered_status.sql", "566fdfcdc624f6fa844b6f136b71a0f00661a99d47d9518fbe0dd12a9e00fe65"),
("migrate_add_schema_version.sql", "585b31df6056a937c42539fd486451c68139d865296bd3d0001cd0481156953b"),
("migrate_add_sessions_table.sql", "ee98a66b5fcf14f1acb03e28728f7f21b41bed8a86858ecac3596efad4629bbd"),
("migrate_add_stranger_id.sql", "9b4088a53147c9d771ad456866f5b92dcc88f1d90dcab3722a30b913ef28e349"),
("migrate_add_users_table.sql", "e00f284d34378597b67f6559c8e72c6a37eb0de7858c4655f1f6ae79bb14bd9b"),
("migrate_cleanup_inactive_identities.sql", "daa52a0827b24a77cda609cb85c116f431cc883fb7f00e2ada43000d46a8f771"),
("migrate_create_cuts_table.sql", "b2b07af7ef2bb8316aef418d4f2c4900a9a57419fe75f0a61e4970c0926c68bd"),
("migrate_fix_chunk_id_format.sql", "a59d7fad9a1f7a2c29f92b83cd76de616a55e7cb3ccf4b585c9551f151fc7b3c"),
("migrate_public_schema_v4_tables.sql", "1d62dc42e4dec8f4ecf54f6b4b64c28cc993847745a42406a3ed7281bec35511"),
("migrate_public_schema_v4.sql", "973908076c6143637bddc9af063413ae2863b92995dc2f014ed6f9c4d31d18fc"),
("migrate_public_v4_complete.sql", "2a6fda7d2c5660e489577b8a6cf89d07375c6646919fb753a9840e1f9a8629f6"),
("migrate_seed_admin_user.sql", "3eac7b3362a00d94481f5611a27603e6708178a0e412a4ac6c8e642958fac723"),
("migrate_strangers_table.sql", "1900ae28ebf5532c05165690f53f22ae852ce2d0ba53e5002b01daf5d36d97bf"),
(
"migrate_add_content_hash.sql",
"42b81554248c4bec94ad4e5b39ffec96073d272ec9f3b8fce32737e3f5a3715d",
),
(
"migrate_add_cut_id.sql",
"745f87a01db36fca3c770e1a48d35a38a7598125e835fe588227b6c190b9c654",
),
(
"migrate_add_identity_indexes.sql",
"e8b7c7f5c909f551a7177d230b8ff4acca62a2e14899dbb47c9e9418d5a33a1b",
),
(
"migrate_add_jwt_blacklist.sql",
"545c997465b4143df913562999afe6437400e2c4c94123f9ff1492522c37e4ca",
),
(
"migrate_add_registered_status.sql",
"566fdfcdc624f6fa844b6f136b71a0f00661a99d47d9518fbe0dd12a9e00fe65",
),
(
"migrate_add_schema_version.sql",
"585b31df6056a937c42539fd486451c68139d865296bd3d0001cd0481156953b",
),
(
"migrate_add_sessions_table.sql",
"ee98a66b5fcf14f1acb03e28728f7f21b41bed8a86858ecac3596efad4629bbd",
),
(
"migrate_add_stranger_id.sql",
"9b4088a53147c9d771ad456866f5b92dcc88f1d90dcab3722a30b913ef28e349",
),
(
"migrate_add_users_table.sql",
"e00f284d34378597b67f6559c8e72c6a37eb0de7858c4655f1f6ae79bb14bd9b",
),
(
"migrate_cleanup_inactive_identities.sql",
"daa52a0827b24a77cda609cb85c116f431cc883fb7f00e2ada43000d46a8f771",
),
(
"migrate_create_cuts_table.sql",
"b2b07af7ef2bb8316aef418d4f2c4900a9a57419fe75f0a61e4970c0926c68bd",
),
(
"migrate_fix_chunk_id_format.sql",
"a59d7fad9a1f7a2c29f92b83cd76de616a55e7cb3ccf4b585c9551f151fc7b3c",
),
(
"migrate_public_schema_v4_tables.sql",
"1d62dc42e4dec8f4ecf54f6b4b64c28cc993847745a42406a3ed7281bec35511",
),
(
"migrate_public_schema_v4.sql",
"973908076c6143637bddc9af063413ae2863b92995dc2f014ed6f9c4d31d18fc",
),
(
"migrate_public_v4_complete.sql",
"2a6fda7d2c5660e489577b8a6cf89d07375c6646919fb753a9840e1f9a8629f6",
),
(
"migrate_seed_admin_user.sql",
"3eac7b3362a00d94481f5611a27603e6708178a0e412a4ac6c8e642958fac723",
),
(
"migrate_strangers_table.sql",
"1900ae28ebf5532c05165690f53f22ae852ce2d0ba53e5002b01daf5d36d97bf",
),
];
for (filename, checksum) in &migrations {
@@ -1708,6 +1894,18 @@ impl PostgresDb {
Ok(chain)
}
/// Returns the set of `file_uuid`s that are currently present in the
/// `videos` table (i.e. registered in the DB). Vectors left behind in
/// Qdrant after an unregister should be filtered against this whitelist
/// before surfacing in search results.
pub async fn get_active_file_uuids(&self) -> Result<std::collections::HashSet<String>> {
let table = schema::table_name("videos");
let rows: Vec<String> = sqlx::query_scalar(&format!("SELECT file_uuid FROM {}", table))
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().collect())
}
pub async fn get_videos_by_uuids(&self, uuids: &[String]) -> Result<Vec<VideoRecord>> {
if uuids.is_empty() {
return Ok(vec![]);
@@ -2130,6 +2328,301 @@ impl PostgresDb {
})
}
pub async fn create_command(
&self,
job_type: &str,
file_path: Option<&str>,
file_uuid: Option<&str>,
user_id: Option<i64>,
payload: &serde_json::Value,
priority: i32,
) -> Result<CommandJob> {
let table = schema::table_name("command_queue");
let row = sqlx::query(
&format!(
r#"
INSERT INTO {} (job_type, file_path, file_uuid, user_id, payload, priority, status)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, 'pending')
RETURNING id, command_id, job_type, file_path, file_uuid, user_id, payload, status, priority, error_count, last_error, retry_count, started_at::TEXT, completed_at::TEXT, updated_at::TEXT, created_at::TEXT
"#,
table
)
)
.bind(job_type)
.bind(file_path)
.bind(file_uuid)
.bind(user_id)
.bind(payload.to_string())
.bind(priority)
.fetch_one(&self.pool)
.await?;
Ok(parse_command_job(row))
}
pub async fn claim_pending_commands(&self, limit: i32) -> Result<Vec<CommandJob>> {
let table = schema::table_name("command_queue");
let rows = sqlx::query(
&format!(
r#"
WITH claimed AS (
SELECT id FROM {} WHERE status = 'pending'
ORDER BY priority DESC, created_at ASC
FOR UPDATE SKIP LOCKED LIMIT $1
)
UPDATE {} cq SET status = 'running', started_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
FROM claimed WHERE cq.id = claimed.id
RETURNING cq.id, cq.command_id, cq.job_type, cq.file_path, cq.file_uuid, cq.user_id, cq.payload, cq.status, cq.priority, cq.error_count, cq.last_error, cq.retry_count, cq.started_at::TEXT, cq.completed_at::TEXT, cq.updated_at::TEXT, cq.created_at::TEXT
"#,
table,
table
)
)
.bind(limit)
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(parse_command_job).collect())
}
pub async fn update_command_status(
&self,
command_id: &str,
status: CommandJobStatus,
error_message: Option<&str>,
) -> Result<()> {
let table = schema::table_name("command_queue");
let (status_clause, completed_clause, retry_clause, error_clause, has_error_bind) =
match status {
CommandJobStatus::Running => (
"status = $1, started_at = COALESCE(started_at, CURRENT_TIMESTAMP)",
"",
"",
"",
false,
),
CommandJobStatus::Completed => (
"status = $1",
", completed_at = CURRENT_TIMESTAMP",
"",
", last_error = NULL",
false,
),
CommandJobStatus::Failed => (
"status = $1",
", completed_at = CURRENT_TIMESTAMP",
", retry_count = retry_count + 1",
if error_message.is_some() {
", last_error = $3"
} else {
""
},
error_message.is_some(),
),
_ => ("status = $1", "", "", "", false),
};
let sql = format!(
"UPDATE {} SET {}{}{}{}, updated_at = CURRENT_TIMESTAMP WHERE command_id = $2",
table, status_clause, completed_clause, retry_clause, error_clause
);
let mut query = sqlx::query(&sql).bind(status.as_str()).bind(command_id);
if has_error_bind {
query = query.bind(error_message.unwrap_or(""));
}
query.execute(&self.pool).await?;
Ok(())
}
pub async fn get_command_by_id(&self, command_id: &str) -> Result<Option<CommandJob>> {
let table = schema::table_name("command_queue");
let row = sqlx::query(
&format!(
r#"
SELECT id, command_id, job_type, file_path, file_uuid, user_id, payload, status, priority, error_count, last_error, retry_count, started_at::TEXT, completed_at::TEXT, updated_at::TEXT, created_at::TEXT
FROM {} WHERE command_id = $1
"#,
table
)
)
.bind(command_id)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(parse_command_job))
}
// ── Token Usage Billing Methods ──
pub async fn log_token_usage(&self, log: &crate::core::billing::LogTokenUsage) -> Result<()> {
let table = schema::table_name("token_usage_logs");
sqlx::query(&format!(
r#"
INSERT INTO {} (
request_id, key_id, service, model, endpoint,
input_tokens, output_tokens, total_tokens,
duration_ms, status_code, error_message
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
"#,
table
))
.bind(&log.request_id)
.bind(&log.key_id)
.bind(&log.service)
.bind(&log.model)
.bind(&log.endpoint)
.bind(log.input_tokens as i32)
.bind(log.output_tokens as i32)
.bind(log.total_tokens as i32)
.bind(log.duration_ms)
.bind(log.status_code)
.bind(&log.error_message)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn get_billing_usage(
&self,
key_id: Option<&str>,
period_month: &str,
) -> Result<Option<crate::core::billing::BillingPeriod>> {
let table = schema::table_name("billing_periods");
let row = sqlx::query(&format!(
"SELECT id, key_id, period_month, total_input_tokens, total_output_tokens, total_tokens, request_count, error_count, service_breakdown, model_breakdown, avg_duration_ms, total_duration_ms, period_start::text, period_end::text FROM {} WHERE key_id = $1 AND period_month = $2",
table
))
.bind(key_id)
.bind(period_month)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(|r| crate::core::billing::BillingPeriod {
id: r.get("id"),
key_id: r.get("key_id"),
period_month: r.get("period_month"),
total_input_tokens: r.get("total_input_tokens"),
total_output_tokens: r.get("total_output_tokens"),
total_tokens: r.get("total_tokens"),
request_count: r.get("request_count"),
error_count: r.get("error_count"),
service_breakdown: r.get("service_breakdown"),
model_breakdown: r.get("model_breakdown"),
avg_duration_ms: r.get("avg_duration_ms"),
total_duration_ms: r.get("total_duration_ms"),
period_start: r.get("period_start"),
period_end: r.get("period_end"),
}))
}
pub async fn get_billing_history(
&self,
key_id: Option<&str>,
limit: i32,
) -> Result<Vec<crate::core::billing::PeriodSummary>> {
let table = schema::table_name("billing_periods");
let rows = sqlx::query(&format!(
"SELECT period_month, total_tokens, request_count FROM {} WHERE key_id = $1 ORDER BY period_month DESC LIMIT $2",
table
))
.bind(key_id)
.bind(limit)
.fetch_all(&self.pool)
.await?;
Ok(rows
.into_iter()
.map(|r| crate::core::billing::PeriodSummary {
period: r.get("period_month"),
total_tokens: r.get("total_tokens"),
request_count: r.get("request_count"),
})
.collect())
}
pub async fn aggregate_monthly_billing(&self, period_month: &str) -> Result<i64> {
let logs_table = schema::table_name("token_usage_logs");
let periods_table = schema::table_name("billing_periods");
let rows: Vec<(Option<String>, i64, i64, i64, i64, i64)> = sqlx::query_as(&format!(
r#"
SELECT key_id,
SUM(input_tokens) as total_input,
SUM(output_tokens) as total_output,
SUM(total_tokens) as total_tokens,
COUNT(*) as request_count,
SUM(CASE WHEN status_code >= 400 THEN 1 ELSE 0 END) as error_count
FROM {}
WHERE to_char(created_at, 'YYYY-MM') = $1
GROUP BY key_id
"#,
logs_table
))
.bind(period_month)
.fetch_all(&self.pool)
.await?;
let period_start = format!("{}-01", period_month);
let period_end = if period_month.ends_with("-12") {
format!("{}-31", period_month)
} else {
let parts: Vec<&str> = period_month.split('-').collect();
let year: i32 = parts[0].parse().unwrap_or(2026);
let month: i32 = parts[1].parse().unwrap_or(1);
format!("{}-{:02}-{:02}", year, month + 1, 1)
};
let mut count = 0i64;
for (key_id, total_input, total_output, total_tokens, request_count, error_count) in rows {
sqlx::query(&format!(
r#"
INSERT INTO {} (key_id, period_month, total_input_tokens, total_output_tokens, total_tokens, request_count, error_count, period_start, period_end)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (key_id, period_month) DO UPDATE SET
total_input_tokens = $3,
total_output_tokens = $4,
total_tokens = $5,
request_count = $6,
error_count = $7,
updated_at = CURRENT_TIMESTAMP
"#,
periods_table
))
.bind(&key_id)
.bind(period_month)
.bind(total_input)
.bind(total_output)
.bind(total_tokens)
.bind(request_count)
.bind(error_count)
.bind(&period_start)
.bind(&period_end)
.execute(&self.pool)
.await?;
count += 1;
}
Ok(count)
}
pub async fn cleanup_old_usage_logs(&self, months_to_keep: i32) -> Result<u64> {
let table = schema::table_name("token_usage_logs");
let cutoff = chrono::Utc::now() - chrono::Duration::days(months_to_keep as i64 * 30);
let result = sqlx::query(&format!("DELETE FROM {} WHERE created_at < $1", table))
.bind(cutoff)
.execute(&self.pool)
.await?;
Ok(result.rows_affected())
}
pub async fn update_video_job_id(&self, video_id: i64, job_id: i32) -> Result<()> {
let videos = schema::table_name("videos");
sqlx::query(&format!(
@@ -2900,7 +3393,7 @@ impl PostgresDb {
let table = schema::table_name("videos");
let status_str = status.as_str();
sqlx::query(&format!(
"UPDATE {} SET status = $1 WHERE file_uuid = $2",
"UPDATE {} SET status = $1, updated_at = CURRENT_TIMESTAMP WHERE file_uuid = $2",
table
))
.bind(status_str)
@@ -3390,19 +3883,26 @@ impl PostgresDb {
) -> Result<()> {
let table = schema::table_name("processor_results");
let s = format!("{:?}", status).to_lowercase();
let query = match status {
crate::core::db::ProcessorJobStatus::Running => {
format!("UPDATE {} SET status = $1, started_at = CURRENT_TIMESTAMP WHERE id = $2", table)
format!(
"UPDATE {} SET status = $1, started_at = CURRENT_TIMESTAMP WHERE id = $2",
table
)
}
crate::core::db::ProcessorJobStatus::Completed | crate::core::db::ProcessorJobStatus::Failed => {
format!("UPDATE {} SET status = $1, completed_at = CURRENT_TIMESTAMP WHERE id = $2", table)
crate::core::db::ProcessorJobStatus::Completed
| crate::core::db::ProcessorJobStatus::Failed => {
format!(
"UPDATE {} SET status = $1, completed_at = CURRENT_TIMESTAMP WHERE id = $2",
table
)
}
_ => {
format!("UPDATE {} SET status = $1 WHERE id = $2", table)
}
};
sqlx::query(&query)
.bind(&s)
.bind(result_id)
@@ -3430,6 +3930,94 @@ impl PostgresDb {
Ok(())
}
pub async fn upsert_scene_vlm_result(&self, file_uuid: &str, status: &str) -> Result<()> {
let table = schema::table_name("processor_results");
let updated = sqlx::query(&format!(
"UPDATE {} SET status = $1, updated_at = CURRENT_TIMESTAMP \
WHERE file_uuid = $2 AND processor_type = 'scene_vlm'",
table
))
.bind(status)
.bind(file_uuid)
.execute(&self.pool)
.await?;
if updated.rows_affected() == 0 {
sqlx::query(&format!(
"INSERT INTO {} (file_uuid, processor_type, processor, status, created_at, updated_at) \
VALUES ($1, 'scene_vlm', 'scene_vlm', $2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
table
))
.bind(file_uuid)
.bind(status)
.execute(&self.pool)
.await?;
}
Ok(())
}
pub async fn mark_scene_vlm_failed(&self, file_uuid: &str) -> Result<()> {
let table = schema::table_name("processor_results");
// scene_vlm rows have job_id = NULL, so ON CONFLICT (job_id, processor_type)
// never matches (NULLs are distinct in unique indexes). Use UPDATE-then-INSERT
// so we never create duplicate scene_vlm rows.
let updated = sqlx::query(&format!(
"UPDATE {} SET status = 'failed', \
retry_count = COALESCE(retry_count, 0) + 1, \
error_message = 'Scene VLM failed, will be retried on next poll', \
updated_at = CURRENT_TIMESTAMP \
WHERE file_uuid = $1 AND processor_type = 'scene_vlm'",
table
))
.bind(file_uuid)
.execute(&self.pool)
.await?;
if updated.rows_affected() == 0 {
sqlx::query(&format!(
"INSERT INTO {} (file_uuid, processor_type, processor, status, retry_count, error_message, created_at, updated_at) \
VALUES ($1, 'scene_vlm', 'scene_vlm', 'failed', 1, 'Scene VLM failed, will be retried on next poll', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
table
))
.bind(file_uuid)
.execute(&self.pool)
.await?;
}
Ok(())
}
pub async fn get_scene_vlm_retry_count(&self, file_uuid: &str) -> i32 {
let table = schema::table_name("processor_results");
sqlx::query_scalar::<_, i32>(&format!(
"SELECT COALESCE(MAX(retry_count), 0) FROM {} WHERE file_uuid = $1 AND processor_type = 'scene_vlm'",
table
))
.bind(file_uuid)
.fetch_one(&self.pool)
.await
.unwrap_or(0)
}
pub async fn update_scene_vlm_progress(
&self,
file_uuid: &str,
progress_current: i32,
progress_total: i32,
) -> Result<()> {
let table = schema::table_name("processor_results");
sqlx::query(&format!(
"UPDATE {} SET progress_current = $1, progress_total = $2, updated_at = CURRENT_TIMESTAMP \
WHERE file_uuid = $3 AND processor_type = 'scene_vlm'",
table
))
.bind(progress_current)
.bind(progress_total)
.bind(file_uuid)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn update_asr_status(
&self,
result_id: i32,
@@ -3681,7 +4269,8 @@ impl PostgresDb {
let like = format!("%{}%", term.replace('%', "%%"));
like_clauses.push(format!(
"(text_content ILIKE ${} OR content::text ILIKE ${})",
param_idx, param_idx + 1
param_idx,
param_idx + 1
));
like_patterns.push(like.clone());
like_patterns.push(like);
@@ -3695,7 +4284,7 @@ impl PostgresDb {
format!("({})", like_sql),
"COALESCE(text_content, content::text, '') != ''".to_string(),
];
if file_uuid.is_some() {
clauses.push(format!("file_uuid = ${}", param_idx));
param_idx += 1;
@@ -3726,12 +4315,12 @@ impl PostgresDb {
// Bind parameters
let mut q = sqlx::query(&sql);
// Bind all LIKE patterns (pairs for text_content and content::text)
for pattern in &like_patterns {
q = q.bind(pattern);
}
// Bind optional parameters
if let Some(u) = file_uuid {
q = q.bind(u);
@@ -3740,7 +4329,7 @@ impl PostgresDb {
q = q.bind(ct);
}
q = q.bind(limit);
let rows = q.fetch_all(&self.pool).await?;
// Phase 2: Filter low-quality OCR results
+182 -2
View File
@@ -6,6 +6,8 @@ use std::collections::HashMap;
use super::{Database, SearchResult, VectorStore};
pub const SCENES_COLLECTION: &str = "_scenes";
pub struct QdrantDb {
pub client: Client,
pub base_url: String,
@@ -725,7 +727,7 @@ impl QdrantDb {
}
});
client
let resp = client
.post(&url)
.header("api-key", api_key)
.header("Content-Type", "application/json")
@@ -737,6 +739,18 @@ impl QdrantDb {
collection
))?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
anyhow::bail!(
"Qdrant delete failed for collection {} (uuid {}): {} - {}",
collection,
uuid,
status,
text
);
}
Ok(())
}
@@ -861,7 +875,10 @@ impl QdrantDb {
);
let mut payload_map = std::collections::HashMap::new();
payload_map.insert("file_uuid".to_string(), serde_json::json!(file_uuid));
payload_map.insert("chunk_id".to_string(), serde_json::json!(point_id.to_string()));
payload_map.insert(
"chunk_id".to_string(),
serde_json::json!(point_id.to_string()),
);
payload_map.insert("chunk_type".to_string(), serde_json::json!(chunk_type));
payload_map.insert("text".to_string(), serde_json::json!(text));
payload_map.insert("start_time".to_string(), serde_json::json!(start_time));
@@ -931,6 +948,169 @@ impl QdrantDb {
Ok(())
}
pub async fn upsert_scene_embedding(
&self,
point_id: u64,
vector: &[f32],
file_uuid: &str,
scene_index: usize,
timestamp_sec: f64,
frame_number: u32,
vlm_description: &str,
vlm_objects: &[String],
vlm_tags: &[String],
) -> Result<()> {
let url = format!(
"{}/collections/{}/points?wait=true",
self.base_url, SCENES_COLLECTION
);
let mut payload_map = std::collections::HashMap::new();
payload_map.insert("file_uuid".to_string(), serde_json::json!(file_uuid));
payload_map.insert("scene_index".to_string(), serde_json::json!(scene_index));
payload_map.insert(
"timestamp_sec".to_string(),
serde_json::json!(timestamp_sec),
);
payload_map.insert("frame_number".to_string(), serde_json::json!(frame_number));
payload_map.insert(
"vlm_description".to_string(),
serde_json::json!(vlm_description),
);
payload_map.insert("vlm_objects".to_string(), serde_json::json!(vlm_objects));
payload_map.insert("vlm_tags".to_string(), serde_json::json!(vlm_tags));
let point = serde_json::json!({
"points": [{
"id": point_id,
"vector": vector,
"payload": payload_map
}]
});
let resp = self
.client
.put(&url)
.header("api-key", &self.api_key)
.json(&point)
.send()
.await?;
if !resp.status().is_success() {
anyhow::bail!("Qdrant upsert scene failed: {}", resp.status());
}
Ok(())
}
pub async fn search_scenes(
&self,
query_vector: &[f32],
file_uuid: Option<&str>,
limit: usize,
) -> Result<Vec<serde_json::Value>> {
let url = format!(
"{}/collections/{}/points/search",
self.base_url, SCENES_COLLECTION
);
let mut filter = None;
if let Some(uuid) = file_uuid {
filter = Some(serde_json::json!({
"must": [
{
"key": "file_uuid",
"match": { "value": uuid }
}
]
}));
}
let body = serde_json::json!({
"vector": query_vector,
"limit": limit,
"with_payload": true,
"filter": filter
});
let resp = self
.client
.post(&url)
.header("api-key", &self.api_key)
.header("Content-Type", "application/json")
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
anyhow::bail!("Qdrant search scenes failed: {}", resp.status());
}
let result: serde_json::Value = resp.json().await?;
let results = result
.get("result")
.and_then(|r| r.as_array())
.map(|arr| arr.clone())
.unwrap_or_default();
Ok(results)
}
/// Search trace VLM summary vectors in the main collection
/// (chunk_type = "vlm_summary", produced by vlm_summary processor).
pub async fn search_trace_vlm(
&self,
query_vector: &[f32],
file_uuid: Option<&str>,
limit: usize,
) -> Result<Vec<serde_json::Value>> {
let url = format!(
"{}/collections/{}/points/search",
self.base_url, self.collection_name
);
let mut conditions = vec![serde_json::json!({
"key": "chunk_type",
"match": { "value": "vlm_summary" }
})];
if let Some(uuid) = file_uuid {
conditions.push(serde_json::json!({
"key": "file_uuid",
"match": { "value": uuid }
}));
}
let body = serde_json::json!({
"vector": query_vector,
"limit": limit,
"with_payload": true,
"filter": {
"must": conditions
}
});
let resp = self
.client
.post(&url)
.header("api-key", &self.api_key)
.header("Content-Type", "application/json")
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
anyhow::bail!("Qdrant search trace VLM failed: {}", resp.status());
}
let result: serde_json::Value = resp.json().await?;
let results = result
.get("result")
.and_then(|r| r.as_array())
.map(|arr| arr.clone())
.unwrap_or_default();
Ok(results)
}
/// Scroll points matching a filter, returning payload data (single page)
pub async fn scroll_points(
&self,
+190 -6
View File
@@ -1,10 +1,15 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, Serializer};
use std::path::{Path, PathBuf};
/// Version of the file profile schema.
const PROFILE_VERSION: &str = "1.0";
/// Helper function to serialize f64 with 2 decimal places
fn serialize_f64_2dec<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_f64((*value * 100.0).round() / 100.0)
}
// ─── Data Types ───
/// Per-file face detection thresholds. `min_confidence` is 0–100 (%),
@@ -15,7 +20,7 @@ pub struct FaceFilterSettings {
pub min_size: i32,
#[serde(default)]
pub min_capture_quality: f64,
// Single Frame Trace 配置
#[serde(default = "default_true")]
pub single_frame_trace_vlm_enabled: bool,
@@ -23,21 +28,23 @@ pub struct FaceFilterSettings {
pub single_frame_trace_group_enabled: bool,
#[serde(default = "default_true")]
pub single_frame_trace_unassigned_enabled: bool,
// Single Trace Group 配置
#[serde(default = "default_true")]
pub single_trace_group_filter_enabled: bool,
}
fn default_true() -> bool { true }
fn default_true() -> bool {
true
}
impl FaceFilterSettings {
/// Load defaults from admin config (processor_config.face).
/// Falls back to hardcoded values if admin config unavailable.
pub fn defaults() -> Self {
let (min_confidence, min_size, min_capture_quality) =
let (min_confidence, min_size, min_capture_quality) =
crate::core::admin_config::get_face_filter_defaults();
Self {
min_confidence,
min_size,
@@ -613,6 +620,179 @@ pub fn count_face_artifacts(output_dir: &str, file_uuid: &str) -> FaceArtifactsC
counts
}
// ─── Scene VLM Profile ───
/// Scene VLM profile stored in `output/{file_uuid}.scenes.json`.
/// Contains selected scene key frames and their VLM analysis results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneProfile {
pub version: String,
pub file_uuid: String,
pub status: SceneStatus,
pub video_info: VideoInfo,
pub config: SceneConfig,
pub total_scenes: usize,
pub created_at: chrono::DateTime<chrono::Utc>,
pub updated_at: chrono::DateTime<chrono::Utc>,
pub scenes: Vec<SceneFrame>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SceneStatus {
Pending,
Ready,
Processing,
Completed,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoInfo {
pub duration_sec: f64,
pub fps: f64,
pub width: u32,
pub height: u32,
pub total_frames: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneConfig {
pub interval_sec: u32,
pub use_cuts: bool,
pub use_faces: bool,
pub quality_metric: String,
pub samples_per_interval: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneFrame {
pub index: usize,
pub filename: String,
#[serde(serialize_with = "serialize_f64_2dec")]
pub timestamp_sec: f64,
pub frame_number: u32,
pub selection_reason: SelectionReason,
#[serde(skip_serializing_if = "Option::is_none")]
pub quality_score: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quality_source: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scene_info: Option<SceneInfo>,
pub face_count: u32,
#[serde(default)]
pub person_traces: Vec<i64>,
pub has_cut: bool,
pub cut_count: u32,
pub vlm_status: VlmStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub vlm_description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vlm_description_localized: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vlm_scene_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vlm_location: Option<String>,
#[serde(default)]
pub vlm_objects: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vlm_attributes: Option<SceneAttributes>,
#[serde(default)]
pub vlm_tags: Vec<String>,
pub embedding_status: EmbeddingStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneInfo {
pub scene_id: u32,
pub scene_start_sec: f64,
pub scene_end_sec: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SelectionReason {
BestBlur,
PreCutBestBlur,
PostCutBestBlur,
SceneStart,
Default,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum VlmStatus {
Pending,
Processing,
Completed,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum EmbeddingStatus {
Pending,
Completed,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneAttributes {
#[serde(skip_serializing_if = "Option::is_none")]
pub lighting: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub weather: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub time_of_day: Option<String>,
}
impl SceneProfile {
pub fn new(file_uuid: &str, video_info: VideoInfo, config: SceneConfig) -> Self {
Self {
version: "1.0".to_string(),
file_uuid: file_uuid.to_string(),
status: SceneStatus::Pending,
video_info,
config,
total_scenes: 0,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
scenes: Vec::new(),
}
}
pub fn scenes_path(output_dir: &str, file_uuid: &str) -> PathBuf {
Path::new(output_dir).join(format!("{}.scenes.json", file_uuid))
}
pub fn scenes_dir(output_dir: &str, file_uuid: &str) -> PathBuf {
Path::new(output_dir).join(file_uuid).join("scenes")
}
pub fn scene_frame_path(output_dir: &str, file_uuid: &str, filename: &str) -> PathBuf {
Self::scenes_dir(output_dir, file_uuid).join(filename)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -808,6 +988,10 @@ mod tests {
min_confidence: 85.0,
min_size: 96,
min_capture_quality: 0.0,
single_frame_trace_vlm_enabled: true,
single_frame_trace_group_enabled: true,
single_frame_trace_unassigned_enabled: true,
single_trace_group_filter_enabled: true,
});
let json = serde_json::to_string(&profile).unwrap();
let restored: FileProfile = serde_json::from_str(&json).unwrap();
+92
View File
@@ -73,6 +73,14 @@ struct ChatRequest {
#[derive(Debug, Deserialize)]
struct ChatResponse {
pub choices: Vec<Choice>,
pub usage: Option<Usage>,
}
#[derive(Debug, Deserialize)]
struct Usage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub total_tokens: u32,
}
#[derive(Debug, Deserialize)]
@@ -87,6 +95,20 @@ pub enum LlmResponse {
ToolCalls(Vec<ToolCall>),
}
impl LlmResponse {
pub fn usage(&self) -> Option<(u32, u32, u32)> {
None
}
}
/// Full LLM response with usage
pub struct LlmResponseWithUsage {
pub response: LlmResponse,
pub input_tokens: u32,
pub output_tokens: u32,
pub total_tokens: u32,
}
/// Get the LLM chat URL from centralized config
pub fn llm_chat_url() -> String {
config::llm::CHAT_URL.clone()
@@ -241,6 +263,76 @@ pub async fn call_llm(
}
}
/// Call Gemma4 with messages and optional tools. Returns response with usage.
pub async fn call_llm_with_usage(
messages: Vec<ChatMessage>,
tools: Option<Vec<ToolDef>>,
max_tokens: u32,
timeout_secs: u64,
) -> anyhow::Result<LlmResponseWithUsage> {
let timeout = if timeout_secs > 0 {
timeout_secs
} else {
*config::llm::CHAT_TIMEOUT_SECS
};
let start = std::time::Instant::now();
let req = ChatRequest {
model: llm_model(),
messages,
temperature: 0.1,
max_tokens,
stream: false,
tools,
};
let res = LLM_CLIENT
.post(&llm_chat_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout))
.send()
.await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
anyhow::bail!("LLM API error: {}", text);
}
let chat_res: ChatResponse = res.json().await?;
let choice = chat_res
.choices
.into_iter()
.next()
.ok_or_else(|| anyhow::anyhow!("Empty LLM response"))?;
let usage = chat_res.usage.unwrap_or(Usage {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
});
let response = match choice.finish_reason.as_deref() {
Some("tool_calls") => {
let calls = choice.message.tool_calls.ok_or_else(|| {
anyhow::anyhow!("finish_reason=tool_calls but no tool_calls in message")
})?;
LlmResponse::ToolCalls(calls)
}
_ => {
let content = choice.message.content.unwrap_or_default();
LlmResponse::Text(content.trim().to_string())
}
};
Ok(LlmResponseWithUsage {
response,
input_tokens: usage.prompt_tokens,
output_tokens: usage.completion_tokens,
total_tokens: usage.total_tokens,
})
}
/// Helper to build the system prompt + user messages
pub fn build_conversation(
system_prompt: &str,
+5 -5
View File
@@ -172,7 +172,7 @@ Include every chunk number exactly once. Only respond with the JSON."#,
}
}
warn!(
warn!(
"LLM rerank: could not parse response — content: {}",
&content[..content.len().min(200)]
);
@@ -187,14 +187,14 @@ mod tests {
fn test_utf8_truncation_safe() {
let long_chinese = "這是一段很長的中文文字,用來測試字元截斷是否正確運作,避免在多位元組字元中間切割造成恐慌。".repeat(3);
let text = long_chinese.as_str();
let display = if text.chars().count() > 100 {
let truncated: String = text.chars().take(100).collect();
format!("{}...", truncated)
} else {
text.to_string()
};
assert!(display.chars().count() <= 103);
assert!(display.starts_with("這是一段很長"));
assert!(display.ends_with("..."));
@@ -209,7 +209,7 @@ mod tests {
} else {
short_text.to_string()
};
assert_eq!(display, "短文字");
assert!(!display.ends_with("..."));
}
@@ -223,7 +223,7 @@ mod tests {
} else {
mixed.to_string()
};
assert!(display.chars().count() <= 103);
assert!(display.ends_with("..."));
}
+1
View File
@@ -2,6 +2,7 @@ pub mod admin_config;
pub mod agent;
pub mod api_key;
pub mod auth;
pub mod billing;
pub mod cache;
pub mod checkin;
pub mod chunk;
+33 -17
View File
@@ -14,17 +14,29 @@ use crate::core::config::{DATABASE_SCHEMA, OUTPUT_DIR, REDIS_KEY_PREFIX};
/// Returns (min_confidence, min_size, min_capture_quality) as Option<String>.
async fn get_face_settings() -> (Option<String>, Option<String>, Option<String>) {
let face_config = crate::core::admin_config::get_filter_config("face").await;
// Priority: Environment variable (runtime override) > Admin config (default)
let min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok()
.or_else(|| face_config.as_ref().and_then(|c| c.min_confidence).map(|v| v.to_string()));
let min_size = std::env::var("FACE_MIN_SIZE").ok()
.or_else(|| face_config.as_ref().and_then(|c| c.min_size).map(|v| v.to_string()));
let min_capture_quality = std::env::var("FACE_MIN_CAPTURE_QUALITY").ok()
.or_else(|| face_config.as_ref().and_then(|c| c.min_capture_quality).map(|v| v.to_string()));
let min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok().or_else(|| {
face_config
.as_ref()
.and_then(|c| c.min_confidence)
.map(|v| v.to_string())
});
let min_size = std::env::var("FACE_MIN_SIZE").ok().or_else(|| {
face_config
.as_ref()
.and_then(|c| c.min_size)
.map(|v| v.to_string())
});
let min_capture_quality = std::env::var("FACE_MIN_CAPTURE_QUALITY").ok().or_else(|| {
face_config
.as_ref()
.and_then(|c| c.min_capture_quality)
.map(|v| v.to_string())
});
(min_confidence, min_size, min_capture_quality)
}
@@ -343,7 +355,8 @@ impl PythonExecutor {
cmd.env("UUID", u);
}
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
let (face_min_confidence, face_min_size, face_min_capture_quality) =
get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
@@ -512,7 +525,8 @@ impl PythonExecutor {
cmd.env("UUID", u);
}
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
let (face_min_confidence, face_min_size, face_min_capture_quality) =
get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
@@ -722,7 +736,8 @@ impl PythonExecutor {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
let (face_min_confidence, face_min_size, face_min_capture_quality) =
get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
@@ -942,7 +957,8 @@ impl PythonExecutor {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
let (face_min_confidence, face_min_size, face_min_capture_quality) =
get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
@@ -1266,9 +1282,9 @@ impl PythonExecutor {
tracing::info!("[{}] Starting rust: {:?}", log_prefix, cmd);
let mut child = cmd.spawn().with_context(|| {
format!("Failed to run Rust processor {:?}", bin_path)
})?;
let mut child = cmd
.spawn()
.with_context(|| format!("Failed to run Rust processor {:?}", bin_path))?;
let child_pid = child.id();
let stdout = child.stdout.take().context("Failed to capture stdout")?;
+11
View File
@@ -31,6 +31,14 @@ impl FaceResult {
self.status = Some(FaceStatus::from_face_count(self.total_faces));
}
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
let json = serde_json::to_string_pretty(self)
.context("Failed to serialize FaceResult")?;
std::fs::write(path, json)
.context("Failed to write face.json")?;
Ok(())
}
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
FaceResult {
@@ -120,6 +128,7 @@ pub async fn process_face(
serde_json::from_str(&json_str).context("Failed to parse existing FACE output")?;
result.compute_status();
result.save_to_file(output_path)?;
tracing::info!(
"[FACE] Loaded from SwiftFacePose: status={}, {} frames, {} total faces",
@@ -233,6 +242,7 @@ pub async fn process_face(
let json_str = std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
let mut result: FaceResult = serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
result.compute_status();
result.save_to_file(output_path)?;
tracing::info!(
"[FACE] Swift result: status={}, {} frames, {} total faces",
@@ -272,6 +282,7 @@ pub async fn process_face(
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
result.compute_status();
result.save_to_file(output_path)?;
tracing::info!(
"[FACE] Result: status={}, {} frames, {} total faces",
+2 -2
View File
@@ -110,8 +110,8 @@ pub async fn process_face_cluster(
Ok(_) => {
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read FACE_CLUSTER output")?;
let result: FaceClusterResult =
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
let result: FaceClusterResult = serde_json::from_str(&json_str)
.context("Failed to parse FACE_CLUSTER output")?;
tracing::info!(
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
result.clusters.len(),
+2
View File
@@ -14,6 +14,7 @@ pub mod heuristic_scene;
pub mod ocr;
pub mod pose;
pub mod scene_classification;
pub mod scene_vlm;
pub mod tkg;
pub mod vlm_summary;
@@ -188,6 +189,7 @@ pub use scene_classification::{
load_scene_from_file, process_scene_classification, SceneClassificationResult, ScenePrediction,
SceneSegment,
};
pub use scene_vlm::SceneVlmProcessor;
pub use tkg::{
build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo,
RepresentativeFrameResult, TkgResult,
+30 -4
View File
@@ -734,7 +734,16 @@ pub async fn build_tkg(
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let n_face = build_face_track_nodes(pool, file_uuid, &pose_data, &face_points, false, &mut progress, &redis).await?;
let n_face = build_face_track_nodes(
pool,
file_uuid,
&pose_data,
&face_points,
false,
&mut progress,
&redis,
)
.await?;
progress.stats.face_track_nodes = n_face as i64;
progress.update_phase(
TkgPhase::FaceTrackNodes,
@@ -1043,8 +1052,16 @@ pub async fn backfill_trace_dirs(
file_uuid
);
let n =
build_face_track_nodes_from_qdrant(pool, file_uuid, &pose_data, &face_points, true, &mut TkgProgress::new(file_uuid), &None).await?;
let n = build_face_track_nodes_from_qdrant(
pool,
file_uuid,
&pose_data,
&face_points,
true,
&mut TkgProgress::new(file_uuid),
&None,
)
.await?;
tracing::info!(
"[TKG-BACKFILL] backfilled {} face_track artifact dirs for {}",
n,
@@ -1062,7 +1079,16 @@ async fn build_face_track_nodes(
progress: &mut TkgProgress,
redis: &Option<Arc<RedisClient>>,
) -> Result<usize> {
build_face_track_nodes_from_qdrant(pool, file_uuid, pose_data, face_points, skip_existing, progress, redis).await
build_face_track_nodes_from_qdrant(
pool,
file_uuid,
pose_data,
face_points,
skip_existing,
progress,
redis,
)
.await
}
async fn build_face_track_nodes_from_qdrant(
+63 -44
View File
@@ -1,5 +1,6 @@
use anyhow::Result;
use base64::Engine;
use futures_util::stream::{self, StreamExt};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::{error, info, warn};
@@ -60,7 +61,7 @@ pub async fn generate_vlm_summaries(
}
info!(
"[VLM] Starting VLM summary generation for {}: {} traces",
"[VLM] Starting VLM summary generation for {}: {} traces (parallel processing)",
file_uuid, total
);
info!(
@@ -73,22 +74,48 @@ pub async fn generate_vlm_summaries(
..Default::default()
};
for (i, &trace_id) in trace_ids.iter().enumerate() {
let current = i + 1;
// Parallel processing with max 5 concurrent tasks
let max_concurrent = 5;
info!(
"[VLM] Processing {} traces with max {} concurrent",
total, max_concurrent
);
// Update progress
if let Some(ref r) = redis {
let mut pp = PipelineProgress::new(file_uuid);
pp.update_stage(
"vlm_summary",
current as f64 / total as f64,
"running",
Some(format!("{}/{}", current, total)),
);
let _ = publish_pipeline_progress(r.as_ref(), file_uuid, &pp).await;
}
let trace_ids_owned: Vec<i32> = trace_ids.into_iter().collect();
match process_single_trace(db, file_uuid, trace_id, output_dir, current, total).await {
let results: Vec<_> = stream::iter(trace_ids_owned.into_iter().enumerate())
.map(|(i, trace_id)| {
let db_clone = db.clone();
let file_uuid = file_uuid.to_string();
let output_dir = output_dir.to_string();
let redis_clone = redis.clone();
async move {
let current = i + 1;
let total = total;
// Update progress
if let Some(ref r) = redis_clone {
let mut pp = PipelineProgress::new(&file_uuid);
pp.update_stage(
"vlm_summary",
current as f64 / total as f64,
"running",
Some(format!("{}/{}", current, total)),
);
let _ = publish_pipeline_progress(r.as_ref(), &file_uuid, &pp).await;
}
process_single_trace(&db_clone, &file_uuid, trace_id, &output_dir, current, total)
.await
}
})
.buffer_unordered(max_concurrent)
.collect()
.await;
// Aggregate results
for res in results {
match res {
Ok((summarized, embedded)) => {
if summarized {
result.summarized += 1;
@@ -99,10 +126,7 @@ pub async fn generate_vlm_summaries(
}
Err(e) => {
result.errors += 1;
error!(
"[VLM] trace {}/{} (tid={}): {}",
current, total, trace_id, e
);
error!("[VLM] Error processing trace: {}", e);
}
}
}
@@ -140,7 +164,7 @@ async fn process_single_trace(
) -> Result<(bool, bool)> {
let trace_id_i64 = trace_id as i64;
let tp_table = table_name("trace_profiles");
// Check frame_count and skip single frame trace if disabled
let frame_count: Option<i32> = sqlx::query_scalar(&format!(
"SELECT frame_count FROM {tp_table} WHERE file_uuid = $1 AND trace_id = $2"
@@ -150,21 +174,22 @@ async fn process_single_trace(
.fetch_optional(db.pool())
.await?
.flatten();
// If this is a single frame trace, check configuration
if frame_count == Some(1) {
let v_table = table_name("videos");
let settings: Option<crate::core::file_profile::FaceFilterSettings> = sqlx::query_scalar(&format!(
"SELECT face_filter FROM {v_table} WHERE file_uuid = $1"
))
let settings: Option<crate::core::file_profile::FaceFilterSettings> = sqlx::query_scalar(
&format!("SELECT face_filter FROM {v_table} WHERE file_uuid = $1"),
)
.bind(file_uuid)
.fetch_optional(db.pool())
.await?
.flatten()
.and_then(|v| serde_json::from_value(v).ok());
let settings = settings.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
let settings =
settings.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
if !settings.single_frame_trace_vlm_enabled {
info!(
"[VLM] trace {}/{} (tid={}): skipping single frame trace (disabled by config)",
@@ -186,7 +211,8 @@ async fn process_single_trace(
.flatten();
let (existing_desc, existing_embed) = existing.unwrap_or((None, None));
let need_vlm = existing_desc.is_none() || existing_desc.as_ref().map(|s| s.is_empty()).unwrap_or(true);
let need_vlm =
existing_desc.is_none() || existing_desc.as_ref().map(|s| s.is_empty()).unwrap_or(true);
let need_embed = existing_embed.is_none();
let summary = if need_vlm {
@@ -213,16 +239,13 @@ async fn process_single_trace(
.as_ref()
.and_then(|p| p.system_prompt.as_deref())
.unwrap_or("You are a scene analysis assistant for a video surveillance/DAM system. Given a video key frame, write a concise summary (2-4 sentences, in the same language as the user) describing: what is happening, the people present (clothing/appearance), the setting/location, and any notable objects or actions. Be factual and specific.");
let user_prompt = vlm_prompt
.as_ref()
.and_then(|p| p.user_prompt.as_deref())
.unwrap_or("Summarize this key frame.");
let max_tokens = vlm_prompt
.as_ref()
.map(|p| p.max_tokens)
.unwrap_or(512);
let max_tokens = vlm_prompt.as_ref().map(|p| p.max_tokens).unwrap_or(900);
// Call VLM
let summary = match call_llm_vision(
@@ -277,9 +300,11 @@ async fn process_single_trace(
trace_id_i64,
);
if profile_path.exists() {
if let Some(mut profile) =
crate::core::file_profile::FaceTraceProfile::load(output_dir, file_uuid, trace_id_i64)
{
if let Some(mut profile) = crate::core::file_profile::FaceTraceProfile::load(
output_dir,
file_uuid,
trace_id_i64,
) {
profile.vlm_summary = Some(summary.clone());
if let Err(e) = profile.save(output_dir, None, None) {
warn!(
@@ -340,13 +365,7 @@ async fn process_single_trace(
// Store in Qdrant (using u64 ID) with trace_id in payload
let qdrant = QdrantDb::new();
if let Err(e) = qdrant
.upsert_vlm_embedding(
point_id,
&vector,
file_uuid,
trace_id,
&summary,
)
.upsert_vlm_embedding(point_id, &vector, file_uuid, trace_id, &summary)
.await
{
warn!(
+17 -7
View File
@@ -249,11 +249,8 @@ static SYNONYM_EXPANDER: Lazy<SynonymExpander> = Lazy::new(|| {
}
// 默認加載內建同義詞檔案
let default_files = vec![
"data/english_synonyms.json",
"data/llm_synonyms.json",
];
let default_files = vec!["data/english_synonyms.json", "data/llm_synonyms.json"];
match SynonymExpander::from_files(&default_files) {
Ok(expander) => {
tracing::info!(
@@ -278,6 +275,19 @@ pub fn global_synonym_expander() -> &'static SynonymExpander {
mod tests {
use super::*;
fn expander_from_map(map: HashMap<String, Vec<String>>) -> SynonymExpander {
let mut reverse_map: HashMap<String, Vec<String>> = HashMap::new();
for (key, synonyms) in &map {
for syn in synonyms {
reverse_map
.entry(syn.clone())
.or_insert_with(Vec::new)
.push(key.clone());
}
}
SynonymExpander { map, reverse_map }
}
#[test]
fn test_expand_word() {
let mut map = HashMap::new();
@@ -289,7 +299,7 @@ mod tests {
"工作".to_string(),
vec!["任務".to_string(), "作業".to_string()],
);
let expander = SynonymExpander { map };
let expander = expander_from_map(map);
assert_eq!(expander.expand_word("電腦"), "(電腦 | 計算機 | 微机)");
assert_eq!(expander.expand_word("工作"), "(工作 | 任務 | 作業)");
@@ -307,7 +317,7 @@ mod tests {
"工作".to_string(),
vec!["任務".to_string(), "作業".to_string()],
);
let expander = SynonymExpander { map };
let expander = expander_from_map(map);
assert_eq!(
expander.expand_query("電腦 工作"),
+1 -1
View File
@@ -48,7 +48,7 @@ pub const PROCESSOR_SCHEMAS: &[ProcessorJsonSchema] = &[
field_type: FieldType::Array,
allow_empty: true,
},
],
],
min_data_threshold: 0,
},
ProcessorJsonSchema {
+1 -1
View File
@@ -45,4 +45,4 @@ mod tests {
assert!(config.batch_size > 0);
assert!(config.processor_timeout_secs > 0);
}
}
}
+1000 -200
View File
File diff suppressed because it is too large Load Diff
+12
View File
@@ -163,6 +163,18 @@ impl ProcessorPool {
mine < budget
}
/// True if the current worker process currently holds at least one live
/// in-flight handler for the given job (across all processor types).
pub async fn is_job_active(&self, job_id: i32) -> bool {
self.running_per_job
.read()
.await
.get(&job_id)
.copied()
.unwrap_or(0)
> 0
}
/// 根據系統資源計算當前安全的並發上限
pub async fn current_max(&self) -> usize {
let resources = SystemResources::check();
+1 -3
View File
@@ -285,9 +285,7 @@ impl SystemResources {
fn get_ane_info() -> (bool, Option<f64>) {
use std::process::Command;
let output = Command::new("ps")
.args(["aux"])
.output();
let output = Command::new("ps").args(["aux"]).output();
if let Ok(o) = output {
let s = String::from_utf8_lossy(&o.stdout);