Spaces:
Build error
Build error
Upload processor/zipper.py with huggingface_hub
Browse files- processor/zipper.py +45 -0
processor/zipper.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import zipfile
|
| 3 |
+
import io
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
def standardize_and_zip(images: List[tuple[str, np.ndarray]]) -> io.BytesIO:
|
| 8 |
+
"""
|
| 9 |
+
Takes a list of tuples (filename, image). Resizes images to standard size
|
| 10 |
+
(e.g., 600x800), encodes them as PNG/JPG, and zips them.
|
| 11 |
+
Returns an in-memory ZIP file stream.
|
| 12 |
+
"""
|
| 13 |
+
TARGET_WIDTH = 600
|
| 14 |
+
TARGET_HEIGHT = 800
|
| 15 |
+
|
| 16 |
+
zip_buffer = io.BytesIO()
|
| 17 |
+
|
| 18 |
+
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
|
| 19 |
+
for idx, (filename, img) in enumerate(images):
|
| 20 |
+
h, w = img.shape[:2]
|
| 21 |
+
|
| 22 |
+
# Determine orientation to preserve aspect ratio
|
| 23 |
+
if w > h:
|
| 24 |
+
# Landscape
|
| 25 |
+
new_w = 800
|
| 26 |
+
new_h = int(h * (800 / w))
|
| 27 |
+
else:
|
| 28 |
+
# Portrait
|
| 29 |
+
new_h = 800
|
| 30 |
+
new_w = int(w * (800 / h))
|
| 31 |
+
|
| 32 |
+
resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_CUBIC)
|
| 33 |
+
|
| 34 |
+
# Encode as PNG to preserve transparent background
|
| 35 |
+
success, buffer = cv2.imencode(".png", resized)
|
| 36 |
+
if success:
|
| 37 |
+
# Keep original name or rename
|
| 38 |
+
name_without_ext = filename.rsplit(".", 1)[0]
|
| 39 |
+
new_filename = f"{name_without_ext}_processed.png"
|
| 40 |
+
|
| 41 |
+
zip_file.writestr(new_filename, buffer.tobytes())
|
| 42 |
+
|
| 43 |
+
# Rewind buffer
|
| 44 |
+
zip_buffer.seek(0)
|
| 45 |
+
return zip_buffer
|