lab-xzcspl5a / utils.py
AlexHanxss's picture
Deploy Gradio app with multiple files
90608de verified
Raw History Blame Contribute Delete
2.79 kB
"""
Utility functions for image processing and validation
"""
import os
from PIL import Image
from config import SUPPORTED_FORMATS, MAX_IMAGE_SIZE
def validate_images(image1, image2):
"""
Validate that both images are in supported formats
Args:
image1: First PIL Image
image2: Second PIL Image
Returns:
Tuple of validated PIL Images
Raises:
ValueError: If images are not in supported formats
"""
if image1 is None or image2 is None:
raise ValueError("Both images must be provided")
# Convert to RGB if necessary
if image1.mode != 'RGB':
image1 = image1.convert('RGB')
if image2.mode != 'RGB':
image2 = image2.convert('RGB')
return image1, image2
def resize_image_if_needed(image, max_size):
"""
Resize image if it exceeds maximum dimensions while maintaining aspect ratio
Args:
image: PIL Image
max_size: Maximum dimension (width or height)
Returns:
Resized PIL Image
"""
width, height = image.size
# Check if resizing is needed
if max(width, height) <= max_size:
return image
# Calculate new dimensions
if width > height:
new_width = max_size
new_height = int(height * max_size / width)
else:
new_height = max_size
new_width = int(width * max_size / height)
# Resize image
resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
print(f"Resized image from {width}x{height} to {new_width}x{new_height}")
return resized_image
def get_image_info(image):
"""
Get basic information about an image
Args:
image: PIL Image
Returns:
Dictionary with image information
"""
return {
"size": image.size,
"mode": image.mode,
"format": image.format
}
def create_example_images():
"""
Create example images for testing (if they don't exist)
"""
os.makedirs("examples", exist_ok=True)
# Create simple example images if they don't exist
example_files = [
("examples/astronaut.jpg", "Astronaut in space suit"),
("examples/egg.jpg", "Egg on moon surface"),
("examples/bear1.jpg", "Magician bear"),
("examples/bear2.jpg", "Alchemist bear")
]
for file_path, description in example_files:
if not os.path.exists(file_path):
# Create a placeholder image
img = Image.new('RGB', (512, 512), color='lightblue')
# In a real application, you would have actual example images
# For now, we'll just create empty files
img.save(file_path)
print(f"Created placeholder: {file_path}")