Spaces:
Paused
Paused
Download apps/renderer/scripts/enhance_compare_sheet.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/scripts/enhance_compare_sheet.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/scripts/enhance_compare_sheet.py
-
curl -L -o enhance_compare_sheet.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/scripts/enhance_compare_sheet.py
10.6 kB
| """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() | |