import os import time import zipfile from typing import Any, Dict, List, Tuple import gradio as gr from PIL import Image import pillow_avif # type: ignore 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 generate_caption(image_path: str, trigger_token: str, description: str) -> str: """Generate caption for an image with trigger token and description.""" # In a real implementation, this would use AI to generate a caption # For now, just combine the token and description if trigger_token: return f"A picture of {trigger_token}, {description}" else: return f"A picture of {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 process_images_with_captions( image_paths: List[str], trigger_token: str = "TOK", description: str = "" ) -> Tuple[List[Dict[str, Any]], List[str]]: """Process multiple images with captioning and return image data and caption paths.""" image_data = [] caption_paths = [] for img_path in image_paths: try: # Skip non-image files try: Image.open(img_path) except (IOError, ValueError, TypeError): continue # Generate caption caption = generate_caption(img_path, trigger_token, description) caption_path = save_caption(img_path, caption) caption_paths.append(caption_path) # Get image metadata metadata = get_image_metadata(img_path) # Create image data entry image_entry = { "path": img_path, "filename": os.path.basename(img_path), "caption": caption, "caption_path": caption_path, **metadata } image_data.append(image_entry) except Exception as e: # Add failed entry image_data.append({ "path": img_path, "filename": os.path.basename(img_path), "error": str(e), "resolution": "Error", "aspect_ratio": "Error", "size": "Error" }) return image_data, caption_paths def update_caption(image_data: List[Dict[str, Any]], index: int, new_caption: str) -> List[Dict[str, Any]]: """Update a caption for a specific image in the image data list.""" if 0 <= index < len(image_data): image_data[index]["caption"] = new_caption if "caption_path" in image_data[index]: # Save the updated caption save_caption(image_data[index]["path"], new_caption) return image_data def delete_image(image_data: List[Dict[str, Any]], index: int) -> List[Dict[str, Any]]: """Remove an image from the image data list.""" if 0 <= index < len(image_data): image_data.pop(index) return image_data 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 dataset name only zip_filename = f"{dataset_name}_" if dataset_name else "" temp_zip_path = f"{zip_filename}captioned_images.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"] # Always use PNG extension image_filename = f"{idx}.png" # Convert image to PNG if needed img = Image.open(image_path) temp_png_path = f"temp_{idx}.png" img.save(temp_png_path, format="PNG") # Add to zip zipf.write(temp_png_path, image_filename) os.remove(temp_png_path) # 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 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 create_interface(): """Create the image captioning interface.""" with gr.Column() as app: gr.Markdown("## Generate captions for images") # Input section with gr.Row(): input_images = gr.File(file_count="multiple", label="Upload Images") with gr.Row(): trigger_token = gr.Textbox(label="Trigger Token", value="TOK", placeholder="Enter trigger token") description = gr.Textbox(label="Description", placeholder="Enter description of product/item/character") dataset_name = gr.Textbox(label="Dataset Name", placeholder="Enter name for your dataset") # Processing process_button = gr.Button("Process Images") # Output section - will be updated after processing image_data_state = gr.State([]) caption_paths_state = gr.State([]) # Container for processed images processed_images_container = gr.Column(visible=False) # Download button with gr.Row(visible=False) as download_row: download_button = gr.Button("Download All as ZIP") download_output = gr.File(label="Download", visible=True) # Helper functions for the interface def process_images(image_paths, token, desc): if not image_paths: return [], [], gr.Column(visible=False), gr.Row(visible=False), None try: # Ensure we're only processing files, not directories valid_paths = [path for path in image_paths if os.path.isfile(path)] # Process images image_data, caption_paths = process_images_with_captions(valid_paths, token, desc) return image_data, caption_paths, gr.Column(visible=True), gr.Row(visible=True), None except Exception as e: error_info = {"error": f"Error processing images: {str(e)}"} return [], [], gr.Column(visible=False), gr.Row(visible=False), None def update_captions_from_textboxes(image_data, captions): for i, caption in enumerate(captions): if i < len(image_data) and caption: image_data[i]["caption"] = caption return image_data def prepare_download(image_data, dataset_name): # First update all captions from textboxes zip_path = create_zip_file(image_data, dataset_name) if zip_path and os.path.exists(zip_path): return zip_path return None def remove_image(image_data, index): updated_data = delete_image(image_data, index) return updated_data # Create a grid gallery for displaying processed images MAX_IMAGES = 200 # Maximum number of images we'll support image_components = [] caption_components = [] delete_buttons = [] with processed_images_container: # Create a grid with 3 columns for i in range(0, MAX_IMAGES, 3): with gr.Row(): # Add up to 3 images per row for j in range(3): idx = i + j if idx < MAX_IMAGES: with gr.Column() as card: img = gr.Image(label=f"Image {idx+1}", show_label=True) info = gr.Markdown() caption = gr.Textbox(label="Caption", lines=3) delete_btn = gr.Button("🗑️", size="sm") delete_buttons.append(delete_btn) # Store components for later access image_components.append({ "card": card, "image": img, "info": info, "caption": caption, "delete": delete_btn }) caption_components.append(caption) # Function to update UI with image data def update_image_cards(image_data): results = [] # Reset all cards to invisible first for i in range(MAX_IMAGES): results.append(gr.Column(visible=False)) results.append(None) # image - use None instead of empty string results.append("") # info results.append("") # caption # Update cards with actual data for i, item in enumerate(image_data): if i >= MAX_IMAGES: break # Set card visibility results[i*4] = gr.Column(visible=True) # Set image - ensure it's a valid file path, not a directory if "path" in item and os.path.exists(item["path"]) and os.path.isfile(item["path"]): results[i*4 + 1] = item["path"] else: results[i*4 + 1] = None # Set info results[i*4 + 2] = format_metadata(item) # Set caption results[i*4 + 3] = item.get("caption", "") return results # Connect events process_button.click( fn=process_images, inputs=[input_images, trigger_token, description], outputs=[ image_data_state, caption_paths_state, processed_images_container, download_row, download_output ] ).then( fn=update_image_cards, inputs=[image_data_state], outputs=[comp for i in range(MAX_IMAGES) for comp in [ image_components[i]["card"], image_components[i]["image"], image_components[i]["info"], image_components[i]["caption"] ]] ) # Set up delete buttons for each image for i, delete_btn in enumerate(delete_buttons): delete_btn.click( fn=remove_image, inputs=[image_data_state, gr.Number(value=i, visible=False)], outputs=[image_data_state] ).then( fn=update_image_cards, inputs=[image_data_state], outputs=[comp for i in range(MAX_IMAGES) for comp in [ image_components[i]["card"], image_components[i]["image"], image_components[i]["info"], image_components[i]["caption"] ]] ) # Collect all caption textboxes for the download button download_button.click( fn=lambda data, *captions: update_captions_from_textboxes(data, captions), inputs=[image_data_state] + [comp["caption"] for comp in image_components], outputs=[image_data_state] ).then( fn=prepare_download, inputs=[image_data_state, dataset_name], outputs=[download_output] ) return app