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:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user