Spaces:
Runtime error

MDBG / app.py
jonels1988's picture
Update app.py
f6c9410 verified
Raw History Blame Contribute Delete
9.37 kB
import os
import io
import csv
import re
import tempfile
import zipfile
import traceback
import requests
from PIL import Image, UnidentifiedImageError
from rembg import remove
import gradio as gr
# ---------- Config ----------
OUTPUT_DIR = "output_images"
os.makedirs(OUTPUT_DIR, exist_ok=True)
URL_PATTERN = re.compile(r"(https?://\S+)", re.IGNORECASE)
# ---------- Helpers ----------
def load_watermark(path: str = "watermark.png"):
"""
Try to load a watermark image. If it fails, just return None.
"""
if not os.path.exists(path):
print(f"Warning: watermark file not found at {path}")
return None
try:
wm = Image.open(path).convert("RGBA")
print(f"Loaded watermark from {path}")
return wm
except Exception as e:
print(f"Warning: failed to open watermark: {e}")
return None
WATERMARK = load_watermark()
def download_image(url: str, timeout: int = 30) -> Image.Image:
"""
Download an image from URL and return a Pillow Image in RGBA.
Raises RuntimeError if anything goes wrong.
"""
try:
r = requests.get(url, timeout=timeout)
r.raise_for_status()
except Exception as e:
raise RuntimeError(f"HTTP error for {url}: {e}")
try:
img = Image.open(io.BytesIO(r.content))
except UnidentifiedImageError as e:
raise RuntimeError(f"cannot identify image file: {e}")
except Exception as e:
raise RuntimeError(f"PIL error opening image: {e}")
if img.mode != "RGBA":
img = img.convert("RGBA")
return img
def apply_watermark(img: Image.Image, watermark: Image.Image | None) -> Image.Image:
"""
Paste a small watermark in the bottom-right corner (if watermark is provided).
"""
if watermark is None:
return img
base = img.copy()
wm = watermark
# Scale watermark to ~15% of image width
max_w = int(base.width * 0.15)
ratio = max_w / wm.width
wm = wm.resize((max_w, int(wm.height * ratio)), Image.LANCZOS)
# Position bottom-right with small margin
margin = int(base.width * 0.02)
x = base.width - wm.width - margin
y = base.height - wm.height - margin
base.alpha_composite(wm, dest=(max(0, x), max(0, y)))
return base
def process_image(url: str, logs: list[str]) -> tuple[Image.Image | None, str | None]:
"""
Download, remove background, optionally watermark, save to file.
Returns (processed_image, saved_path_or_None).
"""
logs.append(f"Downloading: {url}")
img = download_image(url)
logs.append("Removing background…")
no_bg = remove(img)
out_img = apply_watermark(no_bg, WATERMARK)
# Build filename
basename = os.path.basename(url.split("?")[0]) or "image.png"
save_name = basename
save_path = os.path.join(OUTPUT_DIR, save_name)
# Ensure extension is something Pillow understands
_, ext = os.path.splitext(save_name)
ext = ext.lower()
if ext not in [".png", ".jpg", ".jpeg", ".webp"]:
save_path = os.path.splitext(save_path)[0] + ".png"
out_img.save(save_path)
size_kb = os.path.getsize(save_path) / 1024.0
logs.append(f"Saved {save_name} ({size_kb:.0f} KB)")
return out_img, save_path
# ---------- URL parsing ----------
def read_id_url_pairs_from_text(text: str):
"""
Parse pasted multiline text. Extract the first http/https URL from each line.
Returns list of dicts: {"id": "1", "url": "...", "name": "file.jpg"}
"""
if not text:
return []
pairs = []
lines = str(text).splitlines()
for i, raw in enumerate(lines, start=1):
if not raw.strip():
continue
m = URL_PATTERN.search(raw)
if not m:
continue
url = m.group(1).strip().strip('",')
base_name = os.path.basename(url.split("?")[0]) or f"image_{i}.png"
pairs.append({
"id": str(i),
"url": url,
"name": base_name,
})
return pairs
def read_id_url_pairs(file_obj):
"""
Read URLs from a CSV/TXT file uploaded via Gradio.
- CSV: expects a 'url' column OR uses first column as URL.
- TXT: extracts a URL from each line using regex.
"""
if file_obj is None:
return []
path = file_obj.name
_, ext = os.path.splitext(path.lower())
pairs = []
if ext == ".txt":
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for i, raw in enumerate(f, start=1):
if not raw.strip():
continue
m = URL_PATTERN.search(raw)
if not m:
continue
url = m.group(1).strip().strip('",')
base_name = os.path.basename(url.split("?")[0]) or f"image_{i}.png"
pairs.append({"id": str(i), "url": url, "name": base_name})
return pairs
# Default: treat as CSV
with open(path, "r", encoding="utf-8", errors="ignore", newline="") as f:
reader = csv.reader(f)
rows = list(reader)
if not rows:
return []
header = [h.strip().lower() for h in rows[0]]
url_idx = None
if "url" in header:
url_idx = header.index("url")
start = 1
else:
url_idx = 0
start = 0
for i, row in enumerate(rows[start:], start=1):
if len(row) <= url_idx:
continue
raw = row[url_idx].strip()
if not raw:
continue
m = URL_PATTERN.search(raw)
if not m:
continue
url = m.group(1).strip().strip('",')
base_name = os.path.basename(url.split("?")[0]) or f"image_{i}.png"
pairs.append({"id": str(i), "url": url, "name": base_name})
return pairs
# ---------- Main processing (Gradio generator) ----------
def run_stream(csv_file, pasted_text):
logs: list[str] = []
# Prefer file if present; otherwise use pasted text
if csv_file is not None:
pairs = read_id_url_pairs(csv_file)
logs.append("Using uploaded CSV/TXT file for URLs.")
else:
pairs = read_id_url_pairs_from_text(pasted_text)
logs.append("Using pasted text for URLs.")
if not pairs:
logs.append("No valid URLs found. Use CSV/TXT with url column or paste URLs (one per line).")
yield None, None, "\n".join(logs)
return
logs.append(f"Found {len(pairs)} URL(s). Starting processing…")
yield None, None, "\n".join(logs)
tmp_dir = tempfile.mkdtemp(prefix="cleaned_imgs_")
saved_files: list[str] = []
last_image: Image.Image | None = None
for idx, pair in enumerate(pairs, start=1):
url = pair["url"]
prefix = f"[{idx}/{len(pairs)}]"
try:
logs.append(f"{prefix} Downloading: {url}")
yield last_image, None, "\n".join(logs[-200:])
img, path = process_image(url, logs)
saved_files.append(path)
last_image = img
logs.append(f"{prefix} Done.")
yield last_image, None, "\n".join(logs[-200:])
except Exception as e:
logs.append(f"{prefix} ERROR: Failed to download/open image {url}: {e}")
logs.append(traceback.format_exc())
# continue with next URL
yield last_image, None, "\n".join(logs[-200:])
# Create ZIP if we have any files
zip_path = None
if saved_files:
zip_path = os.path.join(tmp_dir, "cleaned_images.zip")
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for path in saved_files:
arcname = os.path.basename(path)
zf.write(path, arcname)
logs.append(f"Created ZIP with {len(saved_files)} images.")
yield last_image, zip_path, "\n".join(logs[-200:])
# ---------- Gradio UI ----------
with gr.Blocks(title="Bulk Background Remover") as demo:
gr.Markdown(
"""
# Bulk Image Background Remover
- Upload a **CSV/TXT** with image URLs (must contain a `url` column or one URL per line),
**or** paste URLs directly (one per line).
- The app will download each image, remove the background, apply a watermark (if `watermark.png` exists),
and save cleaned images.
"""
)
with gr.Row():
csv_in = gr.File(
label="CSV or TXT with image URLs (optional)",
file_types=[".csv", ".txt"],
interactive=True
)
pasted = gr.Textbox(
label="Or paste image URLs here (one per line)",
lines=10,
placeholder="https://example.com/image1.jpg\nhttps://example.com/image2.png\n..."
)
run_btn = gr.Button("Process Images", variant="primary")
with gr.Row():
preview = gr.Image(label="Last Processed Image", type="pil")
zip_out = gr.File(label="Download All Cleaned Images (ZIP)")
log_box = gr.Textbox(
label="Log / Status",
lines=20,
value="",
interactive=False
)
run_btn.click(
fn=run_stream,
inputs=[csv_in, pasted],
outputs=[preview, zip_out, log_box]
)
if __name__ == "__main__":
demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)