"""Main CLI entry point for IP violation detection system.""" import asyncio import click from rich.console import Console from rich.table import Table from loguru import logger import os from datetime import datetime from typing import List, Dict, Optional from .pdf_processing.extractor import PDFImageExtractor from .pdf_processing.thumbnail_generator import ThumbnailGenerator from .llm_providers.provider_factory import LLMProviderFactory from .analysis.orchestrator import AnalysisOrchestrator from .reporting.csv_generator import CSVReportGenerator from .reporting.summary_generator import SummaryGenerator from .reporting.sheets_uploader import GoogleSheetsUploader from .utils.cost_tracker import CostTracker from .config.settings import settings console = Console() async def _sheets_consumer( result_queue: asyncio.Queue, uploader: GoogleSheetsUploader, thumbnail_map: Dict[str, str], batch_size: int, ) -> None: """ Consumer task that reads results from queue and uploads to Sheets in batches. Args: result_queue: Queue producing (index, result) tuples, None sentinel at end uploader: Initialized GoogleSheetsUploader thumbnail_map: Local thumbnail path mapping batch_size: How many results to buffer before flushing """ batch_buffer: List[Dict] = [] batch_image_ids: List[str] = [] loop = asyncio.get_event_loop() while True: item = await result_queue.get() # Sentinel: None means all images are done if item is None: # Flush remaining buffer if batch_buffer: try: thumbnail_urls = await loop.run_in_executor( None, lambda ids=list(batch_image_ids), tmap=thumbnail_map: ( uploader.upload_thumbnails_batch(ids, tmap) ), ) await loop.run_in_executor( None, lambda batch=list(batch_buffer), urls=thumbnail_urls: ( uploader.append_batch(batch, urls) ), ) logger.info( f"Flushed final batch of {len(batch_buffer)} results to Sheets" ) except Exception as e: logger.error(f"Failed to flush final batch to Sheets: {e}") break idx, result = item batch_buffer.append(result) image_id = result.get("image_meta", {}).get("image_id", "unknown") batch_image_ids.append(image_id) # Flush when batch is full if len(batch_buffer) >= batch_size: try: thumbnail_urls = await loop.run_in_executor( None, lambda ids=list(batch_image_ids), tmap=thumbnail_map: ( uploader.upload_thumbnails_batch(ids, tmap) ), ) await loop.run_in_executor( None, lambda batch=list(batch_buffer), urls=thumbnail_urls: ( uploader.append_batch(batch, urls) ), ) logger.info(f"Flushed batch of {len(batch_buffer)} results to Sheets") except Exception as e: logger.error(f"Failed to upload batch to Sheets: {e}") logger.warning( f"Batch of {len(batch_buffer)} results missed in Sheets. " f"Data preserved in checkpoints and Excel report." ) batch_buffer = [] batch_image_ids = [] async def _run_analysis_with_streaming( orchestrator: AnalysisOrchestrator, images: List[Dict], run_quality_check: bool, uploader: Optional[GoogleSheetsUploader], thumbnail_map: Dict[str, str], sheet_id: Optional[str], resume_from: int = 0, pre_loaded_results: Optional[List[Dict]] = None, source_file: Optional[str] = None, results_sheet_url: Optional[str] = None, ) -> List[Dict]: """ Run analysis with concurrent Sheets streaming. Args: orchestrator: Configured AnalysisOrchestrator images: Images to analyze run_quality_check: Whether to run quality checks uploader: Optional Sheets uploader (None if no OAuth) thumbnail_map: Local thumbnail paths sheet_id: Google Sheets spreadsheet ID resume_from: Index to resume from pre_loaded_results: Pre-loaded results from checkpoint Returns: List of all analysis results """ result_queue = None consumer_task = None if uploader is not None: # Initialize sheets (headers, formatting) before analysis loop = asyncio.get_event_loop() try: await loop.run_in_executor(None, uploader.initialize_sheets, sheet_id) except Exception as e: err_str = str(e) if ( "404" in err_str or "SpreadsheetNotFound" in err_str or "Requested entity was not found" in err_str ): console.print( f"\n[red]Google Sheets error:[/red] Sheet ID '{sheet_id}' not found (404)." ) console.print( "[yellow]Make sure the sheet exists and is shared with your OAuth account.[/yellow]" ) console.print( "[yellow]Continuing analysis without Google Sheets upload.[/yellow]" ) else: console.print( f"\n[yellow]Google Sheets initialization failed: {e}[/yellow]" ) console.print( "[yellow]Continuing analysis without Google Sheets upload.[/yellow]" ) uploader = None if uploader is not None: result_queue = asyncio.Queue() consumer_task = asyncio.create_task( _sheets_consumer( result_queue, uploader, thumbnail_map, batch_size=settings.SHEETS_BATCH_SIZE, ) ) # Run analysis (pushes results to queue as they complete) results = await orchestrator.analyze_all_images( images, run_quality_check=run_quality_check, result_queue=result_queue, resume_from=resume_from, pre_loaded_results=pre_loaded_results, source_file=source_file, results_sheet_url=results_sheet_url, ) # Wait for consumer to finish flushing if consumer_task is not None: await consumer_task # Write final statistics loop = asyncio.get_event_loop() sheet_url = await loop.run_in_executor(None, uploader.finalize_sheets) logger.info(f"Sheets finalized: {sheet_url}") return results @click.command() @click.option( "--pdf", type=click.Path(exists=True), required=True, help="Path to PDF file to analyze", ) @click.option( "--output-dir", type=click.Path(), default="output", help="Output directory for results", ) @click.option("--dry-run", is_flag=True, help="Estimate cost only, do not run analysis") @click.option( "--skip-quality", is_flag=True, help="Skip quality control checks (IP detection only)", ) @click.option("--verbose", is_flag=True, help="Show detailed logs") def main(pdf: str, output_dir: str, dry_run: bool, skip_quality: bool, verbose: bool): """ Multi-LLM IP Violation Detection System. Analyzes character images from PDF for potential IP violations using GPT-4o and Gemini 3 Pro with search grounding. """ # Set up logging if verbose: logger.level("DEBUG") # Update output directory settings.OUTPUT_DIR = output_dir settings.REPORTS_DIR = os.path.join(output_dir, "reports") settings.THUMBNAILS_DIR = os.path.join(output_dir, "thumbnails") os.makedirs(settings.REPORTS_DIR, exist_ok=True) os.makedirs(settings.THUMBNAILS_DIR, exist_ok=True) # Banner console.print( "\n[bold cyan]IP Violation Detection System - PREMIUM QUALITY (3 Best Models)[/bold cyan]" ) console.print("=" * 70) console.print( f"[yellow]Parallel processing:[/yellow] {settings.MAX_CONCURRENT_IMAGES} images concurrently" ) # Extract images from PDF console.print(f"\n[yellow]PDF:[/yellow] {pdf}") extractor = PDFImageExtractor(output_dir=os.path.join(output_dir, "extracted")) try: images = extractor.extract_images_from_pdf(pdf) images = extractor.validate_images(images) except Exception as e: console.print(f"[red]Error extracting images:[/red] {e}") return if not images: console.print("[red]No valid images found in PDF[/red]") return console.print(f"[yellow]Images detected:[/yellow] {len(images)}") console.print( "[yellow]Models:[/yellow] GPT-5.2 (OpenAI) + Gemini 3.1 Pro (Google) + Claude Opus 4.6 (Anthropic)" ) console.print( "[yellow]Features:[/yellow] Vision analysis + Search grounding + Extended thinking" ) console.print(f"[yellow]Output:[/yellow] {output_dir}") # Cost estimation cost_tracker = CostTracker() estimates = cost_tracker.estimate_total_cost(len(images)) console.print( f"\n[yellow]Estimated Cost:[/yellow] ${estimates['total']:.2f} (no limit enforced)" ) console.print(f" * GPT-5.2: ${estimates.get('gpt-5.2', 0):.2f}") console.print( f" * Gemini 3.1 Pro: ${estimates.get('gemini-3.1-pro-preview', 0):.2f}" ) console.print(f" * Claude Opus 4.6: ${estimates.get('claude-opus-4-6', 0):.2f}") if dry_run: console.print("\n[cyan]Dry run complete. Exiting.[/cyan]") return # Confirm if not click.confirm("\nProceed with analysis?", default=True): console.print("[yellow]Analysis cancelled[/yellow]") return # Initialize providers console.print("\n[cyan]Initializing AI models...[/cyan]") try: providers = LLMProviderFactory.create_all_providers() console.print(f"[green]v[/green] Initialized {len(providers)} models") except Exception as e: console.print(f"[red]Error initializing providers:[/red] {e}") return # Generate thumbnails console.print("\n[cyan]Generating thumbnails...[/cyan]") thumbnail_gen = ThumbnailGenerator(thumbnail_dir=settings.THUMBNAILS_DIR) thumbnail_map = thumbnail_gen.generate_thumbnails(images) console.print(f"[green]v[/green] Generated {len(thumbnail_map)} thumbnails") # Check for resume from checkpoint orchestrator = AnalysisOrchestrator(providers, cost_tracker) resume_from = 0 pre_loaded_results = None checkpoint = orchestrator.load_latest_checkpoint() if ( checkpoint and checkpoint.get("total_images") == len(images) and checkpoint.get("completed_count", 0) > 0 ): completed = checkpoint["completed_count"] total = checkpoint["total_images"] console.print( f"\n[yellow]Found checkpoint:[/yellow] {completed}/{total} images already processed " f"(cost: ${checkpoint.get('total_cost', 0):.2f})" ) if click.confirm(f"Resume from image {completed + 1}?", default=True): resume_from = completed # Reconstruct pre-loaded results from checkpoint results_by_index = checkpoint.get("results_by_index", {}) pre_loaded_results = [None] * total for idx_str, result in results_by_index.items(): pre_loaded_results[int(idx_str)] = result console.print( f"[green]v[/green] Resuming from image {resume_from + 1}/{total}" ) else: console.print("[yellow]Starting fresh analysis[/yellow]") # Set up Sheets uploader — auto-create a new sheet for this run uploader = None sheet_id = None sheet_url = None if os.path.exists("token.pickle"): try: uploader = GoogleSheetsUploader(use_oauth=True) pdf_name = os.path.splitext(os.path.basename(pdf))[0] sheet_title = f"IP Analysis — {pdf_name} — {datetime.now().strftime('%Y-%m-%d %H:%M')}" sheet_id, sheet_url = uploader.get_or_create_spreadsheet(sheet_title) console.print( f"[green]v[/green] Results sheet: [link={sheet_url}]{sheet_url}[/link]" ) console.print( f"[green]v[/green] Google Sheets streaming enabled (batch size: {settings.SHEETS_BATCH_SIZE})" ) except Exception as e: console.print(f"[yellow]Google Sheets streaming disabled: {e}[/yellow]") uploader = None else: console.print( "[yellow]Google Sheets upload skipped (run authenticate_oauth.py first)[/yellow]" ) # Run analysis with streaming Sheets insertion console.print( f"\n[cyan]Analyzing {len(images)} images ({settings.MAX_CONCURRENT_IMAGES} at a time)...[/cyan]" ) try: results = asyncio.run( _run_analysis_with_streaming( orchestrator=orchestrator, images=images, run_quality_check=not skip_quality, uploader=uploader, thumbnail_map=thumbnail_map, sheet_id=sheet_id, resume_from=resume_from, pre_loaded_results=pre_loaded_results, source_file=os.path.basename(pdf), results_sheet_url=sheet_url, ) ) except KeyboardInterrupt: console.print("\n[yellow]Analysis interrupted by user.[/yellow]") console.print( "[yellow]Progress saved to checkpoint. Run again to resume.[/yellow]" ) return except Exception as e: console.print(f"\n[red]Error during analysis:[/red] {e}") console.print( "[yellow]Progress saved to checkpoint. Run again to resume.[/yellow]" ) logger.exception("Analysis failed") return # Generate reports console.print("\n[cyan]Generating reports...[/cyan]") # Excel report report_gen = CSVReportGenerator(output_dir=settings.REPORTS_DIR) excel_path = report_gen.generate_report(results, thumbnail_map) console.print(f"[green]v[/green] {excel_path}") # Legal summary summary_gen = SummaryGenerator(output_dir=settings.REPORTS_DIR) summary_path = summary_gen.generate_summary(results, cost_tracker.get_summary()) console.print(f"[green]v[/green] {summary_path}") # Cost report cost_report_path = os.path.join(settings.REPORTS_DIR, "cost_report.json") cost_tracker.save_report(cost_report_path) console.print(f"[green]v[/green] {cost_report_path}") if uploader is not None and sheet_url: console.print(f"[bold green]Results sheet:[/bold green] {sheet_url}") # Display summary _display_summary(results, cost_tracker) console.print("\n[bold green]Analysis complete![/bold green]") def _display_summary(results, cost_tracker): """Display analysis summary.""" total_images = len(results) # Count consensus types (supports 3-model majority vote) all_agree_violation = sum( 1 for r in results if r.get("consensus", {}).get("consensus_type") in ("ALL_AGREE_VIOLATION", "BOTH_AGREE_VIOLATION") ) majority_violation = sum( 1 for r in results if r.get("consensus", {}).get("consensus_type") == "MAJORITY_VIOLATION" ) all_agree_safe = sum( 1 for r in results if r.get("consensus", {}).get("consensus_type") in ("ALL_AGREE_SAFE", "BOTH_AGREE_SAFE") ) majority_safe = sum( 1 for r in results if r.get("consensus", {}).get("consensus_type") == "MAJORITY_SAFE" ) split_decisions = sum( 1 for r in results if r.get("consensus", {}).get("consensus_type") == "SPLIT_DECISION" ) single_model = sum( 1 for r in results if r.get("consensus", {}).get("consensus_type") == "SINGLE_MODEL_ONLY" ) both_agree_violation = all_agree_violation # alias for risk assessment below high_risk = sum( 1 for r in results if r.get("consensus", {}).get("avg_similarity", 0) > 60 ) medium_risk = sum( 1 for r in results if 40 <= r.get("consensus", {}).get("avg_similarity", 0) <= 60 ) # Risk assessment if both_agree_violation > 0 or high_risk >= 3: risk_level = "[red]CRITICAL[/red]" elif high_risk > 0 or split_decisions > 5: risk_level = "[yellow]HIGH[/yellow]" elif medium_risk > 3 or split_decisions > 2: risk_level = "[yellow]MEDIUM[/yellow]" else: risk_level = "[green]LOW[/green]" console.print("\n" + "=" * 70) console.print("[bold]ANALYSIS COMPLETE[/bold]") console.print("=" * 70) # Summary table table = Table(show_header=False, box=None) table.add_column("Metric", style="cyan") table.add_column("Value") table.add_row("Images Analyzed:", str(total_images)) table.add_row("Models Used:", "3 (GPT-5.2, Gemini 3.1 Pro, Claude Opus 4.6)") table.add_row("Concurrency:", f"{settings.MAX_CONCURRENT_IMAGES} images at a time") table.add_row("", "") table.add_row("[bold]Consensus Breakdown:[/bold]", "") table.add_row( " All Agree - Violation:", f"{all_agree_violation} ({all_agree_violation / total_images * 100:.1f}%) <- HIGH RISK", ) table.add_row( " Majority - Violation:", f"{majority_violation} ({majority_violation / total_images * 100:.1f}%) <- NEEDS REVIEW", ) table.add_row( " All Agree - Safe:", f"{all_agree_safe} ({all_agree_safe / total_images * 100:.1f}%) <- CLEAR", ) table.add_row( " Majority - Safe:", f"{majority_safe} ({majority_safe / total_images * 100:.1f}%) <- NEEDS REVIEW", ) table.add_row( " Split Decision:", f"{split_decisions} ({split_decisions / total_images * 100:.1f}%) <- NEEDS REVIEW", ) if single_model > 0: table.add_row( " Single/Two Models Only:", f"{single_model} ({single_model / total_images * 100:.1f}%) <- NEEDS REVIEW", ) table.add_row("", "") table.add_row("High Risk (>60% similarity):", str(high_risk)) table.add_row("Medium Risk (40-60%):", str(medium_risk)) table.add_row("", "") table.add_row("Total Cost:", f"${cost_tracker.total_cost:.2f}") table.add_row("", "") table.add_row("[bold]RISK ASSESSMENT:[/bold]", risk_level) console.print(table) console.print("=" * 70) # Warnings if all_agree_violation > 0: console.print( f"\n[red]{all_agree_violation} images flagged by ALL 3 models (high confidence violations)[/red]" ) if majority_violation > 0: console.print( f"[red]{majority_violation} images flagged by majority of models[/red]" ) if split_decisions > 0 or majority_safe > 0: console.print( f"[yellow]{split_decisions + majority_safe} images have split/majority-safe decisions (manual review needed)[/yellow]" ) if single_model > 0: console.print( f"[yellow]{single_model} images analyzed by fewer than 3 models (needs review)[/yellow]" ) if high_risk > 0 or split_decisions > 0: console.print("[yellow]Recommend legal review before publishing[/yellow]") if __name__ == "__main__": main()