fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts'); embedding port 11436→11437
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled

This commit is contained in:
Accusys
2026-11-17 08:41:34 +08:00
parent eac827d932
commit 7fd7df2913
2 changed files with 1076 additions and 0 deletions
@@ -0,0 +1,859 @@
use anyhow::{Context, Result};
use futures_util::future::join_all;
use std::collections::HashMap;
use std::path::Path;
use tokio::process::Command;
use crate::core::file_profile::{
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
};
pub struct SceneVlmProcessor {
samples_per_interval: usize,
use_cuts: bool,
max_workers: usize,
}
impl SceneVlmProcessor {
pub fn new(samples_per_interval: usize, use_cuts: bool, max_workers: usize) -> Self {
Self {
samples_per_interval,
use_cuts,
max_workers,
}
}
pub fn compute_sample_frames(
interval_start_sec: f64,
interval_sec: f64,
fps: f64,
samples: usize,
) -> Vec<u32> {
if samples == 0 {
return vec![];
}
let sample_interval = interval_sec / samples as f64;
let frames: Vec<u32> = (0..samples)
.map(|i| {
let time = interval_start_sec + (i as f64 + 0.5) * sample_interval;
(time * fps).round() as u32
})
.collect();
// Ensure at least frame 0 is included for short videos
if frames.is_empty() || frames.iter().all(|&f| f > 0) {
let mut result = vec![0u32];
result.extend(frames.into_iter().filter(|&f| f > 0));
result
} else {
frames
}
}
pub async fn calculate_blur_single(video_path: &str, frame: u32, fps: f64) -> Result<f64> {
let time_sec = frame as f64 / fps;
let output = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-vf",
"blurdetect",
"-f",
"null",
"-",
])
.output()
.await
.context("FFmpeg blurdetect failed")?;
let stderr = String::from_utf8_lossy(&output.stderr);
for line in stderr.lines() {
if let Some(blur_str) = line.split("blur mean: ").nth(1) {
if let Ok(blur) = blur_str.trim().parse::<f64>() {
return Ok(blur);
}
}
}
Ok(f64::NAN)
}
pub async fn calculate_blur_parallel(
video_path: &str,
frames: &[u32],
fps: f64,
max_workers: usize,
) -> Result<Vec<(u32, f64)>> {
let tasks: Vec<_> = frames
.iter()
.map(|frame| Self::calculate_blur_single(video_path, *frame, fps))
.collect();
let results = join_all(tasks).await;
let mut combined = Vec::new();
for (frame, result) in frames.iter().zip(results.into_iter()) {
if let Ok(blur) = result {
combined.push((*frame, blur));
} else {
combined.push((*frame, f64::NAN));
}
}
Ok(combined)
}
pub fn select_best_frame(blur_scores: &[(u32, f64)]) -> Option<(u32, f64)> {
blur_scores
.iter()
.filter(|(_, blur)| !blur.is_nan())
.min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.map(|(frame, blur)| (*frame, *blur))
}
pub fn find_cuts_in_interval(
interval_start: f64,
interval_end: f64,
cut_data: &serde_json::Value,
) -> Vec<serde_json::Value> {
let mut cuts = Vec::new();
if let Some(scenes) = cut_data.get("scenes").and_then(|s| s.as_array()) {
for scene in scenes {
if let Some(start_time) = scene.get("start_time").and_then(|t| t.as_f64()) {
if start_time > interval_start && start_time < interval_end {
cuts.push(scene.clone());
}
}
}
}
cuts
}
pub async fn process_interval(
video_path: &str,
interval_start: f64,
interval_sec: f64,
fps: f64,
cut_data: &serde_json::Value,
samples_per_interval: usize,
max_workers: usize,
) -> Result<Vec<SceneFrame>> {
let sample_frames =
Self::compute_sample_frames(interval_start, interval_sec, fps, samples_per_interval);
let blur_scores =
Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?;
let cuts =
Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
let mut selected_frames = Vec::new();
if cuts.is_empty() {
if let Some((frame, blur)) = Self::select_best_frame(&blur_scores) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::BestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
} else if let Some(&frame) = sample_frames.first() {
// Fallback: use first sample frame when blur detection yields no scores
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::Default,
quality_score: None,
quality_source: None,
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
} else {
let cut = &cuts[0];
let cut_time = cut
.get("start_time")
.and_then(|t| t.as_f64())
.unwrap_or(interval_start);
let cut_frame = (cut_time * fps).round() as u32;
let pre_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f < cut_frame)
.cloned()
.collect();
let post_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f >= cut_frame)
.cloned()
.collect();
if !pre_frames.is_empty() {
let pre_blur =
Self::calculate_blur_parallel(video_path, &pre_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&pre_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PreCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
if !post_frames.is_empty() {
let post_blur =
Self::calculate_blur_parallel(video_path, &post_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&post_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PostCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
}
for (i, frame) in selected_frames.iter_mut().enumerate() {
frame.index = i;
}
Ok(selected_frames)
}
pub async fn generate_scene_profile(
&self,
video_path: &str,
file_uuid: &str,
output_dir: &str,
interval_sec: u32,
cut_data: &serde_json::Value,
fps: f64,
duration: f64,
width: u32,
height: u32,
total_frames: u32,
) -> Result<SceneProfile> {
let config = SceneConfig {
interval_sec,
use_cuts: true,
use_faces: false,
quality_metric: "ffmpeg_blurdetect".to_string(),
samples_per_interval: self.samples_per_interval,
};
let video_info = VideoInfo {
duration_sec: duration,
fps,
width,
height,
total_frames,
};
let mut profile = SceneProfile::new(file_uuid, video_info, config);
let mut all_frames = Vec::new();
let total_intervals = (duration / interval_sec as f64).ceil() as usize;
for i in 0..total_intervals {
let interval_start = i as f64 * interval_sec as f64;
let interval_end = (interval_start + interval_sec as f64).min(duration);
let actual_interval_sec = interval_end - interval_start;
let frames = Self::process_interval(
video_path,
interval_start,
actual_interval_sec,
fps,
cut_data,
self.samples_per_interval,
self.max_workers,
)
.await?;
all_frames.extend(frames);
}
// Fix indices
for (i, frame) in all_frames.iter_mut().enumerate() {
frame.index = i;
frame.filename = format!("scene_{:03}.jpg", i);
}
profile.scenes = all_frames;
profile.total_scenes = profile.scenes.len();
profile.status = SceneStatus::Ready;
profile.updated_at = chrono::Utc::now();
Ok(profile)
}
pub fn save_scene_profile(profile: &SceneProfile, output_dir: &str) -> Result<()> {
let path = SceneProfile::scenes_path(output_dir, &profile.file_uuid);
let json =
serde_json::to_string_pretty(profile).context("Failed to serialize SceneProfile")?;
std::fs::write(&path, json).context("Failed to write scenes.json")?;
Ok(())
}
pub fn load_scene_profile(output_dir: &str, file_uuid: &str) -> Result<SceneProfile> {
let path = SceneProfile::scenes_path(output_dir, file_uuid);
let json = std::fs::read_to_string(&path).context("Failed to read scenes.json")?;
let profile: SceneProfile =
serde_json::from_str(&json).context("Failed to parse scenes.json")?;
Ok(profile)
}
pub async fn extract_scene_frames(
video_path: &str,
output_dir: &str,
file_uuid: &str,
scenes: &[SceneFrame],
) -> Result<Vec<std::path::PathBuf>> {
let scenes_dir = SceneProfile::scenes_dir(output_dir, file_uuid);
std::fs::create_dir_all(&scenes_dir).context("Failed to create scenes directory")?;
let mut extracted_paths = Vec::new();
for scene in scenes {
let output_path =
SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
let time_sec = scene.timestamp_sec;
let status = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-y",
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-q:v",
"5",
&output_path.to_string_lossy(),
])
.status()
.await
.context("FFmpeg frame extraction failed")?;
if status.success() && output_path.exists() {
extracted_paths.push(output_path);
}
}
Ok(extracted_paths)
}
/// Helper function to extract scene info from parsed JSON
fn extract_scene_info(
parsed: &serde_json::Value,
fallback: &str,
) -> (String, Vec<String>, Vec<String>) {
let desc = parsed
.get("description")
.and_then(|d| d.as_str())
.unwrap_or(fallback)
.to_string();
let objs = parsed
.get("objects")
.and_then(|o| o.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let tgs = parsed
.get("tags")
.and_then(|t| t.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
(desc, objs, tgs)
}
/// Extract objects from text (simple keyword matching)
fn extract_objects_from_text(text: &str) -> Vec<String> {
let keywords = [
"river", "tree", "forest", "mountain", "building", "person", "text", "water", "sky",
"cloud", "road", "car", "house", "flower", "grass", "rock", "bridge", "boat", "animal",
"bird",
];
keywords
.iter()
.filter(|&k| text.to_lowercase().contains(k))
.map(|k| k.to_string())
.collect()
}
/// Extract tags from text (category inference)
fn extract_tags_from_text(text: &str) -> Vec<String> {
let mut tags = vec![];
let lower = text.to_lowercase();
if lower.contains("landscape") || lower.contains("nature") {
tags.push("nature".to_string());
}
if lower.contains("indoor") || lower.contains("room") {
tags.push("indoor".to_string());
}
if lower.contains("outdoor") {
tags.push("outdoor".to_string());
}
if lower.contains("presentation") || lower.contains("slide") {
tags.push("presentation".to_string());
}
if lower.contains("text") || lower.contains("title") {
tags.push("text".to_string());
}
if lower.contains("water") || lower.contains("river") {
tags.push("water".to_string());
}
tags
}
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,
local_language: &str,
) -> Result<(String, Vec<String>, Vec<VlmTagValue>)> {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use std::time::Duration;
// Read image
let jpeg_bytes = std::fs::read(image_path)
.with_context(|| format!("Failed to read image: {:?}", image_path))?;
let base64_img = BASE64.encode(&jpeg_bytes);
// VLM API config
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 {} (local language: {})",
vlm_url,
vlm_model,
local_language
);
let body = serde_json::json!({
"model": vlm_model,
"messages": [{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": format!("data:image/jpeg;base64,{}", base64_img)
}
}
]
}],
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(120))
.build()
.context("Failed to create HTTP client")?;
let resp = client
.post(&vlm_url)
.json(&body)
.send()
.await
.context("VLM API request failed")?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("VLM API returned {}: {}", status, body);
}
let resp_json: serde_json::Value = resp
.json()
.await
.context("Failed to parse VLM API response")?;
// Parse response
let choice = resp_json
.get("choices")
.and_then(|c| c.get(0))
.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")?;
let content = match message
.get("content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => s.trim().to_string(),
None => anyhow::bail!("VLM returned empty content"),
};
tracing::debug!(
"[Scene VLM] VLM response content (first 500 chars): {}",
&content[..content.len().min(500)]
);
// Parse structured JSON; fall back to heuristic extraction if it fails.
if let Some(json_str) = Self::extract_json_object(&content) {
tracing::debug!("[Scene VLM] Extracted JSON object ({} chars)", json_str.len());
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json_str) {
tracing::debug!("[Scene VLM] Successfully parsed JSON");
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"));
tracing::info!(
"[Scene VLM] Parsed {} objects, {} tags from JSON",
objects.len(),
tags.len()
);
return Ok((description, objects, tags));
} else {
tracing::warn!("[Scene VLM] JSON missing 'summary' field or summary is empty");
}
} else {
tracing::warn!("[Scene VLM] Failed to parse extracted JSON: {}", json_str);
}
} else {
tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response");
}
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
pub async fn generate_vlm_descriptions(
output_dir: &str,
file_uuid: &str,
scenes: &mut [SceneFrame],
max_workers: usize,
) -> Result<()> {
tracing::info!(
"[Scene VLM] Generating descriptions for {} scenes",
scenes.len()
);
// 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());
tracing::info!("[Scene VLM] Preferred language: {}", preferred_language);
// Process scenes sequentially to avoid issues
for (idx, scene) in scenes.iter_mut().enumerate() {
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, &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();
tracing::info!(
"[Scene VLM] Scene {}: Generated {} tags: {:?}",
idx,
tags.len(),
tags
);
// Generate localized description by translation if needed
if preferred_language != "en" {
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 translation failed: {}", idx, e);
}
}
} else {
tracing::info!("[Scene VLM] ✅ Scene {}: EN only", idx);
}
scene.vlm_status = VlmStatus::Completed;
}
Err(e) => {
tracing::error!("[Scene VLM] ❌ Scene {}: {}", idx, e);
scene.vlm_status = VlmStatus::Failed;
}
}
}
let success_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Completed)
.count();
let fail_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Failed)
.count();
tracing::info!(
"[Scene VLM] ✅ Generated {} descriptions, {} failed",
success_count,
fail_count
);
Ok(())
}
}