Spaces:
Sleeping
Sleeping
Download src/reporting/summary_generator.py from yashpixl09/IP-Safe: direct link, hf CLI and curl.
- Browser
- Download file 8.08 kB
-
https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/reporting/summary_generator.py
- Command line
-
hf download hf://spaces/yashpixl09/IP-Safe/src/reporting/summary_generator.py
-
curl -L -o summary_generator.py https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/reporting/summary_generator.py
8.08 kB
| """Legal summary report generation.""" | |
| import os | |
| from typing import List, Dict | |
| from datetime import datetime | |
| from loguru import logger | |
| class SummaryGenerator: | |
| """Generate legal compliance summary reports.""" | |
| def __init__(self, output_dir: str = "output/reports"): | |
| """ | |
| Initialize summary generator. | |
| Args: | |
| output_dir: Directory to save summaries | |
| """ | |
| self.output_dir = output_dir | |
| os.makedirs(output_dir, exist_ok=True) | |
| def generate_summary( | |
| self, results: List[Dict], cost_summary: Dict, output_filename: str = None | |
| ) -> str: | |
| """ | |
| Generate legal compliance summary text file. | |
| Args: | |
| results: List of analysis results | |
| cost_summary: Cost tracking summary | |
| output_filename: Optional output filename | |
| Returns: | |
| Path to generated summary file | |
| """ | |
| if output_filename is None: | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| output_filename = f"legal_summary_{timestamp}.txt" | |
| output_path = os.path.join(self.output_dir, output_filename) | |
| # Generate summary content | |
| summary_text = self._generate_summary_text(results, cost_summary) | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| f.write(summary_text) | |
| logger.info(f"Legal summary generated: {output_path}") | |
| return output_path | |
| def _generate_summary_text(self, results: List[Dict], cost_summary: Dict) -> str: | |
| """Generate summary text content.""" | |
| total_images = len(results) | |
| # Analyze results | |
| both_agree_violation = 0 | |
| both_agree_safe = 0 | |
| split_decisions = 0 | |
| high_risk_images = [] | |
| medium_risk_images = [] | |
| ip_categories = {} | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| consensus_type = consensus.get("consensus_type", "UNKNOWN") | |
| image_id = result.get("image_meta", {}).get("image_id", "unknown") | |
| sim = consensus.get("avg_similarity", 0) | |
| identified_ip = consensus.get("identified_ip", "None") | |
| if consensus_type == "BOTH_AGREE_VIOLATION": | |
| both_agree_violation += 1 | |
| elif consensus_type == "BOTH_AGREE_SAFE": | |
| both_agree_safe += 1 | |
| elif consensus_type == "SPLIT_DECISION": | |
| split_decisions += 1 | |
| if sim > 60: | |
| high_risk_images.append((image_id, sim, identified_ip)) | |
| elif sim > 40: | |
| medium_risk_images.append((image_id, sim, identified_ip)) | |
| # Track IP categories | |
| if identified_ip != "None": | |
| model_results = result.get("model_results", []) | |
| for mr in model_results: | |
| cat = mr.get("ip_category", "Unknown") | |
| if cat != "None": | |
| ip_categories[cat] = ip_categories.get(cat, 0) + 1 | |
| # Determine overall risk assessment | |
| if both_agree_violation > 0 or len(high_risk_images) >= 3: | |
| overall_risk = "CRITICAL" | |
| elif len(high_risk_images) > 0 or split_decisions > 5: | |
| overall_risk = "HIGH" | |
| elif len(medium_risk_images) > 3 or split_decisions > 2: | |
| overall_risk = "MEDIUM" | |
| else: | |
| overall_risk = "LOW" | |
| # Generate recommendation | |
| if overall_risk == "CRITICAL": | |
| recommendation = "REJECT - Do not publish without significant revisions" | |
| elif overall_risk == "HIGH": | |
| recommendation = "REVIEW - Requires thorough legal review before publishing" | |
| elif overall_risk == "MEDIUM": | |
| recommendation = "REVIEW - Moderate risk, legal consultation recommended" | |
| else: | |
| recommendation = "APPROVE - Low risk for publishing" | |
| # Build summary text | |
| summary = [] | |
| summary.append("=" * 80) | |
| summary.append("IP VIOLATION DETECTION - LEGAL COMPLIANCE SUMMARY") | |
| summary.append("=" * 80) | |
| summary.append(f"\nGenerated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") | |
| summary.append("Analysis System: Multi-LLM (GPT-4o + Gemini 3 Pro)") | |
| summary.append("\n") | |
| summary.append("## EXECUTIVE SUMMARY") | |
| summary.append("-" * 80) | |
| summary.append(f"Total Images Analyzed: {total_images}") | |
| summary.append("Models Used: 2 (GPT-4o, Gemini 3 Pro)") | |
| summary.append( | |
| f"Total Cost: ${cost_summary.get('total_cost', 0):.2f}" | |
| ) | |
| summary.append(f"\nOverall Risk Assessment: **{overall_risk}**") | |
| summary.append(f"Recommendation: **{recommendation}**") | |
| summary.append("\n") | |
| summary.append("## CONSENSUS BREAKDOWN") | |
| summary.append("-" * 80) | |
| summary.append( | |
| f"Both Models Agree - Violation: {both_agree_violation} ({both_agree_violation / total_images * 100:.1f}%)" | |
| ) | |
| summary.append( | |
| f"Both Models Agree - Safe: {both_agree_safe} ({both_agree_safe / total_images * 100:.1f}%)" | |
| ) | |
| summary.append( | |
| f"Split Decisions (Manual Review): {split_decisions} ({split_decisions / total_images * 100:.1f}%)" | |
| ) | |
| summary.append("\n") | |
| summary.append("## RISK CATEGORIZATION") | |
| summary.append("-" * 80) | |
| summary.append( | |
| f"High Risk (>60% similarity): {len(high_risk_images)} images" | |
| ) | |
| summary.append( | |
| f"Medium Risk (41-60% similarity): {len(medium_risk_images)} images" | |
| ) | |
| summary.append( | |
| f"Low Risk (<40% similarity): {total_images - len(high_risk_images) - len(medium_risk_images)} images" | |
| ) | |
| summary.append("\n") | |
| if high_risk_images: | |
| summary.append("## HIGH-RISK IMAGES (>60% Similarity)") | |
| summary.append("-" * 80) | |
| for img_id, sim, ip in high_risk_images[:10]: # Top 10 | |
| summary.append(f" • {img_id}: {sim:.1f}% similarity to {ip}") | |
| if len(high_risk_images) > 10: | |
| summary.append(f" ... and {len(high_risk_images) - 10} more") | |
| summary.append("\n") | |
| if ip_categories: | |
| summary.append("## IP CATEGORIES DETECTED") | |
| summary.append("-" * 80) | |
| for category, count in sorted( | |
| ip_categories.items(), key=lambda x: x[1], reverse=True | |
| ): | |
| summary.append(f" • {category}: {count} detections") | |
| summary.append("\n") | |
| summary.append("## LEGAL NOTES") | |
| summary.append("-" * 80) | |
| if both_agree_violation > 0: | |
| summary.append( | |
| f"⚠️ {both_agree_violation} images flagged by BOTH AI models as potential" | |
| ) | |
| summary.append(" IP violations. These require immediate legal review.") | |
| if split_decisions > 0: | |
| summary.append( | |
| f"⚠️ {split_decisions} images have split decisions (models disagree)." | |
| ) | |
| summary.append(" Manual review recommended for these cases.") | |
| if len(high_risk_images) > 0: | |
| summary.append( | |
| f"⚠️ {len(high_risk_images)} images show >60% similarity to known IPs." | |
| ) | |
| summary.append(" High risk of infringement claims.") | |
| summary.append("\n") | |
| summary.append("## DISCLAIMER") | |
| summary.append("-" * 80) | |
| summary.append( | |
| "This analysis is provided by AI models and does NOT constitute legal advice." | |
| ) | |
| summary.append( | |
| "Results should be reviewed by qualified IP attorneys before making" | |
| ) | |
| summary.append( | |
| "publishing decisions. The system uses heuristic detection and may produce" | |
| ) | |
| summary.append("false positives or miss certain violations.") | |
| summary.append("\n") | |
| summary.append("=" * 80) | |
| return "\n".join(summary) | |