ops / utils /metadata.py
elieh's picture
utils
f1ec2d1
Raw History Blame Contribute Delete
8.76 kB
from typing import Any, Dict, List, Optional, Tuple
import os
import zipfile
import time
import tempfile
import shutil
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS
def strip_exif(image_path: str, output_path: Optional[str] = None) -> str:
"""
Strip all EXIF metadata from an image.
Args:
image_path: Path to the source image
output_path: Path to save the processed image. If None, overwrites the original.
Returns:
Path to the processed image
"""
if output_path is None:
output_path = image_path
try:
# Open the image
img = Image.open(image_path)
# Create a new image without metadata
data = list(img.getdata())
image_without_exif = Image.new(img.mode, img.size)
image_without_exif.putdata(data)
# Save the image without metadata
image_without_exif.save(output_path)
return output_path
except Exception as e:
raise Exception(f"Failed to strip metadata: {str(e)}")
def get_exif_data(image_path: str) -> Dict[str, Any]:
"""
Extract all EXIF metadata from an image.
Args:
image_path: Path to the image
Returns:
Dictionary containing EXIF metadata
"""
try:
img = Image.open(image_path)
exif_data = {}
# Use getexif() method which is the recommended way to get EXIF
try:
exif = img.getexif()
if exif:
for tag, value in exif.items():
tag_name = TAGS.get(tag, tag)
exif_data[tag_name] = value
except (AttributeError, TypeError):
# If getexif() is not available or fails
pass
return exif_data
except Exception as e:
return {"error": str(e)}
def add_metadata(image_path: str, metadata: Dict[str, Any], output_path: Optional[str] = None) -> str:
"""
Add metadata to an image.
Args:
image_path: Path to the source image
metadata: Dictionary of metadata to add
output_path: Path to save the processed image. If None, overwrites the original.
Returns:
Path to the processed image
"""
if output_path is None:
output_path = image_path
try:
# Open the image
img = Image.open(image_path)
# Create a new image with metadata
exif_dict = {}
# Convert metadata keys to EXIF tag codes
for key, value in metadata.items():
for tag_id, tag_name in TAGS.items():
if tag_name == key:
exif_dict[tag_id] = value
break
# Save the image with metadata
img.save(output_path, exif=exif_dict)
return output_path
except Exception as e:
raise Exception(f"Failed to add metadata: {str(e)}")
def process_zip_file(zip_path: str, strip_metadata: bool = True, custom_metadata: Optional[Dict[str, Any]] = None) -> str:
"""
Process images in a zip file, stripping or adding metadata as specified.
Args:
zip_path: Path to the zip file containing images
strip_metadata: Whether to strip existing metadata
custom_metadata: Optional dictionary of metadata to add
Returns:
Path to the output zip file with processed images
"""
# Create a temporary directory
temp_dir = tempfile.mkdtemp()
output_zip_path = os.path.join(os.path.dirname(zip_path), f"processed_{os.path.basename(zip_path)}")
try:
# Extract the zip file
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(temp_dir)
# Process each image
processed_files = []
for root, _, files in os.walk(temp_dir):
for filename in files:
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.tiff', '.bmp', '.avif')):
file_path = os.path.join(root, filename)
output_file = os.path.join(root, f"processed_{filename}")
# Process the image
if strip_metadata:
strip_exif(file_path, output_file)
else:
shutil.copy(file_path, output_file)
# Add custom metadata if specified
if custom_metadata and not strip_metadata:
add_metadata(output_file, custom_metadata, output_file)
processed_files.append((output_file, os.path.relpath(output_file, temp_dir)))
# Create a new zip file with processed images
with zipfile.ZipFile(output_zip_path, 'w') as zip_out:
for file_path, rel_path in processed_files:
zip_out.write(file_path, rel_path)
return output_zip_path
finally:
# Clean up temporary directory
shutil.rmtree(temp_dir)
def batch_process_images(
image_paths: List[str],
strip_metadata: bool = True,
custom_metadata: Optional[Dict[str, Any]] = None
) -> List[str]:
"""
Process multiple images, stripping or adding metadata as specified.
Args:
image_paths: List of paths to images
strip_metadata: Whether to strip existing metadata
custom_metadata: Optional dictionary of metadata to add
Returns:
List of paths to processed images
"""
processed_paths = []
for image_path in image_paths:
try:
# Create output path
filename = os.path.basename(image_path)
directory = os.path.dirname(image_path)
output_path = os.path.join(directory, f"processed_{filename}")
# Process the image
if strip_metadata:
strip_exif(image_path, output_path)
else:
shutil.copy(image_path, output_path)
# Add custom metadata if specified
if custom_metadata and not strip_metadata:
add_metadata(output_path, custom_metadata, output_path)
processed_paths.append(output_path)
except Exception as e:
# Log error and continue with next image
print(f"Error processing {image_path}: {str(e)}")
return processed_paths
def create_zip_with_processed_images(processed_paths: List[str], dataset_name: str = "") -> str:
"""
Create a zip file containing all processed images.
Args:
processed_paths: List of paths to processed images
dataset_name: Optional name for the dataset
Returns:
Path to the created zip file
"""
if not processed_paths:
return ""
# Create a zip file with a unique 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, path in enumerate(processed_paths, 1):
if os.path.exists(path):
# Add the image file with original name
image_name = os.path.basename(path)
zipf.write(path, image_name)
return temp_zip_path
def format_exif_data(exif_data: Dict[str, Any]) -> str:
"""
Format EXIF data as a string for display.
Args:
exif_data: Dictionary of EXIF data
Returns:
Formatted string
"""
if not exif_data or "error" in exif_data:
return "No EXIF metadata available"
# Common EXIF tags to display
important_tags = [
"Make", "Model", "DateTime", "DateTimeOriginal",
"ExposureTime", "FNumber", "ISOSpeedRatings", "FocalLength",
"GPSInfo", "Copyright", "Artist"
]
result = []
for tag in important_tags:
if tag in exif_data:
value = exif_data[tag]
if tag == "GPSInfo" and value:
result.append(f"GPS: Present (Hidden)")
else:
result.append(f"{tag}: {value}")
# Include other tags if there are few important ones
if len(result) < 3:
for tag, value in exif_data.items():
if tag not in important_tags and not isinstance(value, bytes):
result.append(f"{tag}: {value}")
if len(result) >= 5:
break
if not result:
return "No common EXIF metadata found"
return "<br>".join(result)