File size: 21,780 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#!/usr/bin/env python3
"""MOSS-Image text-to-image server for CT 140: OpenMOSS-Team/MOSS-Image-SFT (Apache-2.0, 5B DiT + Qwen3.5-9B text encoder + FLUX.2 VAE)
on the Arc GPU through OpenVINO, behind one gateway aux route.

  POST /v1/mossimage   JSON {"prompt": "..." | {layout object}, "width": 1024, "height": 1024, "steps": 30, ...}   ->  JSON (+ image files)
  GET  /health         200 once the DiT is in memory and the text encoder has run once (the gateway waits for it)

The gateway replays the body byte for byte and keeps only a text/JSON answer, so the images are files: they are written into the
job's output dir (header x-job-out-dir, set by the gateway) and listed in `files`; the caller downloads them with
GET /v1/jobs/<id>/files/<name>. Called directly (no gateway) they land in $MOSSIMAGE_OUT_DIR/<random>. See the gateway's docs/MOSSIMAGE.md.
"""
import argparse
import asyncio
import gc
import io
import json
import os
import random
import sys
import tempfile
import threading
import time
import uuid

from aiohttp import web

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from moss_pipeline import VARIANTS, Cancelled, MAX_TEXT_TOKENS, MossImage  # noqa: E402

MODEL_NAME = "MOSS-Image-SFT"
MODEL_NAMES = {"sft": "MOSS-Image-SFT", "sft-int8": "MOSS-Image-SFT (int8 weights, ffn_down in fp16)",
               "edit": "MOSS-Image-SFT + Moss-Image-Edit LoRA (merged, fp16)", "edit-int8": "MOSS-Image-SFT + Moss-Image-Edit LoRA (merged, int8 weights, ffn_down in fp16)"}
MIN_SIDE, MAX_SIDE = 256, 2048
MAX_PIXELS = 1536 * 1152          # 1.77 MP: the DiT's scratch memory grows with the token count; this is the largest size that fits the 24 GB card with margin (fp16 models)
MAX_STEPS = 100
MAX_IMAGES = 4
FORMATS = {"png": ("PNG", "png"), "jpeg": ("JPEG", "jpg"), "webp": ("WEBP", "webp")}
MODELS_DIR = os.environ.get("MOSSIMAGE_MODELS_DIR", os.path.join(os.path.dirname(HERE), "models"))
CACHE_DIR = os.environ.get("MOSSIMAGE_CACHE_DIR", os.path.join(os.path.dirname(HERE), "cache"))


def log(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


class Bad(Exception):
    """A request the caller must fix: answered as 4xx {"error": ...}, which the gateway passes through."""

    def __init__(self, msg, code=400):
        super().__init__(msg)
        self.code = code


class State:
    pipe = None
    device = "GPU"
    ready = False
    gpu = threading.Lock()      # one generation at a time inside the service, whatever the gateway does


def number(body, key, default, lo, hi, integer=False):
    v = body.get(key, default)
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not lo <= v <= hi or (integer and int(v) != v):
        raise Bad(f"`{key}` must be {'an integer' if integer else 'a number'} in [{lo}, {hi}]")
    return int(v) if integer else float(v)


def prompt_text(v, field):
    """A prompt is a string, or a layout object/list that is serialised the way the model was trained on (ensure_ascii=False)."""
    if isinstance(v, (dict, list)):
        v = json.dumps(v, ensure_ascii=False)
    if not isinstance(v, str):
        raise Bad(f"`{field}` must be a string (or a layout object)")
    return v


def check_size(width, height, max_pixels=MAX_PIXELS):
    if width % 16 or height % 16:
        raise Bad("`width` and `height` must be multiples of 16")
    if not (MIN_SIDE <= width <= MAX_SIDE and MIN_SIDE <= height <= MAX_SIDE):
        raise Bad(f"`width` and `height` must be between {MIN_SIDE} and {MAX_SIDE}")
    if width * height > max_pixels:
        eg = "1536x1536, 2048x1152, 1792x1280" if max_pixels > MAX_PIXELS else "1536x1152, 1280x1280, 1792x960, 2048x864"
        raise Bad(f"{width}x{height} is {width * height / 1e6:.2f} MP; the limit is {max_pixels / 1e6:.2f} MP (e.g. {eg}): "
                  "the card runs out of memory above it")


def work(body, ctx):
    prompt = body.get("prompt")
    if prompt is None or prompt == "":
        raise Bad("`prompt` is required: text, or a layout object (summary / items / bbox_format / bbox_coord_space)")
    prompt = prompt_text(prompt, "prompt")
    if not prompt.strip():
        raise Bad("`prompt` is empty")
    variant = body.get("model", "sft")
    if not isinstance(variant, str) or variant not in VARIANTS:
        raise Bad(f"`model` must be one of: {', '.join(VARIANTS)}")
    installed = State.pipe.installed_variants()
    if variant not in installed:
        raise Bad(f"model `{variant}` is not installed on this server; installed: {', '.join(installed)}")
    vcfg = VARIANTS[variant]
    if vcfg["sampler"] == "edit":
        return work_edit(body, ctx, prompt, variant, vcfg)
    if body.get("image") is not None or body.get("images") is not None:
        raise Bad(f"`image` / `images` are for editing: use \"model\": \"edit\" (or \"edit-int8\"); `{variant}` is text-to-image")
    negative = prompt_text(body.get("negative_prompt", ""), "negative_prompt")
    width = number(body, "width", 1024, 16, 100000, integer=True)
    height = number(body, "height", 1024, 16, 100000, integer=True)
    check_size(width, height, vcfg.get("max_pixels", MAX_PIXELS))
    steps = number(body, "steps", vcfg["default_steps"], 1, vcfg["max_steps"], integer=True)
    guidance = number(body, "guidance", 3.0, 0.0, 15.0)
    n = number(body, "n", 1, 1, MAX_IMAGES, integer=True)
    seed = body.get("seed")
    if seed is None:
        seed = random.randrange(0, 2**31 - 1 - MAX_IMAGES)
    else:
        seed = number(body, "seed", None, 0, 2**31 - 1 - MAX_IMAGES, integer=True)
    fmt = body.get("format", "png")
    if fmt not in FORMATS:
        raise Bad(f"`format` must be one of: {', '.join(FORMATS)}")
    quality = number(body, "quality", 95, 1, 100, integer=True)
    skip = body.get("uncond_skip", True)
    if not isinstance(skip, bool):
        raise Bad("`uncond_skip` must be true or false")
    for key, val in (("prompt", prompt), ("negative_prompt", negative)):
        if val:
            count = State.pipe.token_count(val)
            if count > MAX_TEXT_TOKENS:
                raise Bad(f"`{key}` is {count} tokens; the limit is {MAX_TEXT_TOKENS}")
    t = time.time()
    images, rows = [], []
    stats = None
    cancel = ctx.get("cancel")
    from PIL import Image, PngImagePlugin

    with State.gpu:
        for i in range(n):
            s = seed + i
            marks = [0]

            def progress(done, total, i=i):
                if done - marks[0] >= 10 or done == total:
                    marks[0] = done
                    log(f"  image {i + 1}/{n} step {done}/{total} ({time.time() - t:.0f} s)")

            img, st = State.pipe.generate(prompt, negative, width, height, steps, guidance, s, skip_uncond_block=skip, progress=progress,
                                          cancel=(cancel.is_set if cancel is not None else None), variant=variant)
            if not st["finite"]:
                raise RuntimeError("the sampler produced non-finite values (fp16 overflow); try another seed or a smaller size")
            name = f"image.{FORMATS[fmt][1]}" if n == 1 else f"image_{i + 1}.{FORMATS[fmt][1]}"
            im = Image.fromarray(img)
            kw = {}
            if fmt == "png":
                info = PngImagePlugin.PngInfo()
                info.add_text("parameters", json.dumps({"model": variant, "prompt": prompt, "negative_prompt": negative, "seed": s, "steps": steps,
                                                        "guidance": guidance, "width": width, "height": height}, ensure_ascii=False))
                kw["pnginfo"] = info
            elif fmt == "jpeg":
                kw.update(quality=quality)
            else:
                kw.update(quality=quality, method=4)
            im.save(os.path.join(ctx["out_dir"], name), FORMATS[fmt][0], **kw)
            images.append(name)
            rows.append({"file": name, "seed": s})
            stats = st
    took = time.time() - t
    gc.collect()
    return {"files": images, "images": rows, "model": variant, "model_name": MODEL_NAMES[variant], "width": width, "height": height, "steps": stats["steps"], "steps_requested": steps,
            "guidance": guidance, "negative_prompt": negative, "uncond_skip": skip, "format": fmt, "n": n, "seed": seed,
            "prompt_tokens": stats["tokens_prompt"], "negative_tokens": stats["tokens_negative"],
            "seconds": round(took, 2), "text_encoder_seconds": stats["text_encoder_s"], "denoise_seconds": stats["denoise_s"],
            "seconds_per_step": stats["s_per_step"], "model_load_seconds": stats.get("dit_load_s", 0.0), "vae_seconds": stats["vae_s"], "peak_gpu_mb": stats["peak_gpu_usm_device_mb"],
            "job": ctx["job"], "device": State.device}


EDIT_MAX_REFS = 1                     # extra reference pictures (the LoRA takes up to 3) are not offered: their memory and results were not measured
EDIT_DEFAULT_PIXELS = 1024 * 1024     # image 1 is scaled to about this many pixels when no width/height is given (the authors' 1024 px default)
EDIT_MAX_INPUT_MP = 40


def decode_image(v, field):
    """base64 or data: URL -> RGB PIL image (EXIF orientation applied)."""
    import base64
    import binascii

    from PIL import Image, ImageOps

    if not isinstance(v, str) or not v:
        raise Bad(f"`{field}` must be a base64 string or a data: URL")
    if v.startswith("data:"):
        v = v.split(",", 1)[1] if "," in v else ""
    try:
        raw = base64.b64decode(v, validate=False)
        Image.MAX_IMAGE_PIXELS = EDIT_MAX_INPUT_MP * 10**6
        im = Image.open(io.BytesIO(raw))
        im = ImageOps.exif_transpose(im)
        if im.mode in ("RGBA", "LA", "P"):
            im = im.convert("RGBA")
            bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
            im = Image.alpha_composite(bg, im)
        return im.convert("RGB")
    except (binascii.Error, ValueError, OSError, Image.DecompressionBombError) as e:
        raise Bad(f"`{field}` is not a readable image ({type(e).__name__}: {str(e)[:120]}); limit {EDIT_MAX_INPUT_MP} MP") from None


def _round16(x, lo=MIN_SIDE):
    return max(lo, int(round(x / 16)) * 16)


def edit_size(w0, h0, max_pixels):
    """Default output size for an edit: image 1's aspect ratio at about EDIT_DEFAULT_PIXELS (never above the model limit, sides 256-2048, multiples of 16).
    Smaller pictures are enlarged to it too: the edit LoRA was trained at that scale."""
    target = min(EDIT_DEFAULT_PIXELS, max_pixels)
    s = (target / (w0 * h0)) ** 0.5
    w, h = _round16(w0 * s), _round16(h0 * s)
    while w * h > max_pixels or w > MAX_SIDE or h > MAX_SIDE:
        s *= 0.98
        w, h = _round16(w0 * s), _round16(h0 * s)
    return min(w, MAX_SIDE), min(h, MAX_SIDE)


def work_edit(body, ctx, prompt, variant, vcfg):
    import numpy as np
    from PIL import Image, PngImagePlugin

    warnings = []
    imgs = body.get("images")
    if imgs is None:
        imgs = [body.get("image")] if body.get("image") is not None else []
    elif body.get("image") is not None:
        raise Bad("give `image` (one picture) or `images` (a list), not both")
    if not isinstance(imgs, list) or not 1 <= len(imgs) <= EDIT_MAX_REFS:
        raise Bad(f"model `{variant}` edits ONE picture: `image` (base64 or data: URL) is required; `images` takes at most {EDIT_MAX_REFS} "
                  "(extra reference pictures are not offered: untested, memory not measured)")
    pics = [decode_image(v, f"images[{i}]" if body.get("images") is not None else "image") for i, v in enumerate(imgs)]
    max_pixels = vcfg.get("max_pixels", MAX_PIXELS)
    w0, h0 = pics[0].size
    if body.get("width") is None and body.get("height") is None:
        width, height = edit_size(w0, h0, max_pixels)
    else:
        if body.get("width") is None or body.get("height") is None:
            raise Bad("give both `width` and `height`, or neither (then the size follows image 1)")
        width = number(body, "width", None, 16, 100000, integer=True)
        height = number(body, "height", None, 16, 100000, integer=True)
        if width % 16 or height % 16:
            raise Bad("`width` and `height` must be multiples of 16")
        if not (MIN_SIDE <= width <= MAX_SIDE and MIN_SIDE <= height <= MAX_SIDE):
            raise Bad(f"`width` and `height` must be between {MIN_SIDE} and {MAX_SIDE}")
        if width * height > max_pixels:
            raise Bad(f"{width}x{height} is {width * height / 1e6:.2f} MP; model `{variant}` edits at most {max_pixels / 1e6:.2f} MP "
                      f"(e.g. {int(max_pixels ** 0.5) // 16 * 16}x{int(max_pixels ** 0.5) // 16 * 16}): the card runs out of memory above it")
        if abs((width / height) / (w0 / h0) - 1) > 0.02:
            warnings.append(f"width/height {width}x{height} has another aspect ratio than image 1 ({w0}x{h0}): image 1 is stretched to it")
    if w0 * h0 < width * height / 4:
        warnings.append(f"image 1 ({w0}x{h0}) is enlarged more than 2x to {width}x{height}: expect a soft result")
    # image 1 = the canvas, at exactly the output size (an edit keeps the picture only when reference and target have the same size);
    # images 2-3 keep their aspect, long side = the output's long side
    arrs = [np.asarray(pics[0].resize((width, height), Image.LANCZOS))]
    long_side = max(width, height)
    for p in pics[1:]:
        s = long_side / max(p.size)
        arrs.append(np.asarray(p.resize((_round16(p.size[0] * s, 16), _round16(p.size[1] * s, 16)), Image.LANCZOS)))
    if len(arrs) > 1:
        warnings.append("more than one reference image: the edit LoRA was only checked here with one (image 1); results with 2-3 are untested")
    negative = prompt_text(body.get("negative_prompt", ""), "negative_prompt")
    steps = number(body, "steps", vcfg["default_steps"], 1, vcfg["max_steps"], integer=True)
    guidance = number(body, "guidance", vcfg.get("default_guidance", 4.0), 0.0, 15.0)
    n = number(body, "n", 1, 1, MAX_IMAGES, integer=True)
    seed = body.get("seed")
    if seed is None:
        seed = random.randrange(0, 2**31 - 1 - MAX_IMAGES)
    else:
        seed = number(body, "seed", None, 0, 2**31 - 1 - MAX_IMAGES, integer=True)
    fmt = body.get("format", "png")
    if fmt not in FORMATS:
        raise Bad(f"`format` must be one of: {', '.join(FORMATS)}")
    quality = number(body, "quality", 95, 1, 100, integer=True)
    skip = body.get("uncond_skip", True)
    if not isinstance(skip, bool):
        raise Bad("`uncond_skip` must be true or false")
    for key, val in (("prompt", prompt), ("negative_prompt", negative)):
        if val:
            count = State.pipe.token_count(val)
            if count > MAX_TEXT_TOKENS:
                raise Bad(f"`{key}` is {count} tokens; the limit is {MAX_TEXT_TOKENS}")
    t = time.time()
    rows, files = [], []
    stats = None
    cancel = ctx.get("cancel")
    with State.gpu:
        State.pipe.select_variant(variant)
        State.pipe.peak_gpu_mb = 0
        t_enc = time.time()
        ref_lat = State.pipe.encode_images(arrs)
        enc_s = round(time.time() - t_enc, 2)
        for i in range(n):
            s = seed + i
            marks = [0]

            def progress(done, total, i=i):
                if done - marks[0] >= 10 or done == total:
                    marks[0] = done
                    log(f"  edit {i + 1}/{n} step {done}/{total} ({time.time() - t:.0f} s)")

            img, st = State.pipe.generate_edit(None, prompt, negative, width, height, steps, guidance, s, skip_uncond_block=skip, progress=progress,
                                               cancel=(cancel.is_set if cancel is not None else None), ref_latents=ref_lat, keep_peak=(i == 0),
                                               release_dit=(i == n - 1))
            if not st["finite"]:
                raise RuntimeError("the sampler produced non-finite values (fp16 overflow); try another seed or a smaller size")
            name = f"edit.{FORMATS[fmt][1]}" if n == 1 else f"edit_{i + 1}.{FORMATS[fmt][1]}"
            im = Image.fromarray(img)
            kw = {}
            if fmt == "png":
                info = PngImagePlugin.PngInfo()
                info.add_text("parameters", json.dumps({"model": variant, "prompt": prompt, "negative_prompt": negative, "seed": s, "steps": steps,
                                                        "guidance": guidance, "width": width, "height": height, "references": len(arrs)}, ensure_ascii=False))
                kw["pnginfo"] = info
            elif fmt == "jpeg":
                kw.update(quality=quality)
            else:
                kw.update(quality=quality, method=4)
            im.save(os.path.join(ctx["out_dir"], name), FORMATS[fmt][0], **kw)
            files.append(name)
            rows.append({"file": name, "seed": s})
            stats = st
    took = time.time() - t
    gc.collect()
    return {"files": files, "images": rows, "mode": "edit", "model": variant, "model_name": MODEL_NAMES[variant], "width": width, "height": height,
            "input_sizes": [list(p.size) for p in pics], "reference_sizes": [[a.shape[1], a.shape[0]] for a in arrs],
            "steps": stats["steps"], "steps_requested": steps, "guidance": guidance, "negative_prompt": negative, "uncond_skip": skip, "format": fmt,
            "n": n, "seed": seed, "prompt_tokens": stats["tokens_prompt"], "negative_tokens": stats["tokens_negative"], "reference_tokens": stats["ref_tokens"],
            "seconds": round(took, 2), "text_encoder_seconds": stats["text_encoder_s"], "vae_encode_seconds": enc_s, "prefill_seconds": stats["prefill_s"],
            "denoise_seconds": stats["denoise_s"], "seconds_per_step": stats["s_per_step"], "model_load_seconds": stats.get("dit_load_s", 0.0),
            "vae_seconds": stats["vae_s"], "peak_gpu_mb": stats["peak_gpu_usm_device_mb"], "warnings": warnings, "job": ctx["job"], "device": State.device}


async def mossimage(request):
    try:
        body = await request.json()
    except ValueError:
        return web.json_response({"error": "body is not valid JSON"}, status=400)
    if not isinstance(body, dict):
        return web.json_response({"error": "body must be a JSON object"}, status=400)
    if not State.ready:
        return web.json_response({"error": "the service is still loading its models; retry in a minute"}, status=503)
    t = time.time()
    out_dir = request.headers.get("x-job-out-dir")
    if not out_dir:                          # called without the gateway: keep the files where the caller can find them
        out_dir = os.path.join(os.environ.get("MOSSIMAGE_OUT_DIR") or os.path.join(tempfile.gettempdir(), "mossimage-out"), uuid.uuid4().hex[:12])
    os.makedirs(out_dir, exist_ok=True)
    cancel = threading.Event()
    ctx = {"out_dir": out_dir, "job": request.headers.get("x-job-id"), "cancel": cancel}
    fut = asyncio.get_running_loop().run_in_executor(None, work, body, ctx)
    fut.add_done_callback(lambda f: None if f.cancelled() else f.exception())      # mark a late error (after a hang-up) as retrieved
    try:
        out = await asyncio.shield(fut)
    except asyncio.CancelledError:           # the caller hung up: stop denoising at the next step
        cancel.set()
        raise
    except Bad as e:
        return web.json_response({"error": str(e)}, status=e.code)
    except Cancelled:
        return web.json_response({"error": "cancelled"}, status=499)
    except Exception as e:
        log("generation failed:", repr(e))
        msg = f"{type(e).__name__}: {e}"
        return web.json_response({"error": msg[:600]}, status=500)
    if not request.headers.get("x-job-out-dir"):
        out["out_dir"] = out_dir
    log(f"{out['n']} image(s) {out['width']}x{out['height']} {out['steps']} steps in {time.time() - t:.1f} s")
    return web.json_response(out)


async def health(request):
    if not State.ready:
        return web.json_response({"ok": False, "loading": True}, status=503)
    return web.json_response({"ok": True, "model": MODEL_NAME, "device": State.device, "max_pixels": MAX_PIXELS, "max_pixels_int8": VARIANTS["sft-int8"].get("max_pixels", MAX_PIXELS), "max_side": MAX_SIDE,
                              "max_steps": MAX_STEPS, "models": State.pipe.installed_variants(),
                              "max_pixels_edit": {k: v.get("max_pixels") for k, v in VARIANTS.items() if v["sampler"] == "edit"}, "active": State.pipe.variant,
                              "resident": ["dit", "text_encoder (loaded per request)", "vae (loaded per request)"]})


def preload():
    try:
        t = time.time()
        State.pipe = MossImage(MODELS_DIR, State.device, CACHE_DIR, log=lambda *a: log(*a), te_precision=os.environ.get("MOSSIMAGE_TE_PRECISION") or None)
        State.pipe.warm()
        log(f"warm in {time.time() - t:.1f} s")
    except BaseException as e:
        log("preload failed:", repr(e))
        os._exit(1)             # systemd shows 'failed' and the gateway reports the journal tail instead of waiting out the timeout
    State.ready = True
    log("ready")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default="127.0.0.1")
    ap.add_argument("--port", type=int, default=8109)
    ap.add_argument("--device", default="GPU", choices=["GPU", "CPU"])
    a = ap.parse_args()
    State.device = a.device
    app = web.Application(client_max_size=96 * 2**20)      # edit requests carry base64 pictures
    app.add_routes([web.post("/v1/mossimage", mossimage), web.get("/health", health)])

    async def start(app):
        loop = asyncio.get_running_loop()
        app["preload"] = loop.run_in_executor(None, preload)
    app.on_startup.append(start)
    web.run_app(app, host=a.host, port=a.port, print=lambda *_: None)


if __name__ == "__main__":
    main()