launch-calcium's picture
Upload 2 files
d05fa08 verified
Raw History Blame Contribute Delete
4.83 kB
import os
import re
import shutil
import tempfile
import zipfile
import gradio as gr
from PIL import Image, ImageDraw
IMG_EXT = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
def natural_key(s):
return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
def collect_images(files):
"""Accepts uploaded images and/or zip files, returns a sorted list of image paths."""
if not files:
return []
paths = []
extract_dir = tempfile.mkdtemp(prefix="frames_")
for f in files:
p = f if isinstance(f, str) else f.name
if p.lower().endswith(".zip"):
with zipfile.ZipFile(p) as z:
for name in z.namelist():
if name.lower().endswith(IMG_EXT) and not name.startswith("__MACOSX"):
out = z.extract(name, extract_dir)
paths.append(out)
elif p.lower().endswith(IMG_EXT):
paths.append(p)
return sorted(paths, key=lambda s: natural_key(os.path.basename(s)))
def draw_preview(files, x, y, w, h):
paths = collect_images(files)
if not paths:
return None, "Upload images or a zip of frames first."
img = Image.open(paths[0]).convert("RGBA")
W, H = img.size
x, y, w, h = int(x), int(y), int(w), int(h)
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
d = ImageDraw.Draw(overlay)
d.rectangle([x, y, x + w - 1, y + h - 1], outline=(255, 0, 0, 255), width=max(2, W // 300))
img = Image.alpha_composite(img, overlay)
return img, f"{len(paths)} images loaded. First image size: {W}x{H}. Click the preview to set the top-left corner."
def click_set_xy(evt: gr.SelectData):
return evt.index[0], evt.index[1]
def crop_all(files, x, y, w, h, target_w, progress=gr.Progress()):
paths = collect_images(files)
if not paths:
return None, [], "No images found."
x, y, w, h, target_w = int(x), int(y), int(w), int(h), int(target_w or 0)
if w <= 0 or h <= 0:
return None, [], "Width and height must be greater than 0."
out_dir = tempfile.mkdtemp(prefix="cropped_")
warnings = 0
previews = []
for i, p in enumerate(progress.tqdm(paths, desc="Cropping")):
img = Image.open(p)
if img.mode not in ("RGB", "RGBA"):
img = img.convert("RGBA")
W, H = img.size
# clamp the box to the image so smaller frames never crash
x0, y0 = max(0, min(x, W - 1)), max(0, min(y, H - 1))
x1, y1 = min(W, x0 + w), min(H, y0 + h)
if (x1 - x0, y1 - y0) != (w, h):
warnings += 1
out = img.crop((x0, y0, x1, y1))
if target_w > 0:
ratio = target_w / out.width
out = out.resize((target_w, max(1, round(out.height * ratio))), Image.LANCZOS)
name = os.path.splitext(os.path.basename(p))[0] + ".png"
out.save(os.path.join(out_dir, name), optimize=False)
if len(previews) < 12:
previews.append(out.copy())
zip_path = os.path.join(tempfile.mkdtemp(), "cropped_frames.zip")
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as z: # PNGs are already compressed
for n in sorted(os.listdir(out_dir), key=natural_key):
z.write(os.path.join(out_dir, n), n)
shutil.rmtree(out_dir, ignore_errors=True)
msg = f"Done: {len(paths)} images cropped."
if warnings:
msg += f" {warnings} images were smaller than the crop box, so they were cropped to the available area."
return zip_path, previews, msg
with gr.Blocks(title="Batch Frame Cropper") as demo:
gr.Markdown("## Batch Frame Cropper\nUpload frames (or one zip), set the crop box, then download a zip of cropped PNGs.")
files = gr.File(label="Frames (images and/or a .zip)", file_count="multiple",
file_types=["image", ".zip"], type="filepath")
with gr.Row():
x = gr.Number(label="X start", value=0, precision=0)
y = gr.Number(label="Y start", value=0, precision=0)
w = gr.Number(label="Crop width", value=512, precision=0)
h = gr.Number(label="Crop height", value=512, precision=0)
target_w = gr.Number(label="Resize to width (0 = keep)", value=0, precision=0)
preview = gr.Image(label="Preview (click to set X/Y)", interactive=False, type="pil")
info = gr.Markdown()
btn = gr.Button("Crop all", variant="primary")
gallery = gr.Gallery(label="Result samples (first 12)", columns=6, height=200)
out_zip = gr.File(label="Download ZIP")
status = gr.Markdown()
for c in (files, x, y, w, h):
c.change(draw_preview, [files, x, y, w, h], [preview, info])
preview.select(click_set_xy, None, [x, y])
btn.click(crop_all, [files, x, y, w, h, target_w], [out_zip, gallery, status])
if __name__ == "__main__":
demo.queue().launch()