Spaces:
Runtime error
Runtime error
Upload 4 files
Browse files
utils/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from .image_utils import resize_image, save_uploaded_image, validate_image
|
2 |
+
|
3 |
+
__all__ = ["validate_image", "save_uploaded_image", "resize_image"]
|
utils/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (332 Bytes). View file
|
|
utils/__pycache__/image_utils.cpython-311.pyc
ADDED
Binary file (5.39 kB). View file
|
|
utils/image_utils.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import os
|
3 |
+
import uuid
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
|
7 |
+
def validate_image(file_object, allowed_extensions=None):
|
8 |
+
"""
|
9 |
+
Validate an uploaded image file
|
10 |
+
|
11 |
+
Args:
|
12 |
+
file_object: The uploaded file object (Streamlit's UploadedFile)
|
13 |
+
allowed_extensions (list, optional): List of allowed file extensions.
|
14 |
+
Defaults to ['.jpg', '.jpeg', '.png', '.bmp', '.gif'].
|
15 |
+
|
16 |
+
Returns:
|
17 |
+
bool: True if valid, False otherwise
|
18 |
+
"""
|
19 |
+
if allowed_extensions is None:
|
20 |
+
allowed_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".gif"]
|
21 |
+
|
22 |
+
# Check if file exists
|
23 |
+
if file_object is None:
|
24 |
+
return False
|
25 |
+
|
26 |
+
# Get filename
|
27 |
+
filename = file_object.name
|
28 |
+
|
29 |
+
# Check file extension
|
30 |
+
file_ext = os.path.splitext(filename)[1].lower()
|
31 |
+
if file_ext not in allowed_extensions:
|
32 |
+
return False
|
33 |
+
|
34 |
+
try:
|
35 |
+
# Try opening the image to verify it's valid
|
36 |
+
image = Image.open(file_object)
|
37 |
+
image.verify()
|
38 |
+
|
39 |
+
# Reset file position
|
40 |
+
file_object.seek(0)
|
41 |
+
return True
|
42 |
+
except Exception as e:
|
43 |
+
print(f"Image validation error: {e}")
|
44 |
+
return False
|
45 |
+
|
46 |
+
|
47 |
+
def save_uploaded_image(file_object, upload_folder):
|
48 |
+
"""
|
49 |
+
Save an uploaded image to disk with a unique filename
|
50 |
+
|
51 |
+
Args:
|
52 |
+
file_object: The uploaded file object (Streamlit's UploadedFile)
|
53 |
+
upload_folder (str): The folder to save the image to
|
54 |
+
|
55 |
+
Returns:
|
56 |
+
str: The path to the saved image or None if failed
|
57 |
+
"""
|
58 |
+
if file_object is None:
|
59 |
+
return None
|
60 |
+
|
61 |
+
try:
|
62 |
+
# Reset file pointer to beginning
|
63 |
+
file_object.seek(0)
|
64 |
+
|
65 |
+
# Read file content
|
66 |
+
contents = file_object.read()
|
67 |
+
|
68 |
+
# Create a unique filename
|
69 |
+
file_ext = os.path.splitext(file_object.name)[1].lower()
|
70 |
+
unique_filename = f"{uuid.uuid4().hex}{file_ext}"
|
71 |
+
|
72 |
+
# Make sure the upload folder exists
|
73 |
+
os.makedirs(upload_folder, exist_ok=True)
|
74 |
+
|
75 |
+
# Define the full file path
|
76 |
+
file_path = os.path.join(upload_folder, unique_filename)
|
77 |
+
|
78 |
+
# Save the file
|
79 |
+
with open(file_path, "wb") as f:
|
80 |
+
f.write(contents)
|
81 |
+
|
82 |
+
# Verify the saved file can be opened
|
83 |
+
try:
|
84 |
+
with Image.open(file_path) as test_img:
|
85 |
+
# Just test that it can be opened
|
86 |
+
test_img.verify()
|
87 |
+
except Exception as e:
|
88 |
+
print(f"Verification of saved image failed: {e}")
|
89 |
+
# Try an alternative approach to save the file
|
90 |
+
img = Image.open(io.BytesIO(contents))
|
91 |
+
img.save(file_path)
|
92 |
+
|
93 |
+
return file_path
|
94 |
+
except Exception as e:
|
95 |
+
print(f"Error saving file: {e}")
|
96 |
+
return None
|
97 |
+
|
98 |
+
|
99 |
+
def resize_image(image, max_size=(800, 800)):
|
100 |
+
"""
|
101 |
+
Resize an image while maintaining aspect ratio
|
102 |
+
|
103 |
+
Args:
|
104 |
+
image (PIL.Image.Image or str): Image to resize or path to image
|
105 |
+
max_size (tuple, optional): Maximum width and height. Defaults to (800, 800).
|
106 |
+
|
107 |
+
Returns:
|
108 |
+
PIL.Image.Image: Resized image
|
109 |
+
"""
|
110 |
+
# Handle image input - could be a file path or PIL Image
|
111 |
+
if isinstance(image, str):
|
112 |
+
try:
|
113 |
+
# Explicitly use 'RGB' mode to ensure proper color handling
|
114 |
+
image = Image.open(image).convert("RGB")
|
115 |
+
except Exception as e:
|
116 |
+
raise ValueError(f"Could not open image file: {str(e)}")
|
117 |
+
|
118 |
+
# Get original dimensions
|
119 |
+
width, height = image.size
|
120 |
+
|
121 |
+
# Check if resize is needed
|
122 |
+
if width <= max_size[0] and height <= max_size[1]:
|
123 |
+
return image
|
124 |
+
|
125 |
+
# Calculate new dimensions
|
126 |
+
if width > height:
|
127 |
+
new_width = max_size[0]
|
128 |
+
new_height = int(height * (max_size[0] / width))
|
129 |
+
else:
|
130 |
+
new_height = max_size[1]
|
131 |
+
new_width = int(width * (max_size[1] / height))
|
132 |
+
|
133 |
+
# Resize and return
|
134 |
+
return image.resize((new_width, new_height), Image.LANCZOS)
|