Spaces:
Running on Zero
Running on Zero
File size: 9,915 Bytes
edec983 | 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 | """Ming Layer Decomposition Studio — gr.Server API plus a gr.Workflow canvas."""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import base64
import binascii
import io
import re
import secrets
import time
import spaces # Must precede torch on ZeroGPU.
import gradio as gr
import torch
import uvicorn
from fastapi.responses import HTMLResponse
from gradio.utils import get_upload_folder
from urllib.parse import quote
from PIL import Image
from ming_engine import get_engine
APP_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_ID = "inclusionAI/Ming-Image-0.2-Design-Layer"
MAX_SEED = 2**31 - 1
MAX_PROMPT_CHARACTERS = 12_000
DEFAULT_LAYERS = 5
MAX_LAYERS = 12
# Public API values: (label, official working-resolution bucket).
RESOLUTIONS = {
"512 · fastest": 512,
"1024 · high quality": 1024,
}
def parse_num_layers(text: str) -> int:
"""Mirror the official infer.py prompt parser."""
match = re.search(r"decompose this image into\s+(\d+)\s+layers?", text.lower())
if match:
return int(match.group(1))
for line in text.splitlines():
stripped = line.strip().lower()
if stripped.startswith("number of layers:"):
try:
return int(stripped.split(":", 1)[1].strip())
except ValueError:
pass
return DEFAULT_LAYERS
def _duration(image_data, resolution, steps, guidance, seed, num_layers, spec, *args):
"""ZeroGPU duration estimate; generation outputs one frame per layer plus the composite."""
try:
fast = resolution == "512 · fastest"
steps_value = int(float(steps))
guidance_value = float(guidance)
layers = int(float(num_layers))
spec_text = (spec or "").strip()
if spec_text:
layers = parse_num_layers(spec_text)
duration = 120 if fast else 200
duration += max(0, layers - DEFAULT_LAYERS) * (12 if fast else 20)
duration += max(0, steps_value - 12) * (2 if fast else 4)
if guidance_value > 1.0:
duration += 20
except (TypeError, ValueError):
return 240
return min(480, max(90, int(duration)))
def _decode_image(image_data: str):
"""Accept a data URL or a bare base64 payload from the Studio frontend."""
payload = (image_data or "").strip()
if not payload:
raise gr.Error("Upload a poster, product shot, or character image first.")
if payload.startswith("data:"):
_, _, payload = payload.partition(",")
try:
raw = base64.b64decode(payload, validate=False)
except (binascii.Error, ValueError) as error:
raise gr.Error("Could not decode the uploaded image data.") from error
try:
return Image.open(io.BytesIO(raw))
except Exception as error:
raise gr.Error("The uploaded file is not a readable image.") from error
@spaces.GPU(duration=_duration, size="xlarge")
def _decompose(image_data, resolution, steps, guidance, seed, num_layers, spec):
"""The single GPU path shared by the Studio API and Workflow operator."""
if not torch.cuda.is_available():
raise gr.Error(
"This Space is on CPU. Assign ZeroGPU under Settings → Hardware; "
"decomposition already requests the 96 GB xlarge worker."
)
if resolution not in RESOLUTIONS:
raise gr.Error("Choose one of the listed working resolutions.")
try:
steps_value = int(float(steps))
guidance_value = float(guidance)
seed_value = int(float(seed))
layers_value = int(float(num_layers))
except (TypeError, ValueError) as error:
raise gr.Error("Sampling settings must be numbers.") from error
if not 1 <= steps_value <= 40:
raise gr.Error("Steps must be between 1 and 40.")
if not 1.0 <= guidance_value <= 8.0:
raise gr.Error("CFG must be between 1.0 and 8.0.")
if not 0 <= seed_value <= MAX_SEED:
raise gr.Error(f"Seed must be between 0 and {MAX_SEED}.")
spec = (spec or "").strip()
if spec:
if len(spec) > MAX_PROMPT_CHARACTERS:
raise gr.Error(f"Keep the layer specification under {MAX_PROMPT_CHARACTERS:,} characters.")
layers_value = parse_num_layers(spec)
if not 1 <= layers_value <= MAX_LAYERS:
raise gr.Error(f"Layer count must be between 1 and {MAX_LAYERS}.")
prompt = spec or f"Decompose this image into {layers_value} layers."
engine = get_engine()
resolution_bucket = RESOLUTIONS[resolution]
# Persist the upload so the official processor can read it by path.
folder = get_upload_folder()
os.makedirs(folder, exist_ok=True)
source_path = os.path.join(folder, f"ming_layer_input_{secrets.token_hex(8)}.png")
_decode_image(image_data).save(source_path, format="PNG")
started = time.perf_counter()
outputs = engine.generate(
prompt=prompt,
input_image=source_path,
resolution=resolution_bucket,
steps=steps_value,
guidance_scale=guidance_value,
seed=seed_value,
num_layers=layers_value,
)
elapsed = time.perf_counter() - started
try:
os.remove(source_path)
except OSError:
pass
composite_path = _publish(outputs[0], "composite")
layer_paths = [
_publish(image, f"layer_{index + 1:02d}")
for index, image in enumerate(outputs[1:])
]
info = (
f"{len(layer_paths)} layers · {resolution_bucket} bucket · "
f"{steps_value} steps · CFG {guidance_value:g} · {elapsed:.1f}s"
)
return composite_path, layer_paths, seed_value, info
def _run(*args):
try:
return _decompose(*args)
except (RuntimeError, ValueError, FileNotFoundError) as error:
raise gr.Error(str(error).split("\n")[0])
def _publish(image, prefix: str) -> str:
"""Persist an RGBA PNG where both Gradio frontends can serve it."""
folder = get_upload_folder()
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, f"ming_layer_{prefix}_{secrets.token_hex(8)}.png")
image.save(path, format="PNG")
return path
def _url(path: str) -> str:
return f"/gradio_api/file={quote(path, safe='/')}"
def _as_media(path: str) -> dict:
return {"path": path, "url": _url(path), "is_file": True}
def ming_decompose(image, resolution="512 · fastest", steps="12", guidance="2.0", seed="42", num_layers="5", spec="") -> dict:
"""Workflow operator: an input image and sampling settings to one composite RGBA canvas."""
image_data = _coerce_image(image)
composite_path, _, _, _ = _run(image_data, resolution, steps, guidance, seed, num_layers, spec)
return _as_media(composite_path)
def _coerce_image(value) -> str:
"""Normalize a workflow image value (file dict, local path, or data URL)."""
if isinstance(value, dict):
for key in ("url", "path"):
candidate = value.get(key)
if isinstance(candidate, str) and candidate:
value = candidate
break
else:
raise gr.Error("The workflow image input did not contain a usable file.")
if not isinstance(value, str) or not value:
raise gr.Error("The workflow image input is not a readable file.")
if value.startswith("data:"):
return value
marker = "/gradio_api/file="
path = value.split(marker, 1)[1] if marker in value else value
try:
with open(path, "rb") as handle:
raw = handle.read()
except OSError as error:
raise gr.Error(f"Could not read the workflow image input: {path}") from error
return "data:image/png;base64," + base64.b64encode(raw).decode("ascii")
# ZeroGPU recommends model placement at module scope. Plain CPU skips the 53 GB
# download; _decompose provides the guarded lazy fallback for other environments.
if torch.cuda.is_available():
get_engine()
# --------------------------------------------------------------- Studio server
server = gr.Server(title="Ming Layer Studio")
@server.get("/", response_class=HTMLResponse)
def _studio_page():
with open(os.path.join(APP_DIR, "studio.html"), encoding="utf-8") as handle:
return handle.read()
@server.api(name="decompose", concurrency_limit=1)
def api_decompose(
image_data: str,
resolution: str = "512 · fastest",
steps: float = 12,
guidance: float = 2.0,
seed: float = 42,
num_layers: float = 5,
spec: str = "",
) -> dict:
"""Studio endpoint returning served PNG URLs and decomposition metadata."""
composite_path, layer_paths, actual_seed, info = _run(
image_data, resolution, steps, guidance, seed, num_layers, spec
)
return {
"composite": _url(composite_path),
"layers": [_url(path) for path in layer_paths],
"seed": actual_seed,
"prompt": (spec or f"Decompose this image into {int(num_layers)} layers.").strip(),
"info": info,
}
# Register Server endpoints and the ZeroGPU hook on a loopback launch first.
# Mounting Workflow before this step can strand its queue on the closed loop.
_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_demo = gr.Workflow(
graph="workflow.json",
bind={"ming_decompose": ming_decompose},
)
workflow_demo.title = "Ming Layer 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)
|