Upload 2 files
Browse files- app.py +120 -0
- requirements.txt +2 -0
app.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import shutil
|
| 4 |
+
import tempfile
|
| 5 |
+
import zipfile
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from PIL import Image, ImageDraw
|
| 9 |
+
|
| 10 |
+
IMG_EXT = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def natural_key(s):
|
| 14 |
+
return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def collect_images(files):
|
| 18 |
+
"""Accepts uploaded images and/or zip files, returns a sorted list of image paths."""
|
| 19 |
+
if not files:
|
| 20 |
+
return []
|
| 21 |
+
paths = []
|
| 22 |
+
extract_dir = tempfile.mkdtemp(prefix="frames_")
|
| 23 |
+
for f in files:
|
| 24 |
+
p = f if isinstance(f, str) else f.name
|
| 25 |
+
if p.lower().endswith(".zip"):
|
| 26 |
+
with zipfile.ZipFile(p) as z:
|
| 27 |
+
for name in z.namelist():
|
| 28 |
+
if name.lower().endswith(IMG_EXT) and not name.startswith("__MACOSX"):
|
| 29 |
+
out = z.extract(name, extract_dir)
|
| 30 |
+
paths.append(out)
|
| 31 |
+
elif p.lower().endswith(IMG_EXT):
|
| 32 |
+
paths.append(p)
|
| 33 |
+
return sorted(paths, key=lambda s: natural_key(os.path.basename(s)))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def draw_preview(files, x, y, w, h):
|
| 37 |
+
paths = collect_images(files)
|
| 38 |
+
if not paths:
|
| 39 |
+
return None, "Upload images or a zip of frames first."
|
| 40 |
+
img = Image.open(paths[0]).convert("RGBA")
|
| 41 |
+
W, H = img.size
|
| 42 |
+
x, y, w, h = int(x), int(y), int(w), int(h)
|
| 43 |
+
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
|
| 44 |
+
d = ImageDraw.Draw(overlay)
|
| 45 |
+
d.rectangle([x, y, x + w - 1, y + h - 1], outline=(255, 0, 0, 255), width=max(2, W // 300))
|
| 46 |
+
img = Image.alpha_composite(img, overlay)
|
| 47 |
+
return img, f"{len(paths)} images loaded. First image size: {W}x{H}. Click the preview to set the top-left corner."
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def click_set_xy(evt: gr.SelectData):
|
| 51 |
+
return evt.index[0], evt.index[1]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def crop_all(files, x, y, w, h, target_w, progress=gr.Progress()):
|
| 55 |
+
paths = collect_images(files)
|
| 56 |
+
if not paths:
|
| 57 |
+
return None, [], "No images found."
|
| 58 |
+
x, y, w, h, target_w = int(x), int(y), int(w), int(h), int(target_w or 0)
|
| 59 |
+
if w <= 0 or h <= 0:
|
| 60 |
+
return None, [], "Width and height must be greater than 0."
|
| 61 |
+
|
| 62 |
+
out_dir = tempfile.mkdtemp(prefix="cropped_")
|
| 63 |
+
warnings = 0
|
| 64 |
+
previews = []
|
| 65 |
+
|
| 66 |
+
for i, p in enumerate(progress.tqdm(paths, desc="Cropping")):
|
| 67 |
+
img = Image.open(p)
|
| 68 |
+
if img.mode not in ("RGB", "RGBA"):
|
| 69 |
+
img = img.convert("RGBA")
|
| 70 |
+
W, H = img.size
|
| 71 |
+
# clamp the box to the image so smaller frames never crash
|
| 72 |
+
x0, y0 = max(0, min(x, W - 1)), max(0, min(y, H - 1))
|
| 73 |
+
x1, y1 = min(W, x0 + w), min(H, y0 + h)
|
| 74 |
+
if (x1 - x0, y1 - y0) != (w, h):
|
| 75 |
+
warnings += 1
|
| 76 |
+
out = img.crop((x0, y0, x1, y1))
|
| 77 |
+
if target_w > 0:
|
| 78 |
+
ratio = target_w / out.width
|
| 79 |
+
out = out.resize((target_w, max(1, round(out.height * ratio))), Image.LANCZOS)
|
| 80 |
+
name = os.path.splitext(os.path.basename(p))[0] + ".png"
|
| 81 |
+
out.save(os.path.join(out_dir, name), optimize=False)
|
| 82 |
+
if len(previews) < 12:
|
| 83 |
+
previews.append(out.copy())
|
| 84 |
+
|
| 85 |
+
zip_path = os.path.join(tempfile.mkdtemp(), "cropped_frames.zip")
|
| 86 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as z: # PNGs are already compressed
|
| 87 |
+
for n in sorted(os.listdir(out_dir), key=natural_key):
|
| 88 |
+
z.write(os.path.join(out_dir, n), n)
|
| 89 |
+
shutil.rmtree(out_dir, ignore_errors=True)
|
| 90 |
+
|
| 91 |
+
msg = f"Done: {len(paths)} images cropped."
|
| 92 |
+
if warnings:
|
| 93 |
+
msg += f" {warnings} images were smaller than the crop box, so they were cropped to the available area."
|
| 94 |
+
return zip_path, previews, msg
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
with gr.Blocks(title="Batch Frame Cropper") as demo:
|
| 98 |
+
gr.Markdown("## Batch Frame Cropper\nUpload frames (or one zip), set the crop box, then download a zip of cropped PNGs.")
|
| 99 |
+
files = gr.File(label="Frames (images and/or a .zip)", file_count="multiple",
|
| 100 |
+
file_types=["image", ".zip"], type="filepath")
|
| 101 |
+
with gr.Row():
|
| 102 |
+
x = gr.Number(label="X start", value=0, precision=0)
|
| 103 |
+
y = gr.Number(label="Y start", value=0, precision=0)
|
| 104 |
+
w = gr.Number(label="Crop width", value=512, precision=0)
|
| 105 |
+
h = gr.Number(label="Crop height", value=512, precision=0)
|
| 106 |
+
target_w = gr.Number(label="Resize to width (0 = keep)", value=0, precision=0)
|
| 107 |
+
preview = gr.Image(label="Preview (click to set X/Y)", interactive=False, type="pil")
|
| 108 |
+
info = gr.Markdown()
|
| 109 |
+
btn = gr.Button("Crop all", variant="primary")
|
| 110 |
+
gallery = gr.Gallery(label="Result samples (first 12)", columns=6, height=200)
|
| 111 |
+
out_zip = gr.File(label="Download ZIP")
|
| 112 |
+
status = gr.Markdown()
|
| 113 |
+
|
| 114 |
+
for c in (files, x, y, w, h):
|
| 115 |
+
c.change(draw_preview, [files, x, y, w, h], [preview, info])
|
| 116 |
+
preview.select(click_set_xy, None, [x, y])
|
| 117 |
+
btn.click(crop_all, [files, x, y, w, h, target_w], [out_zip, gallery, status])
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
demo.queue().launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pillow
|