Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456789105 unmodified lines1617181920212223242526272829305 unmodified lines3637383940414243444546474849505152535455565758591 unmodified line61626364656667686970717210 unmodified lines838485868788899091929313 unmodified lines1071081091101111121131148 unmodified lines1231241251261271281291301311321331341351361371381391401411 unmodified line14314414514614714814910 unmodified lines16016116216316416516616716816917017117217317417517616 unmodified lines1931941951961971981992002012022032042052062072082092102112122133 unmodified lines2172182192202212 unmodified linesfrom PIL import Imageimport torchimport gradio as grimport spaces # ZeroGPU: decorate GPU-bound functionsfrom huggingface_hub import snapshot_downloadfrom diffusers import (StableDiffusionXLPipeline,StableDiffusionPipeline,5 unmodified linesPNDMScheduler,)# -------- Configuration (set as Space Secrets if needed) --------MODEL_REPO_ID = os.getenv("MODEL_REPO_ID", "DB2169/CyberPony_Lora") # your model repo idCHECKPOINT_FILENAME = os.getenv("CHECKPOINT_FILENAME", "SAFETENSORS_FILENAME.safetensors") # exact .safetensors nameHF_TOKEN = os.getenv("HF_TOKEN", None) # only required for private reposDO_WARMUP = os.getenv("WARMUP", "1") == "1" # set to "0" to disable warmup# -------- Runtime defaults --------REPO_DIR = "/home/user/model" # local cache mount for snapshot_download# Defer CUDA detection to GPU-run function for ZeroGPU; do not move to CUDA at import timeSCHEDULERS = {"default": None,5 unmodified lines"dpmpp_2m": DPMSolverMultistepScheduler,}# Globals populated on startuppipe = NoneIS_SDXL = TrueLORA_MANIFEST: Dict[str, Dict[str, str]] = {}# -------- Model bootstrap (CPU) --------def bootstrap_model():global pipe, IS_SDXL, LORA_MANIFESTlocal_dir = snapshot_download(repo_id=MODEL_REPO_ID,token=HF_TOKEN,local_dir=REPO_DIR,ignore_patterns=["*.md"],)ckpt_path = os.path.join(local_dir, CHECKPOINT_FILENAME)if not os.path.exists(ckpt_path):raise FileNotFoundError(f"Checkpoint not found: {ckpt_path}")try:_pipe = StableDiffusionXLPipeline.from_single_file(1 unmodified line)sdxl = Trueexcept Exception:_pipe = StableDiffusionPipeline.from_single_file(ckpt_path, torch_dtype=torch.float16, use_safetensors=True)sdxl = False# Keep on CPU until GPU-decorated call (ZeroGPU attaches GPU on demand)if hasattr(_pipe, "enable_attention_slicing"):_pipe.enable_attention_slicing("max")if hasattr(_pipe, "enable_vae_slicing"):10 unmodified linesexcept Exception as e:print(f"[WARN] Failed to parse loras.json: {e}")pipe = _pipeIS_SDXL = sdxlLORA_MANIFEST = manifestdef apply_loras(selected: List[str], scale: float, repo_dir: str):if not selected or scale <= 0:return13 unmodified linesexcept Exception as e:print(f"[WARN] set_adapters failed: {e}")@spaces.GPU # ZeroGPU: allocate/attach GPU for this function calldef txt2img(prompt: str,negative: str,8 unmodified lineslora_scale: float,fuse_lora: bool,):# Resolve device inside GPU contextlocal_device = "cuda" if torch.cuda.is_available() else "cpu"local_dtype = torch.float16 if local_device == "cuda" else torch.float32pipe.to(local_device)# Scheduler swapif scheduler in SCHEDULERS and SCHEDULERS[scheduler] is not None:try:pipe.scheduler = SCHEDULERS[scheduler].from_config(pipe.scheduler.config)except Exception as e:print(f"[WARN] Scheduler switch failed: {e}")# LoRAsapply_loras(loras, lora_scale, REPO_DIR)if fuse_lora and loras:try:1 unmodified lineexcept Exception as e:print(f"[WARN] fuse_lora failed: {e}")# Determinismgenerator = torch.Generator(device=local_device).manual_seed(int(seed)) if seed not in (None, "") else Nonekwargs: Dict[str, Any] = dict(10 unmodified linesout = pipe(**kwargs)return out.imagesdef warmup():try:_ = txt2img("warmup", "", 512, 512, 4, 4.0, 1, 1234, "default", [], 0.0, False)except Exception as e:print(f"[WARN] Warmup failed: {e}")# --------------------------- Build UI ---------------------------with gr.Blocks(title="SDXL Space (ZeroGPU, single-file checkpoint, LoRA-ready)") as demo:gr.Markdown("### SDXL text‑to‑image with single‑file checkpoint and optional LoRAs")with gr.Row():prompt = gr.Textbox(label="Prompt", lines=3)16 unmodified lineslora_scale = gr.Slider(0.0, 1.5, 0.7, step=0.05, label="LoRA scale")fuse = gr.Checkbox(label="Fuse LoRA (faster after load)")btn = gr.Button("Generate", variant="primary")gallery = gr.Gallery(columns=4, height=420)# Load model + manifest, then populate LoRA choicesdef _startup():bootstrap_model()return gr.CheckboxGroup.update(choices=list(LORA_MANIFEST.keys()))demo.load(_startup, outputs=[lora_names])# Optional warmup (costs a tiny GPU run on first boot); set WARMUP=0 to skipif DO_WARMUP:demo.load(lambda: warmup(), inputs=None, outputs=None)# Event binding inside Blocks; one GPU job at a time for SDXLbtn.click(txt2img,inputs=[prompt, negative, width, height, steps, guidance, images, seed, scheduler, lora_names, lora_scale, fuse],3 unmodified linesconcurrency_id="gpu_queue",)# Global queue limits for Gradio 4.xdemo.queue(max_size=32, default_concurrency_limit=1).launch()2 unmodified lines3456789105 unmodified lines1617181920212223242526275 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line7475767778798081828384858687888910 unmodified lines10010110210310410510610710810911011113 unmodified lines1251261271281291301318 unmodified lines1401411421431441451461471481491501511521531541551561571581 unmodified line16016116216316416510 unmodified lines17617717817918018118218318418518618718818916 unmodified lines2062072082092102112122132142152162172182192202212222232242252263 unmodified lines2302312322332 unmodified linesfrom PIL import Imageimport torchimport gradio as grimport spacesfrom huggingface_hub import snapshot_download, HfHubHTTPErrorfrom diffusers import (StableDiffusionXLPipeline,StableDiffusionPipeline,5 unmodified linesPNDMScheduler,)MODEL_REPO_ID = os.getenv("MODEL_REPO_ID", "").strip()CHECKPOINT_FILENAME = os.getenv("CHECKPOINT_FILENAME", "").strip()HF_TOKEN = os.getenv("HF_TOKEN", None)DO_WARMUP = os.getenv("WARMUP", "1") == "1"REPO_DIR = "/home/user/model"SCHEDULERS = {"default": None,5 unmodified lines"dpmpp_2m": DPMSolverMultistepScheduler,}pipe = NoneIS_SDXL = TrueLORA_MANIFEST: Dict[str, Dict[str, str]] = {}INIT_ERROR: Optional[str] = None # expose bootstrap error to UIdef bootstrap_model():global pipe, IS_SDXL, LORA_MANIFEST, INIT_ERRORINIT_ERROR = Noneif not MODEL_REPO_ID or not CHECKPOINT_FILENAME:INIT_ERROR = "Missing MODEL_REPO_ID or CHECKPOINT_FILENAME environment variables."print(f"[ERROR] {INIT_ERROR}")returntry:local_dir = snapshot_download(repo_id=MODEL_REPO_ID,token=HF_TOKEN,local_dir=REPO_DIR,ignore_patterns=["*.md"],)except HfHubHTTPError as e:INIT_ERROR = f"Failed to download repo {MODEL_REPO_ID}: {e}"print(f"[ERROR] {INIT_ERROR}")returnexcept Exception as e:INIT_ERROR = f"Unexpected error while downloading repo: {e}"print(f"[ERROR] {INIT_ERROR}")returnckpt_path = os.path.join(local_dir, CHECKPOINT_FILENAME)if not os.path.exists(ckpt_path):INIT_ERROR = f"Checkpoint not found at {ckpt_path}. Check CHECKPOINT_FILENAME."print(f"[ERROR] {INIT_ERROR}")returntry:_pipe = StableDiffusionXLPipeline.from_single_file(1 unmodified line)sdxl = Trueexcept Exception:try:_pipe = StableDiffusionPipeline.from_single_file(ckpt_path, torch_dtype=torch.float16, use_safetensors=True)sdxl = Falseexcept Exception as e:INIT_ERROR = f"Failed to load pipeline from {CHECKPOINT_FILENAME}: {e}"print(f"[ERROR] {INIT_ERROR}")returnif hasattr(_pipe, "enable_attention_slicing"):_pipe.enable_attention_slicing("max")if hasattr(_pipe, "enable_vae_slicing"):10 unmodified linesexcept Exception as e:print(f"[WARN] Failed to parse loras.json: {e}")# publishglobal pipe, IS_SDXL, LORA_MANIFESTpipe = _pipeIS_SDXL = sdxlLORA_MANIFEST = manifestdef apply_loras(selected: List[str], scale: float, repo_dir: str):if not selected or scale <= 0:return13 unmodified linesexcept Exception as e:print(f"[WARN] set_adapters failed: {e}")@spaces.GPUdef txt2img(prompt: str,negative: str,8 unmodified lineslora_scale: float,fuse_lora: bool,):if pipe is None:raise RuntimeError(f"Model not initialized. {INIT_ERROR or 'Check Space secrets and logs.'}")local_device = "cuda" if torch.cuda.is_available() else "cpu"local_dtype = torch.float16 if local_device == "cuda" else torch.float32pipe.to(local_device)if scheduler in SCHEDULERS and SCHEDULERS[scheduler] is not None:try:pipe.scheduler = SCHEDULERS[scheduler].from_config(pipe.scheduler.config)except Exception as e:print(f"[WARN] Scheduler switch failed: {e}")apply_loras(loras, lora_scale, REPO_DIR)if fuse_lora and loras:try:1 unmodified lineexcept Exception as e:print(f"[WARN] fuse_lora failed: {e}")generator = torch.Generator(device=local_device).manual_seed(int(seed)) if seed not in (None, "") else Nonekwargs: Dict[str, Any] = dict(10 unmodified linesout = pipe(**kwargs)return out.imagesdef warmup():try:_ = txt2img("warmup", "", 512, 512, 4, 4.0, 1, 1234, "default", [], 0.0, False)except Exception as e:print(f"[WARN] Warmup failed: {e}")with gr.Blocks(title="SDXL Space (ZeroGPU, single-file, LoRA-ready)") as demo:status = gr.Markdown("") # show init status/errorswith gr.Row():prompt = gr.Textbox(label="Prompt", lines=3)16 unmodified lineslora_scale = gr.Slider(0.0, 1.5, 0.7, step=0.05, label="LoRA scale")fuse = gr.Checkbox(label="Fuse LoRA (faster after load)")btn = gr.Button("Generate", variant="primary", interactive=False) # locked until model loadsgallery = gr.Gallery(columns=4, height=420)def _startup():bootstrap_model()if INIT_ERROR:return gr.Markdown.update(value=f"❌ Init failed: {INIT_ERROR}"), gr.CheckboxGroup.update(choices=[]), gr.Button.update(interactive=False)msg = f"✅ Model loaded from {MODEL_REPO_ID} ({'SDXL' if IS_SDXL else 'SD'})"return gr.Markdown.update(value=msg), gr.CheckboxGroup.update(choices=list(LORA_MANIFEST.keys())), gr.Button.update(interactive=True)demo.load(_startup, outputs=[status, lora_names, btn])if DO_WARMUP:demo.load(lambda: warmup(), inputs=None, outputs=None)btn.click(txt2img,inputs=[prompt, negative, width, height, steps, guidance, images, seed, scheduler, lora_names, lora_scale, fuse],3 unmodified linesconcurrency_id="gpu_queue",)demo.queue(max_size=32, default_concurrency_limit=1).launch()
app.py+57-45