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
+123 -41
View File
@@ -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,
)
+17
View File
@@ -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,
})
}
}
}