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:
Accusys
2026-10-24 02:37:53 +08:00
parent d14cd9f3de
commit c151b49334
33 changed files with 3175 additions and 229 deletions
+23 -3
View File
@@ -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(),
}))
+1
View File
@@ -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
View File
@@ -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,
+6
View File
@@ -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)
+321
View File
@@ -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
View File
@@ -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 {