Spaces:
Paused
Paused
File size: 14,397 Bytes
7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a 278b832 7a2334a | 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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | """P-Q-Image-2.1-DWD Studio — gr.Server studio + gr.Workflow canvas.
- "/" Studio: custom UI (studio.html) over the `generate` and `edit` API endpoints
- "/workflow" Workflow canvas: node graph from workflow.json (pq_dwd_generate, pq_dwd_edit)
Qwen-Image-2.1-Turbo with the DWD head: steps 1-7 are the stock model, and at the last step a fine-tuned copy of the
last 4 blocks and a linear pixel head write the image directly, so the last Euler step and the VAE decode never run.
"""
import base64
import io
import json
import os
import random
import time
from urllib.parse import unquote, urlparse
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import gradio as gr
import spaces
import torch
import uvicorn
from fastapi import HTTPException
from fastapi.responses import FileResponse, HTMLResponse
from gradio.utils import get_upload_folder
from gradio_client import utils as client_utils
from PIL import Image, ImageOps
from pq_image_dwd import DWDPipeline
from pq_image_dwd.encoders import calculate_dimensions
APP_DIR = os.path.dirname(os.path.abspath(__file__))
EXAMPLES_DIR = os.path.join(APP_DIR, "examples")
# The tail: a repo id, a local dwd_tail.safetensors or a directory holding it (DWD_TAIL overrides, for local runs).
TAIL = os.environ.get("DWD_TAIL", "PrunaAI/P-Q-Image-2.1-DWD")
BASE = os.environ.get("DWD_BASE", "Qwen/Qwen-Image-2.1-Turbo")
# Log peak GPU memory after every run (on by default; set LOG_MEMORY=0 in the Space variables to turn it off).
LOG_MEMORY = os.environ.get("LOG_MEMORY", "1") != "0"
MAX_SEED = 2**31 - 1
MAX_IMAGES = 4 # the source and up to 3 extra condition images
# The evaluated sizes (width, height) from the model card: about 1 MP (the training size) and the model's 2K sizes.
# Other ratios run at the same area (sides rounded to 32), but were not evaluated.
RATIOS = {"1:1": 1.0, "4:3": 4 / 3, "3:4": 3 / 4, "3:2": 3 / 2, "2:3": 2 / 3, "16:9": 16 / 9, "9:16": 9 / 16}
RESOLUTIONS = {"1 MP": 1024, "2K": 2048}
EVALUATED = {
"1 MP": {"1:1": (1024, 1024), "4:3": (1152, 896), "3:4": (896, 1152), "16:9": (1344, 768), "9:16": (768, 1344)},
"2K": {"1:1": (2048, 2048), "3:2": (2528, 1696), "2:3": (1696, 2528), "16:9": (2752, 1536), "9:16": (1536, 2752)},
}
def _size(aspect: str, resolution: str) -> tuple[int, int]:
if aspect in EVALUATED[resolution]:
return EVALUATED[resolution][aspect]
side = RESOLUTIONS[resolution]
return calculate_dimensions(side * side, RATIOS[aspect])
# ------------------------------------------------------------------ pipeline
# The VAE is loaded for its encoder (edit condition images); its decoder never runs.
PIPE = DWDPipeline.from_pretrained(TAIL, base=BASE, device="cuda", load_vae=True)
def _sync():
torch.cuda.synchronize()
def _render(mode, prompt, images, width, height, seed):
"""One run on the GPU -> (DWD image, timing dict)."""
PIPE._plan = None # sampler tensors live on the device: rebuild them in this GPU call
h, w = height // 16, width // 16
torch.cuda.reset_peak_memory_stats()
_sync()
start = time.perf_counter()
cond = PIPE.encode(prompt, images if mode == "edit" else None)
lat, _ = PIPE.denoise(cond, h, w, seed)
_sync()
shared = time.perf_counter() - start
begin = time.perf_counter()
dwd = PIPE.last_step_dwd(lat, cond, h, w)[0].cpu()
_sync()
timing = {"shared": shared, "dwd": time.perf_counter() - begin}
if LOG_MEMORY:
gb = 1024**3
free, total = torch.cuda.mem_get_info()
print(f"[memory] {mode} {width}x{height}, {len(images)} image(s): "
f"peak allocated {torch.cuda.max_memory_allocated() / gb:.1f} GB, "
f"peak reserved {torch.cuda.max_memory_reserved() / gb:.1f} GB, "
f"device total {total / gb:.1f} GB", flush=True)
return Image.fromarray(dwd.numpy()), timing
def _duration(mode, prompt, images, width, height, seed):
base = 25 if width * height <= 1.5 * 1024**2 else 45
return base + (10 * len(images) if mode == "edit" else 0)
@spaces.GPU(size="xlarge", duration=_duration)
def _render_gpu(mode, prompt, images, width, height, seed):
return _render(mode, prompt, images, width, height, seed)
@spaces.GPU(size="xlarge", duration=180)
def _warmup():
"""Kernels and allocator warm before the first visitor."""
_render("t2i", "a lighthouse on a cliff at dusk", [], 1024, 1024, 0)
_render("edit", "make it night", [Image.new("RGB", (1024, 1024), (120, 140, 160))], 1024, 1024, 0)
try:
_warmup()
except Exception as error: # noqa: BLE001 - the demo still works, the first request just pays the warmup
print(f"warmup failed: {error!r}", flush=True)
def _run(mode, prompt, images, width, height, seed):
"""One GPU call with the classic app's error surface: messages, not stack traces."""
try:
return _render_gpu(mode, prompt, images, width, height, seed)
except (RuntimeError, ValueError) as error:
raise gr.Error(str(error).split("\n")[0])
def _info(size, seed, timing) -> str:
head = f"{size[0]}×{size[1]}, seed {seed}"
dwd_ms, shared = timing["dwd"] * 1000, timing["shared"]
return f"{head} · {shared + timing['dwd']:.1f} s on the GPU · DWD last step {dwd_ms:.0f} ms (no VAE decode)"
# ------------------------------------------------------------------ helpers
def _seed(seed) -> int:
try:
return min(max(int(float(seed)), 0), MAX_SEED)
except (TypeError, ValueError):
return 42
def _resolve_seed(seed, randomize) -> int:
return random.randint(0, MAX_SEED) if randomize else _seed(seed)
def _check_choice(value, choices, name):
if value not in choices:
raise gr.Error(f"{name} must be one of: {', '.join(choices)}.")
return value
def _requested_path(value) -> str:
"""Turn whatever the canvas/API client sends into a path."""
if isinstance(value, str):
return value
if not isinstance(value, dict):
raise gr.Error(f"Expected an image, got {type(value).__name__}")
if path := value.get("path"):
return path
url = value.get("url") or ""
if "/gradio_api/file=" in url:
return unquote(url.split("/gradio_api/file=", 1)[1])
if url.startswith(("http://", "https://")):
raise gr.Error("Upload the image instead of passing a URL.")
return unquote(urlparse(url).path)
def _local_path(value) -> str:
"""A path this process may open: only files inside gradio's upload folder,
where /gradio_api/upload puts uploads and _publish puts results."""
path = os.path.realpath(_requested_path(value))
folder = os.path.realpath(get_upload_folder())
if os.path.commonpath([path, folder]) != folder:
raise gr.Error("Upload the image first.")
return path
def _open_rgb(value) -> Image.Image:
return ImageOps.exif_transpose(Image.open(_local_path(value))).convert("RGB")
def _as_text(value) -> str:
if value is None or isinstance(value, bool):
return ""
if isinstance(value, dict):
for key in ("text", "value", "prompt", "out", "in"):
item = value.get(key)
if isinstance(item, str) and item.strip():
return item.strip()
return ""
return str(value).strip()
def _as_data_uri(image: Image.Image) -> str:
"""Inline a result image so the studio page never needs a file route."""
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=95)
return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode()
def _publish(image: Image.Image) -> str:
"""Save a result into gradio's upload folder, which it already serves, so the workflow canvas can render it."""
folder = get_upload_folder()
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, f"pq_dwd_{os.urandom(8).hex()}.png")
image.save(path)
return path
def _as_media(path: str) -> dict:
"""The dict shape the workflow canvas renders media from."""
return {"path": path, "url": f"/gradio_api/file={client_utils.encode_file_path(path)}", "is_file": True}
def _edit_size(source: Image.Image, resolution: str) -> tuple[int, int]:
"""The source's aspect ratio at the chosen area, sides multiples of 32 (the stock pipeline's sizing)."""
side = RESOLUTIONS[resolution]
return calculate_dimensions(side * side, source.width / source.height)
def _generate(prompt, aspect, resolution, seed):
_check_choice(aspect, RATIOS, "Aspect ratio")
_check_choice(resolution, RESOLUTIONS, "Resolution")
width, height = _size(aspect, resolution)
return _run("t2i", prompt, [], width, height, seed), (width, height)
def _edit(images, instruction, resolution, seed):
_check_choice(resolution, RESOLUTIONS, "Resolution")
width, height = _edit_size(images[0], resolution)
return _run("edit", instruction, images, width, height, seed), (width, height)
# ------------------------------------------------------------------ workflow fns
def pq_dwd_generate(prompt, aspect: str = "1:1", resolution: str = "2K", seed: str = "42") -> dict:
"""Text-to-image with P-Q-Image-2.1-DWD (no VAE decode)."""
prompt = _as_text(prompt)
if not prompt:
raise gr.Error("Write a prompt first.")
(dwd, _), _ = _generate(prompt, _as_text(aspect) or "1:1", _as_text(resolution) or "2K", _seed(seed))
return _as_media(_publish(dwd))
def pq_dwd_edit(image, prompt, seed: str = "42") -> dict:
"""Edit an image with P-Q-Image-2.1-DWD at about 1 MP, at the image's aspect ratio (no VAE decode)."""
prompt = _as_text(prompt)
if not prompt:
raise gr.Error("Describe the edit first.")
(dwd, _), _ = _edit([_open_rgb(image)], prompt, "1 MP", _seed(seed))
return _as_media(_publish(dwd))
# ------------------------------------------------------------------ studio server
with open(os.path.join(APP_DIR, "examples.json"), encoding="utf-8") as handle:
EXAMPLES = json.load(handle)
EXAMPLE_FILES = {ex["file"] for ex in EXAMPLES["edit"]}
server = gr.Server(title="P-Q-Image-2.1-DWD Studio")
@server.get("/", response_class=HTMLResponse)
def _studio_page():
with open(os.path.join(APP_DIR, "studio.html"), encoding="utf-8") as handle:
page = handle.read()
config = {
"name": "P-Q-Image-2.1-DWD",
"modelCard": "https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD",
"comfy": "https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD-Comfy",
"baseName": "Qwen-Image-2.1-Turbo",
"edit": True,
"examples": EXAMPLES,
"ratios": list(RATIOS),
"resolutions": list(RESOLUTIONS),
"defaultResolution": "2K",
"editResolutions": ["1 MP", "2K"],
"evaluated": EVALUATED,
"dwdLabel": "DWD last step (no VAE)",
"sharedLabel": "Prompt encoding and steps 1-7",
}
return page.replace("__STUDIO_CONFIG__", json.dumps(config).replace("</", "<\\/"))
@server.get("/pruna-logo.png")
def _logo():
return FileResponse(os.path.join(APP_DIR, "pruna-logo.png"), media_type="image/png")
@server.get("/examples/{name}")
def _example_file(name: str):
if name not in EXAMPLE_FILES:
raise HTTPException(status_code=404)
return FileResponse(os.path.join(EXAMPLES_DIR, name))
def _payload(dwd, timing, size, seed) -> dict:
return {"image_data": _as_data_uri(dwd), "seed": seed, "info": _info(size, seed, timing),
"timing_ms": {k: round(v * 1000) for k, v in timing.items()}}
@server.api(name="generate", concurrency_limit=1)
def api_generate(
prompt: str,
aspect: str = "1:1",
resolution: str = "2K",
seed: float = 42,
randomize: bool = True,
) -> dict:
"""Text-to-image with P-Q-Image-2.1-DWD (no VAE decode)."""
if not prompt or not prompt.strip():
raise gr.Error("Write a prompt first.")
seed_value = _resolve_seed(seed, randomize)
(dwd, timing), size = _generate(prompt.strip(), aspect, resolution, seed_value)
return _payload(dwd, timing, size, seed_value)
@server.api(name="edit", concurrency_limit=1)
def api_edit(
source: str,
instruction: str,
ref2: str | None = None,
ref3: str | None = None,
ref4: str | None = None,
resolution: str = "1 MP",
seed: float = 42,
randomize: bool = True,
) -> dict:
"""Edit the source (+ up to 3 extra condition images) with P-Q-Image-2.1-DWD, at the source's aspect ratio
(no VAE decode)."""
if not source:
raise gr.Error("Upload a source image first.")
if not instruction or not instruction.strip():
raise gr.Error("Describe the edit first.")
images = [_open_rgb(path) for path in (source, ref2, ref3, ref4) if path]
if len(images) > MAX_IMAGES:
raise gr.Error(f"At most {MAX_IMAGES} images.")
seed_value = _resolve_seed(seed, randomize)
(dwd, timing), size = _edit(images, instruction.strip(), resolution, seed_value)
return _payload(dwd, timing, size, seed_value)
# The @server.api endpoints are deferred until Server.launch(), which also fires
# the ZeroGPU registration hook (pack weights + startup report) through the
# patched Blocks.launch path. Launch on a loopback port for registration, then
# serve the same app via uvicorn.
_port_env = os.environ.get("GRADIO_SERVER_PORT")
os.environ["GRADIO_SERVER_PORT"] = "7861"
try:
server.launch(
prevent_thread_lock=True,
server_name="127.0.0.1",
server_port=7861,
quiet=True,
show_error=False,
ssr_mode=False,
)
finally:
if _port_env is None:
del os.environ["GRADIO_SERVER_PORT"]
else:
os.environ["GRADIO_SERVER_PORT"] = _port_env
try:
server.close()
except Exception:
pass
# ------------------------------------------------------------------ workflow canvas
# Mounted only after the registration launch above. Mounting first starts the
# workflow's queue on the loopback server's event loop, and close() then strands
# it: jobs are accepted on port 7860 but never run.
workflow_demo = gr.Workflow(
graph="workflow.json",
bind={"pq_dwd_generate": pq_dwd_generate, "pq_dwd_edit": pq_dwd_edit},
)
workflow_demo.title = "P-Q-Image-2.1-DWD Workflow"
server = gr.mount_gradio_app(server, workflow_demo, path="/workflow", ssr_mode=False)
if __name__ == "__main__":
uvicorn.run(server, host="0.0.0.0", port=7860)
|