Spaces:
Paused
Paused
Download app.py from PrunaAI/P-Q-Image-2.1-DWD: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/spaces/PrunaAI/P-Q-Image-2.1-DWD/resolve/main/app.py
- Command line
-
hf download hf://spaces/PrunaAI/P-Q-Image-2.1-DWD/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PrunaAI/P-Q-Image-2.1-DWD/resolve/main/app.py
14.4 kB
| """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) | |
| def _render_gpu(mode, prompt, images, width, height, seed): | |
| return _render(mode, prompt, images, width, height, seed) | |
| 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") | |
| 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("</", "<\\/")) | |
| def _logo(): | |
| return FileResponse(os.path.join(APP_DIR, "pruna-logo.png"), media_type="image/png") | |
| 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()}} | |
| 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) | |
| 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) | |