File size: 5,883 Bytes
6307c74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Runtime adapter for the official inclusionAI/Ming-Image implementation.

The Layer checkpoint is a component package rather than a stock Diffusers
pipeline. This module downloads the authors' inference code at an immutable
commit, then uses their own model loader and generation entry point with the
layer-decompose task: one input image and a layer specification in, the
composite plus editable RGBA layers out.
"""

from __future__ import annotations

import importlib
import os
from pathlib import Path, PurePosixPath
import shutil
import sys
import tempfile
import threading
from types import SimpleNamespace
from typing import Any
import urllib.request
import zipfile

import torch

MODEL_ID = "inclusionAI/Ming-Image-0.2-Design-Layer"
SOURCE_COMMIT = "041945f5c36d20cbf0fc6debc0a810a747e19644"
SOURCE_URL = f"https://github.com/inclusionAI/Ming-Image/archive/{SOURCE_COMMIT}.zip"

_engine: Any = None
_engine_lock = threading.Lock()


def _safe_extract(archive: zipfile.ZipFile, destination: Path) -> None:
    """Reject absolute or parent-traversing paths before extracting."""
    for member in archive.infolist():
        path = PurePosixPath(member.filename)
        if path.is_absolute() or ".." in path.parts:
            raise RuntimeError(f"Unsafe path in official source archive: {member.filename}")
    archive.extractall(destination)


def _official_source_directory() -> Path:
    cache = Path(os.environ.get("HF_HOME", "/tmp/huggingface")) / "ming-image-source"
    cache.mkdir(parents=True, exist_ok=True)
    final_root = cache / f"Ming-Image-{SOURCE_COMMIT}"
    if (final_root / "infer.py").is_file():
        return final_root

    with tempfile.TemporaryDirectory(prefix="ming-source-", dir=cache) as temporary:
        temporary_path = Path(temporary)
        archive_path = temporary_path / "source.zip"
        request = urllib.request.Request(
            SOURCE_URL,
            headers={"User-Agent": "Ming-Image-Hugging-Face-Space/1.0"},
        )
        with urllib.request.urlopen(request, timeout=120) as response, archive_path.open("wb") as output:
            shutil.copyfileobj(response, output)

        extracted = temporary_path / "extracted"
        extracted.mkdir()
        with zipfile.ZipFile(archive_path) as archive:
            _safe_extract(archive, extracted)

        candidates = [
            path for path in extracted.iterdir()
            if path.is_dir() and (path / "infer.py").is_file()
        ]
        if len(candidates) != 1:
            raise RuntimeError("Could not locate infer.py in the official Ming-Image source archive")
        if final_root.exists():
            shutil.rmtree(final_root)
        candidates[0].rename(final_root)

    return final_root


def _load_official_module():
    source = _official_source_directory()
    source_string = str(source)
    if source_string not in sys.path:
        sys.path.insert(0, source_string)
    module = importlib.import_module("infer")
    if Path(module.__file__).resolve().parent != source.resolve():
        raise RuntimeError(f"Imported an unexpected infer module: {module.__file__}")
    return module


class OfficialMingEngine:
    """Owns the official model, processor, profile, and generation functions."""

    def __init__(self):
        self.runtime = _load_official_module()
        model_directory = self.runtime.resolve_model_directory(MODEL_ID)
        self.profile = self.runtime.load_checkpoint_capabilities(model_directory)
        self.profile.validate_task(
            "layer-decompose",
            has_reference_image=True,
            num_layers=1,
        )

        arguments = SimpleNamespace(
            processor=None,
            dtype="bfloat16",
            attn_implementation="eager",
            device="cuda",
            device_map="balanced",
            num_gpus=1,
            revision=None,
            cache_dir=None,
            local_files_only=False,
        )
        self.model, self.processor = self.runtime.load_model_and_processor(
            model_directory,
            arguments,
        )
        self.model.eval()
        self.model.requires_grad_(False)

    def generate(
        self,
        *,
        prompt: str,
        input_image,
        resolution: int,
        steps: int,
        guidance_scale: float,
        seed: int,
        num_layers: int,
    ):
        sampling = self.profile.resolve_sampling_parameters(
            steps=int(steps),
            cfg=float(guidance_scale),
        )
        self.profile.validate_task(
            "layer-decompose",
            has_reference_image=True,
            num_layers=int(num_layers),
        )
        with torch.inference_mode():
            images = self.runtime.run_generation(
                self.model,
                self.processor,
                self.profile,
                task="layer-decompose",
                prompt=prompt,
                input_image=input_image,
                resolution=int(resolution),
                sampling=sampling,
                seed=int(seed),
                num_layers=int(num_layers),
                dtype=torch.bfloat16,
            )
        expected_outputs = int(num_layers) + 1
        if len(images) != expected_outputs:
            raise RuntimeError(f"Expected {expected_outputs} output image(s), received {len(images)}")
        return images


def get_engine() -> OfficialMingEngine:
    """Load once per process; callers check CUDA availability before calling."""
    global _engine
    if _engine is None:
        with _engine_lock:
            if _engine is None:
                print(
                    f"Loading {MODEL_ID} with official Ming-Image code at {SOURCE_COMMIT}",
                    flush=True,
                )
                _engine = OfficialMingEngine()
                print("Ming-Image layer pipeline ready", flush=True)
    return _engine