# --- Fix gradio 4.44 api-schema bug (TypeError: bool not iterable) that otherwise # crashes Gradio's startup self-check. See gradio issue #9039. --- import gradio_client.utils as _gcu _orig_js = _gcu._json_schema_to_python_type def _safe_js(schema, defs=None): if isinstance(schema, bool): return "Any" try: return _orig_js(schema, defs) except Exception: return "Any" _gcu._json_schema_to_python_type = _safe_js # ------------------------------------------------------------------------- """Gradio front-end for ERASE on a Hugging Face GPU Space. Wraps the research CLI (main.py / Diffusion_chain_attack.diffattack) so a single uploaded image can be processed in the browser. Weights are pulled at startup from the companion weights repo iLearn-Lab/TDSC26-ERASE. """ import os import types import tempfile os.environ.setdefault("ERASE_DEVICE", "cuda:0") # HF GPU Spaces are single-GPU os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import numpy as np import cv2 import torch import gradio as gr from PIL import Image from huggingface_hub import snapshot_download from diffusers import StableDiffusionPipeline, DDIMScheduler import main as erase_main import other_attacks from loggers import Logger WEIGHTS_REPO = "iLearn-Lab/TDSC26-ERASE" SD_MODEL = "sd2-community/stable-diffusion-2-1-base" # official stabilityai repo now 401/gated CKPT_DIR = os.path.join(erase_main.os.path.dirname(os.path.abspath(__file__)), "checkpoints") _STATE = {} def _setup(): """Download weights, load the diffusion pipeline and 4 surrogate classifiers once.""" if _STATE: return _STATE os.makedirs(CKPT_DIR, exist_ok=True) # Pull ckpt_ori/, noise_prototype_VAE.pt, dncnn_color_blind.pth into checkpoints/ snapshot_download(repo_id=WEIGHTS_REPO, local_dir=CKPT_DIR, allow_patterns=["ckpt_ori/*", "noise_prototype_VAE.pt", "dncnn_color_blind.pth"]) ldm = StableDiffusionPipeline.from_pretrained(SD_MODEL).to("cuda:0") ldm.scheduler = DDIMScheduler.from_config(ldm.scheduler.config) classes = [other_attacks.model_selection(n).eval() for n in ["E", "R", "D", "S"]] for c in classes: c.requires_grad_(False) _STATE.update(ldm=ldm, classes=classes) return _STATE def _erase_224(image, st, diffusion_steps, start_step, iterations, is_encoder, eps_over255, fid_weight, save_dir): """Run the faithful ERASE pipeline at its native 224x224 and return the 224 uint8 result plus detector/quality metrics.""" args = types.SimpleNamespace( dataset_name="ours_try", is_encoder=int(is_encoder), eps=float(eps_over255) / 255.0, attack_loss_weight=10, lr=1e-2, kappa=5.0, fid_weight=float(fid_weight), encoder_weights=os.path.join(CKPT_DIR, "ckpt_ori/Controlvae.pt"), ) logger = Logger(name="space", log_path=os.path.join(save_dir, "run.log")) label = np.zeros(1) classes = [c.to("cuda:0") for c in st["classes"]] adv, a0, a1, a2, a3, psnr, ssim, secs = erase_main.run_diffusion_attack( image.convert("RGB"), label[0:1], st["ldm"], int(diffusion_steps), guidance=0.0, res=224, model_name=["E", "R", "D", "S"], classes=classes, start_step=int(start_step), iterations=int(iterations), logger=logger, save_dir=os.path.join(save_dir, "out"), args=args, ) return np.asarray(adv, dtype=np.uint8), (a0, a1, a2, a3, psnr, ssim, secs) def run(image, diffusion_steps, start_step, iterations, is_encoder, eps_over255, fid_weight, full_res, max_side): if image is None: return None, "Upload an image first." st = _setup() save_dir = tempfile.mkdtemp(prefix="erase_") orig = image.convert("RGB") adv224, (a0, a1, a2, a3, psnr, ssim, secs) = _erase_224( orig, st, diffusion_steps, start_step, iterations, is_encoder, eps_over255, fid_weight, save_dir) if not full_res: out = Image.fromarray(adv224) mode_note = "Output: native 224x224 (raw ERASE resolution)." else: # Cap the long side so very large photos stay within GPU/CPU memory & time. W, H = orig.size scale = min(1.0, float(max_side) / max(W, H)) tgt = (max(1, int(round(W * scale))), max(1, int(round(H * scale)))) orig_full = np.asarray(orig if scale == 1.0 else orig.resize(tgt, Image.LANCZOS), dtype=np.float32) Wt, Ht = tgt # The exact 224 input ERASE consumed (same LANCZOS squash it uses internally). in224 = np.asarray(orig.resize((224, 224), Image.LANCZOS), dtype=np.float32) delta224 = adv224.astype(np.float32) - in224 # net change ERASE applied delta_full = cv2.resize(delta224, (Wt, Ht), interpolation=cv2.INTER_CUBIC) result = np.clip(orig_full + delta_full, 0, 255).astype(np.uint8) out = Image.fromarray(result) mode_note = (f"Output: full resolution {Wt}x{Ht} (ERASE change computed at 224 and " f"overlaid on your original; capped at {int(max_side)} px long side).") metrics = (f"PSNR: {psnr:.2f} dB\nSSIM: {ssim:.4f} (measured at 224, the method's native size)\n" f"Still detected as fake by E/R/D/S: {int(a0)}/{int(a1)}/{int(a2)}/{int(a3)} " f"(0 = evaded) [eps={int(eps_over255)}/255]\n{mode_note}\nTime: {secs:.1f}s") return out, metrics with gr.Blocks(title="ERASE (research)") as demo: gr.Markdown( "# ERASE — AI-image artifact elimination (research)\n" "Academic reproduction of *ERASE (TDSC 2026)*. Upload an AI-generated image; " "the pipeline reconstructs it to suppress generative artifacts and reports PSNR/SSIM " "and the surrogate detectors' verdicts. **Research and security-evaluation use only.**" ) with gr.Row(): with gr.Column(): inp = gr.Image(type="pil", label="Input image") steps = gr.Slider(10, 50, value=20, step=1, label="Diffusion steps") start = gr.Slider(1, 49, value=18, step=1, label="Start step (higher = smaller perturbation)") iters = gr.Slider(1, 30, value=10, step=1, label="Iterations") eps_s = gr.Slider(1, 32, value=4, step=1, label="Attack budget eps (x/255; higher = stronger evasion, lower fidelity)") fidw = gr.Slider(0.0, 20.0, value=2.0, step=0.5, label="Fidelity anchor weight (higher = keep image closer, weaker evasion)") enc = gr.Checkbox(value=True, label="Decoupled frequency processing (is_encoder)") full_res = gr.Checkbox(value=True, label="Full-resolution output (overlay ERASE change onto your original)") max_side = gr.Slider(512, 4096, value=2048, step=64, label="Max output long side (px)") btn = gr.Button("Run ERASE", variant="primary") with gr.Column(): out_img = gr.Image(label="Processed image") out_txt = gr.Textbox(label="Metrics", lines=5) btn.click(run, [inp, steps, start, iters, enc, eps_s, fidw, full_res, max_side], [out_img, out_txt], api_name="run") if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False, show_error=True)