"""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)