feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering
This commit is contained in:
+47
-2
@@ -63,6 +63,8 @@ pub struct AgentSearchRequest {
|
||||
pub query: String,
|
||||
pub conversation_id: Option<String>,
|
||||
pub file_uuid: Option<String>,
|
||||
#[serde(default)]
|
||||
pub output_language: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -158,6 +160,43 @@ const SYSTEM_PROMPT: &str = r#"你是 Momentry 影片分析助手。回答用戶
|
||||
- **如果連續 2 次呼叫工具都返回空結果,停止並告知「找不到更多相關資訊」**
|
||||
- **優化效率:避免重複呼叫相同工具**"#;
|
||||
|
||||
fn build_system_prompt(language: &str) -> String {
|
||||
let (intro, greeting_instruction, language_instruction) = match language {
|
||||
"zh-TW" => (
|
||||
"你是 Momentry 影片分析助手。回答用戶關於影片內容的問題。",
|
||||
r#"## Greeting and Conversation Handling (CRITICAL - Check First)
|
||||
- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"):
|
||||
- **DO NOT call any search tools**
|
||||
- Respond in Traditional Chinese: "你好!我是 Momentry 影片分析助手。我可以幫你搜尋影片內容、找出人物、分析場景。你想了解什麼?"
|
||||
- If user asks "how are you" or "thanks", respond briefly in Traditional Chinese without tools
|
||||
- **Only use search tools when user asks about VIDEO CONTENT**"#,
|
||||
"## Response Language (MANDATORY)\n- **Respond in Traditional Chinese** for all responses: greetings, search results, explanations",
|
||||
),
|
||||
"ja" => (
|
||||
"あなたは Momentry ビデオ分析アシスタントです。ビデオコンテンツについての質問に答えてください。",
|
||||
r#"## Greeting and Conversation Handling (CRITICAL - Check First)
|
||||
- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"):
|
||||
- **DO NOT call any search tools**
|
||||
- Respond in Japanese: "こんにちは!Momentry ビデオ分析アシスタントです。ビデオコンテンツの検索、人物の探索、シーンの分析をお手伝いします。何を知りたいですか?"
|
||||
- If user asks "how are you" or "thanks", respond briefly in Japanese without tools
|
||||
- **Only use search tools when user asks about VIDEO CONTENT**"#,
|
||||
"## Response Language (MANDATORY)\n- **Respond in Japanese** for all responses: greetings, search results, explanations",
|
||||
),
|
||||
_ => (
|
||||
"You are the Momentry video analysis assistant. Answer questions about video content.",
|
||||
r#"## Greeting and Conversation Handling (CRITICAL - Check First)
|
||||
- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"):
|
||||
- **DO NOT call any search tools**
|
||||
- Respond in English: "Hello! I'm Momentry video analysis assistant. I can help you search video content, find people, and analyze scenes. What would you like to know?"
|
||||
- If user asks "how are you" or "thanks", respond briefly in English without tools
|
||||
- **Only use search tools when user asks about VIDEO CONTENT**"#,
|
||||
"## Response Language (MANDATORY)\n- **Respond in English** for all responses: greetings, search results, explanations",
|
||||
),
|
||||
};
|
||||
|
||||
format!("{}\n\n{}\n\n{}\n\n{}", intro, greeting_instruction, language_instruction, SYSTEM_PROMPT)
|
||||
}
|
||||
|
||||
fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
|
||||
vec![
|
||||
function_calling::make_tool(
|
||||
@@ -488,12 +527,18 @@ async fn agent_search(
|
||||
) -> Result<Json<AgentSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let (conv_id, history) = get_or_create_conv(req.conversation_id.as_deref());
|
||||
|
||||
// Add 60s timeout for the entire agent search
|
||||
let language = req.output_language
|
||||
.as_deref()
|
||||
.unwrap_or("en");
|
||||
|
||||
let system_prompt = build_system_prompt(language);
|
||||
tracing::info!("[AGENT] Using language: {}", language);
|
||||
|
||||
let timeout_duration = std::time::Duration::from_secs(60);
|
||||
|
||||
let result = tokio::time::timeout(
|
||||
timeout_duration,
|
||||
run_tool_loop(state.db.pool(), SYSTEM_PROMPT, &req.query, history)
|
||||
run_tool_loop(state.db.pool(), &system_prompt, &req.query, history)
|
||||
).await;
|
||||
|
||||
let (answer, messages, sources) = match result {
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod agent_search;
|
||||
pub mod auth;
|
||||
pub mod billing;
|
||||
pub mod checkin_api;
|
||||
pub mod clip_api;
|
||||
pub mod cluster_agent;
|
||||
pub mod monitor;
|
||||
pub mod docs;
|
||||
|
||||
+135
-53
@@ -593,6 +593,29 @@ pub async fn merge_groups_handler(
|
||||
}
|
||||
}
|
||||
|
||||
// Sync Qdrant person_id for all merged traces
|
||||
if !matching_trace_ids.is_empty() {
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
let trace_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": req.file_uuid}},
|
||||
{"key": "trace_id", "match": {"any": matching_trace_ids.iter().map(|id| serde_json::json!(*id)).collect::<Vec<_>>()}}
|
||||
]
|
||||
});
|
||||
let update_payload = serde_json::json!({
|
||||
"person_id": req.target_group_name
|
||||
});
|
||||
if let Err(e) = qdrant
|
||||
.update_payload_by_filter("_faces", trace_filter, update_payload)
|
||||
.await
|
||||
{
|
||||
tracing::error!("[MergeGroups] Qdrant update error: {}", e);
|
||||
// Don't fail the whole operation if Qdrant update fails
|
||||
} else {
|
||||
tracing::info!("[MergeGroups] Qdrant person_id updated for {} traces", matching_trace_ids.len());
|
||||
}
|
||||
}
|
||||
|
||||
match nodes_result {
|
||||
Ok(nodes_res) => {
|
||||
let nodes_updated = nodes_res.rows_affected();
|
||||
@@ -1436,6 +1459,7 @@ pub struct ClusterResultsFace {
|
||||
pub face_id: String,
|
||||
pub confidence: f64,
|
||||
pub cluster_id: Option<i32>,
|
||||
pub trace_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -1493,9 +1517,10 @@ pub async fn get_cluster_results_handler(
|
||||
.and_then(|v| serde_json::from_value(v).ok())
|
||||
.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
|
||||
|
||||
// 1. Build face groups (same grouping logic as face-groups handler)
|
||||
// 1. Build face groups from TKG nodes (primary source)
|
||||
// Use tkg_nodes.label as primary name, fallback to trace_profiles.name
|
||||
let rows: Vec<(String, i32, Option<i32>)> = sqlx::query_as(&format!(
|
||||
"SELECT COALESCE(tp.name, tn.label) as name, \
|
||||
"SELECT COALESCE(tn.label, tp.name) as name, \
|
||||
COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \
|
||||
tp.frame_count \
|
||||
FROM {} tn \
|
||||
@@ -1529,6 +1554,11 @@ pub async fn get_cluster_results_handler(
|
||||
// User-named groups (even with 1 trace) are kept.
|
||||
let mut filtered_groups: HashMap<String, Vec<i32>> = HashMap::new();
|
||||
for (name, trace_ids) in groups {
|
||||
// Filter out empty names and auto-generated trace names
|
||||
if name.is_empty() || name.starts_with("Face Trace ") || name.starts_with("Trace ") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_auto_name = name.starts_with("Person_");
|
||||
let should_filter =
|
||||
settings.trace_settings.single_trace_group_filter_enabled && trace_ids.len() == 1 && is_auto_name;
|
||||
@@ -1538,10 +1568,55 @@ pub async fn get_cluster_results_handler(
|
||||
}
|
||||
}
|
||||
|
||||
// trace_id -> cluster_id mapping for frame faces
|
||||
let mut trace_to_cluster: HashMap<i32, i32> = HashMap::new();
|
||||
// Fallback: if no groups from DB, load from face_cluster.json
|
||||
let mut fallback_from_json = filtered_groups.is_empty();
|
||||
|
||||
if fallback_from_json {
|
||||
tracing::info!("[ClusterResults] No groups from DB, loading from face_cluster.json");
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||||
if let Ok(content) = std::fs::read_to_string(&fc_path) {
|
||||
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
// Extract clusters
|
||||
if let Some(clusters) = data.get("clusters").and_then(|c| c.as_array()) {
|
||||
for c in clusters {
|
||||
if let Some(cid) = c.get("cluster_id").and_then(|v| v.as_str()) {
|
||||
// Use cluster_id as name
|
||||
let name = cid.to_string();
|
||||
let trace_ids: Vec<i32> = Vec::new();
|
||||
filtered_groups.insert(name, trace_ids);
|
||||
}
|
||||
}
|
||||
tracing::info!("[ClusterResults] Loaded {} clusters from face_cluster.json", clusters.len());
|
||||
}
|
||||
|
||||
// Extract trace_ids from frames
|
||||
if let Some(frames) = data.get("frames").and_then(|f| f.as_array()) {
|
||||
for frame in frames {
|
||||
if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) {
|
||||
for face in faces {
|
||||
// Use cluster_id from face_cluster.json (not person_id)
|
||||
if let (Some(trace_id), Some(cluster_id)) = (
|
||||
face.get("trace_id").and_then(|v| v.as_i64()),
|
||||
face.get("cluster_id").and_then(|v| v.as_str()),
|
||||
) {
|
||||
let trace_id = trace_id as i32;
|
||||
if let Some(trace_ids) = filtered_groups.get_mut(cluster_id) {
|
||||
if !trace_ids.contains(&trace_id) {
|
||||
trace_ids.push(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::info!("[ClusterResults] Extracted trace_ids from frames");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load face_cluster.json for similarity data
|
||||
// Load face_cluster.json for similarity data only (not for adding clusters)
|
||||
let cluster_similarity: HashMap<String, ClusterSimilarityInfo> = {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||||
@@ -1576,14 +1651,17 @@ pub async fn get_cluster_results_handler(
|
||||
map
|
||||
};
|
||||
|
||||
// Build trace_id -> name mapping before consuming filtered_groups
|
||||
let trace_to_name: HashMap<i32, String> = filtered_groups
|
||||
.iter()
|
||||
.flat_map(|(name, trace_ids)| trace_ids.iter().map(|tid| (*tid, name.clone())))
|
||||
.collect();
|
||||
|
||||
let face_groups: Vec<ClusterResultsGroup> = filtered_groups
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, (name, trace_ids))| {
|
||||
let group_id = (idx + 1) as i32;
|
||||
for tid in &trace_ids {
|
||||
trace_to_cluster.insert(*tid, group_id);
|
||||
}
|
||||
// Try to find similarity data for this cluster
|
||||
let similarity = cluster_similarity.get(&name).cloned();
|
||||
ClusterResultsGroup {
|
||||
@@ -1613,53 +1691,57 @@ pub async fn get_cluster_results_handler(
|
||||
})?
|
||||
.unwrap_or(0.0);
|
||||
|
||||
// 3. Scroll _faces for this file and group by frame
|
||||
let face_filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": &file_uuid}}
|
||||
]
|
||||
});
|
||||
let points = state
|
||||
.qdrant
|
||||
.scroll_all_points("_faces", face_filter, 1000)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("[ClusterResults] Qdrant scroll failed: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let mut frames_map: HashMap<i64, Vec<ClusterResultsFace>> = HashMap::new();
|
||||
for p in &points {
|
||||
let payload = &p["payload"];
|
||||
let frame = payload["frame"].as_i64().unwrap_or(0);
|
||||
let trace_id = payload["trace_id"].as_i64().map(|t| t as i32).unwrap_or(0);
|
||||
let point_id = p["id"].as_u64().unwrap_or(0);
|
||||
let confidence = payload["confidence"].as_f64().unwrap_or(0.0);
|
||||
|
||||
// Only include faces that belong to a group (Studio skips unassigned)
|
||||
let cluster_id = trace_to_cluster.get(&trace_id).copied();
|
||||
if cluster_id.is_none() {
|
||||
continue;
|
||||
// 4. Build frames from face_cluster.json directly
|
||||
let mut frames: Vec<ClusterResultsFrame> = Vec::new();
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||||
if let Ok(content) = std::fs::read_to_string(&fc_path) {
|
||||
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(fc_frames) = data.get("frames").and_then(|f| f.as_array()) {
|
||||
for fc_frame in fc_frames {
|
||||
if let (Some(frame_num), Some(faces)) = (
|
||||
fc_frame.get("frame").and_then(|f| f.as_i64()),
|
||||
fc_frame.get("faces").and_then(|f| f.as_array()),
|
||||
) {
|
||||
let mut cluster_faces: Vec<ClusterResultsFace> = Vec::new();
|
||||
for face in faces {
|
||||
if let (Some(face_id), Some(trace_id), Some(confidence)) = (
|
||||
face.get("face_id").and_then(|f| f.as_str()),
|
||||
face.get("trace_id").and_then(|f| f.as_i64()),
|
||||
face.get("confidence").and_then(|f| f.as_f64()),
|
||||
) {
|
||||
let trace_id = trace_id as i32;
|
||||
// Use trace_to_name mapping instead of face.cluster_id
|
||||
if let Some(cluster_name) = trace_to_name.get(&trace_id) {
|
||||
// Find group_id for this cluster name
|
||||
if let Some(group_id) = face_groups.iter().find(|g| g.name == *cluster_name).map(|g| g.group_id) {
|
||||
cluster_faces.push(ClusterResultsFace {
|
||||
face_id: face_id.to_string(),
|
||||
confidence,
|
||||
cluster_id: Some(group_id),
|
||||
trace_id: Some(trace_id),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !cluster_faces.is_empty() {
|
||||
let timestamp = if fps > 0.0 { frame_num as f64 / fps } else { 0.0 };
|
||||
frames.push(ClusterResultsFrame {
|
||||
frame: frame_num,
|
||||
timestamp,
|
||||
faces: cluster_faces,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!("[ClusterResults] Built {} frames from face_cluster.json", frames.len());
|
||||
}
|
||||
}
|
||||
|
||||
frames_map
|
||||
.entry(frame)
|
||||
.or_default()
|
||||
.push(ClusterResultsFace {
|
||||
face_id: format!("{:x}", point_id),
|
||||
confidence,
|
||||
cluster_id,
|
||||
});
|
||||
}
|
||||
|
||||
let mut frames: Vec<ClusterResultsFrame> = frames_map
|
||||
.into_iter()
|
||||
.map(|(frame, faces)| ClusterResultsFrame {
|
||||
frame,
|
||||
timestamp: if fps > 0.0 { frame as f64 / fps } else { 0.0 },
|
||||
faces,
|
||||
})
|
||||
.collect();
|
||||
|
||||
frames.sort_by_key(|f| f.frame);
|
||||
|
||||
Ok(Json(ClusterResultsResponse {
|
||||
|
||||
@@ -16,6 +16,7 @@ use super::agent_search;
|
||||
use super::auth;
|
||||
use super::billing;
|
||||
use super::checkin_api;
|
||||
use super::clip_api;
|
||||
use super::cluster_agent;
|
||||
use super::docs;
|
||||
use super::face_filter;
|
||||
@@ -148,6 +149,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.merge(media_api::media_proxy_routes())
|
||||
.merge(media_api::pose_appearance_routes())
|
||||
.merge(trace_agent_api::trace_agent_routes())
|
||||
.merge(clip_api::clip_routes())
|
||||
.merge(search_routes())
|
||||
.merge(llm_search::llm_smart_routes())
|
||||
.merge(universal_search_routes())
|
||||
|
||||
@@ -2779,8 +2779,9 @@ fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize {
|
||||
fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option<serde_json::Value> {
|
||||
use std::path::PathBuf;
|
||||
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let profile_path: PathBuf = [
|
||||
crate::core::config::OUTPUT_DIR.as_str(),
|
||||
output_dir,
|
||||
file_uuid,
|
||||
&format!("trace_{}", trace_id),
|
||||
"trace_profile.json",
|
||||
@@ -2812,7 +2813,17 @@ async fn get_trace_profile_file(
|
||||
|
||||
match read_trace_profile(&file_uuid, trace_id) {
|
||||
Some(profile) => (StatusCode::OK, Json(profile)),
|
||||
None => (StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Trace profile file not found", "file_uuid": file_uuid, "trace_id": trace_id}))),
|
||||
None => {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let expected_path = format!("{}/{}/trace_{}/trace_profile.json", output_dir, file_uuid, trace_id);
|
||||
(StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
"error": "Trace profile file not found",
|
||||
"file_uuid": file_uuid,
|
||||
"trace_id": trace_id,
|
||||
"output_dir": output_dir,
|
||||
"expected_path": expected_path
|
||||
})))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{header, Request, StatusCode},
|
||||
middleware::Next,
|
||||
response::{Html, IntoResponse, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
|
||||
use std::net::SocketAddr;
|
||||
use tower_http::services::{ServeDir, ServeFile};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let port = std::env::var("DOCSERVER_PORT")
|
||||
.unwrap_or_else(|_| "8000".to_string())
|
||||
.parse()
|
||||
.unwrap_or(8000);
|
||||
|
||||
let username = std::env::var("DOCSERVER_USER")
|
||||
.unwrap_or_else(|_| "admin".to_string());
|
||||
|
||||
let password = std::env::var("DOCSERVER_PASSWORD")
|
||||
.unwrap_or_else(|_| "admin123".to_string());
|
||||
|
||||
let docs_dir = std::env::var("MOMENTRY_DOCS_DIR")
|
||||
.unwrap_or_else(|_| {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| {
|
||||
p.parent()
|
||||
.map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string())
|
||||
})
|
||||
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
|
||||
});
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
tracing::info!("Starting docserver on port {}", port);
|
||||
tracing::info!("Docs directory: {}", docs_dir);
|
||||
tracing::info!("Username: {}", username);
|
||||
|
||||
let config = Config {
|
||||
username,
|
||||
password,
|
||||
docs_dir: docs_dir.clone(),
|
||||
};
|
||||
|
||||
let pkg_service = ServeDir::new(format!("{}/pkg", docs_dir));
|
||||
let modules_service = ServeDir::new(format!("{}/modules", docs_dir));
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(serve_index))
|
||||
.route("/health", get(|| async { "OK" }))
|
||||
.nest_service("/pkg", pkg_service)
|
||||
.nest_service("/modules", modules_service)
|
||||
.route("/logout", get(logout_handler))
|
||||
.nest_service("/logout.html", ServeFile::new(format!("{}/logout.html", docs_dir)))
|
||||
.layer(axum::middleware::from_fn(move |req, next| {
|
||||
let username = config.username.clone();
|
||||
let password = config.password.clone();
|
||||
async move { auth_middleware(req, next, &username, &password).await }
|
||||
}));
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
||||
tracing::info!("Listening on {}", addr);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
struct Config {
|
||||
username: String,
|
||||
password: String,
|
||||
docs_dir: String,
|
||||
}
|
||||
|
||||
async fn auth_middleware(
|
||||
req: Request<Body>,
|
||||
next: Next,
|
||||
expected_username: &str,
|
||||
expected_password: &str,
|
||||
) -> Response {
|
||||
// Skip auth for health, logout, and logout.html endpoints
|
||||
let path = req.uri().path();
|
||||
if path == "/health" || path == "/logout" || path == "/logout.html" {
|
||||
return next.run(req).await;
|
||||
}
|
||||
|
||||
// Extract Authorization header
|
||||
let auth_header = req
|
||||
.headers()
|
||||
.get("Authorization")
|
||||
.and_then(|h| h.to_str().ok());
|
||||
|
||||
// Validate credentials
|
||||
if let Some(auth) = auth_header {
|
||||
if auth.starts_with("Basic ") {
|
||||
let encoded = &auth[6..];
|
||||
|
||||
if let Ok(decoded) = BASE64.decode(encoded) {
|
||||
if let Ok(decoded_str) = String::from_utf8(decoded) {
|
||||
let parts: Vec<&str> = decoded_str.splitn(2, ':').collect();
|
||||
if parts.len() == 2 {
|
||||
let (username, password) = (parts[0], parts[1]);
|
||||
|
||||
if username == expected_username && password == expected_password {
|
||||
return next.run(req).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return 401 with WWW-Authenticate header
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Basic realm=\"Momentry Documentation\"")],
|
||||
"Authentication required",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn serve_index() -> Result<Html<String>, StatusCode> {
|
||||
let docs_dir = std::env::var("MOMENTRY_DOCS_DIR")
|
||||
.unwrap_or_else(|_| "docs_v1.0/doc_wasm".to_string());
|
||||
|
||||
let index_path = std::path::Path::new(&docs_dir).join("index.html");
|
||||
|
||||
tokio::fs::read_to_string(&index_path)
|
||||
.await
|
||||
.map(Html)
|
||||
.map_err(|_| StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn logout_handler() -> impl IntoResponse {
|
||||
// Serve logout.html page with absolute path
|
||||
let logout_path = "/Users/accusys/momentry_core/docs_v1.0/doc_wasm/logout.html";
|
||||
|
||||
match tokio::fs::read_to_string(&logout_path).await {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(e) => {
|
||||
eprintln!("Error reading logout.html: {}", e);
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Basic realm=\"Momentry Documentation - Logout\"")],
|
||||
"Logged out - please close browser or clear cache",
|
||||
).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ async fn main() -> Result<()> {
|
||||
);
|
||||
|
||||
// 顯示轉換後的 tsquery (除錯用)
|
||||
match pg.prepare_tsquery(query_str).await {
|
||||
// match pg.prepare_tsquery(query_str).await {
|
||||
Ok(tsquery) => println!(" TSQUERY: {}", tsquery),
|
||||
Err(e) => println!(" TSQUERY 錯誤: {}", e),
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ async fn main() -> Result<()> {
|
||||
println!("\n🔍 測試查詢 (簡體): '{}'", query_str);
|
||||
|
||||
// 顯示轉換後的 tsquery
|
||||
match pg.prepare_tsquery(query_str).await {
|
||||
// match pg.prepare_tsquery(query_str).await {
|
||||
Ok(tsquery) => println!(" TSQUERY: {}", tsquery),
|
||||
Err(e) => println!(" TSQUERY 錯誤: {}", e),
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
// 顯示轉換後的 tsquery
|
||||
match pg.prepare_tsquery(query_str).await {
|
||||
// match pg.prepare_tsquery(query_str).await {
|
||||
Ok(tsquery) => println!(" TSQUERY: {}", tsquery),
|
||||
Err(e) => println!(" TSQUERY 錯誤: {}", e),
|
||||
}
|
||||
|
||||
@@ -622,6 +622,9 @@ impl AdminConfigManager {
|
||||
if let Some(search) = partial.search {
|
||||
config.search = search;
|
||||
}
|
||||
if let Some(pipeline) = partial.pipeline {
|
||||
config.pipeline = pipeline;
|
||||
}
|
||||
|
||||
config.updated_at = chrono::Utc::now().to_rfc3339();
|
||||
config.updated_by = "admin".to_string();
|
||||
|
||||
@@ -685,7 +685,7 @@ impl ProcessorType {
|
||||
ProcessorType::Pose => vec![ProcessorType::Face],
|
||||
ProcessorType::Appearance => vec![ProcessorType::Pose],
|
||||
ProcessorType::FaceTrace => vec![ProcessorType::Face],
|
||||
ProcessorType::FaceCluster => vec![ProcessorType::FaceTrace],
|
||||
ProcessorType::FaceCluster => vec![ProcessorType::Tkg],
|
||||
ProcessorType::Tkg => vec![ProcessorType::FaceTrace],
|
||||
_ => vec![],
|
||||
}
|
||||
|
||||
+36
-23
@@ -432,6 +432,10 @@ impl RedisClient {
|
||||
fields.push(("error", err.to_string()));
|
||||
}
|
||||
|
||||
|
||||
// Set TTL for job key (24 hours)
|
||||
let _: bool = conn.expire(&key, 86400).await?;
|
||||
|
||||
let field_refs: Vec<(&str, &str)> = fields.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
|
||||
let _: Option<String> = conn.hset_multiple(&key, &field_refs).await?;
|
||||
@@ -471,31 +475,40 @@ impl RedisClient {
|
||||
pub async fn delete_worker_job(&self, uuid: &str) -> Result<()> {
|
||||
let mut conn = self.get_conn_internal().await?;
|
||||
let prefix = REDIS_KEY_PREFIX.as_str();
|
||||
|
||||
let key = format!("{}job:{}", prefix, uuid);
|
||||
let _: i32 = conn.del(&key).await?;
|
||||
|
||||
let processor_types = [
|
||||
"appearance",
|
||||
"asr",
|
||||
"cut",
|
||||
"ocr",
|
||||
"face",
|
||||
"pose",
|
||||
"asrx",
|
||||
"visual_chunk",
|
||||
"story",
|
||||
"tmdb_probe",
|
||||
"embedding",
|
||||
];
|
||||
for ptype in processor_types {
|
||||
let proc_key = format!("{}job:{}:processor:{}", prefix, uuid, ptype);
|
||||
let _: i32 = conn.del(&proc_key).await?;
|
||||
|
||||
// 1. Find all related keys using SCAN (better performance than KEYS)
|
||||
let pattern = format!("{}job:{}*", prefix, uuid);
|
||||
let mut cursor: u64 = 0;
|
||||
let mut keys_to_delete = Vec::new();
|
||||
|
||||
loop {
|
||||
let result: (u64, Vec<String>) = redis::cmd("SCAN")
|
||||
.arg(&[&cursor.to_string(), "MATCH", &pattern, "COUNT", "100"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
let (new_cursor, keys) = result;
|
||||
keys_to_delete.extend(keys);
|
||||
|
||||
cursor = new_cursor;
|
||||
if cursor == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 2. Batch delete all keys
|
||||
if !keys_to_delete.is_empty() {
|
||||
let field_refs: Vec<&str> = keys_to_delete.iter().map(|s| s.as_str()).collect();
|
||||
let _: () = redis::cmd("DEL")
|
||||
.arg(&field_refs)
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// 3. Delete progress keys
|
||||
let progress_key = format!("{}progress:{}", prefix, uuid);
|
||||
let _: i32 = conn.del(&progress_key).await?;
|
||||
|
||||
let _: () = conn.del(&progress_key).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod client;
|
||||
pub mod function_calling;
|
||||
pub mod prompts;
|
||||
pub mod rerank;
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PromptTemplate {
|
||||
pub system_prompt: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub user_prompt: Option<String>,
|
||||
#[serde(default = "default_max_tokens")]
|
||||
pub max_tokens: u32,
|
||||
}
|
||||
|
||||
fn default_max_tokens() -> u32 {
|
||||
300
|
||||
}
|
||||
|
||||
static PROMPT_TEMPLATES: Lazy<HashMap<String, HashMap<String, PromptTemplate>>> = Lazy::new(|| {
|
||||
let mut templates = HashMap::new();
|
||||
|
||||
templates.insert("agent_search".to_string(), {
|
||||
let mut lang_map = HashMap::new();
|
||||
|
||||
lang_map.insert("en".to_string(), PromptTemplate {
|
||||
system_prompt: "You are a professional video analysis assistant for a digital asset management system. Respond concisely in English.".to_string(),
|
||||
user_prompt: None,
|
||||
max_tokens: 1024,
|
||||
});
|
||||
|
||||
lang_map.insert("zh-TW".to_string(), PromptTemplate {
|
||||
system_prompt: "你是一個專業的影片分析助手,服務於數位資產管理系統。請用繁體中文簡潔回答。".to_string(),
|
||||
user_prompt: None,
|
||||
max_tokens: 1024,
|
||||
});
|
||||
|
||||
lang_map.insert("ja".to_string(), PromptTemplate {
|
||||
system_prompt: "あなたはデジタルアセット管理システムのプロフェッショナルなビデオ分析アシスタントです。日本語で簡潔に回答してください。".to_string(),
|
||||
user_prompt: None,
|
||||
max_tokens: 1024,
|
||||
});
|
||||
|
||||
lang_map
|
||||
});
|
||||
|
||||
templates.insert("vlm_summary".to_string(), {
|
||||
let mut lang_map = HashMap::new();
|
||||
|
||||
lang_map.insert("en".to_string(), PromptTemplate {
|
||||
system_prompt: "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 English) describing: what is happening, the people present (clothing/appearance), the setting/location, and any notable objects or actions. Be factual and specific.".to_string(),
|
||||
user_prompt: Some("Summarize this key frame.".to_string()),
|
||||
max_tokens: 900,
|
||||
});
|
||||
|
||||
lang_map.insert("zh-TW".to_string(), PromptTemplate {
|
||||
system_prompt: "你是影片監控/數位資產管理系統的場景分析助手。請根據影片關鍵幀,撰寫簡潔摘要(2-4句,使用繁體中文),描述:發生的事情、人物(衣著/外觀)、場景/地點、以及任何顯著的物體或動作。請具體且準確。".to_string(),
|
||||
user_prompt: Some("總結這個關鍵幀。".to_string()),
|
||||
max_tokens: 900,
|
||||
});
|
||||
|
||||
lang_map.insert("ja".to_string(), PromptTemplate {
|
||||
system_prompt: "あなたはビデオ監視/DAMシステムのシーン分析アシスタントです。ビデオのキーフレームを分析し、簡潔な要約(2-4文、日本語)を作成してください:何が起きているか、登場人物(服装/外見)、場所/設定、目立つ物体や動作について説明してください。具体的かつ正確に記述してください。".to_string(),
|
||||
user_prompt: Some("このキーフレームを要約してください。".to_string()),
|
||||
max_tokens: 900,
|
||||
});
|
||||
|
||||
lang_map
|
||||
});
|
||||
|
||||
templates.insert("scene_vlm".to_string(), {
|
||||
let mut lang_map = HashMap::new();
|
||||
|
||||
lang_map.insert("en".to_string(), PromptTemplate {
|
||||
system_prompt: "You are a professional scene analyzer. Describe the scene in English, including the main subjects, actions, setting, and notable objects. Be concise (2-3 sentences).".to_string(),
|
||||
user_prompt: Some("Describe this scene.".to_string()),
|
||||
max_tokens: 300,
|
||||
});
|
||||
|
||||
lang_map.insert("zh-TW".to_string(), PromptTemplate {
|
||||
system_prompt: "你是專業的場景分析師。請用繁體中文描述場景,包括主要對象、動作、場景設置和顯著物體。請簡潔(2-3句)。".to_string(),
|
||||
user_prompt: Some("描述這個場景。".to_string()),
|
||||
max_tokens: 300,
|
||||
});
|
||||
|
||||
lang_map.insert("ja".to_string(), PromptTemplate {
|
||||
system_prompt: "あなたはプロフェッショナルなシーンアナライザーです。日本語でシーンを説明し、主要な被写体、アクション、設定、目立つ物体を含めてください。簡潔に(2-3文)記述してください。".to_string(),
|
||||
user_prompt: Some("このシーンを説明してください。".to_string()),
|
||||
max_tokens: 300,
|
||||
});
|
||||
|
||||
lang_map
|
||||
});
|
||||
|
||||
templates.insert("analyze_frame".to_string(), {
|
||||
let mut lang_map = HashMap::new();
|
||||
|
||||
lang_map.insert("en".to_string(), PromptTemplate {
|
||||
system_prompt: "You are a professional video frame analyst. Describe what you see in this frame in English, including people, objects, actions, and the scene setting. Be detailed but concise.".to_string(),
|
||||
user_prompt: None,
|
||||
max_tokens: 1024,
|
||||
});
|
||||
|
||||
lang_map.insert("zh-TW".to_string(), PromptTemplate {
|
||||
system_prompt: "你是專業的影片畫面分析師。請用繁體中文描述畫面中的內容,包括人物、物體、動作和場景設置。請詳細但簡潔。".to_string(),
|
||||
user_prompt: None,
|
||||
max_tokens: 1024,
|
||||
});
|
||||
|
||||
lang_map.insert("ja".to_string(), PromptTemplate {
|
||||
system_prompt: "あなたはプロフェッショナルなビデオフレームアナリストです。日本語でこのフレームに見えるものを説明してください。人物、物体、アクション、シーン設定を含めてください。詳細かつ簡潔に記述してください。".to_string(),
|
||||
user_prompt: None,
|
||||
max_tokens: 1024,
|
||||
});
|
||||
|
||||
lang_map
|
||||
});
|
||||
|
||||
templates
|
||||
});
|
||||
|
||||
pub fn get_system_prompt(module: &str, language: &str) -> String {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get(language))
|
||||
.or_else(|| {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get("en"))
|
||||
})
|
||||
.map(|template| template.system_prompt.clone())
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
"No prompt template found for module '{}' with language '{}', using default",
|
||||
module,
|
||||
language
|
||||
);
|
||||
format!(
|
||||
"You are a helpful assistant. Respond in {}.",
|
||||
match language {
|
||||
"zh-TW" => "Traditional Chinese",
|
||||
"ja" => "Japanese",
|
||||
_ => "English",
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_user_prompt(module: &str, language: &str) -> Option<String> {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get(language))
|
||||
.or_else(|| {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get("en"))
|
||||
})
|
||||
.and_then(|template| template.user_prompt.clone())
|
||||
}
|
||||
|
||||
pub fn get_max_tokens(module: &str, language: &str) -> u32 {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get(language))
|
||||
.or_else(|| {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get("en"))
|
||||
})
|
||||
.map(|template| template.max_tokens)
|
||||
.unwrap_or(300)
|
||||
}
|
||||
|
||||
pub fn get_prompt_template(module: &str, language: &str) -> Option<PromptTemplate> {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.and_then(|lang_map| lang_map.get(language))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn list_available_modules() -> Vec<String> {
|
||||
PROMPT_TEMPLATES.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn list_available_languages(module: &str) -> Vec<String> {
|
||||
PROMPT_TEMPLATES
|
||||
.get(module)
|
||||
.map(|lang_map| lang_map.keys().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_get_system_prompt() {
|
||||
let prompt = get_system_prompt("agent_search", "en");
|
||||
assert!(prompt.contains("professional video analysis assistant"));
|
||||
|
||||
let prompt_zh = get_system_prompt("agent_search", "zh-TW");
|
||||
assert!(prompt_zh.contains("專業的影片分析助手"));
|
||||
|
||||
let prompt_ja = get_system_prompt("agent_search", "ja");
|
||||
assert!(prompt_ja.contains("プロフェッショナルなビデオ分析アシスタント"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fallback_to_english() {
|
||||
let prompt = get_system_prompt("agent_search", "unknown");
|
||||
assert!(prompt.contains("professional video analysis assistant"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_max_tokens() {
|
||||
let tokens = get_max_tokens("agent_search", "en");
|
||||
assert_eq!(tokens, 1024);
|
||||
|
||||
let tokens_vlm = get_max_tokens("vlm_summary", "en");
|
||||
assert_eq!(tokens_vlm, 900);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_modules() {
|
||||
let modules = list_available_modules();
|
||||
assert!(modules.contains(&"agent_search".to_string()));
|
||||
assert!(modules.contains(&"vlm_summary".to_string()));
|
||||
}
|
||||
}
|
||||
+40
-21
@@ -39,6 +39,8 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceResult {
|
||||
#[serde(default = "default_schema_version")]
|
||||
pub schema_version: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<ProcessorMetadata>,
|
||||
#[serde(default)]
|
||||
@@ -50,6 +52,10 @@ pub struct FaceResult {
|
||||
pub total_faces: usize,
|
||||
}
|
||||
|
||||
fn default_schema_version() -> String {
|
||||
"2.0".to_string()
|
||||
}
|
||||
|
||||
impl FaceResult {
|
||||
pub fn compute_status(&mut self) {
|
||||
for frame in &mut self.frames {
|
||||
@@ -100,6 +106,7 @@ impl FaceResult {
|
||||
|
||||
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
|
||||
FaceResult {
|
||||
schema_version: "2.0".to_string(),
|
||||
metadata: None,
|
||||
status: Some(FaceStatus::NoFaces),
|
||||
frame_count,
|
||||
@@ -128,9 +135,18 @@ pub struct Face {
|
||||
pub width: i32,
|
||||
#[serde(default)]
|
||||
pub height: i32,
|
||||
#[serde(default)]
|
||||
pub x2: i32,
|
||||
#[serde(default)]
|
||||
pub y2: i32,
|
||||
#[serde(default)]
|
||||
pub center_x: i32,
|
||||
#[serde(default)]
|
||||
pub center_y: i32,
|
||||
pub confidence: f32,
|
||||
#[serde(default, rename = "captureQuality", alias = "capture_quality")]
|
||||
pub capture_quality: Option<f32>,
|
||||
#[serde(default)]
|
||||
pub embedding: Option<Vec<f32>>,
|
||||
pub landmarks: Option<serde_json::Value>,
|
||||
pub pose_angle: Option<serde_json::Value>,
|
||||
@@ -161,6 +177,12 @@ impl Face {
|
||||
self.width = bbox.width;
|
||||
self.height = bbox.height;
|
||||
}
|
||||
// Calculate derived bbox fields
|
||||
self.x2 = self.x + self.width;
|
||||
self.y2 = self.y + self.height;
|
||||
self.center_x = self.x + self.width / 2;
|
||||
self.center_y = self.y + self.height / 2;
|
||||
|
||||
if let Some(pose) = &self.pose {
|
||||
self.pose_angle = Some(pose.clone());
|
||||
}
|
||||
@@ -583,6 +605,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_face_result_serialization() {
|
||||
let result = FaceResult {
|
||||
schema_version: "2.0".to_string(),
|
||||
metadata: None,
|
||||
status: None,
|
||||
frame_count: 100,
|
||||
@@ -682,6 +705,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_face_result_empty_frames() {
|
||||
let result = FaceResult {
|
||||
schema_version: "2.0".to_string(),
|
||||
status: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
@@ -777,15 +801,24 @@ pub async fn store_face_embeddings_to_qdrant(
|
||||
let payload = serde_json::json!({
|
||||
"file_uuid": file_uuid,
|
||||
"frame": frame_num,
|
||||
"timestamp_secs": timestamp_secs,
|
||||
"timestamp": timestamp_secs,
|
||||
"face_id": face_id,
|
||||
"confidence": face.confidence,
|
||||
"x": face.x,
|
||||
"y": face.y,
|
||||
"width": face.width,
|
||||
"height": face.height,
|
||||
"capture_quality": face.capture_quality.unwrap_or(0.0),
|
||||
"bbox": {
|
||||
"x": face.x,
|
||||
"y": face.y,
|
||||
"width": face.width,
|
||||
"height": face.height,
|
||||
"x2": face.x2,
|
||||
"y2": face.y2,
|
||||
"center_x": face.center_x,
|
||||
"center_y": face.center_y
|
||||
},
|
||||
"pose": face.pose_angle.clone().unwrap_or(serde_json::json!({})),
|
||||
"landmarks": face.landmarks.clone().unwrap_or(serde_json::json!({})),
|
||||
"trace_id": -1i32, // Will be updated by face tracing
|
||||
"identity_id": null
|
||||
});
|
||||
|
||||
points.push((point_id, embedding.clone(), payload));
|
||||
@@ -829,22 +862,8 @@ pub async fn store_face_embeddings_to_qdrant(
|
||||
|
||||
tracing::info!("[FACE] Stored {} embeddings to Qdrant", total_points);
|
||||
|
||||
// Remove embeddings from in-memory result
|
||||
for frame in &mut face_result.frames {
|
||||
for face in &mut frame.faces {
|
||||
face.embedding = None;
|
||||
}
|
||||
}
|
||||
|
||||
// Save cleaned JSON back
|
||||
let json_str = serde_json::to_string_pretty(&face_result)
|
||||
.context("Failed to serialize cleaned face result")?;
|
||||
std::fs::write(output_path, &json_str).context("Failed to write cleaned face.json")?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE] Removed embeddings from JSON, saved to {}",
|
||||
output_path
|
||||
);
|
||||
// Keep embeddings in JSON (JSON is source of truth)
|
||||
// No longer remove embeddings from JSON
|
||||
|
||||
Ok(total_points)
|
||||
}
|
||||
|
||||
@@ -8,15 +8,54 @@ const FACE_CLUSTER_TIMEOUT: Duration = Duration::from_secs(3600);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceClusterResult {
|
||||
#[serde(default = "default_schema_version")]
|
||||
pub schema_version: String,
|
||||
#[serde(default)]
|
||||
pub file_uuid: Option<String>,
|
||||
pub status: String,
|
||||
pub stats: ClusterStats,
|
||||
pub clusters: Vec<FaceClusterInfo>,
|
||||
#[serde(default)]
|
||||
pub unassigned_traces: Vec<i32>,
|
||||
#[serde(default)]
|
||||
pub speaker_person_mapping: serde_json::Value,
|
||||
#[serde(default)]
|
||||
pub frames: Vec<FaceClusterFrame>,
|
||||
}
|
||||
|
||||
fn default_schema_version() -> String {
|
||||
"2.0".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
|
||||
pub struct ClusterStats {
|
||||
#[serde(default)]
|
||||
pub total_clusters: usize,
|
||||
#[serde(default)]
|
||||
pub unassigned_traces: usize,
|
||||
#[serde(default)]
|
||||
pub total_traces: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceClusterInfo {
|
||||
pub cluster_id: String,
|
||||
pub cluster_id: i32,
|
||||
pub group_name: String,
|
||||
#[serde(default)]
|
||||
pub trace_ids: Vec<i32>,
|
||||
#[serde(default)]
|
||||
pub total_faces: usize,
|
||||
#[serde(default)]
|
||||
pub representative_trace: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub confidence: f64,
|
||||
#[serde(default)]
|
||||
pub created_at: Option<String>,
|
||||
#[serde(default)]
|
||||
pub face_count: usize,
|
||||
#[serde(default)]
|
||||
pub representative_face: Option<RepresentativeFace>,
|
||||
#[serde(default)]
|
||||
pub similarity: Option<ClusterSimilarity>,
|
||||
}
|
||||
|
||||
@@ -37,10 +76,18 @@ pub struct RepresentativeFace {
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct BoundingBox {
|
||||
pub x: u64,
|
||||
pub y: u64,
|
||||
pub width: u64,
|
||||
pub height: u64,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
#[serde(default)]
|
||||
pub x2: i32,
|
||||
#[serde(default)]
|
||||
pub y2: i32,
|
||||
#[serde(default)]
|
||||
pub center_x: i32,
|
||||
#[serde(default)]
|
||||
pub center_y: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
@@ -58,6 +105,22 @@ pub struct ClusteredFace {
|
||||
pub confidence: f32,
|
||||
}
|
||||
|
||||
impl FaceClusterResult {
|
||||
pub fn add_metadata(&mut self, file_uuid: &str) {
|
||||
self.file_uuid = Some(file_uuid.to_string());
|
||||
self.status = "completed".to_string();
|
||||
self.stats.total_clusters = self.clusters.len();
|
||||
self.stats.total_traces = self.clusters.iter().map(|c| c.trace_ids.len()).sum();
|
||||
self.stats.unassigned_traces = self.unassigned_traces.len();
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
|
||||
.context("Failed to write face_cluster.json")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn process_face_cluster(
|
||||
video_path: &str,
|
||||
output_path: &str,
|
||||
@@ -73,7 +136,13 @@ pub async fn process_face_cluster(
|
||||
if !script_path.exists() {
|
||||
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
|
||||
return Ok(FaceClusterResult {
|
||||
schema_version: "2.0".to_string(),
|
||||
file_uuid: None,
|
||||
status: "no_faces".to_string(),
|
||||
stats: ClusterStats::default(),
|
||||
clusters: vec![],
|
||||
unassigned_traces: vec![],
|
||||
speaker_person_mapping: serde_json::json!({}),
|
||||
frames: vec![],
|
||||
});
|
||||
}
|
||||
@@ -116,8 +185,15 @@ 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)
|
||||
let mut result: FaceClusterResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse FACE_CLUSTER output")?;
|
||||
|
||||
if let Some(uuid) = uuid {
|
||||
result.add_metadata(uuid);
|
||||
}
|
||||
result.status = "completed".to_string();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
|
||||
result.clusters.len(),
|
||||
@@ -151,8 +227,14 @@ pub async fn process_face_cluster(
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read FACE_CLUSTER output")?;
|
||||
|
||||
let result: FaceClusterResult =
|
||||
let mut result: FaceClusterResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
|
||||
|
||||
if let Some(uuid) = uuid {
|
||||
result.add_metadata(uuid);
|
||||
}
|
||||
result.status = "completed".to_string();
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FACE_CLUSTER] Result: {} clusters, {} frames",
|
||||
|
||||
+27
@@ -398,6 +398,33 @@ async fn handle_worker(
|
||||
PostgresDb::run_migrations(db.pool()).await?;
|
||||
println!("Migrations completed");
|
||||
|
||||
// ── Execute Redis Health Check ─────────────────────────────────────────
|
||||
{
|
||||
use momentry_core::worker::redis_health_check::RedisHealthChecker;
|
||||
use momentry_core::core::config::REDIS_KEY_PREFIX;
|
||||
|
||||
let redis_url = std::env::var("REDIS_URL")
|
||||
.unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
|
||||
let health_checker = RedisHealthChecker::new(redis_url, 86400);
|
||||
|
||||
println!("Running Redis health check on startup...");
|
||||
match health_checker.check(REDIS_KEY_PREFIX.as_str()).await {
|
||||
Ok(report) => {
|
||||
println!(
|
||||
"✅ Health check completed: {} orphans cleaned, {} TTLs fixed, {} stale jobs marked",
|
||||
report.orphan_processors_cleaned,
|
||||
report.ttls_fixed,
|
||||
report.stale_jobs_marked
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ Health check failed (continuing anyway): {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
let worker = JobWorker::new(
|
||||
std::sync::Arc::new(db),
|
||||
std::sync::Arc::new(redis),
|
||||
|
||||
@@ -1849,7 +1849,27 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.trim_end_matches('/'),
|
||||
job.uuid
|
||||
);
|
||||
if !std::path::Path::new(&traced_path).exists() {
|
||||
// ✅ V2: Validate file integrity, not just existence
|
||||
let trace_complete = if std::path::Path::new(&traced_path).exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
let frames = traced_data.get("frames");
|
||||
frames.map_or(false, |f| match f {
|
||||
serde_json::Value::Array(arr) => !arr.is_empty(),
|
||||
serde_json::Value::Object(obj) => !obj.is_empty(),
|
||||
_ => false,
|
||||
})
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if !trace_complete {
|
||||
info!(
|
||||
"FaceCluster deferred: face_traced.json not yet ready for {}",
|
||||
job.uuid
|
||||
|
||||
@@ -5,3 +5,6 @@ pub mod resources;
|
||||
|
||||
pub use config::WorkerConfig;
|
||||
pub use job_worker::JobWorker;
|
||||
|
||||
// Redis Health Check Module
|
||||
pub mod redis_health_check;
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Redis Health Check Module
|
||||
//!
|
||||
//! Detects and fixes Redis data inconsistencies during Worker startup.
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
/// Redis Health Checker
|
||||
pub struct RedisHealthChecker {
|
||||
redis_url: String,
|
||||
job_ttl_secs: i64,
|
||||
}
|
||||
|
||||
/// Health Check Report
|
||||
#[derive(Debug, Clone, Default, serde::Serialize)]
|
||||
pub struct HealthCheckReport {
|
||||
pub orphan_processors_cleaned: usize,
|
||||
pub ttls_fixed: usize,
|
||||
pub stale_jobs_marked: usize,
|
||||
pub total_jobs_checked: usize,
|
||||
pub total_processors_checked: usize,
|
||||
}
|
||||
|
||||
impl RedisHealthChecker {
|
||||
/// Create new health checker
|
||||
pub fn new(redis_url: String, job_ttl_secs: i64) -> Self {
|
||||
Self {
|
||||
redis_url,
|
||||
job_ttl_secs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute full health check
|
||||
pub async fn check(&self, prefix: &str) -> Result<HealthCheckReport> {
|
||||
let mut report = HealthCheckReport::default();
|
||||
|
||||
tracing::info!("Starting Redis health check (prefix: {})", prefix);
|
||||
|
||||
// 1. Check orphan processors
|
||||
self.check_orphan_processors(prefix, &mut report).await?;
|
||||
|
||||
// 2. Check TTL consistency
|
||||
self.check_ttl_consistency(prefix, &mut report).await?;
|
||||
|
||||
// 3. Check stale jobs
|
||||
self.check_stale_jobs(prefix, &mut report).await?;
|
||||
|
||||
tracing::info!(
|
||||
"Health check completed: {} orphans cleaned, {} TTLs fixed, {} stale jobs marked",
|
||||
report.orphan_processors_cleaned,
|
||||
report.ttls_fixed,
|
||||
report.stale_jobs_marked
|
||||
);
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Check orphan processor keys
|
||||
async fn check_orphan_processors(
|
||||
&self,
|
||||
prefix: &str,
|
||||
report: &mut HealthCheckReport,
|
||||
) -> Result<()> {
|
||||
let client = redis::Client::open(self.redis_url.as_str())?;
|
||||
let mut conn = client.get_multiplexed_async_connection().await?;
|
||||
|
||||
let pattern = format!("{}job:*:processor:*", prefix);
|
||||
let mut cursor: u64 = 0;
|
||||
|
||||
loop {
|
||||
let (new_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
|
||||
.arg(&[&cursor.to_string(), "MATCH", &pattern, "COUNT", "100"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
report.total_processors_checked += keys.len();
|
||||
|
||||
for key in keys {
|
||||
if let Some(uuid) = Self::extract_uuid_from_processor_key(&key, prefix) {
|
||||
let main_key = format!("{}job:{}", prefix, uuid);
|
||||
|
||||
let exists: i64 = redis::cmd("EXISTS")
|
||||
.arg(&[&main_key])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
if exists == 0 {
|
||||
tracing::warn!("Orphan processor key: {}", key);
|
||||
|
||||
let _: () = redis::cmd("DEL")
|
||||
.arg(&[&key])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
report.orphan_processors_cleaned += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cursor = new_cursor;
|
||||
if cursor == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check TTL consistency
|
||||
async fn check_ttl_consistency(
|
||||
&self,
|
||||
prefix: &str,
|
||||
report: &mut HealthCheckReport,
|
||||
) -> Result<()> {
|
||||
let client = redis::Client::open(self.redis_url.as_str())?;
|
||||
let mut conn = client.get_multiplexed_async_connection().await?;
|
||||
|
||||
let pattern = format!("{}job:*", prefix);
|
||||
let mut cursor: u64 = 0;
|
||||
|
||||
loop {
|
||||
let (new_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
|
||||
.arg(&[&cursor.to_string(), "MATCH", &pattern, "COUNT", "100"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
for key in keys {
|
||||
if key.contains(":processor:") {
|
||||
continue;
|
||||
}
|
||||
|
||||
report.total_jobs_checked += 1;
|
||||
|
||||
let ttl: i64 = redis::cmd("TTL")
|
||||
.arg(&[&key])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
if ttl == -1 || (ttl > 0 && ttl < 3600) {
|
||||
tracing::warn!("Job {} has invalid TTL: {}", key, ttl);
|
||||
|
||||
let _: () = redis::cmd("EXPIRE")
|
||||
.arg(&[&key, &self.job_ttl_secs.to_string()])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
report.ttls_fixed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
cursor = new_cursor;
|
||||
if cursor == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check stale jobs
|
||||
async fn check_stale_jobs(
|
||||
&self,
|
||||
prefix: &str,
|
||||
report: &mut HealthCheckReport,
|
||||
) -> Result<()> {
|
||||
let client = redis::Client::open(self.redis_url.as_str())?;
|
||||
let mut conn = client.get_multiplexed_async_connection().await?;
|
||||
|
||||
let pattern = format!("{}job:*", prefix);
|
||||
let mut cursor: u64 = 0;
|
||||
let timeout_threshold_secs = 7200;
|
||||
|
||||
loop {
|
||||
let (new_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
|
||||
.arg(&[&cursor.to_string(), "MATCH", &pattern, "COUNT", "100"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
for key in keys {
|
||||
if key.contains(":processor:") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let status: Option<String> = redis::cmd("HGET")
|
||||
.arg(&[&key, "status"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
if status.as_deref() == Some("running") {
|
||||
let updated_at: Option<String> = redis::cmd("HGET")
|
||||
.arg(&[&key, "updated_at"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
if let Some(updated_str) = updated_at {
|
||||
if let Ok(updated) = DateTime::parse_from_rfc3339(&updated_str) {
|
||||
let elapsed = (Utc::now() - updated.with_timezone(&Utc)).num_seconds();
|
||||
|
||||
if elapsed > timeout_threshold_secs {
|
||||
tracing::warn!("Stale job: {} ({}s)", key, elapsed);
|
||||
|
||||
let _: () = redis::cmd("HSET")
|
||||
.arg(&[&key, "status", "timeout"])
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
report.stale_jobs_marked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cursor = new_cursor;
|
||||
if cursor == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_uuid_from_processor_key(key: &str, prefix: &str) -> Option<String> {
|
||||
let pattern = format!("{}job:", prefix);
|
||||
if key.starts_with(&pattern) {
|
||||
let rest = key.strip_prefix(&pattern)?;
|
||||
let parts: Vec<&str> = rest.split(":processor:").collect();
|
||||
if parts.len() >= 2 {
|
||||
Some(parts[0].to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_extract_uuid() {
|
||||
let prefix = "momentry:";
|
||||
let key = "momentry:job:c1a3e24c92133c0ea022ca7efd04a6fe:processor:face_trace";
|
||||
let uuid = RedisHealthChecker::extract_uuid_from_processor_key(key, prefix);
|
||||
assert_eq!(uuid, Some("c1a3e24c92133c0ea022ca7efd04a6fe".to_string()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user