Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,27 +1,100 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
import random
|
| 4 |
-
|
| 5 |
-
# import spaces #[uncomment to use ZeroGPU]
|
| 6 |
from diffusers import DiffusionPipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import torch
|
| 8 |
|
| 9 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
-
# @spaces.GPU #[uncomment to use ZeroGPU]
|
| 25 |
def infer(
|
| 26 |
prompt,
|
| 27 |
negative_prompt,
|
|
@@ -31,42 +104,58 @@ def infer(
|
|
| 31 |
height,
|
| 32 |
guidance_scale,
|
| 33 |
num_inference_steps,
|
|
|
|
| 34 |
progress=gr.Progress(track_tqdm=True),
|
| 35 |
):
|
|
|
|
|
|
|
|
|
|
| 36 |
if randomize_seed:
|
| 37 |
seed = random.randint(0, MAX_SEED)
|
| 38 |
|
| 39 |
-
generator
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
return image, seed
|
| 52 |
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"An astronaut riding a green horse",
|
| 57 |
-
"A delicious ceviche cheesecake slice",
|
| 58 |
-
]
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
with gr.Column(elem_id="col-container"):
|
| 69 |
-
gr.Markdown(" # Text-to-Image Gradio Template")
|
| 70 |
|
| 71 |
with gr.Row():
|
| 72 |
prompt = gr.Text(
|
|
@@ -76,8 +165,7 @@ with gr.Blocks(css=css) as demo:
|
|
| 76 |
placeholder="Enter your prompt",
|
| 77 |
container=False,
|
| 78 |
)
|
| 79 |
-
|
| 80 |
-
run_button = gr.Button("Run", scale=0, variant="primary")
|
| 81 |
|
| 82 |
result = gr.Image(label="Result", show_label=False)
|
| 83 |
|
|
@@ -86,7 +174,7 @@ with gr.Blocks(css=css) as demo:
|
|
| 86 |
label="Negative prompt",
|
| 87 |
max_lines=1,
|
| 88 |
placeholder="Enter a negative prompt",
|
| 89 |
-
visible=
|
| 90 |
)
|
| 91 |
|
| 92 |
seed = gr.Slider(
|
|
@@ -94,18 +182,24 @@ with gr.Blocks(css=css) as demo:
|
|
| 94 |
minimum=0,
|
| 95 |
maximum=MAX_SEED,
|
| 96 |
step=1,
|
| 97 |
-
value=
|
| 98 |
)
|
| 99 |
|
| 100 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=
|
| 101 |
|
| 102 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
width = gr.Slider(
|
| 104 |
label="Width",
|
| 105 |
minimum=256,
|
| 106 |
maximum=MAX_IMAGE_SIZE,
|
| 107 |
step=32,
|
| 108 |
-
value=
|
| 109 |
)
|
| 110 |
|
| 111 |
height = gr.Slider(
|
|
@@ -113,29 +207,45 @@ with gr.Blocks(css=css) as demo:
|
|
| 113 |
minimum=256,
|
| 114 |
maximum=MAX_IMAGE_SIZE,
|
| 115 |
step=32,
|
| 116 |
-
value=
|
| 117 |
)
|
| 118 |
|
| 119 |
with gr.Row():
|
| 120 |
guidance_scale = gr.Slider(
|
| 121 |
label="Guidance scale",
|
| 122 |
minimum=0.0,
|
| 123 |
-
maximum=
|
| 124 |
step=0.1,
|
| 125 |
-
value=
|
| 126 |
)
|
| 127 |
|
| 128 |
num_inference_steps = gr.Slider(
|
| 129 |
label="Number of inference steps",
|
| 130 |
minimum=1,
|
| 131 |
-
maximum=
|
| 132 |
step=1,
|
| 133 |
-
value=
|
| 134 |
)
|
| 135 |
|
| 136 |
gr.Examples(examples=examples, inputs=[prompt])
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
fn=infer,
|
| 140 |
inputs=[
|
| 141 |
prompt,
|
|
@@ -146,8 +256,10 @@ with gr.Blocks(css=css) as demo:
|
|
| 146 |
height,
|
| 147 |
guidance_scale,
|
| 148 |
num_inference_steps,
|
|
|
|
| 149 |
],
|
| 150 |
-
outputs=[result, seed],
|
|
|
|
| 151 |
)
|
| 152 |
|
| 153 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
import gradio as gr
|
| 3 |
import numpy as np
|
| 4 |
import random
|
|
|
|
|
|
|
| 5 |
from diffusers import DiffusionPipeline
|
| 6 |
+
from diffusers import (
|
| 7 |
+
DDIMScheduler,
|
| 8 |
+
PNDMScheduler,
|
| 9 |
+
LMSDiscreteScheduler,
|
| 10 |
+
EulerDiscreteScheduler,
|
| 11 |
+
DPMSolverMultistepScheduler,
|
| 12 |
+
)
|
| 13 |
import torch
|
| 14 |
|
| 15 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 17 |
+
MAX_IMAGE_SIZE = 1024
|
| 18 |
|
| 19 |
+
DEFAULT_MODEL = "CompVis/stable-diffusion-v1-4"
|
| 20 |
+
MODEL_OPTIONS = [
|
| 21 |
+
"CompVis/stable-diffusion-v1-4",
|
| 22 |
+
"stabilityai/sdxl-turbo",
|
| 23 |
+
# add other model ids you want to expose here
|
| 24 |
+
]
|
| 25 |
|
| 26 |
+
SCHEDULER_MAP = {
|
| 27 |
+
"default": None,
|
| 28 |
+
"DDIM": DDIMScheduler,
|
| 29 |
+
"PNDM": PNDMScheduler,
|
| 30 |
+
"LMS": LMSDiscreteScheduler,
|
| 31 |
+
"Euler": EulerDiscreteScheduler,
|
| 32 |
+
"DPMSolver": DPMSolverMultistepScheduler,
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_torch_dtype():
|
| 37 |
+
return torch.float16 if torch.cuda.is_available() else torch.float32
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_pipeline(model_id: str, scheduler_name: str = "default"):
|
| 41 |
+
"""Load pipeline from pretrained model_id and optionally replace scheduler."""
|
| 42 |
+
torch_dtype = get_torch_dtype()
|
| 43 |
+
pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch_dtype)
|
| 44 |
+
# try to replace scheduler if requested
|
| 45 |
+
sched_cls = SCHEDULER_MAP.get(scheduler_name)
|
| 46 |
+
if sched_cls is not None:
|
| 47 |
+
try:
|
| 48 |
+
pipe.scheduler = sched_cls.from_config(pipe.scheduler.config)
|
| 49 |
+
except Exception:
|
| 50 |
+
# fallback to default if replacement failed
|
| 51 |
+
pass
|
| 52 |
+
pipe = pipe.to(device)
|
| 53 |
+
return pipe
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# preload default pipeline (may take time on startup)
|
| 57 |
+
print(f"Loading default model {DEFAULT_MODEL} ...")
|
| 58 |
+
try:
|
| 59 |
+
default_pipe = load_pipeline(DEFAULT_MODEL, "default")
|
| 60 |
+
print("Loaded default model.")
|
| 61 |
+
except Exception as e:
|
| 62 |
+
default_pipe = None
|
| 63 |
+
print("Failed to preload default model:", e)
|
| 64 |
+
|
| 65 |
+
css = """
|
| 66 |
+
#col-container {
|
| 67 |
+
margin: 0 auto;
|
| 68 |
+
max-width: 880px;
|
| 69 |
+
}
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
examples = [
|
| 73 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 74 |
+
"An astronaut riding a green horse",
|
| 75 |
+
"A delicious ceviche cheesecake slice",
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
def load_model_and_update(model_id, scheduler_name):
|
| 79 |
+
"""Called when user selects a model or scheduler: load and return new pipeline + status."""
|
| 80 |
+
try:
|
| 81 |
+
pipe = load_pipeline(model_id, scheduler_name)
|
| 82 |
+
return pipe, f"Loaded `{model_id}` (scheduler: {scheduler_name})"
|
| 83 |
+
except Exception as e:
|
| 84 |
+
return None, f"Error loading `{model_id}`: {e}"
|
| 85 |
|
| 86 |
+
|
| 87 |
+
def size_to_dims(size_str):
|
| 88 |
+
try:
|
| 89 |
+
w, h = map(int, size_str.split("x"))
|
| 90 |
+
# clamp to limits
|
| 91 |
+
w = min(max(256, w), MAX_IMAGE_SIZE)
|
| 92 |
+
h = min(max(256, h), MAX_IMAGE_SIZE)
|
| 93 |
+
return gr.Slider.update(value=w), gr.Slider.update(value=h)
|
| 94 |
+
except Exception:
|
| 95 |
+
return gr.Slider.update(value=512), gr.Slider.update(value=512)
|
| 96 |
|
| 97 |
|
|
|
|
| 98 |
def infer(
|
| 99 |
prompt,
|
| 100 |
negative_prompt,
|
|
|
|
| 104 |
height,
|
| 105 |
guidance_scale,
|
| 106 |
num_inference_steps,
|
| 107 |
+
pipe_state, # gr.State containing pipeline
|
| 108 |
progress=gr.Progress(track_tqdm=True),
|
| 109 |
):
|
| 110 |
+
if pipe_state is None:
|
| 111 |
+
return None, seed, "Model not loaded."
|
| 112 |
+
|
| 113 |
if randomize_seed:
|
| 114 |
seed = random.randint(0, MAX_SEED)
|
| 115 |
|
| 116 |
+
# create generator on proper device
|
| 117 |
+
if device.startswith("cuda"):
|
| 118 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 119 |
+
else:
|
| 120 |
+
generator = torch.Generator().manual_seed(seed)
|
| 121 |
|
| 122 |
+
try:
|
| 123 |
+
out = pipe_state(
|
| 124 |
+
prompt=prompt,
|
| 125 |
+
negative_prompt=negative_prompt if negative_prompt else None,
|
| 126 |
+
guidance_scale=float(guidance_scale),
|
| 127 |
+
num_inference_steps=int(num_inference_steps),
|
| 128 |
+
width=int(width),
|
| 129 |
+
height=int(height),
|
| 130 |
+
generator=generator,
|
| 131 |
+
)
|
| 132 |
+
image = out.images[0]
|
| 133 |
+
return image, seed, "OK"
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return None, seed, f"Inference error: {e}"
|
| 136 |
|
|
|
|
| 137 |
|
| 138 |
+
with gr.Blocks(css=css, title="Text-to-Image") as demo:
|
| 139 |
+
pipe_state = gr.State(value=default_pipe)
|
| 140 |
|
| 141 |
+
with gr.Column(elem_id="col-container"):
|
| 142 |
+
gr.Markdown("# Text-to-Image — demo")
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
with gr.Row():
|
| 145 |
+
model_selector = gr.Dropdown(
|
| 146 |
+
label="Model ID",
|
| 147 |
+
choices=MODEL_OPTIONS,
|
| 148 |
+
value=DEFAULT_MODEL,
|
| 149 |
+
interactive=True,
|
| 150 |
+
)
|
| 151 |
+
scheduler_selector = gr.Dropdown(
|
| 152 |
+
label="Scheduler",
|
| 153 |
+
choices=list(SCHEDULER_MAP.keys()),
|
| 154 |
+
value="default",
|
| 155 |
+
interactive=True,
|
| 156 |
+
)
|
| 157 |
|
| 158 |
+
status = gr.Markdown("Model status: ready" if default_pipe else "Model status: not loaded")
|
|
|
|
|
|
|
| 159 |
|
| 160 |
with gr.Row():
|
| 161 |
prompt = gr.Text(
|
|
|
|
| 165 |
placeholder="Enter your prompt",
|
| 166 |
container=False,
|
| 167 |
)
|
| 168 |
+
run_button = gr.Button("Run", variant="primary")
|
|
|
|
| 169 |
|
| 170 |
result = gr.Image(label="Result", show_label=False)
|
| 171 |
|
|
|
|
| 174 |
label="Negative prompt",
|
| 175 |
max_lines=1,
|
| 176 |
placeholder="Enter a negative prompt",
|
| 177 |
+
visible=True,
|
| 178 |
)
|
| 179 |
|
| 180 |
seed = gr.Slider(
|
|
|
|
| 182 |
minimum=0,
|
| 183 |
maximum=MAX_SEED,
|
| 184 |
step=1,
|
| 185 |
+
value=42,
|
| 186 |
)
|
| 187 |
|
| 188 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=False)
|
| 189 |
|
| 190 |
with gr.Row():
|
| 191 |
+
size_preset = gr.Dropdown(
|
| 192 |
+
label="Size preset",
|
| 193 |
+
choices=["512x512", "768x512", "1024x1024"],
|
| 194 |
+
value="512x512",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
width = gr.Slider(
|
| 198 |
label="Width",
|
| 199 |
minimum=256,
|
| 200 |
maximum=MAX_IMAGE_SIZE,
|
| 201 |
step=32,
|
| 202 |
+
value=512,
|
| 203 |
)
|
| 204 |
|
| 205 |
height = gr.Slider(
|
|
|
|
| 207 |
minimum=256,
|
| 208 |
maximum=MAX_IMAGE_SIZE,
|
| 209 |
step=32,
|
| 210 |
+
value=512,
|
| 211 |
)
|
| 212 |
|
| 213 |
with gr.Row():
|
| 214 |
guidance_scale = gr.Slider(
|
| 215 |
label="Guidance scale",
|
| 216 |
minimum=0.0,
|
| 217 |
+
maximum=20.0,
|
| 218 |
step=0.1,
|
| 219 |
+
value=7.0,
|
| 220 |
)
|
| 221 |
|
| 222 |
num_inference_steps = gr.Slider(
|
| 223 |
label="Number of inference steps",
|
| 224 |
minimum=1,
|
| 225 |
+
maximum=150,
|
| 226 |
step=1,
|
| 227 |
+
value=20,
|
| 228 |
)
|
| 229 |
|
| 230 |
gr.Examples(examples=examples, inputs=[prompt])
|
| 231 |
+
|
| 232 |
+
# Events
|
| 233 |
+
model_selector.change(
|
| 234 |
+
fn=load_model_and_update,
|
| 235 |
+
inputs=[model_selector, scheduler_selector],
|
| 236 |
+
outputs=[pipe_state, status],
|
| 237 |
+
queue=True,
|
| 238 |
+
)
|
| 239 |
+
scheduler_selector.change(
|
| 240 |
+
fn=load_model_and_update,
|
| 241 |
+
inputs=[model_selector, scheduler_selector],
|
| 242 |
+
outputs=[pipe_state, status],
|
| 243 |
+
queue=True,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
size_preset.change(fn=size_to_dims, inputs=size_preset, outputs=[width, height])
|
| 247 |
+
|
| 248 |
+
run_button.click(
|
| 249 |
fn=infer,
|
| 250 |
inputs=[
|
| 251 |
prompt,
|
|
|
|
| 256 |
height,
|
| 257 |
guidance_scale,
|
| 258 |
num_inference_steps,
|
| 259 |
+
pipe_state,
|
| 260 |
],
|
| 261 |
+
outputs=[result, seed, status],
|
| 262 |
+
queue=True,
|
| 263 |
)
|
| 264 |
|
| 265 |
if __name__ == "__main__":
|