From 474a5bee99b1bdca407e2dec0492a158d9a56069 Mon Sep 17 00:00:00 2001 From: Accusys Date: Thu, 17 Sep 2026 16:56:25 +0800 Subject: [PATCH] refactor: remove YOLO processor and dependencies - Delete YOLO processor implementation (src/core/processor/yolo.rs) - Remove YOLO from processing pipeline and worker - Clean up YOLO-related code across multiple modules - Add migration 033_remove_yolo.sql YOLO functionality removed as part of architecture simplification --- migrations/033_remove_yolo.sql | 50 ++++++ scripts/add_yolo_to_chunks.py | 137 --------------- scripts/qa/judges/yolo.py | 62 ------- src/api/health.rs | 6 +- src/api/mod.rs | 1 + src/api/processing.rs | 7 - src/api/profile.rs | 73 ++++++-- src/api/server.rs | 10 ++ src/cli/args.rs | 4 +- src/core/mod.rs | 1 + src/core/processor/mod.rs | 2 - src/core/processor/yolo.rs | 313 --------------------------------- src/processing/decision.rs | 4 - src/processing/modules/mod.rs | 2 - src/processing/modules/yolo.rs | 50 ------ src/ui/progress/mod.rs | 4 - src/verification/schema.rs | 23 +-- src/verification/verifier.rs | 32 ---- src/worker/processor.rs | 82 --------- src/worker/resources.rs | 29 +++ 20 files changed, 161 insertions(+), 731 deletions(-) create mode 100644 migrations/033_remove_yolo.sql delete mode 100644 scripts/add_yolo_to_chunks.py delete mode 100644 scripts/qa/judges/yolo.py delete mode 100644 src/core/processor/yolo.rs delete mode 100644 src/processing/modules/yolo.rs diff --git a/migrations/033_remove_yolo.sql b/migrations/033_remove_yolo.sql new file mode 100644 index 00000000..81c87dfd --- /dev/null +++ b/migrations/033_remove_yolo.sql @@ -0,0 +1,50 @@ +-- ================================================================ +-- Migration 033: Remove YOLO from Pipeline +-- Date: 2026-08-30 +-- Purpose: Remove all YOLO-related columns, data, and indexes +-- ================================================================ + +BEGIN; + +-- 1. Remove YOLO data from tkg_nodes +DELETE FROM tkg_nodes WHERE node_type = 'yolo_object'; + +-- 2. Remove YOLO-related edges from tkg_edges +DELETE FROM tkg_edges +WHERE source_node_id IN (SELECT id FROM tkg_nodes WHERE node_type = 'yolo_object') + OR target_node_id IN (SELECT id FROM tkg_nodes WHERE node_type = 'yolo_object'); + +-- 3. Drop tkg_co_occurrence materialized view (contains YOLO placeholders) +DROP MATERIALIZED VIEW IF EXISTS tkg_co_occurrence CASCADE; + +-- 4. Remove YOLO index from frames table +DROP INDEX IF EXISTS idx_frames_yolo_gin; + +-- 5. Remove yolo_objects column from frames table +ALTER TABLE frames DROP COLUMN IF EXISTS yolo_objects; + +-- 6. Remove YOLO processor from pre_chunks +DELETE FROM pre_chunks WHERE processor_type = 'yolo'; + +-- 7. Remove YOLO chunks (trace_yolo_* and visual type) +DELETE FROM chunks WHERE chunk_id LIKE 'trace_yolo_%'; +DELETE FROM chunks WHERE chunk_type = 'visual'; + +-- 8. Remove YOLO from processor_versions +DELETE FROM processor_versions WHERE processor_name = 'yolo'; + +COMMIT; + +-- ================================================================ +-- Post-migration cleanup (run manually if needed) +-- ================================================================ + +-- Reindex after major deletion +-- REINDEX TABLE tkg_nodes; +-- REINDEX TABLE tkg_edges; +-- REINDEX TABLE frames; + +-- Vacuum analyze +-- VACUUM ANALYZE tkg_nodes; +-- VACUUM ANALYZE tkg_edges; +-- VACUUM ANALYZE frames; \ No newline at end of file diff --git a/scripts/add_yolo_to_chunks.py b/scripts/add_yolo_to_chunks.py deleted file mode 100644 index 03a801d8..00000000 --- a/scripts/add_yolo_to_chunks.py +++ /dev/null @@ -1,137 +0,0 @@ -#!/opt/homebrew/bin/python3.11 -""" -Add YOLO metadata to chunks -""" - -import json -import psycopg2 - - -YOLO_FILE = "/Users/accusys/test_video/Old_Time_Movie_Show_-_Charade_1963.HD.yolo.json" -VIDEO_UUID = "39567a0eb16f39fd" -FPS = 24.0 - -POSTGRES_CONFIG = { - "host": "localhost", - "port": 5432, - "user": "accusys", - "password": "Test3200", - "database": "momentry", -} - - -def load_yolo_data(): - """Load YOLO JSON data""" - print(f"Loading YOLO data from {YOLO_FILE}...") - with open(YOLO_FILE) as f: - data = json.load(f) - print(f"Loaded {len(data['frames'])} frames") - return data - - -def get_chunk_yolo_metadata(yolo_data, start_time, end_time): - """Get YOLO objects that appear in a time range""" - start_frame = int(start_time * FPS) - end_frame = int(end_time * FPS) - - objects = set() - detections = [] - - for frame_num in range(start_frame, end_frame + 1): - frame_str = str(frame_num) - if frame_str in yolo_data["frames"]: - frame_data = yolo_data["frames"][frame_str] - for det in frame_data.get("detections", []): - if det["confidence"] >= 0.3: - objects.add(det["class_name"]) - detections.append( - { - "class_name": det["class_name"], - "confidence": det["confidence"], - } - ) - - return { - "objects": list(objects), - "detection_count": len(detections), - } - - -def add_yolo_metadata_to_chunks(): - """Add YOLO metadata to all chunks""" - yolo_data = load_yolo_data() - - conn = psycopg2.connect(**POSTGRES_CONFIG) - cur = conn.cursor() - - # Get all sentence chunks for this video - cur.execute( - """ - SELECT chunk_id, start_time, end_time - FROM chunks - WHERE uuid = %s AND chunk_type = 'sentence' - ORDER BY chunk_index - """, - (VIDEO_UUID,), - ) - - chunks = cur.fetchall() - print(f"Processing {len(chunks)} chunks...") - - for i, (chunk_id, start_time, end_time) in enumerate(chunks): - # Get YOLO metadata for this chunk - yolo_meta = get_chunk_yolo_metadata(yolo_data, start_time, end_time) - - if yolo_meta["objects"]: - # Update chunk with YOLO metadata - cur.execute( - """ - UPDATE chunks - SET metadata = COALESCE(metadata, '{}'::jsonb) || %s - WHERE chunk_id = %s - """, - (json.dumps({"yolo": yolo_meta}), chunk_id), - ) - - if (i + 1) % 100 == 0: - print(f"Processed {i + 1}/{len(chunks)} chunks...") - conn.commit() - - conn.commit() - cur.close() - conn.close() - - print("Done!") - - -def test_object_search(): - """Test object search""" - _ = load_yolo_data() - - conn = psycopg2.connect(**POSTGRES_CONFIG) - cur = conn.cursor() - - test_objects = ["person", "car", "clock", "tie", "chair", "bottle"] - - for obj in test_objects: - # Count chunks with this object - query = """ - SELECT COUNT(*) - FROM chunks - WHERE uuid = %s - AND chunk_type = 'sentence' - AND metadata IS NOT NULL - AND metadata->'yolo'->'objects' ? %s - """ - cur.execute(query, (VIDEO_UUID, obj)) - count = cur.fetchone()[0] - print(f"Object '{obj}': {count} chunks") - - cur.close() - conn.close() - - -if __name__ == "__main__": - add_yolo_metadata_to_chunks() - print("\nTesting object search:") - test_object_search() diff --git a/scripts/qa/judges/yolo.py b/scripts/qa/judges/yolo.py deleted file mode 100644 index 161edfd9..00000000 --- a/scripts/qa/judges/yolo.py +++ /dev/null @@ -1,62 +0,0 @@ -"""YOLO judge: object detection matching against expected objects""" -import cv2, numpy as np, re -from ultralytics import YOLO - -MODEL_PATH = "/Users/accusys/momentry_core_0.1/yolov8s.mlpackage" -COCO = [ - "person","bicycle","car","motorbike","aeroplane","bus","train","truck","boat", - "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat","dog", - "horse","sheep","cow","elephant","bear","zebra","giraffe","backpack","umbrella", - "handbag","tie","suitcase","frisbee","skis","snowboard","sports ball","kite", - "baseball bat","baseball glove","skateboard","surfboard","tennis racket","bottle", - "wine glass","cup","fork","knife","spoon","bowl","banana","apple","sandwich","orange", - "broccoli","carrot","hot dog","pizza","donut","cake","chair","sofa","pottedplant", - "bed","diningtable","toilet","tvmonitor","laptop","mouse","remote","keyboard", - "cell phone","microwave","oven","toaster","sink","refrigerator","book","clock", - "vase","scissors","teddy bear","hair drier","toothbrush", -] - -_model = None - -def load(): - global _model - if _model is None: - try: - _model = YOLO(MODEL_PATH, task="detect", verbose=False) - except: - _model = YOLO("yolov8s.pt") - -def score(frames, prompt): - load() - prompt_lower = prompt.lower() - - # Extract expected objects from prompt: check each COCO class (word boundary) - expected = [c for c in COCO if re.search(r'\b' + re.escape(c) + r'\b', prompt_lower)] - if not expected: - expected = ["person"] # default fallback - - results = [] - for img in frames: - # Convert PIL to numpy - arr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) - dets = _model(arr, verbose=False, imgsz=640) - - found = [] - if dets and len(dets) > 0 and dets[0].boxes is not None: - for cls_id in dets[0].boxes.cls.int().tolist(): - cls_name = COCO[cls_id] if cls_id < len(COCO) else f"cls_{cls_id}" - found.append(cls_name) - - match = sum(1 for e in expected if e in found) - results.append({"expected": expected, "found": found, "match_count": match, "total": len(expected)}) - - total_match = sum(r["match_count"] for r in results) - total_expected = sum(r["total"] for r in results) or 1 - score_val = int(100 * total_match / total_expected) - - return { - "agent": "YOLO", - "score": score_val, - "reasoning": f"Found {total_match}/{total_expected} expected objects: {expected}", - "details": {"frames": results} - } diff --git a/src/api/health.rs b/src/api/health.rs index e62e8d90..6d620c33 100644 --- a/src/api/health.rs +++ b/src/api/health.rs @@ -148,7 +148,6 @@ struct ScriptIntegrity { #[derive(Debug, Serialize)] struct ProcessorInventory { asr: bool, - yolo: bool, face: bool, pose: bool, ocr: bool, @@ -172,6 +171,8 @@ struct ResourceStatus { gpu_available: bool, gpu_utilization: Option, gpu_memory_used_pct: Option, + ane_available: bool, + ane_utilization: Option, } #[derive(Debug, Serialize)] @@ -348,6 +349,8 @@ pub async fn health_detailed(State(state): State) -> Json) -> Json Result, StatusCode> { let tkg_table = schema::table_name("tkg_nodes"); let tp_table = schema::table_name("trace_profiles"); + let v_table = schema::table_name("videos"); + + // Read face_filter settings + let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!( + "SELECT face_filter FROM {v_table} WHERE file_uuid = $1" + )) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .ok() + .flatten() + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults); - let rows: Vec<(String, i32)> = sqlx::query_as(&format!( + let rows: Vec<(String, i32, Option)> = sqlx::query_as(&format!( "SELECT COALESCE(tp.name, tn.label) as name, \ - COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id \ + COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \ + tp.frame_count \ FROM {} tn \ LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ AND tp.trace_id = (tn.properties->>'trace_id')::int \ @@ -1240,7 +1254,17 @@ pub async fn get_face_groups_handler( let mut groups: HashMap> = HashMap::new(); let mut unassigned: Vec = Vec::new(); - for (name, trace_id) in rows { + for (name, trace_id, frame_count) in rows { + // Filter single frame traces if disabled + if frame_count == Some(1) { + if !settings.single_frame_trace_group_enabled && !name.starts_with("Face Trace ") && !name.starts_with("Trace ") { + continue; + } + if !settings.single_frame_trace_unassigned_enabled && (name.starts_with("Face Trace ") || name.starts_with("Trace ")) { + continue; + } + } + if name.starts_with("Face Trace ") || name.starts_with("Trace ") { unassigned.push(trace_id); } else { @@ -1248,10 +1272,17 @@ pub async fn get_face_groups_handler( } } - // All Person_N groups are shown as face groups regardless of trace count. + // Filter single-trace groups if enabled let mut filtered_groups: HashMap> = HashMap::new(); for (name, trace_ids) in groups { - filtered_groups.insert(name, trace_ids); + let is_auto_name = name.starts_with("Person_"); + let should_filter = settings.single_trace_group_filter_enabled + && trace_ids.len() == 1 + && is_auto_name; + + if !should_filter { + filtered_groups.insert(name, trace_ids); + } } let include_trace_ids = q.include_trace_ids.unwrap_or(true); @@ -1337,11 +1368,25 @@ pub async fn get_cluster_results_handler( let file_uuid = params.file_hash; let tkg_table = schema::table_name("tkg_nodes"); let tp_table = schema::table_name("trace_profiles"); + let v_table = schema::table_name("videos"); + + // Read face_filter settings + let settings: crate::core::file_profile::FaceFilterSettings = sqlx::query_scalar(&format!( + "SELECT face_filter FROM {v_table} WHERE file_uuid = $1" + )) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .ok() + .flatten() + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults); // 1. Build face groups (same grouping logic as face-groups handler) - let rows: Vec<(String, i32)> = sqlx::query_as(&format!( + let rows: Vec<(String, i32, Option)> = sqlx::query_as(&format!( "SELECT COALESCE(tp.name, tn.label) as name, \ - COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id \ + COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id, \ + tp.frame_count \ FROM {} tn \ LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ AND tp.trace_id = (tn.properties->>'trace_id')::int \ @@ -1358,7 +1403,12 @@ pub async fn get_cluster_results_handler( })?; let mut groups: HashMap> = HashMap::new(); - for (name, trace_id) in rows { + for (name, trace_id, frame_count) in rows { + // Filter out single frame traces if disabled + if frame_count == Some(1) && !settings.single_frame_trace_group_enabled { + continue; + } + if !(name.starts_with("Face Trace ") || name.starts_with("Trace ")) { groups.entry(name).or_default().push(trace_id); } @@ -1369,10 +1419,13 @@ pub async fn get_cluster_results_handler( let mut filtered_groups: HashMap> = HashMap::new(); for (name, trace_ids) in groups { let is_auto_name = name.starts_with("Person_"); - if trace_ids.len() > 1 || !is_auto_name { + let should_filter = settings.single_trace_group_filter_enabled + && trace_ids.len() == 1 + && is_auto_name; + + if !should_filter { filtered_groups.insert(name, trace_ids); } - // Single-trace auto-generated groups are silently dropped } // trace_id -> cluster_id mapping for frame faces diff --git a/src/api/server.rs b/src/api/server.rs index 68d58c2b..07e22bd9 100644 --- a/src/api/server.rs +++ b/src/api/server.rs @@ -9,6 +9,7 @@ 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; @@ -99,6 +100,14 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { 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); @@ -136,6 +145,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> { .merge(cluster_agent::cluster_agent_routes()) .merge(profile::profile_routes()) .merge(face_filter::face_filter_routes()) + .merge(admin_config::admin_config_routes().with_state(admin_config_manager.clone())) .layer(axum::middleware::from_fn_with_state( state.api_state.clone(), unified_auth, diff --git a/src/cli/args.rs b/src/cli/args.rs index 6e068461..f8a061ce 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -20,12 +20,12 @@ pub enum Commands { Process { /// UUID or path target: String, - /// Modules to process (comma separated: asr,cut,asrx,yolo,ocr,face,pose,story,caption) + /// Modules to process (comma separated: asr,cut,asrx,ocr,face,pose,story,caption) /// If not specified, processes all modules #[arg(short, long, value_delimiter = ',')] modules: Option>, /// Modules to process via cloud (comma separated) - /// Example: --cloud asr,yolo + /// Example: --cloud asr,ocr #[arg(long, value_delimiter = ',')] cloud: Option>, /// Force reprocess even if JSON exists (skip completeness check) diff --git a/src/core/mod.rs b/src/core/mod.rs index e746c757..b572d148 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1,3 +1,4 @@ +pub mod admin_config; pub mod agent; pub mod api_key; pub mod auth; diff --git a/src/core/processor/mod.rs b/src/core/processor/mod.rs index 867498f7..6134efff 100644 --- a/src/core/processor/mod.rs +++ b/src/core/processor/mod.rs @@ -16,7 +16,6 @@ pub mod pose; pub mod scene_classification; pub mod tkg; pub mod vlm_summary; -pub mod yolo; use serde::{Deserialize, Serialize}; @@ -193,4 +192,3 @@ pub use tkg::{ build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo, RepresentativeFrameResult, TkgResult, }; -pub use yolo::{process_yolo, YoloFrame, YoloObject, YoloResult}; diff --git a/src/core/processor/yolo.rs b/src/core/processor/yolo.rs deleted file mode 100644 index 153130f0..00000000 --- a/src/core/processor/yolo.rs +++ /dev/null @@ -1,313 +0,0 @@ -use anyhow::{Context, Result}; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::time::Duration; - -use super::executor::PythonExecutor; - -const YOLO_TIMEOUT: Duration = Duration::from_secs(7200); - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloResult { - pub frame_count: u64, - pub fps: f64, - pub frames: Vec, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloFrame { - pub frame: u64, - pub timestamp: f64, - pub objects: Vec, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloObject { - pub class_name: String, - pub class_id: u32, - pub x: i32, - pub y: i32, - pub width: i32, - pub height: i32, - pub confidence: f32, -} - -// New structs for parsing Python YOLO output -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloPythonMetadata { - video_path: String, - fps: f64, - width: i32, - height: i32, - total_frames: i64, - total_duration: f64, - processed_at: String, - auto_save_interval: i32, - auto_save_frames: i32, - status: String, - last_saved_at: String, - last_saved_frame: i64, - completed_at: Option, - processing_time: Option, - total_detections: Option, - auto_save_count: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloPythonDetection { - class_name: String, - confidence: f32, - x1: f32, - y1: f32, - x2: f32, - y2: f32, - width: i32, - height: i32, - class_id: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloPythonFrame { - frame_number: u64, - time_seconds: f64, - time_formatted: String, - detections: Vec, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct YoloPythonResult { - metadata: YoloPythonMetadata, - frames: HashMap, -} - -impl YoloPythonResult { - pub fn to_yolo_result(&self) -> YoloResult { - let mut frames = Vec::new(); - - // Sort frames by frame number (key is string, but we parse as u64) - let mut frame_entries: Vec<_> = self.frames.iter().collect(); - frame_entries.sort_by_key(|(key, _)| key.parse::().unwrap_or(0)); - - for (_, frame) in frame_entries { - let mut objects = Vec::new(); - for detection in &frame.detections { - objects.push(YoloObject { - class_name: detection.class_name.clone(), - class_id: detection.class_id.unwrap_or(0), - x: detection.x1 as i32, - y: detection.y1 as i32, - width: detection.width, - height: detection.height, - confidence: detection.confidence, - }); - } - frames.push(YoloFrame { - frame: frame.frame_number, - timestamp: frame.time_seconds, - objects, - }); - } - - YoloResult { - frame_count: frames.len() as u64, - fps: self.metadata.fps, - frames, - } - } -} - -pub async fn process_yolo( - video_path: &str, - output_path: &str, - uuid: Option<&str>, - frames: Option<&[i64]>, -) -> Result { - let executor = PythonExecutor::new()?; - let script_path = executor.script_path("yolo_processor.py"); - - tracing::info!("[YOLO] Starting object detection: {}", video_path); - - if !script_path.exists() { - tracing::warn!("[YOLO] Script not found, returning empty result"); - return Ok(YoloResult { - frame_count: 0, - fps: 0.0, - frames: vec![], - }); - } - - executor - .run_with_frames( - "yolo_processor.py", - &[video_path, output_path], - uuid, - "YOLO", - Some(YOLO_TIMEOUT), - frames, - ) - .await - .with_context(|| format!("Failed to run {:?}", script_path))?; - - let json_str = std::fs::read_to_string(output_path).context("Failed to read YOLO output")?; - - let python_result: YoloPythonResult = - serde_json::from_str(&json_str).context("Failed to parse YOLO output")?; - - let result = python_result.to_yolo_result(); - - tracing::info!( - "[YOLO] Result: {} frames, {:.2} fps", - result.frame_count, - result.fps - ); - - Ok(result) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_yolo_result_serialization() { - let result = YoloResult { - frame_count: 100, - fps: 30.0, - frames: vec![YoloFrame { - frame: 0, - timestamp: 0.0, - objects: vec![YoloObject { - class_name: "person".to_string(), - class_id: 0, - x: 100, - y: 200, - width: 50, - height: 100, - confidence: 0.95, - }], - }], - }; - - let json = serde_json::to_string(&result).unwrap(); - assert!(json.contains("person")); - assert!(json.contains("100")); - } - - #[test] - fn test_yolo_result_deserialization() { - let json = r#"{ - "frame_count": 50, - "fps": 25.0, - "frames": [ - { - "frame": 10, - "timestamp": 0.4, - "objects": [ - {"class_name": "car", "class_id": 2, "x": 0, "y": 0, "width": 100, "height": 80, "confidence": 0.87} - ] - } - ] - }"#; - - let result: YoloResult = serde_json::from_str(json).unwrap(); - assert_eq!(result.frame_count, 50); - assert_eq!(result.fps, 25.0); - assert_eq!(result.frames.len(), 1); - assert_eq!(result.frames[0].objects[0].class_name, "car"); - } - - #[test] - fn test_yolo_object_confidence_range() { - let obj = YoloObject { - class_name: "test".to_string(), - class_id: 0, - x: 0, - y: 0, - width: 10, - height: 10, - confidence: 0.5, - }; - assert!(obj.confidence >= 0.0 && obj.confidence <= 1.0); - } - - #[test] - fn test_yolo_result_empty_frames() { - let result = YoloResult { - frame_count: 0, - fps: 0.0, - frames: vec![], - }; - assert!(result.frames.is_empty()); - } - - #[test] - fn test_yolo_python_result_parsing() { - // Sample JSON matching Python script output - let json = r#"{ - "metadata": { - "video_path": "/test/video.mp4", - "fps": 22.0, - "width": 640, - "height": 360, - "total_frames": 3512, - "total_duration": 159.63636363636363, - "processed_at": "2026-03-26T05:20:48.230143", - "auto_save_interval": 30, - "auto_save_frames": 300, - "status": "completed", - "last_saved_at": "2026-03-26T05:23:22.791673", - "last_saved_frame": 0, - "completed_at": "2026-03-26T05:23:22.791666", - "processing_time": 154.5577518939972, - "total_detections": 12786, - "auto_save_count": 11 - }, - "frames": { - "13": { - "frame_number": 13, - "time_seconds": 0.545, - "time_formatted": "00:00:00", - "detections": [ - { - "class_id": 0, - "class_name": "person", - "confidence": 0.8424218893051147, - "x1": 473.4156494140625, - "y1": 79.5609359741211, - "x2": 639.77783203125, - "y2": 303.8714294433594, - "width": 166, - "height": 224 - } - ] - } - } - }"#; - - let python_result: YoloPythonResult = serde_json::from_str(json).unwrap(); - assert_eq!(python_result.metadata.fps, 22.0); - assert_eq!(python_result.frames.len(), 1); - let frame = python_result.frames.get("13").unwrap(); - assert_eq!(frame.frame_number, 13); - assert_eq!(frame.detections.len(), 1); - let detection = &frame.detections[0]; - assert_eq!(detection.class_id, Some(0)); - assert_eq!(detection.class_name, "person"); - assert!((detection.confidence - 0.8424218893051147).abs() < 0.0001); - assert!((detection.x1 - 473.4156494140625).abs() < 0.0001); - - // Convert to YoloResult - let yolo_result = python_result.to_yolo_result(); - assert_eq!(yolo_result.frames.len(), 1); - assert_eq!(yolo_result.frames[0].frame, 13); - assert_eq!(yolo_result.frames[0].objects.len(), 1); - let obj = &yolo_result.frames[0].objects[0]; - assert_eq!(obj.class_name, "person"); - assert_eq!(obj.class_id, 0); - assert_eq!(obj.x, 473); - assert_eq!(obj.y, 79); - assert_eq!(obj.width, 166); - assert_eq!(obj.height, 224); - assert!((obj.confidence - 0.842421889).abs() < 0.0001); - } -} diff --git a/src/processing/decision.rs b/src/processing/decision.rs index 6b333bff..378ca00f 100644 --- a/src/processing/decision.rs +++ b/src/processing/decision.rs @@ -87,10 +87,6 @@ impl SystemResources { pub fn recommend_parallel_modules(&self) -> Vec<&'static str> { let mut recommended = Vec::new(); - if self.gpu_available { - recommended.push("yolo"); - } - if self.memory_available_mb >= 8192 { recommended.push("ocr"); recommended.push("face"); diff --git a/src/processing/modules/mod.rs b/src/processing/modules/mod.rs index 71151f17..2b101a2b 100644 --- a/src/processing/modules/mod.rs +++ b/src/processing/modules/mod.rs @@ -8,7 +8,6 @@ pub mod cut; pub mod face; pub mod ocr; pub mod pose; -pub mod yolo; pub use appearance::*; pub use asr::*; @@ -18,4 +17,3 @@ pub use cut::*; pub use face::*; pub use ocr::*; pub use pose::*; -pub use yolo::*; diff --git a/src/processing/modules/yolo.rs b/src/processing/modules/yolo.rs deleted file mode 100644 index 521425b4..00000000 --- a/src/processing/modules/yolo.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! YOLO (Object Detection) processing module - -use anyhow::Result; -use momentry_core::ui::progress::{ProcessorType, ProgressState, ProgressUi}; -use momentry_core::OutputDir; -use std::path::Path; -use std::sync::{Arc, Mutex}; - -/// Process YOLO module -pub async fn process_yolo_module( - yolo_path: &Path, - video_path: &str, - uuid: &str, - progress_state: &Arc>, - ui: &Arc>>, -) -> Result<()> { - { - let mut state = progress_state.lock().unwrap(); - state.get_processor(ProcessorType::Yolo).start(1); - } - - let yolo_result = momentry_core::core::processor::process_yolo( - video_path, - yolo_path.to_str().unwrap(), - Some(uuid), - None, - ) - .await?; - - let yolo_json = serde_json::to_string_pretty(&yolo_result)?; - std::fs::write(yolo_path, &yolo_json)?; - - let output_dir = OutputDir::new(); - let _ = output_dir.backup_file(uuid, "yolo.json"); - - println!(" ✓ YOLO saved: {} frames", yolo_result.frame_count); - - { - let mut state = progress_state.lock().unwrap(); - state - .get_processor(ProcessorType::Yolo) - .complete(&format!("{} frames", yolo_result.frame_count)); - } - - if let Some(ref mut ui) = *ui.lock().unwrap() { - let _ = ui.render(); - } - - Ok(()) -} diff --git a/src/ui/progress/mod.rs b/src/ui/progress/mod.rs index e4589e39..3ca83c68 100644 --- a/src/ui/progress/mod.rs +++ b/src/ui/progress/mod.rs @@ -16,7 +16,6 @@ pub enum ProcessorType { Asr, Cut, Asrx, - Yolo, Ocr, Face, Pose, @@ -31,7 +30,6 @@ impl ProcessorType { ProcessorType::Asr => "ASR", ProcessorType::Cut => "CUT", ProcessorType::Asrx => "ASRX", - ProcessorType::Yolo => "YOLO", ProcessorType::Ocr => "OCR", ProcessorType::Face => "Face", ProcessorType::Pose => "Pose", @@ -138,7 +136,6 @@ impl ProgressState { ProcessorProgress::new(ProcessorType::Asr), ProcessorProgress::new(ProcessorType::Cut), ProcessorProgress::new(ProcessorType::Asrx), - ProcessorProgress::new(ProcessorType::Yolo), ProcessorProgress::new(ProcessorType::Ocr), ProcessorProgress::new(ProcessorType::Face), ProcessorProgress::new(ProcessorType::Pose), @@ -194,7 +191,6 @@ impl ProgressState { "ASR" => ProcessorType::Asr, "CUT" => ProcessorType::Cut, "ASRX" => ProcessorType::Asrx, - "YOLO" => ProcessorType::Yolo, "OCR" => ProcessorType::Ocr, "FACE" => ProcessorType::Face, "POSE" => ProcessorType::Pose, diff --git a/src/verification/schema.rs b/src/verification/schema.rs index 068d818b..13e5d2e2 100644 --- a/src/verification/schema.rs +++ b/src/verification/schema.rs @@ -48,28 +48,7 @@ pub const PROCESSOR_SCHEMAS: &[ProcessorJsonSchema] = &[ field_type: FieldType::Array, allow_empty: true, }, - ], - min_data_threshold: 0, - }, - ProcessorJsonSchema { - processor: ProcessorType::Yolo, - required_fields: &[ - RequiredField { - path: "metadata.fps", - field_type: FieldType::PositiveNumber, - allow_empty: false, - }, - RequiredField { - path: "metadata.total_frames", - field_type: FieldType::PositiveNumber, - allow_empty: false, - }, - RequiredField { - path: "frames", - field_type: FieldType::Object, - allow_empty: true, - }, - ], + ], min_data_threshold: 0, }, ProcessorJsonSchema { diff --git a/src/verification/verifier.rs b/src/verification/verifier.rs index 712e0f44..d31aae08 100644 --- a/src/verification/verifier.rs +++ b/src/verification/verifier.rs @@ -130,14 +130,6 @@ fn count_data_items(processor: &ProcessorType, value: &serde_json::Value) -> usi .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0), - ProcessorType::Yolo => { - // YOLO uses dict-based frames - value - .get("frames") - .and_then(|v| v.as_object()) - .map(|o| o.len()) - .unwrap_or(0) - } ProcessorType::Ocr | ProcessorType::Face | ProcessorType::Pose @@ -277,7 +269,6 @@ fn check_reasonableness( let is_sampled = matches!( processor, ProcessorType::Cut - | ProcessorType::Yolo | ProcessorType::Ocr | ProcessorType::Face | ProcessorType::Pose @@ -419,29 +410,6 @@ fn build_data_summary(processor: &ProcessorType, value: &serde_json::Value) -> s .count()); } } - ProcessorType::Yolo => { - if let Some(frames) = value.get("frames").and_then(|v| v.as_object()) { - let total_detections: usize = frames - .values() - .map(|f| { - f.get("objects") - .and_then(|v| v.as_array()) - .map(|a| a.len()) - .unwrap_or(0) - }) - .sum(); - summary["total_detections"] = serde_json::json!(total_detections); - summary["frames_with_data"] = serde_json::json!(frames - .values() - .filter(|f| { - f.get("objects") - .and_then(|v| v.as_array()) - .map(|a| !a.is_empty()) - .unwrap_or(false) - }) - .count()); - } - } ProcessorType::Asr => { if let Some(segments) = value.get("segments").and_then(|v| v.as_array()) { summary["segment_count"] = serde_json::json!(segments.len()); diff --git a/src/worker/processor.rs b/src/worker/processor.rs index 62b7e4b1..aac3c7c3 100644 --- a/src/worker/processor.rs +++ b/src/worker/processor.rs @@ -84,7 +84,6 @@ use crate::core::processor::face::FaceResult; use crate::core::processor::ocr::OcrResult; use crate::core::processor::pose::PoseResult; use crate::core::processor::scene_classification::SceneClassificationResult; -use crate::core::processor::yolo::YoloResult; use crate::worker::resources::SystemResources; #[derive(Debug)] @@ -710,53 +709,6 @@ impl ProcessorPool { total_faces: 0, }) } - ProcessorType::Yolo => { - let result = processor::process_yolo( - video_path, - output_path.to_str().unwrap(), - uuid, - Some(&sample_frames), - ) - .await?; - let chunks_produced = result.frames.len() as i32; - tracing::info!( - "YOLO completed, storing {} frames for {}", - chunks_produced, - job.uuid - ); - if let Err(e) = Self::store_yolo_chunks(db, &job.uuid, &result).await { - tracing::error!("Failed to store YOLO chunks for {}: {}", job.uuid, e); - } - if let Some(ref ws) = workspace { - for frame in &result.frames { - let data = serde_json::json!({"objects": frame.objects}); - let _ = ws - .store_pre_chunk( - "yolo", - "raw", - Some(frame.frame as i64), - None, - Some(frame.timestamp), - None, - Some(&data.to_string()), - None, - ) - .await; - } - } - Ok(ProcessorOutput { - data: serde_json::to_value(result)?, - chunks_produced, - frames_processed: total_frames, - total_frames, - retry_count: 0, - pid: 0, - asr_status: None, - segment_count: 0, - face_status: None, - total_faces: 0, - }) - } ProcessorType::Ocr => { let result = processor::process_ocr( video_path, @@ -1321,40 +1273,6 @@ impl ProcessorPool { Ok(()) } - pub async fn store_yolo_chunks( - db: &PostgresDb, - uuid: &str, - yolo_result: &YoloResult, - ) -> Result<()> { - let frames_count = yolo_result.frames.len(); - tracing::info!( - "Storing {} YOLO pre-chunks for video {}", - frames_count, - uuid - ); - - let mut pre_chunks_to_store = Vec::new(); - - for frame in yolo_result.frames.iter() { - let data = serde_json::json!({ - "objects": frame.objects, - "timestamp": frame.timestamp, - }); - - pre_chunks_to_store.push(( - frame.frame as i64, // coordinate_index - Some(frame.timestamp), // timestamp - data, - None, // identity_id - None, // confidence - )); - } - - db.store_raw_pre_chunks_batch(uuid, "yolo", &pre_chunks_to_store) - .await?; - Ok(()) - } - pub async fn store_ocr_chunks( db: &PostgresDb, uuid: &str, diff --git a/src/worker/resources.rs b/src/worker/resources.rs index b863c3dd..7c38ace5 100644 --- a/src/worker/resources.rs +++ b/src/worker/resources.rs @@ -9,6 +9,8 @@ pub struct SystemResources { pub gpu_available: bool, pub gpu_utilization: Option, pub gpu_memory_used_pct: Option, + pub ane_available: bool, + pub ane_utilization: Option, } impl SystemResources { @@ -23,6 +25,7 @@ impl SystemResources { 0.0 }; let (gpu_avail, gpu_util, gpu_mem) = Self::get_gpu_info(); + let (ane_avail, ane_util) = Self::get_ane_info(); Self { cpu_idle_percent: cpu_idle, @@ -33,6 +36,8 @@ impl SystemResources { gpu_available: gpu_avail, gpu_utilization: gpu_util, gpu_memory_used_pct: gpu_mem, + ane_available: ane_avail, + ane_utilization: ane_util, } } @@ -276,4 +281,28 @@ impl SystemResources { (false, None, None) } + + fn get_ane_info() -> (bool, Option) { + use std::process::Command; + + let output = Command::new("ps") + .args(["aux"]) + .output(); + + if let Ok(o) = output { + let s = String::from_utf8_lossy(&o.stdout); + for line in s.lines() { + if line.contains("/usr/libexec/aned") { + if let Some(cpu_str) = line.split_whitespace().nth(2) { + if let Ok(cpu) = cpu_str.parse::() { + return (true, Some(cpu)); + } + } + return (true, None); + } + } + } + + (false, None) + } }