Spaces:
Sleeping
Sleeping
File size: 4,418 Bytes
68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """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
|