Spaces:
Running
on
Zero
Running
on
Zero
File size: 5,257 Bytes
4c2d0e3 a344ac6 4c2d0e3 4e13a1e 62ff71a 4e13a1e 10ac12a 4e13a1e 62ff71a 4e13a1e 62ff71a 4e13a1e 4c2d0e3 4e13a1e a344ac6 4e13a1e 4c2d0e3 4e13a1e 4c2d0e3 a344ac6 4c2d0e3 10ac12a a344ac6 4c2d0e3 4e13a1e 4c2d0e3 4e13a1e 4c2d0e3 4e13a1e a344ac6 4c2d0e3 4e13a1e 4c2d0e3 4e13a1e 4c2d0e3 4e13a1e 62ff71a 4e13a1e 62ff71a 4e13a1e 62ff71a 10ac12a 62ff71a 4e13a1e 62ff71a a344ac6 10ac12a 62ff71a 10ac12a 4e13a1e 4c2d0e3 4e13a1e a344ac6 62ff71a a344ac6 62ff71a a344ac6 10ac12a 62ff71a 10ac12a a290ddb a344ac6 62ff71a 4e13a1e 4c2d0e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# ============================================================
# Hugging Face Spaces GPU app
# IMPORTANT:
# - spaces MUST be imported first
# - @spaces.GPU MUST be used directly
# ============================================================
import spaces # MUST be first
import os
import random
import gc
import gradio as gr
import numpy as np
from PIL import Image
import torch
from diffusers import (
StableDiffusionPipeline,
StableDiffusionImg2ImgPipeline,
EulerAncestralDiscreteScheduler,
)
from transformers import CLIPTokenizer, CLIPTextModel
from huggingface_hub import login
# ============================================================
# Config
# ============================================================
MODEL_ID = "telcom/dee-unlearning-tiny-sd"
REVISION = "main"
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
if HF_TOKEN:
login(token=HF_TOKEN)
device = torch.device("cuda")
dtype = torch.float16
IMAGE_SIZE = 512
MAX_SEED = np.iinfo(np.int32).max
# ============================================================
# Load model (once at startup)
# ============================================================
pipe_txt2img = StableDiffusionPipeline.from_pretrained(
MODEL_ID,
revision=REVISION,
torch_dtype=dtype,
safety_checker=None,
).to(device)
# 🔑 Force tokenizer + text encoder
pipe_txt2img.tokenizer = CLIPTokenizer.from_pretrained(
MODEL_ID, subfolder="tokenizer"
)
pipe_txt2img.text_encoder = CLIPTextModel.from_pretrained(
MODEL_ID,
subfolder="text_encoder",
torch_dtype=dtype,
).to(device)
# Scheduler
pipe_txt2img.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipe_txt2img.scheduler.config
)
# Memory optimisations
pipe_txt2img.enable_attention_slicing()
pipe_txt2img.enable_vae_slicing()
try:
pipe_txt2img.enable_xformers_memory_efficient_attention()
except Exception:
pass
pipe_txt2img.set_progress_bar_config(disable=True)
# Img2Img pipeline
pipe_img2img = StableDiffusionImg2ImgPipeline(
**pipe_txt2img.components
).to(device)
pipe_img2img.scheduler = EulerAncestralDiscreteScheduler.from_config(
pipe_img2img.scheduler.config
)
# ============================================================
# GPU INFERENCE FUNCTION (Spaces requires this)
# ============================================================
@spaces.GPU
def infer(
prompt,
negative_prompt,
seed,
randomize_seed,
guidance_scale,
num_inference_steps,
init_image,
strength,
):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=device).manual_seed(seed)
try:
with torch.inference_mode():
if init_image is not None:
image = pipe_img2img(
prompt=prompt,
negative_prompt=negative_prompt,
image=init_image,
strength=float(strength),
guidance_scale=float(guidance_scale),
num_inference_steps=int(num_inference_steps),
generator=generator,
).images[0]
else:
image = pipe_txt2img(
prompt=prompt,
negative_prompt=negative_prompt,
width=IMAGE_SIZE,
height=IMAGE_SIZE,
guidance_scale=float(guidance_scale),
num_inference_steps=int(num_inference_steps),
generator=generator,
).images[0]
return image, f"Seed: {seed}"
finally:
gc.collect()
torch.cuda.empty_cache()
# ============================================================
# UI
# ============================================================
with gr.Blocks(title="Stable Diffusion (512×512)") as demo:
gr.Markdown("## Stable Diffusion Generator (GPU, 512×512)")
prompt = gr.Textbox(
label="Prompt",
placeholder="Describe the image you want to generate",
lines=2,
)
init_image = gr.Image(
label="Initial image (optional, enables img2img)",
type="pil",
)
run_button = gr.Button("Generate")
result = gr.Image(label="Result")
status = gr.Markdown("")
with gr.Accordion("Advanced Settings", open=False):
negative_prompt = gr.Textbox(
label="Negative prompt",
value="nsfw, (low quality, worst quality:1.2), watermark, signature, ugly, deformed",
)
seed = gr.Slider(0, MAX_SEED, step=1, value=0, label="Seed")
randomize_seed = gr.Checkbox(True, label="Randomize seed")
guidance_scale = gr.Slider(1, 20, step=0.5, value=7.5, label="Guidance scale")
num_inference_steps = gr.Slider(1, 40, step=1, value=30, label="Steps")
strength = gr.Slider(0.0, 1.0, step=0.05, value=0.7, label="Image strength (img2img)")
run_button.click(
fn=infer,
inputs=[
prompt,
negative_prompt,
seed,
randomize_seed,
guidance_scale,
num_inference_steps,
init_image,
strength,
],
outputs=[result, status],
)
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|