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
+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("電腦 工作"),