File size: 17,850 Bytes
73828b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Synthetic checks for the diffusion refinement pass.

No model downloads, no GPU, no server -- pure numpy/PIL, runs in about a
second. Covers everything in services/refine except the SDXL call itself.

    py -3.12 scripts/test_refine.py

The invariant worth caring about most is the last section: a refinement pass
must not change a single pixel outside its own mask. Everything else is
quality; that one is correctness, and it is asserted at runtime too.
"""

from __future__ import annotations

import base64
import pathlib
import sys
import uuid

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))

import numpy as np
from PIL import Image

from services.refine.assets import (
    read_refine_assets,
    refine_assets_path,
    surface_masks_from_bundle,
    write_refine_assets,
)
from services.refine.diffusion import get_processing_size
from services.refine.grouping import group_surfaces_by_material
from services.refine.guide import apply_diffusion_as_realism_guide, recover_detail
from services.refine.masks import (
    composite_surface_only,
    make_binary_mask,
    mask_coverage,
    mask_to_bool,
    outside_mask_difference,
    prepare_safe_diffusion_mask,
)
from services.refine.photometric import (
    add_camera_noise,
    apply_shadow_map,
    enhance_material_microdetail,
    extract_shadow_map,
    prepare_depth,
    transfer_original_lighting,
)
from services.refine.profiles import (
    MATERIALS,
    SURFACE_KINDS,
    build_prompts,
    detail_recovery_for,
    normalize_material_type,
    normalize_surface_kind,
)

H, W = 240, 320
FLOOR = (slice(150, 240), slice(0, 320))
WALL_LEFT = (slice(20, 150), slice(0, 150))
WALL_RIGHT = (slice(20, 150), slice(170, 320))

failures: list[str] = []


def check(label: str, condition: bool, detail: str = "") -> None:
    if condition:
        print(f"  PASS  {label}")
    else:
        failures.append(label)
        print(f"  FAIL  {label}" + (f"  ({detail})" if detail else ""))


def mask_of(*regions) -> np.ndarray:
    mask = np.zeros((H, W), dtype=np.uint8)
    for region in regions:
        mask[region] = 1
    return mask


def room_photo() -> Image.Image:
    """A toy room: bright wall, darker floor, a light gradient across it."""
    rgb = np.zeros((H, W, 3), dtype=np.uint8)
    rgb[:, :] = (90, 90, 95)
    rgb[WALL_LEFT] = (185, 182, 175)
    rgb[WALL_RIGHT] = (185, 182, 175)
    rgb[FLOOR] = (120, 105, 88)
    gradient = np.linspace(0.72, 1.18, W, dtype=np.float32)[None, :, None]
    return Image.fromarray(np.clip(rgb * gradient, 0, 255).astype(np.uint8), mode="RGB")


def tiled_composite(original: Image.Image, mask: np.ndarray) -> Image.Image:
    """The original with a flat, evenly lit "tile" pasted into the mask."""
    array = np.array(original, dtype=np.uint8, copy=True)
    inside = mask > 0
    array[inside] = (196, 190, 178)
    return Image.fromarray(array, mode="RGB")


def main() -> int:
    original = room_photo()
    floor_mask = mask_of(FLOOR)
    composite = tiled_composite(original, floor_mask)

    print("\nProfiles")
    check("every material defines both surface kinds",
          all(kind in MATERIALS[m] for m in MATERIALS for kind in SURFACE_KINDS),
          str([(m, k) for m in MATERIALS for k in SURFACE_KINDS if k not in MATERIALS[m]]))
    check("numeric tuning is shared, not duplicated per kind",
          all("diffusion_strength" in MATERIALS[m] and "diffusion_strength" not in MATERIALS[m]["wall"]
              for m in MATERIALS))
    check("wood floor tuning is unchanged from the reference script",
          MATERIALS["wood"]["diffusion_strength"] == 0.36
          and MATERIALS["wood"]["guidance"] == 3.0
          and MATERIALS["wood"]["controlnet"] == 0.15
          and MATERIALS["wood"]["steps"] == 24)
    check("marble tuning is unchanged from the reference script",
          MATERIALS["marble"]["diffusion_strength"] == 0.46
          and MATERIALS["marble"]["steps"] == 28
          and MATERIALS["marble"]["controlnet"] == 0.25)
    check("unknown material falls back to generic",
          normalize_material_type("brushed-titanium") == "generic")
    check("missing material falls back to generic", normalize_material_type(None) == "generic")
    check("material lookup is case and space insensitive",
          normalize_material_type("  MarBle ") == "marble")
    check("unknown surface kind falls back to floor",
          normalize_surface_kind("ceiling") == "floor")

    floor_prompt, floor_negative, wood = build_prompts("wood", "floor")
    wall_prompt, wall_negative, wood_again = build_prompts("wood", "wall")
    check("floor and wall share one profile object", wood is wood_again)
    check("floor prompt talks about flooring", "flooring" in floor_prompt.lower())
    check("wall prompt does not talk about flooring",
          "flooring" not in wall_prompt.lower() and "floor contact" not in wall_prompt.lower())
    check("wall prompt talks about panelling", "panelling" in wall_prompt.lower())
    check("wall negative guards the ceiling join",
          "wall bleeding into ceiling" in wall_negative.lower())
    check("floor negative guards the wall join",
          "floor bleeding into wall" in floor_negative.lower())
    check("material description is threaded into the prompt",
          "warm grey veining" in build_prompts("marble", "wall", "warm grey veining")[0])
    check("wood gets the strongest pattern recovery",
          detail_recovery_for("wood")["pattern"] > detail_recovery_for("porcelain")["pattern"])

    print("\nMasks")
    binary = make_binary_mask(np.full((H, W), 200, dtype=np.uint8))
    check("threshold produces only 0 and 255",
          set(np.unique(np.asarray(binary))).issubset({0, 255}))
    soft = np.zeros((H, W), dtype=np.uint8)
    soft[FLOOR] = 127
    check("just-below-threshold is excluded", not mask_to_bool(soft).any())
    soft[FLOOR] = 128
    check("exactly-at-threshold is included", mask_to_bool(soft)[FLOOR].all())

    # Regression. The reference script only ever saw masks decoded from a JPEG,
    # so it assumed 0/255. Internal masks are 0/1 uint8, and thresholding those
    # at 128 emptied them -- which turned every later stage into a silent no-op
    # rather than an error, so the output looked merely unimproved.
    check("a 0/1 uint8 mask is not thresholded away", mask_to_bool(mask_of(FLOOR))[200, 160])
    check("a boolean mask is accepted", mask_to_bool(mask_of(FLOOR).astype(bool))[200, 160])
    check("a 0/255 mask still works", mask_to_bool(mask_of(FLOOR) * 255)[200, 160])
    check("a float 0..1 mask is accepted",
          mask_to_bool(mask_of(FLOOR).astype(np.float32))[200, 160])
    check("a 0/1 mask composites for real",
          (np.asarray(composite_surface_only(
              original, Image.fromarray(np.full((H, W, 3), 255, np.uint8), "RGB"),
              mask_of(FLOOR)))[FLOOR] == 255).all())

    safe = prepare_safe_diffusion_mask(floor_mask, edge_guard=8)
    safe_np = np.asarray(safe) >= 128
    check("edge guard shrinks the mask", safe_np.sum() < floor_mask.sum())
    check("edge guard keeps the interior", safe_np[200, 160])
    check("edge guard clears the boundary row", not safe_np[150, 160])
    check("coverage is reported as a sane fraction",
          0.4 < mask_coverage(safe, floor_mask) < 1.0,
          f"{mask_coverage(safe, floor_mask):.3f}")
    check("a mask thinner than the guard survives as empty rather than crashing",
          np.asarray(prepare_safe_diffusion_mask(mask_of((slice(10, 14), slice(10, 300))), 8)).sum() == 0)

    print("\nPhotometric stages")
    lit = transfer_original_lighting(original, composite, floor_mask, sigma=35, strength=0.5)
    original_np = np.asarray(original).astype(int)
    composite_np = np.asarray(composite).astype(int)
    lit_np = np.asarray(lit).astype(int)
    outside = ~mask_to_bool(floor_mask)
    check("lighting transfer leaves outside pixels untouched",
          np.array_equal(lit_np[outside], composite_np[outside]))
    left_before = abs(composite_np[200, 20].mean() - original_np[200, 20].mean())
    left_after = abs(lit_np[200, 20].mean() - original_np[200, 20].mean())
    check("lighting transfer moves the tile toward the room's brightness",
          left_after < left_before, f"{left_before:.1f} -> {left_after:.1f}")

    shadow_map = extract_shadow_map(original, floor_mask, blur_sigma=22, strength=0.58)
    check("shadow map never brightens", shadow_map.max() <= 1.0 + 1e-6)
    check("shadow map is clamped from below", shadow_map.min() >= 0.58 - 1e-6)
    check("shadow map is neutral outside the mask", np.allclose(shadow_map[outside], 1.0))
    shadowed = np.asarray(apply_shadow_map(composite, floor_mask, shadow_map)).astype(int)
    check("shadow application leaves outside pixels untouched",
          np.array_equal(shadowed[outside], composite_np[outside]))

    detailed = np.asarray(
        enhance_material_microdetail(composite, floor_mask, 0.12, 0.015)).astype(int)
    check("microdetail leaves outside pixels untouched",
          np.array_equal(detailed[outside], composite_np[outside]))

    noisy = np.asarray(add_camera_noise(composite, floor_mask, 0.2, seed=42)).astype(int)
    check("camera noise leaves outside pixels untouched",
          np.array_equal(noisy[outside], composite_np[outside]))
    check("camera noise is reproducible for a fixed seed",
          np.array_equal(noisy, np.asarray(
              add_camera_noise(composite, floor_mask, 0.2, seed=42)).astype(int)))

    ramp = np.tile(np.linspace(20, 220, W, dtype=np.uint8), (H, 1))
    depth_rgb = np.asarray(prepare_depth(Image.fromarray(ramp, mode="L")))
    check("depth is normalised to the full 8-bit range",
          depth_rgb.min() == 0 and depth_rgb.max() == 255)
    check("depth is expanded to three channels", depth_rgb.shape == (H, W, 3))
    flat = np.asarray(prepare_depth(Image.fromarray(np.full((H, W), 77, np.uint8), mode="L")))
    check("a constant depth map does not divide by zero", np.isfinite(flat).all())

    print("\nBlending")
    generated = Image.fromarray(
        np.clip(np.asarray(composite).astype(np.float32) * 1.06, 0, 255).astype(np.uint8), "RGB")
    recovered = recover_detail(generated, composite, "wood")
    check("detail recovery returns the same size", recovered.size == composite.size)
    check("detail recovery stays in gamut",
          np.asarray(recovered).min() >= 0 and np.asarray(recovered).max() <= 255)
    guided = apply_diffusion_as_realism_guide(composite, generated, floor_mask)
    check("realism guide leaves outside pixels untouched",
          np.array_equal(np.asarray(guided).astype(int)[outside], composite_np[outside]))
    check("realism guide changes less than raw diffusion",
          np.abs(np.asarray(guided).astype(int) - composite_np).mean()
          < np.abs(np.asarray(generated).astype(int) - composite_np).mean())

    print("\nStrict compositing")
    wild = Image.fromarray(np.full((H, W, 3), 255, np.uint8), "RGB")
    strict = composite_surface_only(original, wild, floor_mask)
    check("compositing takes refined pixels inside the mask",
          (np.asarray(strict)[FLOOR] == 255).all())
    check("compositing takes base pixels outside the mask",
          outside_mask_difference(strict, original, floor_mask) == 0)
    smaller = wild.resize((W // 2, H // 2), Image.Resampling.LANCZOS)
    check("a differently sized refinement is resized rather than rejected",
          composite_surface_only(original, smaller, floor_mask).size == original.size)
    check("an empty mask is a no-op",
          outside_mask_difference(
              composite_surface_only(original, wild, np.zeros((H, W), np.uint8)),
              original, np.zeros((H, W), np.uint8)) == 0)

    print("\nMaterial grouping")
    groups = group_surfaces_by_material(
        [
            {"segmentIds": [0], "materialType": "wood", "surfaceKind": "floor"},
            {"segmentIds": [1, 2], "materialType": "marble", "surfaceKind": "wall"},
        ],
        {0: mask_of(FLOOR), 1: mask_of(WALL_LEFT), 2: mask_of(WALL_RIGHT)},
    )
    check("one group per material", len(groups) == 2, f"got {len(groups)}")
    check("walls sharing a material are unioned",
          int(groups[1]["mask"].sum()) == int(mask_of(WALL_LEFT, WALL_RIGHT).sum()))
    check("groups are disjoint",
          not (groups[0]["mask"].astype(bool) & groups[1]["mask"].astype(bool)).any())
    check("surface kind rides along with the group", groups[1]["surfaceKind"] == "wall")

    same = group_surfaces_by_material(
        [
            {"segmentIds": [0], "materialType": "marble", "surfaceKind": "floor"},
            {"segmentIds": [1], "materialType": "marble", "surfaceKind": "wall"},
        ],
        {0: mask_of(FLOOR), 1: mask_of(WALL_LEFT)},
    )
    check("one material on two planes stays two groups, not one",
          len(same) == 2, f"got {len(same)} — floor and wall prompts must not merge")

    merged = group_surfaces_by_material(
        [
            {"segmentIds": [1], "materialType": "marble", "surfaceKind": "wall"},
            {"segmentIds": [2], "materialType": "marble", "surfaceKind": "wall"},
        ],
        {1: mask_of(WALL_LEFT), 2: mask_of(WALL_RIGHT)},
    )
    check("same material and same kind collapses to one pass", len(merged) == 1)

    check("unknown segment ids are skipped rather than crashing",
          group_surfaces_by_material(
              [{"segmentIds": [0, 99], "materialType": "wood", "surfaceKind": "floor"}],
              {0: mask_of(FLOOR)})[0]["mask"].sum() == mask_of(FLOOR).sum())
    check("a group with no resolvable mask is dropped",
          group_surfaces_by_material(
              [{"segmentIds": [99], "materialType": "wood", "surfaceKind": "floor"}],
              {0: mask_of(FLOOR)}) == [])
    check("an empty request yields no groups", group_surfaces_by_material([], {}) == [])

    print("\nRefinement asset side-car")
    job_id = "test-refine-" + uuid.uuid4().hex[:8]
    depth_in = np.linspace(0.8, 6.4, H * W, dtype=np.float32).reshape(H, W)
    depth_in[0, 0] = np.nan  # MoGe leaves holes where geometry is unresolved
    try:
        written = write_refine_assets(
            job_id, depth_in,
            {0: mask_of(FLOOR), 1: mask_of(WALL_LEFT), 2: mask_of(WALL_RIGHT)}, W, H)
        check("side-car is written", written is not None and written.exists())
        loaded = read_refine_assets(job_id)
        check("side-car round-trips every segment", sorted(loaded["masks"]) == [0, 1, 2])
        check("masks survive bit-packing exactly",
              np.array_equal(loaded["masks"][1], mask_of(WALL_LEFT)))
        check("shape is preserved", loaded["masks"][0].shape == (H, W))
        check("depth survives as a monotonic uint16",
              loaded["depth"].dtype == np.uint16
              and loaded["depth"][H - 1, W - 1] > loaded["depth"][H // 2, 0])
        check("non-finite depth does not poison the normalisation",
              np.isfinite(loaded["depth"]).all())
        raw_bytes = H * W * 4 + 3 * H * W  # float32 depth + three uint8 masks
        check("side-car is much smaller than the raw arrays",
              written.stat().st_size < raw_bytes // 3,
              f"{written.stat().st_size} vs {raw_bytes} raw")
    finally:
        refine_assets_path(job_id).unlink(missing_ok=True)

    check("a missing side-car reads as None",
          read_refine_assets("test-refine-does-not-exist") is None)
    check("no masks means no side-car", write_refine_assets(job_id, None, {}, W, H) is None)

    bundle = {
        "width": W, "height": H,
        "segments": [
            {"id": 0, "mask": base64.b64encode(
                np.flatnonzero(mask_of(FLOOR).ravel()).astype(np.uint32).tobytes()).decode()},
            {"id": 3, "mask": None},
        ],
    }
    rebuilt = surface_masks_from_bundle(bundle)
    check("bundle indices rebuild into masks", np.array_equal(rebuilt[0], mask_of(FLOOR)))
    check("a segment with no mask is skipped", 3 not in rebuilt)

    print("\nProcessing size")
    check("a large image is scaled under the cap", get_processing_size(1920, 1080, 896)[0] == 896)
    check("sizes are multiples of eight",
          all(value % 8 == 0 for value in get_processing_size(1920, 1080, 896)))
    # Rounding to the VAE's multiple of 8 can nudge a dimension up by a few px
    # (300 -> 304). Harmless: the result is composited back at full resolution.
    check("a small image is not scaled down", get_processing_size(400, 300, 896) == (400, 304))
    check("rounding never moves a dimension by more than 8px",
          all(abs(a - b) < 8 for a, b in zip(get_processing_size(400, 300, 896), (400, 300))))
    check("aspect ratio is held to within a pixel of the eight-grid",
          abs(get_processing_size(1600, 900, 896)[1] / get_processing_size(1600, 900, 896)[0]
              - 900 / 1600) < 0.01)

    print("\nMulti-pass invariant")
    # Two passes over disjoint masks, each writing garbage inside its own area:
    # the untouched middle strip and everything else must survive exactly.
    working = original
    for group in groups:
        working = composite_surface_only(
            working, Image.fromarray(np.full((H, W, 3), 7, np.uint8), "RGB"), group["mask"])
    combined = np.zeros((H, W), np.uint8)
    for group in groups:
        combined |= group["mask"]
    check("after two passes nothing outside the union changed",
          outside_mask_difference(working, original, combined) == 0)
    check("the gap between the two walls is untouched",
          np.array_equal(np.asarray(working)[100, 155:168], np.asarray(original)[100, 155:168]))

    print()
    if failures:
        print(f"{len(failures)} FAILED: {', '.join(failures)}")
        return 1
    print("All checks passed.")
    return 0


if __name__ == "__main__":
    sys.exit(main())