File size: 10,617 Bytes
c7a38a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Before/after comparison sheet for one "Enhance with AI" run (an ENHANCE_DEBUG_DIR dump).

    python scripts/enhance_compare_sheet.py <run_dir> [--out sheet.png]

Row 1: original photo | editor preview | corrected preview (repaired coverage, no AI) |
       AI answer (lighting reference only, never used as pixels) | final.
Rows 2-3: enlarged crops (3x, nearest) at the ceiling line, a wall corner, the skirting,
       the largest repairs and the pattern interior, each as editor / corrected / final.
Row 4: gain field per layer and the repaired (green) / trimmed (red) / given back (blue) overlay.
Writes metrics.json next to the sheet (pixels outside the wallpaper, pattern fidelity,
gain ranges, repaired pixels).
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

CROP = 96
ZOOM = 3
TILE_W = 420
PAD = 12
LABEL_H = 26
BG = (245, 245, 242)
INK = (40, 44, 52)


def _load(path: Path) -> np.ndarray | None:
    if not path.exists():
        return None
    with Image.open(path) as opened:
        return np.asarray(opened.convert("RGB") if opened.mode not in ("L",) else opened)


def _font(size: int):
    for name in ("/System/Library/Fonts/Supplemental/Arial.ttf", "/Library/Fonts/Arial.ttf", "DejaVuSans.ttf"):
        try:
            return ImageFont.truetype(name, size)
        except OSError:
            continue
    return ImageFont.load_default()


def _labelled(image: np.ndarray, label: str, width: int) -> Image.Image:
    picture = Image.fromarray(image)
    picture = picture.resize((width, max(1, round(picture.height * width / picture.width))), Image.Resampling.LANCZOS)
    canvas = Image.new("RGB", (width, picture.height + LABEL_H), BG)
    canvas.paste(picture, (0, LABEL_H))
    ImageDraw.Draw(canvas).text((4, 5), label, fill=INK, font=_font(14))
    return canvas


def _crop(image: np.ndarray, centre: tuple[int, int]) -> np.ndarray:
    height, width = image.shape[:2]
    x = int(np.clip(centre[0] - CROP // 2, 0, max(0, width - CROP)))
    y = int(np.clip(centre[1] - CROP // 2, 0, max(0, height - CROP)))
    patch = image[y: y + CROP, x: x + CROP]
    return cv2.resize(patch, (patch.shape[1] * ZOOM, patch.shape[0] * ZOOM), interpolation=cv2.INTER_NEAREST)


def _crop_points(alpha: np.ndarray, repaired: np.ndarray, seg_map: np.ndarray | None) -> list[tuple[str, tuple[int, int]]]:
    """Where to look closely: edges against ceiling, skirting and other classes, a corner, repairs, the interior."""
    points: list[tuple[str, tuple[int, int]]] = []
    covered = alpha > 0.5
    if not covered.any():
        return points
    ys, xs = np.nonzero(covered)
    edge = covered & ~cv2.erode(covered.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)
    eys, exs = np.nonzero(edge)
    if eys.size:
        top = np.argmin(eys)
        points.append(("ceiling line", (int(exs[top]), int(eys[top]))))
        bottom = np.argmax(eys)
        points.append(("skirting line", (int(exs[bottom]), int(eys[bottom]))))
        left = np.argmin(exs)
        points.append(("wall edge / corner", (int(exs[left]), int(eys[left]))))
    if repaired.any():
        count, labels, stats, centroids = cv2.connectedComponentsWithStats(repaired.astype(np.uint8))
        order = np.argsort(-stats[1:, cv2.CC_STAT_AREA])[:2] + 1
        for rank, index in enumerate(order):
            points.append((f"repair #{rank + 1} ({stats[index, cv2.CC_STAT_AREA]} px)", (int(centroids[index][0]), int(centroids[index][1]))))
    interior = cv2.erode(covered.astype(np.uint8), np.ones((CROP // 2, CROP // 2), np.uint8)).astype(bool)
    iys, ixs = np.nonzero(interior if interior.any() else covered)
    middle = len(iys) // 2
    points.append(("pattern interior", (int(ixs[middle]), int(iys[middle]))))
    return points


GAIN_LOW, GAIN_HIGH = 0.4, 1.6


def _heat(gain: np.ndarray, alpha: np.ndarray) -> np.ndarray:
    normalised = np.clip((gain - GAIN_LOW) / (GAIN_HIGH - GAIN_LOW), 0, 1)
    coloured = cv2.applyColorMap((normalised * 255).astype(np.uint8), cv2.COLORMAP_TWILIGHT_SHIFTED)[..., ::-1]
    return np.where(alpha[..., None] > 0.05, coloured, 30).astype(np.uint8)


def _high_pass(image: np.ndarray) -> np.ndarray:
    lab = cv2.cvtColor(image, cv2.COLOR_RGB2LAB).astype(np.float32)
    return lab - cv2.GaussianBlur(lab, (0, 0), 3.0)


def build_sheet(run: Path, out: Path) -> dict:
    original = _load(run / "original.png")
    editor = _load(run / "editor.png")
    preview = _load(run / "preview.png")
    answer = _load(run / "ai_answer.png")
    final = _load(run / "final.png")
    summary = json.loads((run / "summary.json").read_text()) if (run / "summary.json").exists() else {}
    manifest = json.loads((run / "manifest.json").read_text())
    seg_map = np.load(run / "seg_map.npy") if (run / "seg_map.npy").exists() else None
    layer_ids = [layer["id"] for layer in manifest["layers"]]
    alphas = [(_load(run / f"alpha.{i}.png").astype(np.float32) / 255.0) for i in layer_ids]
    repaired = [(_load(run / f"repaired.{i}.png") > 0) for i in layer_ids]
    trimmed = [(_load(run / f"trimmed.{i}.png") > 0) for i in layer_ids]
    # The final coverage (minus objects given back to the photo after the AI), when the run got that far.
    alphas = [(_load(run / f"final_alpha.{n}.png").astype(np.float32) / 255.0) if (run / f"final_alpha.{n}.png").exists() else alpha
              for n, alpha in enumerate(alphas)]
    restored = [(_load(run / f"restored.{n}.png") > 0) if (run / f"restored.{n}.png").exists() else np.zeros(alpha.shape, bool)
                for n, alpha in enumerate(alphas)]
    gains = [np.load(run / f"gain.{n}.npy").astype(np.float32) if (run / f"gain.{n}.npy").exists() else None for n in range(len(layer_ids))]
    result = final if final is not None else preview

    rows: list[Image.Image] = []
    top = [_labelled(original, "Original photo", TILE_W), _labelled(editor, "Editor preview", TILE_W),
           _labelled(preview, "Corrected preview (no AI)", TILE_W)]
    if answer is not None:
        top.append(_labelled(answer, "AI answer — lighting reference only", TILE_W))
    top.append(_labelled(result, "Final" if final is not None else "Final (not produced)", TILE_W))
    rows.append(_row(top))

    total_alpha = np.sum(alphas, axis=0)
    all_repaired = np.any(repaired, axis=0)
    crops: list[Image.Image] = []
    points = _crop_points(total_alpha, all_repaired, seg_map)
    all_restored = np.any(restored, axis=0)
    if all_restored.any():
        count, _, stats, centroids = cv2.connectedComponentsWithStats(all_restored.astype(np.uint8))
        biggest = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
        points.append((f"object given back ({stats[biggest, cv2.CC_STAT_AREA]} px)", (int(centroids[biggest][0]), int(centroids[biggest][1]))))
    for label, centre in points:
        trio = np.concatenate([_crop(editor, centre), _crop(preview, centre), _crop(result, centre)], axis=1)
        crops.append(_labelled(trio, f"{label}: editor | corrected | final", trio.shape[1]))
    for start in range(0, len(crops), 2):
        rows.append(_row(crops[start: start + 2]))

    diagnostics = []
    for layer_id, alpha, gain in zip(layer_ids, alphas, gains):
        if gain is not None:
            diagnostics.append(_labelled(_heat(gain, alpha), f"{layer_id} gain {GAIN_LOW} (dark) .. {GAIN_HIGH} (light)", TILE_W))
    overlay = (original.astype(np.float32) * 0.55).astype(np.uint8)
    overlay[np.any(repaired, axis=0)] = (40, 220, 90)
    overlay[np.any(trimmed, axis=0)] = (230, 50, 50)
    overlay[np.any(restored, axis=0)] = (60, 120, 255)
    diagnostics.append(_labelled(overlay, "Repaired (green) / trimmed (red) / objects given back (blue)", TILE_W))
    rows.append(_row(diagnostics))

    sheet_w = max(row.width for row in rows) + 2 * PAD
    sheet_h = sum(row.height for row in rows) + PAD * (len(rows) + 1) + 34
    sheet = Image.new("RGB", (sheet_w, sheet_h), BG)
    title = f"{run.name} — " + ", ".join(
        f"{layer['tile']['name']} ({'mural' if layer['tile'].get('mural') else 'repeat'}) on {layer['kind']} {layer['segmentId']}"
        for layer in manifest["layers"]
    )
    ImageDraw.Draw(sheet).text((PAD, 8), title, fill=INK, font=_font(16))
    y = 34 + PAD
    for row in rows:
        sheet.paste(row, (PAD, y))
        y += row.height + PAD
    out.parent.mkdir(parents=True, exist_ok=True)
    sheet.save(out)

    metrics: dict = {"run": run.name, "summary": summary, "layers": []}
    if final is not None:
        outside = total_alpha <= 0
        metrics["outsideMaxAbsDiffPng"] = int(np.abs(final[outside].astype(int) - original[outside]).max()) if outside.any() else 0
        hp_final, hp_preview = _high_pass(final), _high_pass(preview)
    for layer_id, alpha, rep, trim, back, gain in zip(layer_ids, alphas, repaired, trimmed, restored, gains):
        inside = cv2.erode((alpha > 0.99).astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool)
        entry = {"id": layer_id, "repairedPx": int(rep.sum()), "trimmedPx": int(trim.sum()), "restoredPx": int(back.sum()),
                 "coveredPx": int((alpha > 0.5).sum())}
        if final is not None and inside.any():
            a, b = hp_final[inside].ravel(), hp_preview[inside].ravel()
            entry["patternHighPassCorrelation"] = round(float(np.corrcoef(a, b)[0, 1]), 4)
            entry["meanAbsDiffToCorrected"] = round(float(np.abs(final[inside].astype(int) - preview[inside]).mean()), 2)
        if gain is not None and inside.any():
            entry["gain"] = {"min": round(float(gain[inside].min()), 3), "max": round(float(gain[inside].max()), 3),
                             "mean": round(float(gain[inside].mean()), 3)}
        metrics["layers"].append(entry)
    out.with_suffix(".metrics.json").write_text(json.dumps(metrics, indent=2))
    return metrics


def _row(images: list[Image.Image]) -> Image.Image:
    width = sum(image.width for image in images) + PAD * max(0, len(images) - 1)
    height = max(image.height for image in images)
    row = Image.new("RGB", (width, height), BG)
    x = 0
    for image in images:
        row.paste(image, (x, 0))
        x += image.width + PAD
    return row


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("run", type=Path)
    parser.add_argument("--out", type=Path)
    args = parser.parse_args()
    out = args.out or args.run / "sheet.png"
    print(json.dumps(build_sheet(args.run, out), indent=2))


if __name__ == "__main__":
    main()