"""Analysis orchestrator coordinating multiple LLM providers with parallel processing.""" import asyncio from typing import List, Dict, Any, Optional from tqdm import tqdm from loguru import logger import json import os from datetime import datetime from ..llm_providers.base_provider import BaseLLMProvider from ..utils.cost_tracker import CostTracker from ..utils.retry_handler import call_with_timeout from ..utils.supabase_tracker import RunTracker from ..config import prompts from ..config.settings import settings from .result_aggregator import ResultAggregator class AnalysisOrchestrator: """Coordinate 2 best LLM providers to analyze each image with parallel processing.""" def __init__(self, providers: List[BaseLLMProvider], cost_tracker: CostTracker): """ Initialize the orchestrator. Args: providers: List of LLM providers (GPT-4o, Gemini 3 Pro) cost_tracker: Cost tracking instance """ self.providers = providers self.cost_tracker = cost_tracker self.result_aggregator = ResultAggregator() self.checkpoint_dir = "output/checkpoints" os.makedirs(self.checkpoint_dir, exist_ok=True) # Concurrency controls self._semaphore = asyncio.Semaphore(settings.MAX_CONCURRENT_IMAGES) self._checkpoint_lock = asyncio.Lock() self._cost_lock = asyncio.Lock() async def analyze_all_images( self, images: List[Dict], run_quality_check: bool = True, result_queue: Optional[asyncio.Queue] = None, resume_from: int = 0, pre_loaded_results: Optional[List[Dict]] = None, source_file: Optional[str] = None, results_sheet_url: Optional[str] = None, ) -> List[Dict[str, Any]]: """ Main orchestration loop - analyze all images with parallel processing. Args: images: List of image metadata dicts run_quality_check: Whether to run quality control checks result_queue: Optional queue to push results for Sheets streaming resume_from: Index to resume from (skip already-processed images) pre_loaded_results: Pre-loaded results from checkpoint for resumed images Returns: List of analysis results with consensus, in original order """ total_images = len(images) results: List[Optional[Dict[str, Any]]] = [None] * total_images completed_count = 0 # Start Supabase run tracking tracker = RunTracker("ip_check", source_file=source_file) tracker.start(total_images) # Load pre-existing results if resuming if pre_loaded_results and resume_from > 0: for i, result in enumerate(pre_loaded_results): if i < resume_from and result is not None: results[i] = result completed_count += 1 remaining = total_images - resume_from logger.info( f"Starting analysis of {remaining} images " f"({'resuming from ' + str(resume_from) if resume_from > 0 else 'fresh start'}) " f"with {len(self.providers)} models, concurrency={settings.MAX_CONCURRENT_IMAGES}" ) pbar = tqdm( total=total_images, initial=resume_from, desc="Analyzing images", unit="img" ) async def _process_image(idx: int, image_meta: Dict): """Process a single image under semaphore control with retry.""" nonlocal completed_count async with self._semaphore: image_result = None max_retries = settings.IMAGE_RETRY_ATTEMPTS for attempt in range(1, max_retries + 1): try: image_result = await self._analyze_single_image( image_meta, run_quality_check=run_quality_check ) break # Success — exit retry loop except Exception as e: if attempt < max_retries: wait_time = 2**attempt logger.warning( f"Image {image_meta['image_id']} failed (attempt {attempt}/{max_retries}): {e}. " f"Retrying in {wait_time}s..." ) await asyncio.sleep(wait_time) else: logger.error( f"Image {image_meta['image_id']} failed after {max_retries} attempts: {e}" ) image_result = { "image_meta": image_meta, "error": str(e), "attempts": max_retries, } results[idx] = image_result # Thread-safe checkpoint save async with self._checkpoint_lock: completed_results = { str(i): r for i, r in enumerate(results) if r is not None } self._save_checkpoint(completed_results, total_images) # Push to queue for Sheets consumer if result_queue is not None: await result_queue.put((idx, image_result)) # Update progress bar completed_count += 1 tracker.update(completed_count) consensus = (image_result or {}).get("consensus", {}) violation = consensus.get("ip_violation", "UNKNOWN") pbar.update(1) pbar.set_postfix( { "cost": f"${self.cost_tracker.total_cost:.2f}", "flagged": violation == "YES", "review": violation == "NEEDS_REVIEW", } ) # Create tasks for remaining images only tasks = [ _process_image(idx, image_meta) for idx, image_meta in enumerate(images) if idx >= resume_from ] # Run all tasks — semaphore limits actual concurrency to MAX_CONCURRENT_IMAGES await asyncio.gather(*tasks) pbar.close() # Signal queue consumer that all work is done if result_queue is not None: await result_queue.put(None) # Sentinel # Convert results list (filter None for safety, though all should be filled) final_results = [r for r in results if r is not None] logger.info( f"Analysis complete. Processed {len(final_results)}/{total_images} images" ) tracker.finish( "completed", results_sheet_url=results_sheet_url, cost_usd=round(self.cost_tracker.total_cost, 4), ) return final_results async def _call_provider_with_retry(self, provider, method_name: str, *args): """ Call a provider method with per-provider retry and exponential backoff. Args: provider: LLM provider instance method_name: Method to call ('analyze_ip_violation' or 'analyze_quality') *args: Arguments to pass to the method Returns: Provider result dict, or error dict if all retries fail """ provider_name = getattr(provider, "model_name", "Unknown") method = getattr(provider, method_name) max_retries = settings.IMAGE_RETRY_ATTEMPTS for attempt in range(1, max_retries + 1): try: result = await call_with_timeout( method(*args), timeout_seconds=settings.TIMEOUT_SECONDS ) return result except Exception as e: if attempt < max_retries: wait_time = 2**attempt logger.warning( f"{provider_name} failed (attempt {attempt}/{max_retries}): {e}. " f"Retrying in {wait_time}s..." ) await asyncio.sleep(wait_time) else: logger.error( f"{provider_name} failed after {max_retries} attempts: {e}" ) return {"error": str(e), "provider": provider_name} async def _analyze_single_image( self, image_meta: Dict, run_quality_check: bool = True ) -> Dict[str, Any]: """ Analyze a single image with all providers. Each provider call has its own retry logic. Args: image_meta: Image metadata dict run_quality_check: Whether to run quality checks Returns: Dictionary with all analysis results and consensus """ image_id = image_meta["image_id"] image_path = image_meta["path"] logger.debug(f"Analyzing {image_id} with {len(self.providers)} models") # Run IP violation analysis with both models in parallel (each with retry) ip_tasks = [ self._call_provider_with_retry( provider, "analyze_ip_violation", image_path, prompts.IP_VIOLATION_PROMPT, ) for provider in self.providers ] model_results = await asyncio.gather(*ip_tasks) # Aggregate IP violation results consensus = self.result_aggregator.aggregate(image_id, model_results) # Track costs (thread-safe) async with self._cost_lock: self.cost_tracker.add_analysis_cost(model_results) result = { "image_meta": image_meta, "model_results": model_results, "consensus": consensus, } # Optionally run quality check + kids safety (in parallel with each other) if run_quality_check: quality_tasks = [ self._call_provider_with_retry( provider, "analyze_quality", image_path, prompts.QUALITY_CONTROL_PROMPT, ) for provider in self.providers ] kids_tasks = [ self._call_provider_with_retry( provider, "analyze_quality", image_path, prompts.KIDS_SAFETY_PROMPT ) for provider in self.providers ] quality_results, kids_results = await asyncio.gather( asyncio.gather(*quality_tasks), asyncio.gather(*kids_tasks) ) # Aggregate quality results quality_consensus = self.result_aggregator.aggregate_quality( quality_results ) # Aggregate kids safety results kids_consensus = self.result_aggregator.aggregate_kids_safety(kids_results) result["quality_results"] = quality_results result["quality_consensus"] = quality_consensus result["kids_results"] = kids_results result["kids_consensus"] = kids_consensus # Track costs (thread-safe) async with self._cost_lock: self.cost_tracker.add_analysis_cost(quality_results) self.cost_tracker.add_analysis_cost(kids_results) return result def _save_checkpoint(self, results_by_index: Dict[str, Dict], total_images: int): """ Save progress checkpoint with index-based tracking for resume support. Args: results_by_index: Dict mapping string index to result total_images: Total number of images in the analysis """ checkpoint_path = os.path.join( self.checkpoint_dir, f"checkpoint_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", ) checkpoint_data = { "timestamp": datetime.now().isoformat(), "total_images": total_images, "completed_count": len(results_by_index), "processed_indices": sorted(int(k) for k in results_by_index.keys()), "total_cost": self.cost_tracker.total_cost, "results_by_index": results_by_index, } try: with open(checkpoint_path, "w") as f: json.dump(checkpoint_data, f, indent=2, default=str) # Keep only latest 3 checkpoints checkpoints = sorted( [ f for f in os.listdir(self.checkpoint_dir) if f.startswith("checkpoint_") ], reverse=True, ) for old_checkpoint in checkpoints[3:]: os.remove(os.path.join(self.checkpoint_dir, old_checkpoint)) except Exception as e: logger.warning(f"Failed to save checkpoint: {e}") def load_latest_checkpoint(self) -> Optional[Dict]: """ Load the most recent checkpoint for resume support. Returns: Checkpoint data dict or None if no checkpoint exists """ try: checkpoints = sorted( [ f for f in os.listdir(self.checkpoint_dir) if f.startswith("checkpoint_") ], reverse=True, ) if not checkpoints: return None checkpoint_path = os.path.join(self.checkpoint_dir, checkpoints[0]) with open(checkpoint_path, "r") as f: checkpoint_data = json.load(f) logger.info( f"Loaded checkpoint: {checkpoint_data['completed_count']}/{checkpoint_data['total_images']} images, " f"cost: ${checkpoint_data['total_cost']:.2f}" ) return checkpoint_data except Exception as e: logger.warning(f"Failed to load checkpoint: {e}") return None def load_checkpoint(self, checkpoint_path: str) -> List[Dict]: """ Load results from a specific checkpoint file (backward compatible). Args: checkpoint_path: Path to checkpoint JSON file Returns: List of results from checkpoint """ with open(checkpoint_path, "r") as f: checkpoint_data = json.load(f) # Handle both old format (list) and new format (index dict) if "results_by_index" in checkpoint_data: results_by_index = checkpoint_data["results_by_index"] max_idx = ( max(int(k) for k in results_by_index.keys()) if results_by_index else -1 ) results = [None] * (max_idx + 1) for idx_str, result in results_by_index.items(): results[int(idx_str)] = result return [r for r in results if r is not None] else: # Old format compatibility return checkpoint_data.get("results", [])