ops / apps /metadata.py
elieh's picture
fix filename
3eba1b7
Raw History Blame Contribute Delete
9.05 kB
import os
from typing import Any, Dict, List, Optional, Tuple, Set
import gradio as gr
from PIL import Image
import pillow_avif # type: ignore
from utils.image import get_image_metadata, format_metadata
from utils.metadata import (
strip_exif,
get_exif_data,
add_metadata,
batch_process_images,
create_zip_with_processed_images,
format_exif_data
)
def create_metadata_dict(metadata_text: str) -> Dict[str, Any]:
metadata = {}
if not metadata_text:
return metadata
lines = metadata_text.strip().split("\n")
for line in lines:
if ":" in line:
key, value = line.split(":", 1)
metadata[key.strip()] = value.strip()
return metadata
def process_images_metadata(
image_paths: List[str],
strip_metadata: bool,
custom_metadata_text: str,
convert_to_png: bool
) -> Tuple[List[Dict[str, Any]], List[str]]:
image_data = []
processed_paths = []
# Parse custom metadata if provided
custom_metadata = create_metadata_dict(custom_metadata_text) if not strip_metadata and custom_metadata_text else None
# Process each image
for img_path in image_paths:
try:
# Get original metadata and image info
original_metadata = get_exif_data(img_path)
img_info = get_image_metadata(img_path)
# Process the image
filename = os.path.basename(img_path)
directory = os.path.dirname(img_path)
# Preserve original filename but add "processed_" prefix
output_filename = f"processed_{filename}"
# Change extension to PNG if needed
if convert_to_png:
base_name, _ = os.path.splitext(output_filename)
output_filename = f"{base_name}.png"
output_path = os.path.join(directory, output_filename)
if convert_to_png:
# Convert to PNG and optionally handle metadata
img = Image.open(img_path)
if strip_metadata:
# Save as PNG without metadata
img.save(output_path, format="PNG")
elif custom_metadata:
# Save as PNG first, then add metadata
img.save(output_path, format="PNG")
output_path = add_metadata(output_path, custom_metadata, output_path)
else:
# Just convert to PNG
img.save(output_path, format="PNG")
else:
# Process without format conversion
if strip_metadata:
processed_path = strip_exif(img_path, output_path)
elif custom_metadata:
processed_path = add_metadata(img_path, custom_metadata, output_path)
else:
# If neither stripping nor adding, just copy the file
import shutil
processed_path = output_path
shutil.copy(img_path, processed_path)
output_path = processed_path
processed_paths.append(output_path)
# Get processed metadata
processed_metadata = get_exif_data(output_path)
# Create image data entry
image_entry = {
"original_path": img_path,
"processed_path": output_path,
"filename": filename,
"original_metadata": original_metadata,
"processed_metadata": processed_metadata,
**img_info
}
image_data.append(image_entry)
except Exception as e:
# Add failed entry
image_data.append({
"original_path": img_path,
"filename": os.path.basename(img_path),
"error": str(e),
"resolution": "Error",
"aspect_ratio": "Error",
"size": "Error"
})
return image_data, processed_paths
def create_interface():
with gr.Blocks(css="footer {visibility: hidden}") as interface:
# State variables
image_data_state = gr.State([])
processed_paths_state = gr.State([])
gr.Markdown("## Metadata Editor")
# Upload section
file_upload = gr.File(
file_count="multiple",
label="Upload Images",
file_types=["image"],
)
# Metadata options
with gr.Row():
strip_metadata = gr.Checkbox(
label="Strip all metadata (EXIF, etc.)",
value=True,
)
dataset_name = gr.Textbox(
label="Dataset Name (optional)",
placeholder="Enter dataset name",
)
with gr.Row():
convert_to_png = gr.Checkbox(
label="Convert all images to PNG",
value=False,
)
custom_metadata = gr.Textbox(
label="Custom Metadata (one per line, format: Key: Value)",
placeholder="Example:\nArtist: John Doe\nCopyright: 2023\nDescription: My artwork",
lines=3,
)
gr.Markdown("Note: Custom metadata will only be applied if 'Strip all metadata' is unchecked.")
# Processing
process_btn = gr.Button("Process Images", variant="primary")
processing_indicator = gr.Markdown(visible=False, value="⏳ Processing images... Please wait.")
# Results output
results_container = gr.Column(visible=False)
with results_container:
gr.Markdown("## Processed Images")
results_gallery = gr.Gallery(label="Processed Images", columns=3, height=400)
results_info = gr.Markdown()
# Download section
with gr.Row(visible=False) as download_row:
download_btn = gr.Button("Download Processed Files")
download_output = gr.File(label="Download")
# Event handlers
def process_images_handler(files, strip, metadata_text, convert_png):
if not files:
return [], [], gr.Column(visible=False), gr.Row(visible=False)
image_data, processed_paths = process_images_metadata(
[f.name for f in files], strip, metadata_text, convert_png
)
# Prepare gallery images
gallery_images = []
for item in image_data:
if "processed_path" in item and os.path.exists(item["processed_path"]):
gallery_images.append(item["processed_path"])
info_text = f"Processed {len(gallery_images)} images successfully."
return image_data, processed_paths, gr.Column(visible=True), gr.Row(visible=True)
def update_gallery(image_data):
gallery_images = []
info_text = ""
for item in image_data:
if "processed_path" in item and os.path.exists(item["processed_path"]):
gallery_images.append(item["processed_path"])
info_text = f"Processed {len(gallery_images)} images successfully."
return gallery_images, info_text
def prepare_download(processed_paths, dataset_name):
if not processed_paths:
return None
# Create the zip file
zip_path = create_zip_with_processed_images(processed_paths, dataset_name)
return zip_path if zip_path else None
# Setup event handlers
process_btn.click(
lambda: gr.update(visible=True),
outputs=[processing_indicator]
).then(
process_images_handler,
inputs=[file_upload, strip_metadata, custom_metadata, convert_to_png],
outputs=[image_data_state, processed_paths_state, results_container, download_row]
).then(
update_gallery,
inputs=[image_data_state],
outputs=[results_gallery, results_info]
).then(
lambda: gr.update(visible=False),
outputs=[processing_indicator]
)
download_btn.click(
prepare_download,
inputs=[processed_paths_state, dataset_name],
outputs=[download_output]
)
# Make strip_metadata and custom_metadata interactive
def update_custom_metadata_interactivity(strip):
return gr.update(interactive=not strip)
strip_metadata.change(
update_custom_metadata_interactivity,
inputs=[strip_metadata],
outputs=[custom_metadata]
)
return interface