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 = """