"""Thumbnail generation module for report images.""" from PIL import Image, ImageDraw, ImageFont import os from typing import Dict, Tuple from loguru import logger class ThumbnailGenerator: """Generate thumbnails for report visualization.""" def __init__( self, thumbnail_dir: str = "output/thumbnails", size: Tuple[int, int] = (800, 800), ): """ Initialize the thumbnail generator. Args: thumbnail_dir: Directory to save thumbnails size: Maximum thumbnail size (width, height) """ self.thumbnail_dir = thumbnail_dir self.size = size os.makedirs(thumbnail_dir, exist_ok=True) def generate_thumbnail( self, image_path: str, image_id: str, add_label: bool = True ) -> str: """ Generate a thumbnail from an image file. Args: image_path: Path to the source image image_id: Unique identifier for the image add_label: Whether to add image ID label to thumbnail Returns: Path to the generated thumbnail """ try: # Open image with Image.open(image_path) as img: # Convert to RGB if necessary if img.mode not in ("RGB", "RGBA"): img = img.convert("RGB") # Calculate thumbnail size maintaining aspect ratio img.thumbnail(self.size, Image.Resampling.LANCZOS) # Create a new image with border border_size = 2 new_size = (img.width + border_size * 2, img.height + border_size * 2) if add_label: # Add space for label at the bottom label_height = 30 new_size = (new_size[0], new_size[1] + label_height) # Create white background thumbnail = Image.new("RGB", new_size, "white") # Paste the image with border thumbnail.paste(img, (border_size, border_size)) # Add border draw = ImageDraw.Draw(thumbnail) draw.rectangle( [(0, 0), (new_size[0] - 1, new_size[1] - 1)], outline="gray", width=border_size, ) # Add label if requested if add_label: label_y = border_size + img.height + 5 try: # Try to use a nicer font if available font = ImageFont.truetype("arial.ttf", 12) except Exception: # Fall back to default font font = ImageFont.load_default() draw.text( (new_size[0] // 2, label_y), image_id, fill="black", font=font, anchor="mt", ) # Save thumbnail thumbnail_path = os.path.join( self.thumbnail_dir, f"{image_id}_thumb.png" ) thumbnail.save(thumbnail_path, "PNG", quality=95) logger.debug( f"Generated thumbnail for {image_id}: {thumbnail.width}x{thumbnail.height}" ) return thumbnail_path except Exception as e: logger.error(f"Failed to generate thumbnail for {image_id}: {e}") # Return original path as fallback return image_path def generate_thumbnails( self, images: list, add_labels: bool = True ) -> Dict[str, str]: """ Generate thumbnails for multiple images. Args: images: List of image metadata dicts with 'image_id' and 'path' add_labels: Whether to add image ID labels Returns: Dictionary mapping image_id to thumbnail_path """ thumbnail_map = {} for img_meta in images: image_id = img_meta["image_id"] image_path = img_meta["path"] thumbnail_path = self.generate_thumbnail(image_path, image_id, add_labels) thumbnail_map[image_id] = thumbnail_path logger.info(f"Generated {len(thumbnail_map)} thumbnails") return thumbnail_map