File size: 14,120 Bytes
f1ec2d1 57a42f7 f1ec2d1 | 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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | 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
|