fix: Face processor now saves status and total_faces to face.json
This commit is contained in:
+20
-15
@@ -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
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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,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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
}))
|
||||
}
|
||||
Reference in New Issue
Block a user