feat: implement service management API for VLM control
- Add /api/v1/mbe/health endpoint for status checks - Add /api/v2/service/start to start llama-server - Add /api/v2/service/stop to stop llama-server - Use TCP connection test for port detection (more reliable than lsof) - Add ps aux fallback for PID detection - Implement structured bilingual VLM tags - Add VLM integration documentation for Studio team Endpoints tested and working with Momentry Studio AdminView UI.
This commit is contained in:
+23
-3
@@ -53,7 +53,8 @@ async fn translate_text(
|
||||
],
|
||||
"stream": false,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let response = LLM_CLIENT
|
||||
@@ -75,14 +76,33 @@ async fn translate_text(
|
||||
)
|
||||
})?;
|
||||
|
||||
let translated_text = llm_resp["choices"][0]["message"]["content"]
|
||||
let choice = llm_resp["choices"].get(0).ok_or((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Empty LLM response".to_string(),
|
||||
))?;
|
||||
if let Some(fr) = choice.get("finish_reason").and_then(|v| v.as_str()) {
|
||||
if fr == "length" {
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Translation truncated (finish_reason=length)".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let translated_text = choice["message"]["content"]
|
||||
.as_str()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if translated_text.trim().is_empty() {
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Translation returned empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Json(TranslationResponse {
|
||||
success: true,
|
||||
translated_text,
|
||||
translated_text: translated_text.trim().to_string(),
|
||||
source_language_detected: req.source_language.unwrap_or_else(|| "auto".to_string()),
|
||||
model_used: model.to_string(),
|
||||
}))
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod profile;
|
||||
pub mod scan;
|
||||
pub mod search;
|
||||
pub mod server;
|
||||
pub mod service_management;
|
||||
pub mod tmdb_api;
|
||||
pub mod trace_agent_api;
|
||||
pub mod types;
|
||||
|
||||
+4
-3
@@ -161,8 +161,8 @@ async fn enrich_vlm_from_pg(
|
||||
};
|
||||
|
||||
let tp_table = crate::core::db::schema::table_name("trace_profiles");
|
||||
let rows: Vec<(Option<i64>, Option<i64>, Option<String>)> = sqlx::query_as(&format!(
|
||||
"SELECT start_frame, end_frame, vlm_description FROM {tp_table} \
|
||||
let rows: Vec<(Option<i64>, Option<i64>, Option<String>, Option<String>)> = sqlx::query_as(&format!(
|
||||
"SELECT start_frame, end_frame, vlm_description, vlm_description_localized FROM {tp_table} \
|
||||
WHERE file_uuid = $1 AND trace_id = $2"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
@@ -171,7 +171,7 @@ async fn enrich_vlm_from_pg(
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let (start_frame, end_frame, vlm_desc) = rows.into_iter().next()?;
|
||||
let (start_frame, end_frame, vlm_desc, vlm_desc_localized) = rows.into_iter().next()?;
|
||||
let text = vlm_desc.unwrap_or_default();
|
||||
let sf = start_frame.unwrap_or(0);
|
||||
let ef = end_frame.unwrap_or(0);
|
||||
@@ -192,6 +192,7 @@ async fn enrich_vlm_from_pg(
|
||||
metadata: Some(serde_json::json!({
|
||||
"type": "vlm_summary",
|
||||
"trace_id": trace_id,
|
||||
"vlm_description_localized": vlm_desc_localized,
|
||||
})),
|
||||
similarity: Some(qdrant_score as f64),
|
||||
file_name: None,
|
||||
|
||||
@@ -35,6 +35,7 @@ use super::processing;
|
||||
use super::profile;
|
||||
use super::scan;
|
||||
use super::search::search_routes;
|
||||
use super::service_management;
|
||||
use super::tmdb_api;
|
||||
use super::trace_agent_api;
|
||||
use super::types::AppState;
|
||||
@@ -183,6 +184,10 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.route(
|
||||
"/api/v1/health/queue",
|
||||
axum::routing::get(health_queue),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/mbe/health",
|
||||
axum::routing::get(service_management::mbe_health),
|
||||
);
|
||||
|
||||
let app = Router::new()
|
||||
@@ -191,6 +196,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.merge(health::health_routes())
|
||||
.merge(docs::doc_routes())
|
||||
.merge(monitor::monitor_routes())
|
||||
.merge(service_management::router())
|
||||
.nest_service("/monitor", ServeDir::new("static/monitor"))
|
||||
.merge(protected_routes)
|
||||
.layer(cors)
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::api::types::AppState;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ServiceStartRequest {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub model: Option<String>,
|
||||
#[serde(default = "default_port")]
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
fn default_port() -> u16 {
|
||||
8080
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ServiceStopRequest {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ServiceResponse {
|
||||
pub result: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pid: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MbeHealthResponse {
|
||||
pub status: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub uptime: Option<u64>,
|
||||
}
|
||||
|
||||
/// Check if a port is in use by attempting to connect
|
||||
fn is_port_in_use(port: u16) -> bool {
|
||||
use std::net::TcpStream;
|
||||
|
||||
let addr = format!("127.0.0.1:{}", port);
|
||||
match TcpStream::connect(&addr) {
|
||||
Ok(_) => {
|
||||
tracing::info!("[Service] Port {} is in use (connection successful)", port);
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::info!("[Service] Port {} not in use: {}", port, e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get PID of process listening on a port using lsof
|
||||
fn get_port_pid(port: u16) -> Option<u32> {
|
||||
// Try lsof first
|
||||
let output = Command::new("/usr/sbin/lsof")
|
||||
.args(["-nP", "-iTCP", &format!("{}", port), "-t"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
let pid_str = String::from_utf8_lossy(&output.stdout);
|
||||
return pid_str.trim().parse::<u32>().ok();
|
||||
}
|
||||
|
||||
// Fallback: try to find by process name and port
|
||||
let output = Command::new("ps")
|
||||
.args(["aux"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
for line in stdout.lines() {
|
||||
if line.contains("llama-server") && line.contains(&format!("--port {}", port)) {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() > 1 {
|
||||
return parts[1].parse::<u32>().ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Kill process by PID
|
||||
fn kill_process(pid: u32) -> bool {
|
||||
Command::new("kill")
|
||||
.arg(pid.to_string())
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Start llama.cpp server
|
||||
async fn start_llama_server(port: u16, model: Option<String>) -> Result<u32, String> {
|
||||
// Check if port is already in use
|
||||
if is_port_in_use(port) {
|
||||
if let Some(pid) = get_port_pid(port) {
|
||||
tracing::info!("[Service] Port {} is occupied by PID {}, stopping it", port, pid);
|
||||
kill_process(pid);
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Default model path
|
||||
let model_path = model.unwrap_or_else(|| {
|
||||
"/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf".to_string()
|
||||
});
|
||||
|
||||
let mmproj_path = "/Users/accusys/models/mmproj-F16.gguf";
|
||||
let llama_binary = "/Users/accusys/llama.cpp/build/bin/llama-server";
|
||||
|
||||
tracing::info!("[Service] Spawning llama-server: {} with model {}", llama_binary, model_path);
|
||||
|
||||
// Start llama-server with proper PATH
|
||||
let mut cmd = Command::new(llama_binary);
|
||||
cmd.args([
|
||||
"-m", &model_path,
|
||||
"--mmproj", mmproj_path,
|
||||
"--host", "0.0.0.0",
|
||||
"--port", &port.to_string(),
|
||||
"-ngl", "99",
|
||||
"-c", "8192",
|
||||
"--temp", "0.1",
|
||||
"-b", "4096",
|
||||
"-ub", "4096",
|
||||
]);
|
||||
|
||||
// Set environment variables including PATH
|
||||
cmd.env("PATH", "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin");
|
||||
|
||||
// Spawn the process
|
||||
let mut child = cmd.spawn()
|
||||
.map_err(|e| format!("Failed to start llama-server: {}", e))?;
|
||||
|
||||
let pid = child.id();
|
||||
tracing::info!("[Service] Started llama-server with PID {}", pid);
|
||||
|
||||
// Detach the child process so it continues running independently
|
||||
std::mem::forget(child);
|
||||
|
||||
// Wait for server to be ready
|
||||
for i in 0..30 {
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
|
||||
if is_port_in_use(port) {
|
||||
// Try to call health endpoint
|
||||
let health_url = format!("http://127.0.0.1:{}/v1/models", port);
|
||||
if let Ok(resp) = reqwest::get(&health_url).await {
|
||||
if resp.status().is_success() {
|
||||
tracing::info!("[Service] llama-server is ready after {} seconds", i * 2);
|
||||
return Ok(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err("llama-server failed to start within 60 seconds".to_string())
|
||||
}
|
||||
|
||||
/// Stop llama.cpp server
|
||||
fn stop_llama_server(port: u16) -> Result<(), String> {
|
||||
if let Some(pid) = get_port_pid(port) {
|
||||
tracing::info!("[Service] Stopping llama-server on port {} (PID {})", port, pid);
|
||||
if kill_process(pid) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Failed to kill process {}", pid))
|
||||
}
|
||||
} else {
|
||||
Err(format!("No service running on port {}", port))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check MBE health
|
||||
async fn check_mbe_health(port: u16) -> Result<MbeHealthResponse, String> {
|
||||
tracing::info!("[Service] Checking MBE health on port {}", port);
|
||||
|
||||
if !is_port_in_use(port) {
|
||||
tracing::warn!("[Service] Port {} not in use", port);
|
||||
return Err("Port not in use".to_string());
|
||||
}
|
||||
|
||||
tracing::info!("[Service] Port {} is in use, checking HTTP endpoint", port);
|
||||
|
||||
let url = format!("http://127.0.0.1:{}/v1/models", port);
|
||||
let resp = reqwest::get(&url)
|
||||
.await
|
||||
.map_err(|e| format!("HTTP request failed: {}", e))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("HTTP {}", resp.status()));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = resp.json().await
|
||||
.map_err(|e| format!("Failed to parse JSON: {}", e))?;
|
||||
|
||||
tracing::info!("[Service] Health check response: {:?}", json);
|
||||
|
||||
// Extract model name from /v1/models response
|
||||
let model = json["models"][0]["name"]
|
||||
.as_str()
|
||||
.map(|s| {
|
||||
// Extract just the model name from path
|
||||
s.split('/')
|
||||
.last()
|
||||
.unwrap_or(s)
|
||||
.to_string()
|
||||
});
|
||||
|
||||
Ok(MbeHealthResponse {
|
||||
status: "ok".to_string(),
|
||||
model,
|
||||
uptime: Some(0), // Would need to track actual uptime
|
||||
})
|
||||
}
|
||||
|
||||
/// POST /api/v2/service/start
|
||||
pub async fn start_service(
|
||||
State(_state): State<AppState>,
|
||||
Json(req): Json<ServiceStartRequest>,
|
||||
) -> Result<Json<ServiceResponse>, StatusCode> {
|
||||
tracing::info!("[Service] Start request received: {:?}", req);
|
||||
|
||||
if req.name != "mbe" {
|
||||
tracing::error!("[Service] Invalid service name: {}", req.name);
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
let port = req.port;
|
||||
tracing::info!("[Service] Starting llama-server on port {}", port);
|
||||
|
||||
match start_llama_server(port, req.model).await {
|
||||
Ok(pid) => {
|
||||
tracing::info!("[Service] Successfully started llama-server with PID {}", pid);
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "started".to_string(),
|
||||
pid: Some(pid),
|
||||
error: None,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[Service] Failed to start service: {}", e);
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "failed".to_string(),
|
||||
pid: None,
|
||||
error: Some(e),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v2/service/stop
|
||||
pub async fn stop_service(
|
||||
State(_state): State<AppState>,
|
||||
Json(req): Json<ServiceStopRequest>,
|
||||
) -> Result<Json<ServiceResponse>, StatusCode> {
|
||||
tracing::info!("[Service] Stop request: {:?}", req);
|
||||
|
||||
if req.name != "mbe" {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
let port = 8080;
|
||||
|
||||
match stop_llama_server(port) {
|
||||
Ok(()) => {
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "stopped".to_string(),
|
||||
pid: None,
|
||||
error: None,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[Service] Failed to stop service: {}", e);
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "failed".to_string(),
|
||||
pid: None,
|
||||
error: Some(e),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/mbe/health
|
||||
pub async fn mbe_health(
|
||||
State(_state): State<AppState>,
|
||||
) -> Result<Json<MbeHealthResponse>, StatusCode> {
|
||||
let port = 8080;
|
||||
|
||||
match check_mbe_health(port).await {
|
||||
Ok(health) => Ok(Json(health)),
|
||||
Err(e) => {
|
||||
tracing::error!("[Service] Health check failed: {}", e);
|
||||
Ok(Json(MbeHealthResponse {
|
||||
status: "offline".to_string(),
|
||||
model: None,
|
||||
uptime: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router() -> axum::Router<AppState> {
|
||||
axum::Router::new()
|
||||
.route("/api/v2/service/start", axum::routing::post(start_service))
|
||||
.route("/api/v2/service/stop", axum::routing::post(stop_service))
|
||||
}
|
||||
+112
-36
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::api::types::AppState;
|
||||
use crate::core::admin_config::SearchConfig;
|
||||
use crate::core::file_profile::VlmTagValue;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ErrorResponse {
|
||||
@@ -74,8 +75,10 @@ pub struct SceneSearchResult {
|
||||
pub frame_number: u32,
|
||||
pub thumbnail_url: String,
|
||||
pub vlm_description: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vlm_description_localized: Option<String>,
|
||||
pub vlm_objects: Vec<String>,
|
||||
pub vlm_tags: Vec<String>,
|
||||
pub vlm_tags: Vec<VlmTagValue>,
|
||||
pub score: f64,
|
||||
pub source: String,
|
||||
}
|
||||
@@ -116,12 +119,28 @@ pub struct TraceSearchResult {
|
||||
pub identity_uuid: Option<String>,
|
||||
pub identity_name: Option<String>,
|
||||
pub vlm_description: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vlm_description_localized: Option<String>,
|
||||
pub vlm_clothing: Option<String>,
|
||||
pub vlm_tags: Vec<String>,
|
||||
pub vlm_location: Option<String>,
|
||||
pub thumbnail_url: String,
|
||||
pub score: f64,
|
||||
pub source: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub start_frame: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub end_frame: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub start_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub end_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub frame_number: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timestamp_sec: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub best_face_frame: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn search_vlm_scenes(
|
||||
@@ -206,15 +225,31 @@ pub async fn search_vlm_scenes(
|
||||
|
||||
// Filter by vlm_tags
|
||||
if let Some(ref tags) = filters.vlm_tags {
|
||||
let empty_vec = Vec::new();
|
||||
let payload_tags = payload
|
||||
.get("vlm_tags")
|
||||
.and_then(|v| v.as_array())
|
||||
.unwrap_or(&empty_vec);
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let all_match = tags
|
||||
.iter()
|
||||
.all(|tag| payload_tags.contains(&serde_json::json!(tag)));
|
||||
let all_match = tags.iter().all(|filter_tag| {
|
||||
let filter_lower = filter_tag.to_lowercase();
|
||||
payload_tags.iter().any(|tag| {
|
||||
if let Some(s) = tag.as_str() {
|
||||
return s.to_lowercase() == filter_lower || s.to_lowercase().contains(&filter_lower);
|
||||
}
|
||||
let en = tag
|
||||
.get("en")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_lowercase();
|
||||
let local = tag
|
||||
.get("local")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_lowercase();
|
||||
en == filter_lower || local == filter_lower || en.contains(&filter_lower) || local.contains(&filter_lower)
|
||||
})
|
||||
});
|
||||
|
||||
if !all_match {
|
||||
continue;
|
||||
@@ -272,6 +307,11 @@ pub async fn search_vlm_scenes(
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let vlm_description_localized = payload
|
||||
.get("vlm_description_localized")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
let vlm_objects = payload
|
||||
.get("vlm_objects")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -287,8 +327,8 @@ pub async fn search_vlm_scenes(
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.collect()
|
||||
.filter_map(|v| serde_json::from_value::<VlmTagValue>(v.clone()).ok())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -310,6 +350,7 @@ pub async fn search_vlm_scenes(
|
||||
file_uuid, scene_index
|
||||
),
|
||||
vlm_description,
|
||||
vlm_description_localized,
|
||||
vlm_objects,
|
||||
vlm_tags,
|
||||
score,
|
||||
@@ -463,34 +504,55 @@ pub async fn search_vlm_traces(
|
||||
}
|
||||
}
|
||||
|
||||
// Query file name + profile enrichment
|
||||
let (file_name, vlm_clothing, vlm_location, vlm_tags_arr, identity_uuid, identity_name) =
|
||||
sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<Vec<String>>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
),
|
||||
>(
|
||||
"SELECT COALESCE(v.file_name, ''), tp.vlm_clothing, tp.vlm_location, tp.vlm_tags, \
|
||||
i.uuid, i.name \
|
||||
FROM trace_profiles tp \
|
||||
LEFT JOIN videos v ON v.file_uuid = tp.file_uuid \
|
||||
LEFT JOIN identity_bindings ib ON ib.identity_type = 'trace' \
|
||||
AND ib.identity_value = tp.trace_id::text \
|
||||
LEFT JOIN identities i ON i.id = ib.identity_id \
|
||||
WHERE tp.file_uuid = $1 AND tp.trace_id = $2",
|
||||
)
|
||||
.bind(&file_uuid)
|
||||
.bind(trace_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| Json(ErrorResponse::new(format!("Database query failed: {}", e))))?
|
||||
.unwrap_or_default();
|
||||
// Query file name + profile enrichment + trace timing
|
||||
let row = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<Vec<String>>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<i64>,
|
||||
Option<i64>,
|
||||
Option<i32>,
|
||||
Option<i64>,
|
||||
Option<f64>,
|
||||
),
|
||||
>(
|
||||
"SELECT COALESCE(v.file_name, ''), tp.vlm_clothing, tp.vlm_location, tp.vlm_tags, \
|
||||
tp.vlm_description_localized, \
|
||||
i.uuid, i.name, tp.start_frame, tp.end_frame, tp.frame_count, tp.best_face_frame, \
|
||||
COALESCE(v.fps, 24.0) as fps \
|
||||
FROM trace_profiles tp \
|
||||
LEFT JOIN videos v ON v.file_uuid = tp.file_uuid \
|
||||
LEFT JOIN identity_bindings ib ON ib.identity_type = 'trace' \
|
||||
AND ib.identity_value = tp.trace_id::text \
|
||||
LEFT JOIN identities i ON i.id = ib.identity_id \
|
||||
WHERE tp.file_uuid = $1 AND tp.trace_id = $2",
|
||||
)
|
||||
.bind(&file_uuid)
|
||||
.bind(trace_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| Json(ErrorResponse::new(format!("Database query failed: {}", e))))?;
|
||||
|
||||
let (
|
||||
file_name,
|
||||
vlm_clothing,
|
||||
vlm_location,
|
||||
vlm_tags_arr,
|
||||
vlm_description_localized,
|
||||
identity_uuid,
|
||||
identity_name,
|
||||
start_frame,
|
||||
end_frame,
|
||||
_frame_count,
|
||||
best_face_frame,
|
||||
fps,
|
||||
) = row.unwrap_or_default();
|
||||
|
||||
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
|
||||
@@ -499,6 +561,12 @@ pub async fn search_vlm_traces(
|
||||
continue;
|
||||
}
|
||||
|
||||
let fps = fps.unwrap_or(24.0);
|
||||
let start_time = start_frame.map(|f| f as f64 / fps);
|
||||
let end_time = end_frame.map(|f| f as f64 / fps);
|
||||
let jump_frame = best_face_frame.or(start_frame);
|
||||
let jump_time = jump_frame.map(|f| f as f64 / fps);
|
||||
|
||||
results.push(TraceSearchResult {
|
||||
file_uuid: file_uuid.clone(),
|
||||
file_name,
|
||||
@@ -506,12 +574,20 @@ pub async fn search_vlm_traces(
|
||||
identity_uuid,
|
||||
identity_name,
|
||||
vlm_description,
|
||||
vlm_description_localized,
|
||||
vlm_clothing,
|
||||
vlm_tags: vlm_tags_arr.unwrap_or_default(),
|
||||
vlm_location,
|
||||
thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id),
|
||||
score,
|
||||
source: "vector".to_string(),
|
||||
start_frame,
|
||||
end_frame,
|
||||
start_time,
|
||||
end_time,
|
||||
frame_number: jump_frame,
|
||||
timestamp_sec: jump_time,
|
||||
best_face_frame,
|
||||
});
|
||||
|
||||
if results.len() >= req.page_size {
|
||||
|
||||
@@ -182,6 +182,7 @@ async fn main() -> Result<()> {
|
||||
scene.timestamp_sec,
|
||||
scene.frame_number,
|
||||
desc,
|
||||
scene.vlm_description_localized.as_deref(),
|
||||
&scene.vlm_objects,
|
||||
&scene.vlm_tags,
|
||||
)
|
||||
|
||||
@@ -40,8 +40,9 @@ async fn main() -> Result<()> {
|
||||
|
||||
println!("找到 {} 筆結果:", results.len());
|
||||
for (i, r) in results.iter().enumerate() {
|
||||
let text_preview: String = r.text.chars().take(60).collect();
|
||||
let text_preview = if r.text.chars().count() > 60 {
|
||||
let text: String = r.text.clone().unwrap_or_default();
|
||||
let text_preview: String = text.chars().take(60).collect();
|
||||
let text_preview = if text.chars().count() > 60 {
|
||||
format!("{}...", text_preview)
|
||||
} else {
|
||||
text_preview
|
||||
@@ -55,7 +56,10 @@ async fn main() -> Result<()> {
|
||||
);
|
||||
println!(
|
||||
" 分數: {:.4}, 時間: {:.1}-{:.1}s, 類型: {}",
|
||||
r.bm25_score, r.start_time, r.end_time, r.chunk_type
|
||||
r.bm25_score,
|
||||
r.start_time.unwrap_or(0.0),
|
||||
r.end_time.unwrap_or(0.0),
|
||||
r.chunk_type
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -329,7 +329,7 @@ fn default_vlm_min_score() -> f64 {
|
||||
|
||||
fn default_vlm_output_language() -> String {
|
||||
std::env::var("MOMENTRY_PREFERRED_LANGUAGE")
|
||||
.unwrap_or_else(|_| "zh-TW".to_string())
|
||||
.unwrap_or_else(|_| "ja".to_string())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -396,6 +396,12 @@ pub struct ServerConfig {
|
||||
pub serve_base_url: String,
|
||||
#[serde(default = "default_storage_root")]
|
||||
pub storage_root: String,
|
||||
#[serde(default = "default_system_timezone")]
|
||||
pub timezone: String,
|
||||
}
|
||||
|
||||
fn default_system_timezone() -> String {
|
||||
std::env::var("MOMENTRY_TIMEZONE").unwrap_or_else(|_| "Asia/Taipei".to_string())
|
||||
}
|
||||
|
||||
fn default_server_port() -> u16 {
|
||||
|
||||
+1
-1
@@ -352,7 +352,7 @@ pub mod llm {
|
||||
env::var("MOMENTRY_LLM_CHAT_MODEL")
|
||||
.or_else(|_| env::var("MOMENTRY_LLM_SUMMARY_MODEL"))
|
||||
.or_else(|_| env::var("MOMENTRY_LLM_MODEL"))
|
||||
.unwrap_or_else(|_| "e4b".to_string())
|
||||
.unwrap_or_else(|_| "gemma-4-12b-it".to_string())
|
||||
});
|
||||
|
||||
pub static VISION_URL: Lazy<String> =
|
||||
|
||||
+29
-18
@@ -545,21 +545,22 @@ pub enum PipelineType {
|
||||
Cross,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProcessorType {
|
||||
Cut,
|
||||
Asr,
|
||||
Ocr,
|
||||
Face,
|
||||
Pose,
|
||||
Hand,
|
||||
Asrx,
|
||||
Scene,
|
||||
Appearance,
|
||||
FaceCluster,
|
||||
FaceTrace,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProcessorType {
|
||||
Cut,
|
||||
Asr,
|
||||
Ocr,
|
||||
Face,
|
||||
Pose,
|
||||
Hand,
|
||||
Asrx,
|
||||
Scene,
|
||||
Appearance,
|
||||
FaceCluster,
|
||||
FaceTrace,
|
||||
Tkg,
|
||||
}
|
||||
|
||||
impl sqlx::Type<sqlx::Postgres> for ProcessorType {
|
||||
fn type_info() -> sqlx::postgres::PgTypeInfo {
|
||||
@@ -592,10 +593,11 @@ impl ProcessorType {
|
||||
ProcessorType::Pose => "pose",
|
||||
ProcessorType::Hand => "hand",
|
||||
ProcessorType::Asrx => "asrx",
|
||||
ProcessorType::Scene => "scene",
|
||||
ProcessorType::Scene => "scene_vlm",
|
||||
ProcessorType::Appearance => "appearance",
|
||||
ProcessorType::FaceCluster => "face_cluster",
|
||||
ProcessorType::FaceTrace => "face_trace",
|
||||
ProcessorType::Tkg => "tkg",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,9 +611,11 @@ impl ProcessorType {
|
||||
"hand" => Some(ProcessorType::Hand),
|
||||
"asrx" => Some(ProcessorType::Asrx),
|
||||
"scene" => Some(ProcessorType::Scene),
|
||||
"scene_vlm" => Some(ProcessorType::Scene), // Alias for scene
|
||||
"appearance" => Some(ProcessorType::Appearance),
|
||||
"face_cluster" => Some(ProcessorType::FaceCluster),
|
||||
"face_trace" => Some(ProcessorType::FaceTrace),
|
||||
"tkg" => Some(ProcessorType::Tkg),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -629,6 +633,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => 0.3,
|
||||
ProcessorType::FaceCluster => 0.7,
|
||||
ProcessorType::FaceTrace => 0.4,
|
||||
ProcessorType::Tkg => 0.5,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -652,6 +657,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => 512,
|
||||
ProcessorType::FaceCluster => 1024,
|
||||
ProcessorType::FaceTrace => 1024,
|
||||
ProcessorType::Tkg => 512,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -668,6 +674,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => None,
|
||||
ProcessorType::FaceCluster => Some("sklearn/agglomerative"),
|
||||
ProcessorType::FaceTrace => None,
|
||||
ProcessorType::Tkg => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,6 +686,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => vec![ProcessorType::Pose],
|
||||
ProcessorType::FaceTrace => vec![ProcessorType::Face],
|
||||
ProcessorType::FaceCluster => vec![ProcessorType::FaceTrace],
|
||||
ProcessorType::Tkg => vec![ProcessorType::FaceTrace],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
@@ -690,8 +698,10 @@ impl ProcessorType {
|
||||
ProcessorType::Asrx,
|
||||
ProcessorType::Ocr,
|
||||
ProcessorType::Face,
|
||||
ProcessorType::FaceTrace,
|
||||
ProcessorType::FaceCluster,
|
||||
ProcessorType::Scene, // Scene VLM processor
|
||||
// Scene (scenes.json) and TKG (tkg_nodes) are produced by dedicated
|
||||
// pipelines, not by the generic processor pool.
|
||||
// ProcessorType::Pose, // Disabled in production pipeline
|
||||
// ProcessorType::Hand, // Disabled in production pipeline
|
||||
// ProcessorType::Appearance, // Disabled in production pipeline
|
||||
@@ -706,7 +716,8 @@ impl ProcessorType {
|
||||
| ProcessorType::Hand
|
||||
| ProcessorType::Appearance
|
||||
| ProcessorType::FaceCluster
|
||||
| ProcessorType::FaceTrace => PipelineType::Frame,
|
||||
| ProcessorType::FaceTrace
|
||||
| ProcessorType::Tkg => PipelineType::Frame,
|
||||
|
||||
ProcessorType::Cut
|
||||
| ProcessorType::Asr
|
||||
|
||||
@@ -977,8 +977,9 @@ impl QdrantDb {
|
||||
timestamp_sec: f64,
|
||||
frame_number: u32,
|
||||
vlm_description: &str,
|
||||
vlm_description_localized: Option<&str>,
|
||||
vlm_objects: &[String],
|
||||
vlm_tags: &[String],
|
||||
vlm_tags: &[crate::core::file_profile::VlmTagValue],
|
||||
) -> Result<()> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points?wait=true",
|
||||
@@ -997,6 +998,12 @@ impl QdrantDb {
|
||||
"vlm_description".to_string(),
|
||||
serde_json::json!(vlm_description),
|
||||
);
|
||||
if let Some(localized) = vlm_description_localized {
|
||||
payload_map.insert(
|
||||
"vlm_description_localized".to_string(),
|
||||
serde_json::json!(localized),
|
||||
);
|
||||
}
|
||||
payload_map.insert("vlm_objects".to_string(), serde_json::json!(vlm_objects));
|
||||
payload_map.insert("vlm_tags".to_string(), serde_json::json!(vlm_tags));
|
||||
|
||||
|
||||
@@ -785,6 +785,35 @@ pub struct SceneConfig {
|
||||
pub samples_per_interval: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VlmTag {
|
||||
pub en: String,
|
||||
pub local: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum VlmTagValue {
|
||||
Structured(VlmTag),
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl VlmTagValue {
|
||||
pub fn en(&self) -> &str {
|
||||
match self {
|
||||
Self::Structured(t) => &t.en,
|
||||
Self::String(s) => s,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local(&self) -> &str {
|
||||
match self {
|
||||
Self::Structured(t) => &t.local,
|
||||
Self::String(_) => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SceneFrame {
|
||||
pub index: usize,
|
||||
@@ -834,7 +863,7 @@ pub struct SceneFrame {
|
||||
pub vlm_attributes: Option<SceneAttributes>,
|
||||
|
||||
#[serde(default)]
|
||||
pub vlm_tags: Vec<String>,
|
||||
pub vlm_tags: Vec<VlmTagValue>,
|
||||
|
||||
pub embedding_status: EmbeddingStatus,
|
||||
}
|
||||
|
||||
+38
-15
@@ -32,22 +32,23 @@ struct Choice {
|
||||
}
|
||||
|
||||
pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
|
||||
let req = ChatRequest {
|
||||
model: (*config::llm::SUMMARY_MODEL).clone(),
|
||||
messages: vec![
|
||||
ChatMessage {
|
||||
role: "system".to_string(),
|
||||
content: system_prompt.to_string(),
|
||||
let req = serde_json::json!({
|
||||
"model": (*config::llm::SUMMARY_MODEL).clone(),
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": system_prompt.to_string(),
|
||||
},
|
||||
ChatMessage {
|
||||
role: "user".to_string(),
|
||||
content: prompt.to_string(),
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt.to_string(),
|
||||
},
|
||||
],
|
||||
temperature: 0.1,
|
||||
max_tokens: 512,
|
||||
stream: false,
|
||||
};
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 512,
|
||||
"stream": false,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
debug!("Calling LLM: {}", *config::llm::SUMMARY_URL);
|
||||
|
||||
@@ -64,10 +65,32 @@ pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
|
||||
anyhow::bail!("LLM API error: {}", text);
|
||||
}
|
||||
|
||||
let chat_res: ChatResponse = res.json().await?;
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChatResponseExt {
|
||||
choices: Vec<ChoiceExt>,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChoiceExt {
|
||||
message: ChatMessageExt,
|
||||
finish_reason: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChatMessageExt {
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
let chat_res: ChatResponseExt = res.json().await?;
|
||||
if let Some(choice) = chat_res.choices.first() {
|
||||
if choice.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
}
|
||||
if let Some(choice) = chat_res.choices.into_iter().next() {
|
||||
Ok(choice.message.content.trim().to_string())
|
||||
let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("Empty response from LLM");
|
||||
}
|
||||
Ok(content.trim().to_string())
|
||||
} else {
|
||||
anyhow::bail!("Empty response from LLM");
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@ pub async fn call_llm_vision(
|
||||
"temperature": 0.1,
|
||||
"max_tokens": max_tokens,
|
||||
"stream": false,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let res = LLM_CLIENT
|
||||
@@ -176,19 +177,30 @@ pub async fn call_llm_vision(
|
||||
#[derive(Deserialize)]
|
||||
struct VisionChoice {
|
||||
message: VisionMessage,
|
||||
finish_reason: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct VisionMessage {
|
||||
content: Option<String>,
|
||||
reasoning_content: Option<String>,
|
||||
}
|
||||
|
||||
let vision_res: VisionResponse = res.json().await?;
|
||||
if let Some(choice) = vision_res.choices.first() {
|
||||
if choice.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("Vision LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
}
|
||||
let content = vision_res
|
||||
.choices
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|c| c.message.content)
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("Vision LLM returned empty content");
|
||||
}
|
||||
Ok(content.trim().to_string())
|
||||
}
|
||||
|
||||
@@ -221,14 +233,17 @@ pub async fn call_llm(
|
||||
*config::llm::CHAT_TIMEOUT_SECS
|
||||
};
|
||||
|
||||
let req = ChatRequest {
|
||||
let mut req = serde_json::to_value(&ChatRequest {
|
||||
model: llm_model(),
|
||||
messages,
|
||||
temperature: 0.1,
|
||||
max_tokens,
|
||||
stream: false,
|
||||
tools,
|
||||
};
|
||||
})?;
|
||||
if let Some(obj) = req.as_object_mut() {
|
||||
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
|
||||
}
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_chat_url())
|
||||
@@ -243,6 +258,13 @@ pub async fn call_llm(
|
||||
}
|
||||
|
||||
let chat_res: ChatResponse = res.json().await?;
|
||||
let choice = chat_res
|
||||
.choices
|
||||
.first()
|
||||
.ok_or_else(|| anyhow::anyhow!("Empty LLM response"))?;
|
||||
if choice.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
let choice = chat_res
|
||||
.choices
|
||||
.into_iter()
|
||||
@@ -257,7 +279,10 @@ pub async fn call_llm(
|
||||
Ok(LlmResponse::ToolCalls(calls))
|
||||
}
|
||||
_ => {
|
||||
let content = choice.message.content.unwrap_or_default();
|
||||
let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("LLM returned empty content");
|
||||
}
|
||||
Ok(LlmResponse::Text(content.trim().to_string()))
|
||||
}
|
||||
}
|
||||
@@ -278,14 +303,17 @@ pub async fn call_llm_with_usage(
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
let req = ChatRequest {
|
||||
let mut req = serde_json::to_value(&ChatRequest {
|
||||
model: llm_model(),
|
||||
messages,
|
||||
temperature: 0.1,
|
||||
max_tokens,
|
||||
stream: false,
|
||||
tools,
|
||||
};
|
||||
})?;
|
||||
if let Some(obj) = req.as_object_mut() {
|
||||
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
|
||||
}
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_chat_url())
|
||||
@@ -300,6 +328,13 @@ pub async fn call_llm_with_usage(
|
||||
}
|
||||
|
||||
let chat_res: ChatResponse = res.json().await?;
|
||||
let choice_ref = chat_res
|
||||
.choices
|
||||
.first()
|
||||
.ok_or_else(|| anyhow::anyhow!("Empty LLM response"))?;
|
||||
if choice_ref.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
let choice = chat_res
|
||||
.choices
|
||||
.into_iter()
|
||||
@@ -320,7 +355,10 @@ pub async fn call_llm_with_usage(
|
||||
LlmResponse::ToolCalls(calls)
|
||||
}
|
||||
_ => {
|
||||
let content = choice.message.content.unwrap_or_default();
|
||||
let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("LLM returned empty content");
|
||||
}
|
||||
LlmResponse::Text(content.trim().to_string())
|
||||
}
|
||||
};
|
||||
|
||||
@@ -90,3 +90,15 @@ pub fn probe_video(video_path: &str) -> Result<ProbeResult> {
|
||||
|
||||
Ok(ProbeResult { streams, format })
|
||||
}
|
||||
|
||||
/// Returns `Some(true/false)` when probing succeeds, `None` when it fails.
|
||||
pub fn has_audio_stream(video_path: &str) -> Option<bool> {
|
||||
probe_video(video_path)
|
||||
.ok()
|
||||
.map(|probe| {
|
||||
probe
|
||||
.streams
|
||||
.iter()
|
||||
.any(|s| s.codec_type.as_deref() == Some("audio"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
pub mod ffprobe;
|
||||
pub mod unified;
|
||||
|
||||
pub use ffprobe::{probe_video, FormatInfo, ProbeResult, StreamInfo};
|
||||
pub use ffprobe::{has_audio_stream, probe_video, FormatInfo, ProbeResult, StreamInfo};
|
||||
|
||||
@@ -96,6 +96,17 @@ pub async fn process_asr(
|
||||
) -> Result<AsrResult> {
|
||||
tracing::info!("[ASR] Starting ASR processing: {}", video_path);
|
||||
|
||||
// Files without an audio stream cannot be transcribed. Skipping Whisper
|
||||
// immediately also lets ingestion finish (asr_status=no_audio_track).
|
||||
if crate::core::probe::has_audio_stream(video_path) == Some(false) {
|
||||
tracing::info!("[ASR] No audio track, skipping Whisper: {}", video_path);
|
||||
let mut result = AsrResult::no_audio_track();
|
||||
result.add_metadata("asr", "none", uuid);
|
||||
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
|
||||
.context("Failed to write ASR output")?;
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let mlx_whisper_cli = std::path::Path::new("/opt/homebrew/bin/mlx_whisper");
|
||||
|
||||
if mlx_whisper_cli.exists() {
|
||||
@@ -150,6 +161,10 @@ pub async fn process_asr(
|
||||
let json_str =
|
||||
std::fs::read_to_string(&final_json_path).context("Failed to read MLX Whisper output")?;
|
||||
|
||||
// MLX Whisper outputs NaN for avg_logprob when no speech detected
|
||||
// NaN is not valid JSON - replace with null before parsing
|
||||
let json_str = json_str.replace("NaN", "null");
|
||||
|
||||
let whisper_result: WhisperJsonOutput =
|
||||
serde_json::from_str(&json_str).context("Failed to parse MLX Whisper output")?;
|
||||
|
||||
|
||||
@@ -108,6 +108,16 @@ pub async fn process_asrx(
|
||||
) -> Result<AsrxResult> {
|
||||
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
|
||||
|
||||
// No audio stream means no speakers; emit a valid empty result instead of
|
||||
// letting the diarization tool fail.
|
||||
if crate::core::probe::has_audio_stream(video_path) == Some(false) {
|
||||
tracing::info!("[ASRX] No audio track, skipping diarization: {}", video_path);
|
||||
let mut result = AsrxResult::no_audio_track();
|
||||
result.add_metadata("asrx", "none", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
use super::tool_selector::ToolSelector;
|
||||
let executor = PythonExecutor::new()?;
|
||||
let selector = ToolSelector::new("asrx");
|
||||
|
||||
+183
-88
@@ -6,7 +6,7 @@ use tokio::process::Command;
|
||||
|
||||
use crate::core::file_profile::{
|
||||
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
|
||||
SelectionReason, VideoInfo, VlmStatus,
|
||||
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
|
||||
};
|
||||
|
||||
pub struct SceneVlmProcessor {
|
||||
@@ -476,11 +476,98 @@ impl SceneVlmProcessor {
|
||||
tags
|
||||
}
|
||||
|
||||
/// Call VLM API to generate scene description
|
||||
fn language_display_name(language: &str) -> &'static str {
|
||||
match language {
|
||||
"zh-TW" => "Traditional Chinese (zh-TW)",
|
||||
"zh-CN" => "Simplified Chinese (zh-CN)",
|
||||
"ja" => "Japanese (ja)",
|
||||
"ko" => "Korean (ko)",
|
||||
"es" => "Spanish (es)",
|
||||
"fr" => "French (fr)",
|
||||
"de" => "German (de)",
|
||||
_ => "English (en)",
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the structured scene analysis prompt.
|
||||
fn build_scene_prompt(local_language: &str) -> String {
|
||||
let local_name = Self::language_display_name(local_language);
|
||||
format!(
|
||||
r#"You are an expert visual analyst for a multimodal video search system.
|
||||
|
||||
Analyze the attached image frame and return ONLY valid JSON with NO markdown, NO explanations, NO reasoning, NO thinking.
|
||||
|
||||
Use this exact schema:
|
||||
|
||||
{{
|
||||
"summary": "Concise English summary of the core content (1-2 sentences). Factual, avoid superlatives like beautiful/stunning/amazing.",
|
||||
"category": "Single highest-level category. Choose ONE from: landscape|architecture|interior|people|event|nature|urban|transport|food|animal|product|other",
|
||||
"scene_type": "Environment/background. Choose ONE from: indoor|outdoor|city street|resort|nature|mountain|beach|forest|building exterior|building interior|road|park|unknown",
|
||||
"objects": ["3-5 most prominent objects or subjects in English. Concrete and specific."],
|
||||
"actions": ["Main actions/events or static state if no motion. Use English (e.g. 'static scene', 'driving', 'walking')."],
|
||||
"visual_attributes": {{
|
||||
"lighting": "e.g. natural daylight, golden hour, overcast, artificial, backlit, mixed lighting",
|
||||
"composition": "e.g. aerial view, wide angle, eye level, low angle, close-up, drone shot, street level",
|
||||
"color_palette": ["3-5 dominant colors in English (e.g. gray, green, blue, orange)"]
|
||||
}},
|
||||
"detected_text": ["Exact visible signs, logos, plaques, or printed text. Only if legible. Empty array if none."],
|
||||
"tags": [
|
||||
{{"en": "english_tag", "local": "localized_tag"}}
|
||||
]
|
||||
}}
|
||||
|
||||
Rules:
|
||||
- summary must be English only
|
||||
- objects, actions, visual_attributes must use concrete English terms. Avoid generic words like "photo", "image", "view", "scene"
|
||||
- tags: 5-10 items. Each item MUST be an object with both "en" and "local" keys
|
||||
- Use {local_name} for "local". If the preferred language is English, set "local" equal to "en" but keep both keys
|
||||
- Prioritize search-relevant terms (environment type, key structures/objects). Do NOT just copy the full summary into tags
|
||||
- Do NOT duplicate objects 1:1 unless genuinely useful as search tags
|
||||
- Keep tags concise (1-3 words). Avoid redundancy between tags
|
||||
- detected_text: only extract text actually visible, do not guess or infer
|
||||
- Output ONLY the JSON object"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Extract the first JSON object from a VLM response (tolerates markdown fences).
|
||||
fn extract_json_object(content: &str) -> Option<&str> {
|
||||
let start = content.find('{')?;
|
||||
let end = content.rfind('}')?;
|
||||
if end <= start {
|
||||
return None;
|
||||
}
|
||||
Some(&content[start..=end])
|
||||
}
|
||||
|
||||
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
|
||||
let Some(arr) = value.and_then(|v| v.as_array()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
arr.iter()
|
||||
.filter_map(|tag| {
|
||||
if let Some(en) = tag.get("en").and_then(|v| v.as_str()) {
|
||||
let local = tag
|
||||
.get("local")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(en)
|
||||
.to_string();
|
||||
Some(VlmTagValue::Structured(VlmTag {
|
||||
en: en.to_string(),
|
||||
local,
|
||||
}))
|
||||
} else {
|
||||
tag.as_str().map(|s| VlmTagValue::String(s.to_string()))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Call VLM API to generate structured scene info.
|
||||
/// Returns (english_description, objects, bilingual_tags).
|
||||
pub async fn generate_scene_description(
|
||||
image_path: &std::path::Path,
|
||||
language: &str,
|
||||
) -> Result<(String, Vec<String>, Vec<String>)> {
|
||||
local_language: &str,
|
||||
) -> Result<(String, Vec<String>, Vec<VlmTagValue>)> {
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -493,33 +580,15 @@ impl SceneVlmProcessor {
|
||||
let vlm_url = crate::core::config::llm::VISION_URL.clone();
|
||||
let vlm_model = crate::core::config::llm::VISION_MODEL.clone();
|
||||
|
||||
let prompt = Self::build_scene_prompt(local_language);
|
||||
|
||||
tracing::debug!(
|
||||
"[VLM API] Calling {} with model {} (language: {})",
|
||||
"[VLM API] Calling {} with model {} (local language: {})",
|
||||
vlm_url,
|
||||
vlm_model,
|
||||
language
|
||||
local_language
|
||||
);
|
||||
|
||||
// Language-specific prompts
|
||||
let (prompt, max_tokens) = match language {
|
||||
"zh-TW" => (
|
||||
"請用繁體中文描述這個場景,用2-3句話。重點說明:環境、物體和活動。簡潔且準確。",
|
||||
800
|
||||
),
|
||||
"zh-CN" => (
|
||||
"请用简体中文描述这个场景,用2-3句话。重点说明:环境、物体和活动。简洁且准确。",
|
||||
800
|
||||
),
|
||||
"ja" => (
|
||||
"このシーンを2-3文で説明してください。環境、物体、活動に焦点を当ててください。簡潔で正確に。",
|
||||
800
|
||||
),
|
||||
_ => (
|
||||
"Describe this scene in 2-3 sentences. Focus on: environment, objects, and activities. Be concise and factual.",
|
||||
800
|
||||
),
|
||||
};
|
||||
|
||||
let body = serde_json::json!({
|
||||
"model": vlm_model,
|
||||
"messages": [{
|
||||
@@ -537,8 +606,9 @@ impl SceneVlmProcessor {
|
||||
}
|
||||
]
|
||||
}],
|
||||
"max_tokens": max_tokens,
|
||||
"temperature": 0.1
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
@@ -564,60 +634,59 @@ impl SceneVlmProcessor {
|
||||
.await
|
||||
.context("Failed to parse VLM API response")?;
|
||||
|
||||
// Parse response - handle both 'content' and 'reasoning_content' (Gemma4)
|
||||
let message = resp_json
|
||||
// Parse response
|
||||
let choice = resp_json
|
||||
.get("choices")
|
||||
.and_then(|c| c.get(0))
|
||||
.and_then(|c| c.get("message"))
|
||||
.context("Invalid VLM API response structure")?;
|
||||
if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") {
|
||||
anyhow::bail!("VLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
let message = choice.get("message").context("Invalid VLM API response structure")?;
|
||||
|
||||
// Try content first (final answer), fall back to reasoning_content if content is empty
|
||||
let content = match message
|
||||
.get("content")
|
||||
.and_then(|c| c.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
Some(s) => s.to_string(),
|
||||
None => message
|
||||
.get("reasoning_content")
|
||||
.and_then(|c| c.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
Some(s) => s.trim().to_string(),
|
||||
None => anyhow::bail!("VLM returned empty content"),
|
||||
};
|
||||
|
||||
if content.is_empty() {
|
||||
anyhow::bail!("VLM returned empty response");
|
||||
// Parse structured JSON; fall back to heuristic extraction if it fails.
|
||||
if let Some(json_str) = Self::extract_json_object(&content) {
|
||||
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json_str) {
|
||||
let description = parsed
|
||||
.get("summary")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
|
||||
if let Some(description) = description {
|
||||
let objects = parsed
|
||||
.get("objects")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let tags = Self::parse_tags(parsed.get("tags"));
|
||||
return Ok((description, objects, tags));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if content.is_empty() {
|
||||
tracing::warn!("[VLM API] Empty response for {:?}", image_path);
|
||||
}
|
||||
|
||||
// Parse content - Gemma4 outputs thinking + description
|
||||
// Skip thinking part (starts with "The user wants" or "I need to")
|
||||
let description =
|
||||
if content.starts_with("The user wants") || content.starts_with("I need to") {
|
||||
// Find where actual description starts (after first newline or second sentence)
|
||||
content
|
||||
.lines()
|
||||
.skip_while(|line| {
|
||||
line.starts_with("The user wants")
|
||||
|| line.starts_with("I need to")
|
||||
|| line.trim().is_empty()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.trim()
|
||||
.to_string()
|
||||
} else {
|
||||
content.clone()
|
||||
};
|
||||
|
||||
// Extract objects and tags from description (simple heuristic)
|
||||
let objects = Self::extract_objects_from_text(&description);
|
||||
let tags = Self::extract_tags_from_text(&description);
|
||||
|
||||
Ok((description, objects, tags))
|
||||
tracing::warn!(
|
||||
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
|
||||
);
|
||||
let objects = Self::extract_objects_from_text(&content);
|
||||
let tags = Self::extract_tags_from_text(&content)
|
||||
.into_iter()
|
||||
.map(VlmTagValue::String)
|
||||
.collect();
|
||||
Ok((content, objects, tags))
|
||||
}
|
||||
|
||||
/// Generate VLM descriptions for all scene frames
|
||||
@@ -633,7 +702,13 @@ impl SceneVlmProcessor {
|
||||
);
|
||||
|
||||
// Get preferred language from admin config
|
||||
let preferred_language = crate::core::config::get_preferred_language();
|
||||
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
|
||||
.get_full_config()
|
||||
.await
|
||||
.search
|
||||
.vlm_output_language
|
||||
.clone();
|
||||
crate::core::config::set_preferred_language(preferred_language.clone());
|
||||
tracing::info!("[Scene VLM] Preferred language: {}", preferred_language);
|
||||
|
||||
// Process scenes sequentially to avoid issues
|
||||
@@ -641,31 +716,51 @@ impl SceneVlmProcessor {
|
||||
let frame_path = SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
|
||||
|
||||
// Generate English description (for indexing)
|
||||
match Self::generate_scene_description(&frame_path, "en").await {
|
||||
match Self::generate_scene_description(&frame_path, &preferred_language).await {
|
||||
Ok((description_en, objects, tags)) => {
|
||||
scene.vlm_description = Some(description_en.clone());
|
||||
scene.vlm_objects = objects.clone();
|
||||
scene.vlm_tags = tags.clone();
|
||||
|
||||
// Generate localized description if needed
|
||||
// Generate localized description by translation if needed
|
||||
if preferred_language != "en" {
|
||||
match Self::generate_scene_description(&frame_path, &preferred_language)
|
||||
.await
|
||||
{
|
||||
Ok((description_localized, _, _)) => {
|
||||
scene.vlm_description_localized = Some(description_localized);
|
||||
tracing::info!(
|
||||
"[Scene VLM] ✅ Scene {}: EN + {}",
|
||||
idx,
|
||||
preferred_language
|
||||
);
|
||||
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
|
||||
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
|
||||
let body = serde_json::json!({
|
||||
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"stream": false,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
|
||||
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
|
||||
Ok(resp) => {
|
||||
if resp.status().is_success() {
|
||||
if let Ok(v) = resp.json::<serde_json::Value>().await {
|
||||
if let Some(choice) = v["choices"].get(0) {
|
||||
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
|
||||
if let Some(tr) = choice["message"]["content"].as_str() {
|
||||
let tr = tr.trim();
|
||||
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
|
||||
scene.vlm_description_localized = Some(tr.to_string());
|
||||
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[Scene VLM] ⚠️ Scene {} localized failed: {}",
|
||||
idx,
|
||||
e
|
||||
);
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
+123
-41
@@ -927,6 +927,16 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Scene (scenes.json) and TKG (tkg_nodes) are handled by dedicated
|
||||
// pipelines; never execute them in the generic processor pool. This also
|
||||
// covers legacy jobs whose processors list still contains them.
|
||||
processors_to_run.retain(|p| {
|
||||
!matches!(
|
||||
p,
|
||||
crate::core::db::ProcessorType::Scene | crate::core::db::ProcessorType::Tkg
|
||||
)
|
||||
});
|
||||
|
||||
let total_processor_types = processors_to_run.len() as i32;
|
||||
|
||||
// Get video total_frames for progress tracking
|
||||
@@ -3708,27 +3718,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
};
|
||||
|
||||
// Wait for Qdrant to have all face points AND the full trace count.
|
||||
// (up to 60 seconds). Point count alone isn't enough — store_traced_faces.py
|
||||
// (up to 120 seconds). Point count alone isn't enough — store_traced_faces
|
||||
// writes face_traced.json first, then uploads trace_id to Qdrant
|
||||
// incrementally. Two consecutive equal polls (2s apart) can falsely look
|
||||
// "stable" between upload batches. So we additionally require the Qdrant
|
||||
// distinct trace count to reach the expected count from face_traced.json.
|
||||
let expected_traces: i64 =
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) =
|
||||
serde_json::from_str::<serde_json::Value>(&content)
|
||||
{
|
||||
traced_data
|
||||
.get("traces")
|
||||
.and_then(|t| t.as_object())
|
||||
.map(|o| o.len() as i64)
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// NOTE: expected_traces is re-read inside the loop to handle updates from
|
||||
// rust_store_traced_faces that may complete while we're waiting.
|
||||
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
let filter = serde_json::json!({
|
||||
@@ -3738,8 +3734,29 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
let mut attempts = 0;
|
||||
let max_attempts = 60;
|
||||
let mut stable_trace_count: Option<i64> = None;
|
||||
let mut trace_stability_attempts = 0;
|
||||
let max_trace_stability_attempts = 30;
|
||||
loop {
|
||||
attempts += 1;
|
||||
|
||||
// Re-read expected_traces each iteration to handle face_traced.json updates
|
||||
let expected_traces: i64 =
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) =
|
||||
serde_json::from_str::<serde_json::Value>(&content)
|
||||
{
|
||||
traced_data
|
||||
.get("traces")
|
||||
.and_then(|t| t.as_object())
|
||||
.map(|o| o.len() as i64)
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
match qdrant.count_points("_faces", filter.clone()).await {
|
||||
Ok(count) if count >= expected_faces && expected_faces > 0 => {
|
||||
// Point count met — now verify trace stability
|
||||
@@ -3770,8 +3787,17 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
}
|
||||
}
|
||||
stable_trace_count = Some(trace_count);
|
||||
info!("⏳ TKG point count met ({} faces), verifying trace stability ({})...",
|
||||
count, trace_count);
|
||||
trace_stability_attempts += 1;
|
||||
|
||||
// Timeout: if trace stability check exceeds limit, proceed anyway
|
||||
if trace_stability_attempts >= max_trace_stability_attempts {
|
||||
warn!("⚠️ TKG trace stability timeout after {} attempts (trace={}, expected={}), proceeding anyway: {}",
|
||||
trace_stability_attempts, trace_count, expected_traces, uuid);
|
||||
break;
|
||||
}
|
||||
|
||||
info!("⏳ TKG point count met ({} faces), verifying trace stability ({}/{}, expected {})...",
|
||||
count, trace_count, trace_stability_attempts, expected_traces);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Qdrant scroll for trace check failed: {}, proceeding anyway", e);
|
||||
@@ -3884,6 +3910,21 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
)
|
||||
.await;
|
||||
|
||||
// Create processor_results entry for TKG
|
||||
if let Err(e) = db_clone
|
||||
.upsert_processor_result(
|
||||
job_id,
|
||||
crate::core::db::ProcessorType::Tkg,
|
||||
&uuid_clone,
|
||||
"completed",
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to create processor_results for tkg: {}", e);
|
||||
} else {
|
||||
info!("✅ Created processor_results record for tkg");
|
||||
}
|
||||
|
||||
// Trigger Rule 2 ingestion after TKG complete
|
||||
if total_edges > 0 {
|
||||
// Mark rule2_ingestion as running
|
||||
@@ -4029,6 +4070,19 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
);
|
||||
publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp)
|
||||
.await;
|
||||
|
||||
// Create processor_results entry for TKG (no-faces path)
|
||||
if let Err(e) = db_clone
|
||||
.upsert_processor_result(
|
||||
job_id,
|
||||
crate::core::db::ProcessorType::Tkg,
|
||||
&uuid_clone,
|
||||
"completed",
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to create processor_results for tkg (no-faces): {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e),
|
||||
}
|
||||
@@ -4627,39 +4681,66 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
&scene.filename,
|
||||
);
|
||||
|
||||
// Get preferred language
|
||||
let preferred_language = crate::core::config::get_preferred_language();
|
||||
// Get preferred language from admin config
|
||||
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
|
||||
.get_full_config()
|
||||
.await
|
||||
.search
|
||||
.vlm_output_language
|
||||
.clone();
|
||||
crate::core::config::set_preferred_language(preferred_language.clone());
|
||||
|
||||
// Generate English description (for indexing)
|
||||
match SceneVlmProcessor::generate_scene_description(&frame_path, "en").await {
|
||||
match SceneVlmProcessor::generate_scene_description(&frame_path, &preferred_language).await {
|
||||
Ok((description_en, objects, tags)) => {
|
||||
scene.vlm_description = Some(description_en.clone());
|
||||
scene.vlm_objects = objects.clone();
|
||||
scene.vlm_tags = tags.clone();
|
||||
|
||||
// Generate localized description if needed
|
||||
// Generate localized description by translation if needed
|
||||
if preferred_language != "en" {
|
||||
match SceneVlmProcessor::generate_scene_description(
|
||||
&frame_path,
|
||||
&preferred_language,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((description_localized, _, _)) => {
|
||||
scene.vlm_description_localized = Some(description_localized);
|
||||
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
|
||||
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
|
||||
let body = serde_json::json!({
|
||||
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"stream": false,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
|
||||
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
|
||||
Ok(resp) => {
|
||||
if resp.status().is_success() {
|
||||
if let Ok(v) = resp.json::<serde_json::Value>().await {
|
||||
if let Some(choice) = v["choices"].get(0) {
|
||||
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
|
||||
if let Some(tr) = choice["message"]["content"].as_str() {
|
||||
let tr = tr.trim();
|
||||
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
|
||||
scene.vlm_description_localized = Some(tr.to_string());
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
|
||||
processed += 1;
|
||||
if processed % 10 == 0 || processed == total_scenes {
|
||||
let _ = db.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32).await;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
tracing::info!(
|
||||
"[Scene VLM] ✅ Scene {}: EN + {}",
|
||||
idx,
|
||||
preferred_language
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[Scene VLM] ⚠️ Scene {} localized failed: {}",
|
||||
idx,
|
||||
e
|
||||
);
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
}
|
||||
}
|
||||
@@ -4780,6 +4861,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
scene.timestamp_sec,
|
||||
scene.frame_number,
|
||||
desc,
|
||||
scene.vlm_description_localized.as_deref(),
|
||||
&scene.vlm_objects,
|
||||
&scene.vlm_tags,
|
||||
)
|
||||
|
||||
@@ -1252,6 +1252,23 @@ impl ProcessorPool {
|
||||
total_faces: 0,
|
||||
})
|
||||
}
|
||||
ProcessorType::Tkg => {
|
||||
// TKG is handled separately in job_worker.rs via build_tkg
|
||||
// This is a no-op placeholder for the processor type
|
||||
tracing::info!("TKG processor stub called for {} (handled by build_tkg)", job.uuid);
|
||||
Ok(ProcessorOutput {
|
||||
data: serde_json::Value::Null,
|
||||
chunks_produced: 0,
|
||||
frames_processed: 0,
|
||||
total_frames,
|
||||
retry_count: 0,
|
||||
pid: 0,
|
||||
asr_status: None,
|
||||
segment_count: 0,
|
||||
face_status: None,
|
||||
total_faces: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user