Trial / app.py
Bubbles30's picture
Update app.py
67f5812 verified
Raw History Blame Contribute Delete
30.8 kB
import gradio as gr
import pandas as pd
import requests
import tempfile, shutil, os, zipfile
from io import BytesIO
from PIL import Image, ImageChops
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse, urlunparse
from datetime import datetime
import random
import time
import threading
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from urllib.parse import quote
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# === Globals & Configuration ===
stop_event = threading.Event()
CPU_CORES = os.cpu_count() or 4
CANVAS_SIZE = 1000 # output canvas is 1000Γ—1000 px
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
]
# === Helpers ===
def random_headers(referer):
return {
"User-Agent": random.choice(USER_AGENTS),
"Referer": referer,
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
}
def log_failure(path, reason):
with open(path, "a") as f:
f.write(reason + "\n")
def count_links(workbook_file):
if not workbook_file:
return ""
try:
links = read_links_from_workbook(workbook_file.name)
return f"πŸ”— Detected {len(links)} image link(s)."
except Exception as e:
return f"❌ Error reading workbook: {e}"
def download_direct_image(url, out_path):
try:
r = requests.get(url, stream=True, timeout=30)
r.raise_for_status()
if "image" in r.headers.get("Content-Type", "").lower():
with open(out_path, "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
return True
return False
except Exception as e:
print(f"Direct download failed: {e}")
return False
from io import BytesIO
from PIL import Image
def download_image(url, out_path, fail_log, code, suf):
"""
Tries multiple methods to download an image, logs failures with ItemCode names.
Order:
1) cloudscraper
2) requests
3) public proxy (weserv)
4) Selenium canvas fallback
Returns True on success, False on all failures.
"""
import requests, cloudscraper, random, time, base64, os
from urllib.parse import urlparse, quote
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
def log(msg):
entry = f"{code}{suf}: {msg}"
with open(fail_log, "a") as f:
f.write(entry + "\n")
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
"Mozilla/5.0 (Linux; Android 10)",
"Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X)",
]
parsed = urlparse(url)
referer = f"{parsed.scheme}://{parsed.netloc}/"
headers = {
"User-Agent": random.choice(USER_AGENTS),
"Referer": referer,
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
}
log(f"Starting download: {url}")
# 1) cloudscraper
try:
scraper = cloudscraper.create_scraper(browser={"browser":"chrome","platform":"windows"})
r = scraper.get(url, headers=headers, stream=True, timeout=30)
r.raise_for_status()
if "image" in r.headers.get("Content-Type","").lower():
with open(out_path, "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
return True
log(f"Cloudscraper non-image: {r.headers.get('Content-Type')}")
except Exception as e:
log(f"Cloudscraper error: {e}")
# 2) requests
try:
r = requests.get(url, headers=headers, stream=True,
timeout=60, allow_redirects=True, verify=False)
r.raise_for_status()
if "image" in r.headers.get("Content-Type","").lower():
with open(out_path, "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
return True
log(f"Requests non-image: {r.headers.get('Content-Type')}")
except Exception as e:
log(f"Requests error: {e}")
# 3) public proxy
try:
proxy_target = parsed.netloc + parsed.path + (f"?{parsed.query}" if parsed.query else "")
proxy_url = f"https://images.weserv.nl/?url={quote(proxy_target, safe='')}"
r = requests.get(proxy_url, headers=headers, stream=True, timeout=30)
r.raise_for_status()
if "image" in r.headers.get("Content-Type","").lower():
with open(out_path, "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
return True
log(f"Proxy non-image: {r.headers.get('Content-Type')}")
except Exception as e:
log(f"Proxy error: {e}")
# 4) Selenium canvas fallback
try:
opts = Options()
opts.add_argument("--headless")
opts.add_argument("--disable-gpu")
opts.add_argument("--no-sandbox")
opts.add_argument(f"user-agent={headers['User-Agent']}")
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()),
options=opts
)
driver.get(url)
time.sleep(5) # allow JS & image to load
img_el = driver.find_element("tag name", "img")
data_url = driver.execute_script("""
const img = arguments[0];
const c = document.createElement('canvas');
c.width = img.naturalWidth; c.height = img.naturalHeight;
c.getContext('2d').drawImage(img,0,0);
return c.toDataURL('image/png');
""", img_el)
driver.quit()
header, b64 = data_url.split(",", 1)
raw = base64.b64decode(b64)
with open(out_path, "wb") as f:
f.write(raw)
return True
except Exception as e:
try: driver.quit()
except: pass
log(f"Selenium error: {e}")
# All methods failed
log("Download failed for all methods")
return False
from PIL import Image, ImageChops
import io, os, tempfile, shutil, zipfile
from urllib.parse import urlparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
# ==== IMAGE PROCESSING ====
def pad_to_square(img: Image.Image, size: int, fill=(255,255,255)) -> Image.Image:
"""Resize longest side to `size` (no upscaling if smaller),
then center-paste onto a white sizeΓ—size canvas."""
w, h = img.size
# compute new dimensions
if w <= size and h <= size:
nw, nh = w, h
elif w > h:
scale = size / w
nw, nh = size, int(round(h * scale))
else:
scale = size / h
nw, nh = int(round(w * scale)), size
if (nw, nh) != (w, h):
img = img.resize((nw, nh), Image.LANCZOS)
# if it has alpha, composite onto white first
if img.mode in ("RGBA","LA"):
bg = Image.new("RGB", img.size, fill)
bg.paste(img, mask=img.split()[-1])
img = bg
canvas = Image.new("RGB", (size, size), fill)
x = (size - img.width) // 2
y = (size - img.height) // 2
canvas.paste(img, (x, y))
return canvas
def crop_to_content(img: Image.Image, tol: int = 5) -> Image.Image:
"""Trim uniform-color borders (within tolerance)."""
rgb = img.convert("RGB")
w,h = rgb.size
corners = [
rgb.getpixel((0,0)), rgb.getpixel((w-1,0)),
rgb.getpixel((0,h-1)), rgb.getpixel((w-1,h-1))
]
bgcol = max(set(corners), key=corners.count)
solid = Image.new("RGB", (w,h), bgcol)
diff = ImageChops.difference(rgb, solid).convert("L")
if tol > 0:
diff = diff.point(lambda p: p if p>tol else 0)
bbox = diff.getbbox()
return img.crop(bbox) if bbox else img
def smart_pad_or_crop(img: Image.Image, size: int, fill=(255,255,255)) -> Image.Image:
"""
If content is roughly centered, just pad.
Else crop to content then pad.
"""
if is_content_centered(img, tol_frac=0.12):
return pad_to_square(img, size, fill)
else:
cropped = crop_to_content(img, tol=5)
return pad_to_square(cropped, size, fill)
def save_jpeg_under_limit(img: Image.Image, out_path: str,
max_kb: int=350, min_q: int=60) -> bool:
"""Save `img` as JPEG ≀ max_kb, dropping quality in steps."""
q = 95
while q >= min_q:
buf = io.BytesIO()
img.save(buf, "JPEG", quality=q,
optimize=True, progressive=True, subsampling=0)
if buf.tell()/1024 <= max_kb:
with open(out_path, "wb") as f:
f.write(buf.getvalue())
return True
q -= 5
# final write at min_q
with open(out_path, "wb") as f:
f.write(buf.getvalue())
return False
def is_content_centered(img: Image.Image, tol_frac: float = 0.12) -> bool:
"""True if the content-bbox is within tol_frac of the image center."""
w,h = img.size
trimmed = crop_to_content(img, tol=5)
bbox = trimmed.getbbox()
if not bbox:
return True
left,top,right,bottom = bbox
cx,cy = w/2, h/2
bx,by = (left+right)/2, (top+bottom)/2
return abs(cx-bx)/w < tol_frac and abs(cy-by)/h < tol_frac
def resize_and_pad_adaptive(img: Image.Image, target: int, fill=(255,255,255)) -> Image.Image:
"""
Longest side β†’ target px, preserve aspect, no up-scale if smaller,
then center-paste onto a targetΓ—target canvas.
"""
w,h = img.size
if w >= h:
scale = min(target/w, 1.0)
else:
scale = min(target/h, 1.0)
nw,nh = int(w*scale), int(h*scale)
img = img.resize((nw,nh), Image.LANCZOS)
# flatten alpha onto white
if img.mode in ("RGBA","LA"):
bg = Image.new("RGB", (nw,nh), fill)
bg.paste(img, mask=img.split()[-1])
img = bg
canvas = Image.new("RGB", (target,target), fill)
x = (target-nw)//2; y = (target-nh)//2
canvas.paste(img, (x,y))
return canvas
def smart_crop_and_pad(img, size):
return process_image_smart_center(img, size)
def process_image_smart_center(img: Image.Image, target: int = 1000,
fill=(255,255,255), tol_frac: float = 0.12) -> Image.Image:
"""
Crop only if off-center, then pad/resize adaptive.
"""
if not is_content_centered(img, tol_frac=tol_frac):
img = crop_to_content(img, tol=5)
return resize_and_pad_adaptive(img, target, fill)
# match any http(s) URL
from openpyxl import load_workbook
import re, os, pandas as pd
# your full list of extensions
def read_links_from_workbook(path):
ext = os.path.splitext(path)[1].lower()
engine = "pyxlsb" if ext == ".xlsb" else "openpyxl"
sheets = pd.read_excel(path, sheet_name=None, engine=engine)
tasks = []
for name, df in sheets.items():
if name.strip().lower() == "clear sheet data":
continue
df.columns = df.columns.str.strip()
for _, row in df.iterrows():
raw = row.get("ItemCode", "")
if pd.isna(raw):
continue
code = str(int(raw)) if isinstance(raw, float) and raw.is_integer() else str(raw).strip()
# Main image URL
if "MainImageURL" in df.columns:
main = row.get("MainImageURL")
if pd.notna(main):
tasks.append((code, str(main).strip(), ""))
# Perspective URLs – only if columns exist
for i in range(1, 8):
col = f"Perspective{i}URL"
if col in df.columns:
val = row.get(col)
if pd.notna(val):
tasks.append((code, str(val).strip(), f"_{i}"))
return tasks
# === Batch & Single Handlers ===
# --- Batch handler ---
def handle_batch(workbook_path, fmt, w, h):
if workbook_path is None:
return [], None, "❌ Upload a workbook first."
tmpdir = tempfile.mkdtemp()
outdir = os.path.join(tmpdir, "out"); os.makedirs(outdir, exist_ok=True)
fail_log = os.path.join(tmpdir, "failed.txt")
try:
jobs = read_links_from_workbook(workbook_path.name)
except Exception as e:
shutil.rmtree(tmpdir)
return [], None, f"❌ Read error: {e}"
if not jobs:
shutil.rmtree(tmpdir)
return [], None, "❌ No URLs found."
tasks = []
for itemcode, url, _ in jobs:
count = sum(1 for t in tasks if t[2] == itemcode)
suf = "" if count == 0 else f"_{count}"
ext_in = os.path.splitext(urlparse(url).path)[1] or ".jpg"
dl_path = os.path.join(outdir, f"{itemcode}{suf}{ext_in}")
tasks.append((url, dl_path, itemcode, suf))
total = len(tasks)
# Download all images (assuming you have a download_image function)
from concurrent.futures import as_completed
futures = []
with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as ex:
for url, dl_path, code, suf in tasks:
futures.append(ex.submit(download_image, url, dl_path, fail_log, code, suf))
for fut in as_completed(futures):
fut.result()
processed = []
ext_out = ".jpg" if fmt.upper() == "JPEG" else f".{fmt.lower()}"
for url, dl_path, itemcode, suf in tasks:
if not os.path.exists(dl_path):
continue
try:
img = Image.open(dl_path)
final = smart_crop_and_pad(img, w) # << use smart crop+pad
root = os.path.splitext(os.path.join(outdir, f"{itemcode}{suf}"))[0]
outp = root + ".jpg" if fmt.upper() == "JPEG" else root + ext_out
if fmt.upper() == "JPEG":
if final.mode not in ("RGBA", "LA"):
final = final.convert("RGBA")
bg = Image.new("RGB", final.size, (255,255,255))
bg.paste(final, mask=final.split()[-1])
ok = save_jpeg_under_limit(bg, outp, max_kb=350)
if not ok:
log_failure(fail_log, f"{itemcode}{suf}: Could not compress under 350 KB")
else:
final.save(outp, fmt.upper())
processed.append(outp)
except Exception as e:
log_failure(fail_log, f"{itemcode}{suf}: Process error: {e}")
done = len(processed)
failed = total - done
msg = f"βœ… Batch fetched: {total}, downloaded: {done}, failed: {failed}."
if failed:
msg += "\n\n❌ Failed to download:"
for _, dl_path, itemcode, suf in tasks:
if not os.path.exists(dl_path):
msg += f"\n β€’ {itemcode}{suf}"
zip_path = os.path.join(tmpdir, f"batch_{datetime.now():%Y%m%d_%H%M%S}.zip")
with zipfile.ZipFile(zip_path, "w") as zf:
for fp in processed:
zf.write(fp, os.path.basename(fp))
if os.path.exists(fail_log):
zf.write(fail_log, os.path.basename(fail_log))
return processed, zip_path, msg
def handle_single_upload(uploaded_files, fmt, w, h):
"""
Process one or more uploaded image files: smart crop/center, flatten alpha β†’ white if JPEG.
"""
if not uploaded_files:
return [], None, "❌ No files uploaded."
tmpdir = tempfile.mkdtemp()
out_paths = []
for file in uploaded_files:
try:
img = Image.open(file)
final = process_image_smart_center(img, w) # <--- use smart center logic
base, _ = os.path.splitext(os.path.basename(getattr(file, "name", "file")))
outp = os.path.join(tmpdir, f"{base}.jpg" if fmt.upper() == "JPEG" else f"{base}.{fmt.lower()}")
if fmt.upper() == "JPEG":
if final.mode not in ("RGBA", "LA"):
final = final.convert("RGBA")
bg = Image.new("RGB", final.size, (255,255,255))
bg.paste(final, mask=final.split()[-1])
bg.save(
outp,
format="JPEG",
quality=100,
subsampling=0,
optimize=True,
progressive=True
)
else:
final.save(outp, fmt.upper())
if os.path.exists(outp):
out_paths.append(outp)
except Exception as e:
print(f"Failed to process {getattr(file, 'name', file)}: {e}")
continue
msg = f"βœ… {len(out_paths)} image(s) processed."
return out_paths, None, msg
def handle_single_url(url, fmt, w, h):
"""
Download a single URL, smart crop/center, flatten alpha β†’ white if JPEG, and return the saved path.
"""
if not url.strip():
return None, None, "❌ No URL provided."
tmpdir = tempfile.mkdtemp()
fail_log = os.path.join(tmpdir, "failed.txt")
parts = urlparse(url)
ext = os.path.splitext(parts.path)[1] or ".jpg"
dl_path = os.path.join(tmpdir, f"dl{ext}")
ok = download_image(url, dl_path, fail_log, "single", "")
if not ok:
reason = "unknown error"
if os.path.exists(fail_log):
with open(fail_log) as f:
reason = next((l.strip() for l in f if l.strip()), reason)
shutil.rmtree(tmpdir)
return None, None, f"❌ Download failed: {reason}"
try:
img = Image.open(dl_path)
final = process_image_smart_center(img, w)
except Exception as e:
shutil.rmtree(tmpdir)
return None, None, f"❌ Processing failed: {e}"
outp = os.path.join(tmpdir, f"single.jpg" if fmt.upper() == "JPEG" else f"single.{fmt.lower()}")
try:
if fmt.upper() == "JPEG":
if final.mode not in ("RGBA", "LA"):
final = final.convert("RGBA")
bg = Image.new("RGB", final.size, (255,255,255))
bg.paste(final, mask=final.split()[-1])
bg.save(
outp,
format="JPEG",
quality=100,
subsampling=0,
optimize=True,
progressive=True
)
else:
final.save(outp, fmt.upper())
except Exception as e:
shutil.rmtree(tmpdir)
return None, None, f"❌ Save failed: {e}"
return [outp], None, "βœ… URL processed successfully."
def do_clear(tmp_dir):
stop_event.set()
# (optional) shutil.rmtree(tmp_dir) if you want to clean up
return None, [], None, None, None, "Cleared.", None
# === css ===
lamp_html = """
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #979281;
transition: background 0.3s ease;
}
body.lit {
background: radial-gradient(#555, #111);
}
.lamp-fixed {
position: fixed;
top: 0;
right: 0;
width: 100px;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
z-index: 9999;
pointer-events: none;
}
.mount {
width: 30px;
height: 5px;
background: #111;
border-radius: 6px;
pointer-events: none;
}
.wire {
width: 4px;
height: 120px;
background: #000;
margin: 0;
pointer-events: none;
}
.blub {
position: relative;
width: 47px;
height: 47px;
background: #444;
border-radius: 50%;
cursor: pointer;
margin-top: -1px;
transition: all 0.3s ease;
z-index: 2;
pointer-events: auto;
}
.blub.on {
background: #ffec99;
box-shadow: 0 0 28px #ffec99, 0 0 56px #ffec99,
0 0 84px #ffec99, 0 0 168px #ffec99;
}
.blub.on::before {
background: #ffec99;
}
.blub.on::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-60%, -50%);
width: 78px;
height: 78px;
background: #ffec99;
border-radius: 100%;
filter: blur(26px);
z-index: -1;
}
.blub::before {
content: "";
position: absolute;
top: -30px;
left: 11px;
width: 25px;
height: 47px;
background: #444;
border-top: 19px solid #000;
border-radius: 8px;
transition: background 0.3s ease;
}
.blub span:nth-child(1) {
position: absolute;
top: -10px;
left: -2px;
width: 20px;
height: 18px;
background: transparent;
transform: rotate(343deg);
border-bottom-right-radius: 40px;
box-shadow: 12px 12px 0 5px #444;
transition: box-shadow 0.3s ease;
}
.blub.on span:nth-child(1) {
box-shadow: 12px 12px 0 5px #ffec99;
}
.blub span:nth-child(2) {
position: absolute;
top: -10px;
right: -2px;
width: 20px;
height: 18px;
background: transparent;
transform: rotate(18deg);
border-bottom-left-radius: 50px;
box-shadow: -12px 12px 0 5px #444;
transition: box-shadow 0.3s ease;
}
.blub.on span:nth-child(2) {
box-shadow: -12px 12px 0 5px #ffec99;
}
</style>
<div class="lamp-fixed">
<div class="mount"></div>
<div class="wire"></div>
<div class="blub" onclick="this.classList.toggle('on'); document.body.classList.toggle('lit')">
<span></span>
<span></span>
</div>
</div>
"""
# === CSS including overflow fix ===
# === CSS ===
css = """
body {
margin: 0;
background: #C4DFE5;
font-family: 'Segoe UI', sans-serif;
color: #222;
display: flex;
justify-content: center;
padding: 2rem;
transition: background 0.3s, color 0.3s;
}
.gradio-container {
max-width: 1200px; /* You can reduce this (e.g., 600px) */
width: 100%;
margin: 0 auto;
h1 {
font-size: 24px !important;
font-weight: 700 !important;
margin-bottom: 1rem !important;
color: #FFFFFF !important;
text-align: center !important;
}
.panel {
background: white;
padding: 1rem;
border-radius: 6px;
border: 1px solid #ddd;
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
#clear-btn, #stop-btn {
margin-top: 1rem;
font-size: 0.85rem !important;
font-weight: 600 !important;
padding: 0.5rem 1rem !important;
border-radius: 8px !important;
border: none !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
transition: background-color 0.2s ease !important;
width: 100% !important;
}
.btn-row {
display: flex;
justify-content: space-between;
gap: 0.5rem;
}
#clear-btn {
background-color: #e74c3c !important;
color: white !important;
width: 50% !important;
}
#clear-btn:hover {
background-color: #c0392b !important;
cursor: pointer !important;
}
#stop-btn {
background-color: #CA7842 !important;
color: white !important;
width: 50% !important;
}
#stop-btn:hover {
background-color: #FFA55D !important;
cursor: pointer !important;
}
.gradio-container .gr-row > div {
padding: 4px !important;
}
#process-btn-url {
background-color: #A4B465 !important;
color: #333 !important;
}
#fetch-btn {
background-color: #cfbed7 !important;
color: #333 !important;
}
#status-box {
background-color: #ffffff;
border: 2px solid #cfbed7;
border-radius: 6px;
padding: 1rem;
font-size: 0.95rem;
color: #333;
/* Styling the toggle radio buttons */
.gradio-container label.svelte-1ipelgc {
font-weight: 600 !important;
border: 2px solid #A4B465 !important;
padding: 0.4rem 1rem !important;
border-radius: 12px !important;
margin: 0.25rem !important;
background-color: #f5fbe8 !important;
transition: all 0.3s ease-in-out;
cursor: pointer;
}
/* Selected option */
input[type="radio"]:checked + label.svelte-1ipelgc {
background-color: #A4B465 !important;
color: white !important;
border-color: #889E46 !important;
}
/* Unselected hover */
.gradio-container input[type="radio"] + label.svelte-1ipelgc:hover {
background-color: #e0f1c4 !important;
}
}
"""
gr.HTML("""
<div class="wrapper">
<div class="toggle-icon-group">
<input type="radio" id="spreadsheet" name="mode" checked>
<label for="spreadsheet"><span>πŸ“„</span> Spreadsheet</label>
<input type="radio" id="upload" name="mode">
<label for="upload"><span>πŸ“</span> Upload</label>
</div>
</div>
""")
# β€” UI layout & launch β€”
# === Gradio UI ===
with gr.Blocks(css=css) as demo:
image_data_state = gr.State([])
temp_dir_state = gr.State(None)
gr.HTML(lamp_html)
# …rest of your Gradio UI…
# Header
with gr.Row():
gr.Markdown("<h1>πŸ–ΌοΈ Image Processor</h1>")
with gr.Row():
# ─── Left column: Inputs ────────────────────────────────
with gr.Column(scale=3):
with gr.Group(elem_classes="panel"):
mode_toggle = gr.Radio(
["πŸ“„ Upload Workbook", "πŸ“ Upload Images"],
value="πŸ“„ Upload Workbook",
label="Select Input Method"
)
workbook_input = gr.File(
label="πŸ“„ Upload .xlsx or .xlsm",
file_types=[".xlsx", ".xlsm"],
visible=True
)
upload_box = gr.File(
label="πŸ“ Upload Images",
file_count="multiple",
visible=False
)
image_url_input = gr.Textbox(
label="🌐 Paste Image URLs",
visible=False
)
# toggle visibility
def toggle_inputs(choice):
if choice == "πŸ“„ Upload Workbook":
# show only the sheet‐uploader
return (
gr.update(visible=True), # workbook_input
gr.update(visible=False), # upload_box
gr.update(visible=False) # image_url_input
)
else:
# show BOTH the image uploader AND the URL textbox
return (
gr.update(visible=False), # workbook_input
gr.update(visible=True), # upload_box
gr.update(visible=True) # image_url_input
)
mode_toggle.change(
fn=toggle_inputs,
inputs=[mode_toggle],
outputs=[workbook_input, upload_box, image_url_input]
)
process_btn_url = gr.Button("βš™οΈ Process", elem_id="process-btn-url")
with gr.Group(elem_classes="panel"):
with gr.Row():
format_choice = gr.Dropdown(
["JPEG", "PNG", "WEBP", "TIFF", "GIF", "JFIF", "AVIF"],
label="πŸ–ΌοΈ Format",
value="JPEG",
scale=1
)
width = gr.Number(
label="πŸ“ Width (px)",
value=1000,
precision=0,
scale=1
)
height = gr.Number(
label="πŸ“ Height (px)",
value=1000,
precision=0,
scale=1
)
# ─── Right column: Outputs ──────────────────────────────
with gr.Column(scale=2):
with gr.Group(elem_classes="panel"):
status = gr.Textbox(
label="πŸ“£ Status",
lines=6,
interactive=False,
elem_id="status-box"
)
workbook_input.change(
fn=count_links,
inputs=[workbook_input],
outputs=[status]
)
zip_download_btn = gr.Button("πŸ“¦ Download ZIP")
zip_file_hidden = gr.File(visible=False)
with gr.Accordion("🧷 Batch Individual Files", open=False):
single_downloads = gr.File(
label="Files",
file_count="multiple"
)
with gr.Row(elem_classes="btn-row"):
stop_btn = gr.Button("β›” Stop", elem_id="stop-btn")
clear_btn = gr.Button("πŸ—‘οΈ Clear", elem_id="clear-btn")
gr.HTML("<center style='margin-top:1rem; color:white;'>Created with πŸ’œ by Vishakha</center>")
# ─── Dispatch callback ───────────────────────────────────
# ─── Dispatch callback ───────────────────────────────────
def dispatch(mode, wb, uploads, url, fmt, w, h):
if mode == "πŸ“„ Upload Workbook":
files, zip_path, msg = handle_batch(wb, fmt, w, h)
return files, zip_path, msg
else:
if uploads:
files, _, msg = handle_single_upload(uploads, fmt, w, h)
return files, None, msg
else:
files, _, msg = handle_single_url(url, fmt, w, h)
return files, None, msg
# ─── Wire up the Process button here ───────────────────
process_btn_url.click(
fn=dispatch,
inputs=[
mode_toggle,
workbook_input,
upload_box,
image_url_input,
format_choice,
width,
height
],
outputs=[
single_downloads,
zip_file_hidden,
status
]
)
zip_download_btn.click(
None,
inputs=[zip_file_hidden],
js="(file) => { if (file) window.open(file.url,'_blank'); }"
)
clear_btn.click(
fn=do_clear,
inputs=[temp_dir_state],
outputs=[
workbook_input,
image_data_state,
upload_box,
zip_file_hidden,
single_downloads,
status,
temp_dir_state
]
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)