from typing import Any, Dict, List, Tuple import os import time import zipfile from PIL import Image def get_image_metadata(image_path: str) -> Dict[str, Any]: """Get metadata for an image including aspect ratio, resolution, and size.""" try: img = Image.open(image_path) width, height = img.size # Calculate simplified aspect ratio gcd = lambda a, b: a if b == 0 else gcd(b, a % b) div = gcd(width, height) simplified_ratio = f"{width//div}:{height//div}" file_size = os.path.getsize(image_path) # Convert to appropriate unit size_str = f"{file_size} bytes" if file_size > 1024: size_str = f"{file_size/1024:.2f} KB" if file_size > 1024*1024: size_str = f"{file_size/(1024*1024):.2f} MB" return { "resolution": f"{width}x{height}", "aspect_ratio": simplified_ratio, "size": size_str, "width": width, "height": height } except Exception as e: return { "resolution": "Unknown", "aspect_ratio": "Unknown", "size": "Unknown", "width": 0, "height": 0, "error": str(e) } def format_metadata(metadata: Dict[str, Any]) -> str: """Format metadata as a string for display.""" if not metadata: return "No metadata available" result = [] if "resolution" in metadata: result.append(f"Resolution: {metadata['resolution']}") if "aspect_ratio" in metadata: result.append(f"Aspect Ratio: {metadata['aspect_ratio']}") if "size" in metadata: result.append(f"Size: {metadata['size']}") return " | ".join(result) def generate_caption(image_path: str, trigger_token: str, description: str) -> str: """Generate caption for an image with trigger token and description.""" if trigger_token: return f"A picture of {trigger_token}, {description}" else: return f"{description}" def save_caption(image_path: str, caption: str) -> str: """Save caption to a text file with the same name as the image.""" txt_path = os.path.splitext(image_path)[0] + ".txt" with open(txt_path, "w") as f: f.write(caption) return txt_path def create_zip_file(image_data: List[Dict[str, Any]], dataset_name: str = "") -> str: """Create a zip file containing all processed images and their captions.""" if not image_data: return "" # Create a zip file with a unique name based on timestamp and optional dataset name timestamp = int(time.time()) zip_name = f"{dataset_name}_{timestamp}" if dataset_name else f"processed_images_{timestamp}" temp_zip_path = f"{zip_name}.zip" with zipfile.ZipFile(temp_zip_path, 'w') as zipf: for idx, item in enumerate(image_data, 1): if "path" in item and os.path.exists(item["path"]): # Add the image file with incremental naming image_path = item["path"] image_ext = os.path.splitext(image_path)[1] zipf.write(image_path, f"{idx}{image_ext}") # Create and add the caption file with the same incremental name if "caption" in item: caption_content = item["caption"] txt_filename = f"{idx}.txt" # Create a temporary text file temp_txt_path = f"temp_{txt_filename}" with open(temp_txt_path, "w") as f: f.write(caption_content) # Add to zip and then delete the temp file zipf.write(temp_txt_path, txt_filename) os.remove(temp_txt_path) return temp_zip_path