From 7fd7df2913d07798618ea2b77bcc8713ca4b2f84 Mon Sep 17 00:00:00 2001 From: Accusys Date: Tue, 17 Nov 2026 08:41:34 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20scripts=5Fdir()=20=E6=81=A2=E5=BE=A9?= =?UTF-8?q?=E6=AD=A3=E7=A2=BA=E8=B7=AF=E5=BE=91=20resolve=5Fasset=5Fpath('?= =?UTF-8?q?MOMENTRY=5FSCRIPTS=5FDIR',=20'scripts');=20embedding=20port=201?= =?UTF-8?q?1436=E2=86=9211437?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/server.rs.backup_20261111_100307 | 217 +++++ .../scene_vlm.rs.bak.20261108_011617 | 859 ++++++++++++++++++ 2 files changed, 1076 insertions(+) create mode 100644 src/api/server.rs.backup_20261111_100307 create mode 100644 src/core/processor/scene_vlm.rs.bak.20261108_011617 diff --git a/src/api/server.rs.backup_20261111_100307 b/src/api/server.rs.backup_20261111_100307 new file mode 100644 index 00000000..0781a0c6 --- /dev/null +++ b/src/api/server.rs.backup_20261111_100307 @@ -0,0 +1,217 @@ +use std::time::Duration; + +use axum::{Json, Router}; +use serde_json::json; +use tokio::time::timeout; +use tower_http::cors::{Any, CorsLayer}; +use tower_http::services::ServeDir; + +use crate::core::cache::{MongoCache, RedisCache}; +use crate::core::db::{Database, PostgresDb, QdrantDb}; +use crate::Embedder; + +use super::admin_config; +use super::agent_api; +use super::agent_search; +use super::auth; +use super::billing; +use super::checkin_api; +use super::clip_api; +use super::cluster_agent; +use super::docs; +use super::face_filter; +use super::file_progress; +use super::files; +use super::health; +use super::health::{health, health_consistency, health_detailed, health_queue}; +use super::identities; +use super::identity_api; +use super::identity_binding; +use super::llm_search; +use super::markbase_compat; +use super::media_api; +use super::middleware::unified_auth; +use super::pipeline; +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; +use super::monitor; +use super::universal_search::universal_search_routes; +use super::vlm_search; +use super::job_management; + +pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { + health::init_server_state(host, port); + + let embedder = std::sync::Arc::new(Embedder::new("embeddinggemma-300m".to_string())); + + // ── ⚠️ WARNING: DO NOT move MongoCache::init() back to critical path ── + // + // MongoDB is ONLY a cache layer — if unavailable, the server MUST still + // start with Redis cache alone. This keeps 3002 bootable on machines + // without MongoDB installed. If you add a new dependency here, ask: + // "Can this service degrade gracefully if the dependant is missing?" + // + // See also: MongoCache::disabled() in mongo_cache.rs + let mongo_cache = match timeout(Duration::from_secs(5), MongoCache::init()).await { + Ok(Ok(cache)) => cache, + Ok(Err(e)) => { + tracing::warn!("MongoDB cache unavailable (continuing without): {e}"); + MongoCache::disabled().await + } + Err(_) => { + tracing::warn!("MongoDB init timed out (continuing without cache)"); + MongoCache::disabled().await + } + }; + let redis_cache = RedisCache::new()?; + let db = PostgresDb::init().await?; + + // Run migrations (create identity_history table if not exists) + PostgresDb::run_migrations(db.pool()).await?; + + let schema_health = health::check_schema_migrations(db.pool()).await; + if schema_health.ok { + tracing::info!( + "[SCHEMA] All {}/{} required migrations applied ✓", + schema_health.required.len(), + schema_health.required.len() + ); + } else if !schema_health.table_exists { + tracing::warn!("[SCHEMA] schema_migrations table not found!"); + } else { + let missing: Vec<&str> = schema_health + .required + .iter() + .filter(|req| { + !schema_health + .applied + .iter() + .any(|app| app.filename == req.filename && app.checksum == req.checksum) + }) + .map(|m| m.filename.as_str()) + .collect(); + tracing::warn!( + "[SCHEMA] {}/{} migrations match. Missing: {}", + schema_health.applied.len(), + schema_health.required.len(), + missing.join(", ") + ); + } + + let db = std::sync::Arc::new(db); + let api_state = super::middleware::ApiState { db: db.clone() }; + + let qdrant = std::sync::Arc::new(QdrantDb::new()); + + // Initialize AdminConfigManager + let admin_config_manager = std::sync::Arc::new( + crate::core::admin_config::AdminConfigManager::new( + &crate::core::admin_config::get_default_config_path(), + ) + .expect("Failed to initialize AdminConfigManager"), + ); + + // Ensure trash collection exists for trace hard-delete undo + if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await { + tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e); + } + + let state = AppState { + db, + qdrant, + embedder, + embedder_model: "nomic-embed-text-v2-moe:latest".to_string(), + mongo_cache, + redis_cache, + api_state, + admin_config_manager, + }; + + let protected_routes = Router::new() + .merge(files::file_routes()) + .merge(markbase_compat::markbase_routes()) + .merge(scan::scan_routes()) + .merge(identity_binding::identity_binding_routes()) + .merge(identities::identity_routes()) + .merge(tmdb_api::tmdb_routes()) + .merge(identity_api::identity_routes()) + .merge(agent_api::agent_routes()) + .merge(agent_search::agent_search_routes()) + .merge(processing::processing_routes()) + .merge(file_progress::file_progress_routes()) + .merge(media_api::bbox_routes()) + .merge(media_api::media_proxy_routes()) + .merge(media_api::pose_appearance_routes()) + .merge(trace_agent_api::trace_agent_routes()) + .merge(clip_api::clip_routes()) + .merge(search_routes()) + .merge(llm_search::llm_smart_routes()) + .merge(universal_search_routes()) + .merge(pipeline::pipeline_routes()) + .merge(checkin_api::checkin_routes()) + .merge(cluster_agent::cluster_agent_routes()) + .merge(profile::profile_routes()) + .merge(face_filter::face_filter_routes()) + .merge(admin_config::admin_config_routes()) + .merge(vlm_search::vlm_search_routes()) + .merge(billing::billing_routes()) + .merge(job_management::job_management_routes()) + .merge(service_management::router()) + .layer(axum::middleware::from_fn_with_state( + state.api_state.clone(), + unified_auth, + )) + .with_state(state.clone()); + + let cors = CorsLayer::new() + .allow_origin(Any) + .allow_methods(Any) + .allow_headers(Any); + + let public_health_routes = Router::new() + .route("/api/v1/health", axum::routing::get(health)) + .route( + "/api/v1/health/detailed", + axum::routing::get(health_detailed), + ) + .route( + "/api/v1/health/consistency", + axum::routing::get(health_consistency), + ) + .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() + .merge(auth::auth_routes()) + .merge(public_health_routes) + .merge(docs::doc_routes()) + .merge(monitor::monitor_routes()) + .nest_service("/monitor", ServeDir::new("static/monitor")) + .merge(protected_routes) + .layer(cors) + .layer(axum::middleware::from_fn(super::middleware::request_logger)) + .layer(axum::middleware::from_fn( + super::middleware::concurrency_limit, + )) + .with_state(state); + + let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap(); + tracing::info!("Starting API server at http://{}", addr); + + let listener = tokio::net::TcpListener::bind(addr).await?; + axum::serve(listener, app).await?; + + Ok(()) +} diff --git a/src/core/processor/scene_vlm.rs.bak.20261108_011617 b/src/core/processor/scene_vlm.rs.bak.20261108_011617 new file mode 100644 index 00000000..0bcf6b61 --- /dev/null +++ b/src/core/processor/scene_vlm.rs.bak.20261108_011617 @@ -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 { + if samples == 0 { + return vec![]; + } + let sample_interval = interval_sec / samples as f64; + + let frames: Vec = (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 { + 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::() { + 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 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 = 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("/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, 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 + } + + 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 { + 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, 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(); + + 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::(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::>() + }) + .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::().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(()) + } +}