diff --git a/src/core/processor/scene_vlm.rs b/src/core/processor/scene_vlm.rs new file mode 100644 index 00000000..65a9d776 --- /dev/null +++ b/src/core/processor/scene_vlm.rs @@ -0,0 +1,683 @@ +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, +}; + +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 { + let sample_interval = interval_sec / samples as f64; + + (0..samples) + .map(|i| { + let time = interval_start_sec + (i as f64 + 0.5) * sample_interval; + (time * fps).round() as u32 + }) + .collect() + } + + pub async fn calculate_blur_single(video_path: &str, frame: u32, fps: f64) -> Result { + let time_sec = frame as f64 / fps; + + let output = Command::new("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::() { + return Ok(blur); + } + } + } + + Ok(f64::NAN) + } + + pub async fn calculate_blur_parallel( + video_path: &str, + frames: &[u32], + fps: f64, + max_workers: usize, + ) -> Result> { + 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 { + 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> { + 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 { + 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 = sample_frames + .iter() + .filter(|f| **f < cut_frame) + .cloned() + .collect(); + + let post_frames: Vec = 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 { + 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 { + 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> { + 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("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, Vec) { + 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 { + 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 { + 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 + } + + /// Call VLM API to generate scene description + pub async fn generate_scene_description( + image_path: &std::path::Path, + language: &str, + ) -> Result<(String, Vec, Vec)> { + 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(); + + tracing::debug!("[VLM API] Calling {} with model {} (language: {})", vlm_url, vlm_model, 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": [{ + "role": "user", + "content": [ + { + "type": "text", + "text": prompt + }, + { + "type": "image_url", + "image_url": { + "url": format!("data:image/jpeg;base64,{}", base64_img) + } + } + ] + }], + "max_tokens": max_tokens, + "temperature": 0.1 + }); + + 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 - handle both 'content' and 'reasoning_content' (Gemma4) + let message = resp_json + .get("choices") + .and_then(|c| c.get(0)) + .and_then(|c| c.get("message")) + .context("Invalid VLM API response structure")?; + + // Try reasoning_content first (Gemma4), fall back to content + let content = message + .get("reasoning_content") + .and_then(|c| c.as_str()) + .or_else(|| message.get("content").and_then(|c| c.as_str())) + .unwrap_or("") + .to_string(); + + 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::>() + .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)) + } + + /// 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::config::get_preferred_language(); + 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, "en").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 + 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 + ); + } + Err(e) => { + tracing::warn!("[Scene VLM] ⚠️ Scene {} localized 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(()) + } +}