Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import rembg
|
| 4 |
+
import io
|
| 5 |
+
import zipfile
|
| 6 |
+
|
| 7 |
+
def remove_background(image):
|
| 8 |
+
"""Remove background and return transparent PNG"""
|
| 9 |
+
img_byte_arr = io.BytesIO()
|
| 10 |
+
image.save(img_byte_arr, format='PNG')
|
| 11 |
+
result_bytes = rembg.remove(img_byte_arr.getvalue())
|
| 12 |
+
return Image.open(io.BytesIO(result_bytes)).convert("RGBA")
|
| 13 |
+
|
| 14 |
+
def process_batch(image_files):
|
| 15 |
+
"""Process batch of images and return ZIP of transparent PNGs"""
|
| 16 |
+
zip_buffer = io.BytesIO()
|
| 17 |
+
with zipfile.ZipFile(zip_buffer, "w") as zip_file:
|
| 18 |
+
for i, img_file in enumerate(image_files):
|
| 19 |
+
# Open and process image
|
| 20 |
+
img = Image.open(img_file).convert("RGBA")
|
| 21 |
+
processed_img = remove_background(img)
|
| 22 |
+
# Save to in-memory buffer
|
| 23 |
+
img_byte_arr = io.BytesIO()
|
| 24 |
+
processed_img.save(img_byte_arr, format='PNG')
|
| 25 |
+
# Add to ZIP
|
| 26 |
+
zip_file.writestr(f"processed_{i+1}.png", img_byte_arr.getvalue())
|
| 27 |
+
zip_buffer.seek(0)
|
| 28 |
+
return zip_buffer
|
| 29 |
+
|
| 30 |
+
# Gradio Interface
|
| 31 |
+
image_upload = gr.Files(label="Upload Images (Batch)", file_types=["image"])
|
| 32 |
+
output_zip = gr.File(label="Download Processed Images (ZIP)")
|
| 33 |
+
|
| 34 |
+
interface = gr.Interface(
|
| 35 |
+
fn=process_batch,
|
| 36 |
+
inputs=image_upload,
|
| 37 |
+
outputs=output_zip,
|
| 38 |
+
title="Transparent Background Remover (Batch)",
|
| 39 |
+
description="Upload multiple images, remove backgrounds, and download as transparent PNGs (batch).",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
interface.launch()
|