okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
4.0 KiB83 linesraw
1"""A stand-in for stable-diffusion.cpp's sd-cli (serve/test_images.py): reads the arguments serve/images.py passes and
2writes one small PNG per image whose pixels encode the seed, size and prompt, so a test can tell the images apart.
3FAKE_SD_FAIL=1: exits 1 after a log line.  FAKE_SD_SLEEP=<s>: waits that long first (cancel tests).
4FAKE_SD_ARGS=<file>: writes its argument list there (JSON).  FAKE_SD_RGBA=1: RGBA pictures like Qwen-Image-2.1's
5(rgba_png); with FAKE_SD_BROKEN=1 their IDAT CRC is wrong."""
6import hashlib
7import json
8import os
9import struct
10import sys
11import time
12import zlib
13
14
15def png(w: int, h: int, seed: int, text: str) -> bytes:
16    digest = hashlib.sha256(f"{seed}|{w}x{h}|{text}".encode()).digest()
17    row = b"\x00" + digest[:3] * 4
18    raw = row * 4
19    def chunk(t, d):
20        return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
21    return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 2, 0, 0, 0))
22            + chunk(b"tEXt", f"parameters\x00{text}, Seed: {seed}, Size: {w}x{h}".encode("latin-1", "replace"))
23            + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
24
25
26KEY = (160, 50, 200)          # the flat colour Qwen-Image-2.1 leaves under alpha 0 (a purple)
27
28
29def rgba_png(w: int, h: int, seed: int, text: str, broken: bool = False) -> bytes:
30    """A 4x4 8-bit RGBA PNG like Qwen-Image-2.1's: row 0 alpha 0 over the key colour, row 1 alpha 128, row 2 alpha
31    255, row 3 alpha 1 / 64 / 254 / 255; the "parameters" chunk carries non-ASCII bytes.  broken: a bad IDAT CRC."""
32    digest = hashlib.sha256(f"{seed}|{w}x{h}|{text}".encode()).digest()
33    r, g, b = digest[0], digest[1], digest[2]
34    rows = [bytes(KEY) + b"\x00", bytes((r, g, b, 128)), bytes((r, g, b, 255))]
35    raw = b"".join(b"\x00" + px * 4 for px in rows)
36    raw += b"\x00" + b"".join(bytes((r, g, b, a)) for a in (1, 64, 254, 255))
37    def chunk(t, d, bad=False):
38        crc = zlib.crc32(t + d) & 0xFFFFFFFF
39        return struct.pack(">I", len(d)) + t + d + struct.pack(">I", crc ^ (1 if bad else 0))
40    return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 6, 0, 0, 0))
41            + chunk(b"tEXt", f"parameters\x00{text}, Seed: {seed}, Size: {w}x{h} é".encode("latin-1", "replace"))
42            + chunk(b"IDAT", zlib.compress(raw), broken) + chunk(b"IEND", b""))
43
44
45def main(argv):
46    a = {}
47    i = 0
48    while i < len(argv):
49        if argv[i].startswith("-") and i + 1 < len(argv) and not argv[i + 1].startswith("--"):
50            a[argv[i]] = argv[i + 1]
51            i += 2
52        else:
53            a[argv[i]] = True
54            i += 1
55    if os.environ.get("FAKE_SD_ARGS"):
56        with open(os.environ["FAKE_SD_ARGS"], "w", encoding="utf-8") as f:
57            json.dump(argv, f)
58    time.sleep(float(os.environ.get("FAKE_SD_SLEEP") or 0))
59    print("[INFO ] loading tensors completed, taking 0.10s", flush=True)
60    if os.environ.get("FAKE_SD_FAIL"):
61        print("[ERROR] ggml_vulkan: ErrorDeviceLost", flush=True)
62        return 1
63    steps = int(a.get("--steps", 20))
64    for s in range(1, steps + 1):
65        print(f"  |{'=' * s}| {s}/{steps} - 0.01s/it", flush=True)
66    # stable-diffusion.cpp 2988060 prints seconds here (pipeline/image.cpp: "taking %.2fs")
67    print("[I] get_learned_condition completed, taking 0.70s --- image.cpp:529", flush=True)
68    print("[INFO ] sampling completed, taking 0.08s", flush=True)
69    print("[INFO ] decode_first_stage completed, taking 0.02s", flush=True)
70    w, h, seed, n = int(a["-W"]), int(a["-H"]), int(a["-s"]), int(a.get("-b", 1))
71    with open(a["--prompt-file"], encoding="utf-8", newline="") as f:     # the prompt is never an argument (#4202)
72        prompt = f.read()
73    for k in range(n):
74        with open(a["-o"] % k, "wb") as f:
75            if os.environ.get("FAKE_SD_RGBA"):
76                f.write(rgba_png(w, h, seed + k, prompt, broken=bool(os.environ.get("FAKE_SD_BROKEN"))))
77            else:
78                f.write(png(w, h, seed + k, prompt))
79    return 0
80
81
82if __name__ == "__main__":
83    sys.exit(main(sys.argv[1:]))