okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
4.5 KiB99 linesraw
1"""tools/test_png_write.py - our PNG writer (src/image/png/png_write.cpp): CRC-32 / Adler-32 against published check
2values; PNG files of several shapes (grey, RGB, RGBA; one row, many stored deflate blocks) decoded back by an
3independent reader (Python's zlib, every chunk CRC checked, plus Pillow when it is installed) to the same pixels; the
4"parameters" tEXt chunk kept right after IHDR as stable-diffusion.cpp's stb_image_write writes it.  No GPU.
5
6    python -m pytest tools/test_png_write.py"""
7import shutil
8import struct
9import subprocess
10import tempfile
11import unittest
12import zlib
13from pathlib import Path
14
15ROOT = Path(__file__).resolve().parents[1]
16CXX = shutil.which("g++") or shutil.which("c++") or shutil.which("clang++")
17
18
19def read_png(data: bytes):
20    """chunks (type, payload), checking each CRC; the decoded rows (filter 0 only) as bytes"""
21    assert data[:8] == b"\x89PNG\r\n\x1a\n"
22    at, chunks = 8, []
23    while at < len(data):
24        n, = struct.unpack(">I", data[at:at + 4])
25        typ, body = data[at + 4:at + 8], data[at + 8:at + 8 + n]
26        crc, = struct.unpack(">I", data[at + 8 + n:at + 12 + n])
27        assert crc == zlib.crc32(typ + body), typ
28        chunks.append((typ, body))
29        at += 12 + n
30    w, h, depth, ctype, comp, filt, inter = struct.unpack(">IIBBBBB", chunks[0][1])
31    ch = {0: 1, 4: 2, 2: 3, 6: 4}[ctype]
32    raw = zlib.decompress(b"".join(b for t, b in chunks if t == b"IDAT"))
33    row = w * ch
34    assert len(raw) == h * (row + 1)
35    pixels = bytearray()
36    for y in range(h):
37        assert raw[y * (row + 1)] == 0
38        pixels += raw[y * (row + 1) + 1:(y + 1) * (row + 1)]
39    return chunks, (w, h, ch, depth, comp, filt, inter), bytes(pixels)
40
41
42def pattern(w, h, c):
43    return bytes(((7 * x + 13 * y + 29 * k) & 255) for y in range(h) for x in range(w) for k in range(c))
44
45
46@unittest.skipUnless(CXX, "no C++ compiler")
47class PngWriter(unittest.TestCase):
48    @classmethod
49    def setUpClass(cls):
50        cls.td = tempfile.TemporaryDirectory()
51        cls.exe = Path(cls.td.name) / "strata-png-write"
52        r = subprocess.run([CXX, "-std=c++17", "-O2", "-I", str(ROOT / "include"),
53                            str(ROOT / "src" / "image" / "png" / "png_write.cpp"),
54                            str(ROOT / "src" / "image" / "png" / "png_write_main.cpp"), "-o", str(cls.exe)],
55                           capture_output=True, text=True, timeout=300)
56        assert r.returncode == 0, r.stderr[-3000:]
57
58    @classmethod
59    def tearDownClass(cls):
60        cls.td.cleanup()
61
62    def test_vectors(self):
63        r = subprocess.run([str(self.exe), "--vectors"], capture_output=True, text=True, timeout=60)
64        self.assertIn("VECTORS PASS", r.stdout, r.stdout)
65        self.assertIn("adler32 of 1 MiB of 0xff: %08x" % zlib.adler32(b"\xff" * (1 << 20)), r.stdout)
66
67    def test_shapes_round_trip(self):
68        params = "a red fox in the snow\nSteps: 8, Sampler: euler, CFG scale: 1, Seed: 42, Size: 64x48"
69        for w, h, c in ((1, 1, 3), (3, 2, 3), (64, 48, 1), (64, 48, 4), (300, 200, 3), (1024, 1, 3)):
70            with self.subTest(shape=(w, h, c)):
71                out = Path(self.td.name) / ("p_%d_%d_%d.png" % (w, h, c))
72                subprocess.run([str(self.exe), "--pattern", str(w), str(h), str(c), str(out), params], check=True)
73                chunks, (W, H, C, depth, comp, filt, inter), px = read_png(out.read_bytes())
74                self.assertEqual((W, H, C, depth, comp, filt, inter), (w, h, c, 8, 0, 0, 0))
75                self.assertEqual(px, pattern(w, h, c))
76                self.assertEqual([t for t, _ in chunks], [b"IHDR", b"tEXt", b"IDAT", b"IEND"])
77                self.assertEqual(chunks[1][1], b"parameters\x00" + params.encode())
78                try:
79                    from PIL import Image
80                except ImportError:
81                    continue
82                with Image.open(out) as im:
83                    self.assertEqual(im.tobytes(), px)
84                    self.assertEqual(im.info.get("parameters"), params)
85
86    def test_no_parameters_and_raw(self):
87        w, h, c = 17, 5, 3
88        raw = Path(self.td.name) / "in.raw"
89        data = bytes((i * 31) & 255 for i in range(w * h * c))
90        raw.write_bytes(data)
91        out = Path(self.td.name) / "raw.png"
92        subprocess.run([str(self.exe), "--raw", str(raw), str(w), str(h), str(c), str(out)], check=True)
93        chunks, _, px = read_png(out.read_bytes())
94        self.assertEqual([t for t, _ in chunks], [b"IHDR", b"IDAT", b"IEND"])
95        self.assertEqual(px, data)
96
97
98if __name__ == "__main__":
99    unittest.main()