Spaces:
Sleeping
Sleeping
Download src/reporting/csv_generator.py from yashpixl09/IP-Safe: direct link, hf CLI and curl.
- Browser
- Download file 27 kB
-
https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/reporting/csv_generator.py
- Command line
-
hf download hf://spaces/yashpixl09/IP-Safe/src/reporting/csv_generator.py
-
curl -L -o csv_generator.py https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/reporting/csv_generator.py
27 kB
| """Excel/CSV report generation for IP violation analysis results.""" | |
| import pandas as pd | |
| from openpyxl import load_workbook | |
| from openpyxl.styles import Font, PatternFill, Alignment | |
| from openpyxl.drawing.image import Image as ExcelImage | |
| import os | |
| from typing import List, Dict | |
| from loguru import logger | |
| from datetime import datetime | |
| class CSVReportGenerator: | |
| """Generate Excel/CSV reports with multiple sheets.""" | |
| def __init__(self, output_dir: str = "output/reports"): | |
| """ | |
| Initialize report generator. | |
| Args: | |
| output_dir: Directory to save reports | |
| """ | |
| self.output_dir = output_dir | |
| os.makedirs(output_dir, exist_ok=True) | |
| def generate_report( | |
| self, | |
| results: List[Dict], | |
| thumbnail_map: Dict[str, str], | |
| output_filename: str = None, | |
| ) -> str: | |
| """ | |
| Generate client-friendly Excel report with 3 focused sheets. | |
| Args: | |
| results: List of analysis results | |
| thumbnail_map: Mapping of image_id to thumbnail path | |
| output_filename: Optional output filename | |
| Returns: | |
| Path to generated Excel file | |
| """ | |
| if output_filename is None: | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| output_filename = f"analysis_report_{timestamp}.xlsx" | |
| output_path = os.path.join(self.output_dir, output_filename) | |
| # Create 3 client-focused sheets | |
| with pd.ExcelWriter(output_path, engine="openpyxl") as writer: | |
| # Sheet 1: Publishing Dashboard | |
| self._create_dashboard_sheet(results, thumbnail_map, writer) | |
| # Sheet 2: Detailed Analysis | |
| self._create_detailed_analysis_sheet(results, thumbnail_map, writer) | |
| # Sheet 3: Summary Report | |
| self._create_summary_report_sheet(results, writer) | |
| # Apply formatting (color coding, column widths) | |
| self._apply_formatting(output_path, thumbnail_map) | |
| logger.info(f"Excel report generated: {output_path}") | |
| return output_path | |
| def _create_dashboard_sheet( | |
| self, results: List[Dict], thumbnail_map: Dict[str, str], writer | |
| ) -> None: | |
| """Create Publishing Dashboard sheet - client-focused quick decision view.""" | |
| rows = [] | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| image_id = result.get("image_meta", {}).get("image_id", "unknown") | |
| # Format image ID nicely (Page 3 Image 1 instead of page_03_img_001) | |
| formatted_id = ( | |
| image_id.replace("_", " ") | |
| .replace("page", "Page") | |
| .replace("img", "Image") | |
| ) | |
| # Get thumbnail path (will show as local path in Excel) | |
| thumbnail_path = thumbnail_map.get(image_id, "[No image]") | |
| row = { | |
| "Image": thumbnail_path, # Thumbnail file path | |
| "Image ID": formatted_id, | |
| "Status": consensus.get("status", "⚠️ NEEDS REVIEW"), | |
| "Risk Level": consensus.get("risk_level", "Unknown"), | |
| "Match Found": consensus.get("identified_ip", "None"), | |
| "Rights Holder": consensus.get("ip_owner", "N/A"), | |
| "Match Strength": f"{consensus.get('avg_similarity', 0):.0f}% match to original", | |
| "AI Agreement": consensus.get("ai_agreement_text", "Unknown"), | |
| "Action Required": consensus.get("action_required", "Review required"), | |
| } | |
| rows.append(row) | |
| df = pd.DataFrame(rows) | |
| # Sort by risk level (Critical > High > Moderate > Minimal) | |
| risk_order = { | |
| "Critical Risk": 0, | |
| "High Risk": 1, | |
| "Moderate Risk": 2, | |
| "Minimal Risk": 3, | |
| "Unknown": 4, | |
| } | |
| df["_sort"] = df["Risk Level"].map(risk_order) | |
| df = df.sort_values("_sort").drop("_sort", axis=1) | |
| df.to_excel(writer, sheet_name="Publishing Dashboard", index=False) | |
| def _create_detailed_analysis_sheet( | |
| self, results: List[Dict], thumbnail_map: Dict[str, str], writer | |
| ) -> None: | |
| """Create Detailed Analysis sheet - deep dive with redesign suggestions.""" | |
| rows = [] | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| image_id = result.get("image_meta", {}).get("image_id", "unknown") | |
| formatted_id = ( | |
| image_id.replace("_", " ") | |
| .replace("page", "Page") | |
| .replace("img", "Image") | |
| ) | |
| # Get thumbnail path | |
| thumbnail_path = thumbnail_map.get(image_id, "[No image]") | |
| # Format "What Matches" from matching_elements_detailed | |
| matching_elements = consensus.get("matching_elements", {}) | |
| what_matches = [] | |
| for category, details in matching_elements.items(): | |
| if isinstance(details, dict): | |
| desc = details.get("description", "") | |
| if desc and desc != "No match": | |
| what_matches.append(f"• {category.title()}: {desc}") | |
| what_matches_str = ( | |
| "\n".join(what_matches) | |
| if what_matches | |
| else "No specific elements identified" | |
| ) | |
| # Format "Suggested Changes" | |
| suggestions = consensus.get("redesign_suggestions", []) | |
| suggested_changes = ( | |
| "\n".join([f"• {s}" for s in suggestions]) if suggestions else "N/A" | |
| ) | |
| # Model details — dynamic across 1-3 models | |
| model_results = result.get("model_results", []) | |
| model_parts = [ | |
| f"{r.get('provider', r.get('model', 'Model'))}: {r.get('similarity_percentage', 0):.0f}%" | |
| for r in model_results | |
| if "similarity_percentage" in r | |
| ] | |
| if model_parts: | |
| model_details = ( | |
| " | ".join(model_parts) | |
| + f" | Avg: {consensus.get('avg_similarity', 0):.0f}%\nModel variance: {consensus.get('similarity_stddev', 0):.1f}%" | |
| ) | |
| else: | |
| model_details = "No model data" | |
| row = { | |
| "Image": thumbnail_path, # Thumbnail file path | |
| "Image ID": formatted_id, | |
| "Status": consensus.get("status", "⚠️"), | |
| "Risk Level": consensus.get("risk_level", "Unknown"), | |
| "Match Found": consensus.get("identified_ip", "None"), | |
| "Rights Holder": consensus.get("ip_owner", "N/A"), | |
| "Match Strength": f"{consensus.get('avg_similarity', 0):.0f}% match", | |
| "What Matches": what_matches_str, | |
| "Why It's Flagged": consensus.get( | |
| "combined_description", "No description" | |
| ), # FULL text | |
| "Suggested Changes": suggested_changes, | |
| "Model Details": model_details, | |
| } | |
| rows.append(row) | |
| df = pd.DataFrame(rows) | |
| df.to_excel(writer, sheet_name="Detailed Analysis", index=False) | |
| def _create_summary_report_sheet(self, results: List[Dict], writer) -> None: | |
| """Create Summary Report sheet - high-level overview for legal review.""" | |
| # Count status categories | |
| status_counts = {} | |
| risk_counts = { | |
| "Minimal Risk": 0, | |
| "Moderate Risk": 0, | |
| "High Risk": 0, | |
| "Critical Risk": 0, | |
| } | |
| ip_owner_risks = {} | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| # Status | |
| status = consensus.get("status", "⚠️ NEEDS REVIEW") | |
| status_counts[status] = status_counts.get(status, 0) + 1 | |
| # Risk | |
| risk = consensus.get("risk_level", "Unknown") | |
| if risk in risk_counts: | |
| risk_counts[risk] += 1 | |
| # IP owners | |
| ip_owner = consensus.get("ip_owner", "Unknown") | |
| similarity = consensus.get("avg_similarity", 0) | |
| if ip_owner not in ip_owner_risks: | |
| ip_owner_risks[ip_owner] = {"count": 0, "max_risk": 0, "max_image": ""} | |
| ip_owner_risks[ip_owner]["count"] += 1 | |
| if similarity > ip_owner_risks[ip_owner]["max_risk"]: | |
| ip_owner_risks[ip_owner]["max_risk"] = similarity | |
| ip_owner_risks[ip_owner]["max_image"] = result.get( | |
| "image_meta", {} | |
| ).get("image_id", "unknown") | |
| # Section A: Key Metrics | |
| metrics_rows = [ | |
| ["Total Images Analyzed", len(results)], | |
| ["Analysis Date", datetime.now().strftime("%Y-%m-%d")], | |
| ["Models Used", "GPT-5.2 + Gemini 3.1 Pro + Claude Opus 4.6"], | |
| ["", ""], | |
| ["PUBLISHING STATUS", ""], | |
| ["✅ Safe to Publish", status_counts.get("✅ SAFE TO PUBLISH", 0)], | |
| ["⚠️ Needs Review", status_counts.get("⚠️ NEEDS REVIEW", 0)], | |
| ["❌ Do Not Publish", status_counts.get("❌ DO NOT PUBLISH", 0)], | |
| ["", ""], | |
| ["RISK BREAKDOWN", ""], | |
| ["Minimal Risk (0-40%)", risk_counts["Minimal Risk"]], | |
| ["Moderate Risk (41-60%)", risk_counts["Moderate Risk"]], | |
| ["High Risk (61-80%)", risk_counts["High Risk"]], | |
| ["Critical Risk (81-100%)", risk_counts["Critical Risk"]], | |
| ] | |
| df_metrics = pd.DataFrame(metrics_rows, columns=["Metric", "Value"]) | |
| df_metrics.to_excel( | |
| writer, sheet_name="Summary Report", index=False, startrow=0 | |
| ) | |
| # Section B: IP Owners (write below metrics) | |
| ip_rows = [] | |
| for owner, data in sorted( | |
| ip_owner_risks.items(), key=lambda x: x[1]["count"], reverse=True | |
| ): | |
| ip_rows.append( | |
| { | |
| "Rights Holder": owner, | |
| "Images Flagged": data["count"], | |
| "Highest Risk Image": f"{data['max_image']} ({data['max_risk']:.0f}%)", | |
| "Action Needed": "Legal review + redesign" | |
| if data["max_risk"] > 60 | |
| else "Review required", | |
| } | |
| ) | |
| df_ip = pd.DataFrame(ip_rows) | |
| # Write below metrics section | |
| startrow = len(metrics_rows) + 3 | |
| df_ip.to_excel( | |
| writer, sheet_name="Summary Report", index=False, startrow=startrow | |
| ) | |
| # OLD METHODS KEPT FOR BACKWARD COMPATIBILITY (not used in new generate_report) | |
| def _create_all_results_sheet( | |
| self, results: List[Dict], thumbnail_map: Dict[str, str] | |
| ) -> pd.DataFrame: | |
| """Create sheet with all model results.""" | |
| rows = [] | |
| for result in results: | |
| image_meta = result.get("image_meta", {}) | |
| image_id = image_meta.get("image_id", "unknown") | |
| thumbnail_path = thumbnail_map.get(image_id, "") | |
| model_results = result.get("model_results", []) | |
| consensus = result.get("consensus", {}) | |
| # Add row for each model | |
| for model_result in model_results: | |
| if "error" not in model_result: | |
| rows.append( | |
| { | |
| "Image ID": image_id, | |
| "Thumbnail Path": thumbnail_path, | |
| "Model": model_result.get("model", "unknown"), | |
| "IP Violation": model_result.get("ip_violation", "UNKNOWN"), | |
| "Similarity %": model_result.get( | |
| "similarity_percentage", 0 | |
| ), | |
| "Identified IP": model_result.get("identified_ip", "None"), | |
| "IP Category": model_result.get("ip_category", "None"), | |
| "Confidence": model_result.get("confidence", "UNKNOWN"), | |
| "Reason": model_result.get("clash_description", "")[:200], | |
| "Legal Risk": model_result.get( | |
| "legal_risk_level", "UNKNOWN" | |
| ), | |
| } | |
| ) | |
| # Add consensus row | |
| rows.append( | |
| { | |
| "Image ID": image_id, | |
| "Thumbnail Path": thumbnail_path, | |
| "Model": "**CONSENSUS**", | |
| "IP Violation": consensus.get("ip_violation", "UNKNOWN"), | |
| "Similarity %": consensus.get("avg_similarity", 0), | |
| "Identified IP": consensus.get("identified_ip", "None"), | |
| "IP Category": "-", | |
| "Confidence": consensus.get("consensus_type", "UNKNOWN"), | |
| "Reason": consensus.get("combined_description", "")[:200], | |
| "Legal Risk": "HIGH" | |
| if consensus.get("avg_similarity", 0) > 60 | |
| else "MEDIUM" | |
| if consensus.get("avg_similarity", 0) > 40 | |
| else "LOW", | |
| } | |
| ) | |
| return pd.DataFrame(rows) | |
| def _create_consensus_sheet( | |
| self, results: List[Dict], thumbnail_map: Dict[str, str] | |
| ) -> pd.DataFrame: | |
| """Create sheet with consensus summary.""" | |
| rows = [] | |
| for result in results: | |
| image_meta = result.get("image_meta", {}) | |
| image_id = image_meta.get("image_id", "unknown") | |
| thumbnail_path = thumbnail_map.get(image_id, "") | |
| consensus = result.get("consensus", {}) | |
| rows.append( | |
| { | |
| "Image ID": image_id, | |
| "Thumbnail Path": thumbnail_path, | |
| "Consensus": consensus.get("ip_violation", "UNKNOWN"), | |
| "Type": consensus.get("consensus_type", "UNKNOWN"), | |
| "Similarity %": consensus.get("avg_similarity", 0), | |
| "Std Dev": consensus.get("similarity_stddev", 0), | |
| "Identified IP": consensus.get("identified_ip", "None"), | |
| "Model Agreement": consensus.get("model_agreement", 0), | |
| "Needs Review": consensus.get("needs_review", False), | |
| "Description": consensus.get("combined_description", "")[:300], | |
| } | |
| ) | |
| return pd.DataFrame(rows) | |
| def _create_high_risk_sheet( | |
| self, results: List[Dict], thumbnail_map: Dict[str, str] | |
| ) -> pd.DataFrame: | |
| """Create sheet with high-risk images (>60% similarity).""" | |
| rows = [] | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| if consensus.get("avg_similarity", 0) > 60: | |
| image_meta = result.get("image_meta", {}) | |
| image_id = image_meta.get("image_id", "unknown") | |
| thumbnail_path = thumbnail_map.get(image_id, "") | |
| rows.append( | |
| { | |
| "Image ID": image_id, | |
| "Thumbnail Path": thumbnail_path, | |
| "Similarity %": consensus.get("avg_similarity", 0), | |
| "Identified IP": consensus.get("identified_ip", "None"), | |
| "Consensus": consensus.get("ip_violation", "UNKNOWN"), | |
| "Type": consensus.get("consensus_type", "UNKNOWN"), | |
| "Description": consensus.get("combined_description", "")[:300], | |
| } | |
| ) | |
| return pd.DataFrame(rows) | |
| def _create_split_decisions_sheet( | |
| self, results: List[Dict], thumbnail_map: Dict[str, str] | |
| ) -> pd.DataFrame: | |
| """Create sheet with split decisions (models disagree).""" | |
| rows = [] | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| if consensus.get("consensus_type") == "SPLIT_DECISION": | |
| image_meta = result.get("image_meta", {}) | |
| image_id = image_meta.get("image_id", "unknown") | |
| thumbnail_path = thumbnail_map.get(image_id, "") | |
| rows.append( | |
| { | |
| "Image ID": image_id, | |
| "Thumbnail Path": thumbnail_path, | |
| "Similarity %": consensus.get("avg_similarity", 0), | |
| "Std Dev": consensus.get("similarity_stddev", 0), | |
| "Identified IP": consensus.get("identified_ip", "None"), | |
| "Model Agreement": consensus.get("model_agreement", 0), | |
| "Description": consensus.get("combined_description", "")[:300], | |
| } | |
| ) | |
| return pd.DataFrame(rows) | |
| def _create_statistics_sheet(self, results: List[Dict]) -> pd.DataFrame: | |
| """Create sheet with summary statistics.""" | |
| total_images = len(results) | |
| # Count consensus types | |
| consensus_types = {} | |
| high_risk_count = 0 | |
| medium_risk_count = 0 | |
| for result in results: | |
| consensus = result.get("consensus", {}) | |
| consensus_type = consensus.get("consensus_type", "UNKNOWN") | |
| consensus_types[consensus_type] = consensus_types.get(consensus_type, 0) + 1 | |
| sim = consensus.get("avg_similarity", 0) | |
| if sim > 60: | |
| high_risk_count += 1 | |
| elif sim >= 40: | |
| medium_risk_count += 1 | |
| low_risk_count = total_images - high_risk_count - medium_risk_count | |
| rows = [ | |
| {"Metric": "Total Images Analyzed", "Value": total_images}, | |
| {"Metric": "", "Value": ""}, | |
| {"Metric": "CONSENSUS BREAKDOWN", "Value": ""}, | |
| { | |
| "Metric": "Both Agree - Violation", | |
| "Value": consensus_types.get("BOTH_AGREE_VIOLATION", 0), | |
| }, | |
| { | |
| "Metric": "Both Agree - Safe", | |
| "Value": consensus_types.get("BOTH_AGREE_SAFE", 0), | |
| }, | |
| { | |
| "Metric": "Split Decisions", | |
| "Value": consensus_types.get("SPLIT_DECISION", 0), | |
| }, | |
| { | |
| "Metric": "Single Model Only", | |
| "Value": consensus_types.get("SINGLE_MODEL_ONLY", 0), | |
| }, | |
| {"Metric": "", "Value": ""}, | |
| {"Metric": "RISK BREAKDOWN", "Value": ""}, | |
| {"Metric": "High Risk (>60%)", "Value": high_risk_count}, | |
| {"Metric": "Medium Risk (40-60%)", "Value": medium_risk_count}, | |
| {"Metric": "Low Risk (<40%)", "Value": low_risk_count}, | |
| ] | |
| return pd.DataFrame(rows) | |
| def _apply_formatting(self, excel_path: str, thumbnail_map: Dict[str, str]): | |
| """Apply color coding and formatting to new 3-sheet layout.""" | |
| try: | |
| wb = load_workbook(excel_path) | |
| # Common header formatting | |
| header_fill = PatternFill( | |
| start_color="4472C4", end_color="4472C4", fill_type="solid" | |
| ) | |
| header_font = Font(bold=True, color="FFFFFF") | |
| # Format each sheet | |
| for sheet_name in wb.sheetnames: | |
| ws = wb[sheet_name] | |
| # Apply header formatting | |
| for cell in ws[1]: | |
| cell.fill = header_fill | |
| cell.font = header_font | |
| cell.alignment = Alignment(horizontal="center", vertical="center") | |
| # Sheet-specific formatting | |
| if sheet_name == "Publishing Dashboard": | |
| # Apply color coding by Status column | |
| self._apply_dashboard_colors(ws) | |
| # Set column widths | |
| ws.column_dimensions["A"].width = 20 # Image ID | |
| ws.column_dimensions["B"].width = 25 # Status | |
| ws.column_dimensions["C"].width = 20 # Risk Level | |
| ws.column_dimensions["D"].width = 20 # Match Found | |
| ws.column_dimensions["E"].width = 18 # Rights Holder | |
| ws.column_dimensions["F"].width = 22 # Match Strength | |
| ws.column_dimensions["G"].width = 35 # AI Agreement | |
| ws.column_dimensions["H"].width = 30 # Action Required | |
| elif sheet_name == "Detailed Analysis": | |
| # Set column widths for detailed view | |
| ws.column_dimensions["A"].width = 20 # Image ID | |
| ws.column_dimensions["B"].width = 20 # Status | |
| ws.column_dimensions["C"].width = 18 # Risk Level | |
| ws.column_dimensions["D"].width = 20 # Match Found | |
| ws.column_dimensions["E"].width = 18 # Rights Holder | |
| ws.column_dimensions["F"].width = 18 # Match Strength | |
| ws.column_dimensions["G"].width = 50 # What Matches | |
| ws.column_dimensions[ | |
| "H" | |
| ].width = 80 # Why It's Flagged (wide for full text) | |
| ws.column_dimensions["I"].width = 50 # Suggested Changes | |
| ws.column_dimensions["J"].width = 30 # Model Details | |
| elif sheet_name == "Summary Report": | |
| # Set column widths for summary | |
| ws.column_dimensions["A"].width = 35 # Metric | |
| ws.column_dimensions["B"].width = 15 # Value | |
| wb.save(excel_path) | |
| logger.info("Applied formatting with color coding") | |
| except Exception as e: | |
| logger.error(f"Failed to apply formatting: {e}") | |
| def _apply_dashboard_colors(self, ws): | |
| """Apply color coding to Publishing Dashboard based on Status column.""" | |
| # Find Status column (usually column B, index 2) | |
| status_col = 2 | |
| for row in range(2, ws.max_row + 1): | |
| status_cell = ws.cell(row, status_col) | |
| status = str(status_cell.value) | |
| # Determine colors based on status | |
| if "✅" in status: | |
| fill = PatternFill( | |
| start_color="C6EFCE", end_color="C6EFCE", fill_type="solid" | |
| ) | |
| font = Font(color="006100") | |
| elif "❌" in status: | |
| fill = PatternFill( | |
| start_color="FFC7CE", end_color="FFC7CE", fill_type="solid" | |
| ) | |
| font = Font(color="9C0006") | |
| elif "⚠️" in status: | |
| fill = PatternFill( | |
| start_color="FFEB9C", end_color="FFEB9C", fill_type="solid" | |
| ) | |
| font = Font(color="9C5700") | |
| else: | |
| continue | |
| # Apply to entire row | |
| for col in range(1, ws.max_column + 1): | |
| cell = ws.cell(row, col) | |
| cell.fill = fill | |
| cell.font = font | |
| # OLD METHOD - kept for backward compatibility but not used in new reports | |
| def _apply_formatting_old(self, excel_path: str, thumbnail_map: Dict[str, str]): | |
| """OLD: Apply formatting to Excel workbook and embed thumbnails.""" | |
| try: | |
| wb = load_workbook(excel_path) | |
| # Format each sheet | |
| for sheet_name in wb.sheetnames: | |
| ws = wb[sheet_name] | |
| # Header formatting | |
| header_fill = PatternFill( | |
| start_color="4472C4", end_color="4472C4", fill_type="solid" | |
| ) | |
| header_font = Font(bold=True, color="FFFFFF") | |
| # Find the thumbnail column index | |
| thumbnail_col_idx = None | |
| for idx, cell in enumerate(ws[1], start=1): | |
| cell.fill = header_fill | |
| cell.font = header_font | |
| cell.alignment = Alignment(horizontal="center", vertical="center") | |
| if cell.value == "Thumbnail Path": | |
| thumbnail_col_idx = idx | |
| # Rename header to "Thumbnail" | |
| cell.value = "Thumbnail" | |
| # Embed thumbnails if column exists | |
| if thumbnail_col_idx: | |
| thumbnail_col_letter = ws.cell( | |
| row=1, column=thumbnail_col_idx | |
| ).column_letter | |
| # Set thumbnail column width | |
| ws.column_dimensions[thumbnail_col_letter].width = 15 | |
| # Insert thumbnails | |
| for row_idx in range(2, ws.max_row + 1): | |
| cell = ws.cell(row=row_idx, column=thumbnail_col_idx) | |
| thumbnail_path = cell.value | |
| if thumbnail_path and os.path.exists(thumbnail_path): | |
| try: | |
| # Clear the cell text | |
| cell.value = "" | |
| # Insert image | |
| img = ExcelImage(thumbnail_path) | |
| # Resize to fit in cell (100 pixels height) | |
| img.height = 100 | |
| img.width = 100 | |
| # Position image in cell | |
| img.anchor = f"{thumbnail_col_letter}{row_idx}" | |
| ws.add_image(img) | |
| # Set row height to fit image (in points, 1 point = 1.33 pixels approx) | |
| ws.row_dimensions[row_idx].height = 75 | |
| except Exception as e: | |
| logger.warning( | |
| f"Failed to embed thumbnail {thumbnail_path}: {e}" | |
| ) | |
| cell.value = "Image error" | |
| # Auto-adjust other column widths | |
| for column in ws.columns: | |
| column_letter = column[0].column_letter | |
| # Skip thumbnail column as we already set it | |
| if thumbnail_col_idx and column_letter == thumbnail_col_letter: | |
| continue | |
| max_length = 0 | |
| for cell in column: | |
| try: | |
| if len(str(cell.value)) > max_length: | |
| max_length = len(str(cell.value)) | |
| except Exception: | |
| pass | |
| adjusted_width = min(max_length + 2, 50) | |
| ws.column_dimensions[column_letter].width = adjusted_width | |
| wb.save(excel_path) | |
| logger.info("Excel formatting and thumbnails applied") | |
| except Exception as e: | |
| logger.warning(f"Failed to apply Excel formatting: {e}") | |