Spaces:
Paused
Paused
File size: 8,717 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 | """Checks the browser's layers against the job before anything is charged or sent to the AI.
A layer whose coverage does not match the job's own surface mask, or whose
rendered support reaches beyond what a gap repair could need, is refused (422):
there is never a fallback to an unrestricted AI edit.
"""
from __future__ import annotations
import io
from dataclasses import dataclass
import cv2
import numpy as np
from PIL import Image
from services.enhance.job_context import JobContext
MAX_LAYERS = 6
# The editor's coverage must match the job's mask (minus occluded pixels) this closely.
MIN_COVERAGE_IOU = 0.97
# The rendered support may reach this far beyond the mask (fraction of the short side), plus enclosed holes.
MAX_SUPPORT_REACH = 0.03
MAX_HOLE_AREA = 0.004 # of the image
MIN_SUPPORT_CONTAINS_COVERAGE = 0.995
MAX_LAYER_OVERLAP = 0.005 # of the smaller layer
SURFACE_KINDS = {"wall": "wall", "floor": "floor"}
class LayerRejected(Exception):
def __init__(self, code: str, message: str):
super().__init__(message)
self.code = code
self.message = message
@dataclass
class TileRef:
slug: str
name: str
image_url: str | None
width_mm: float | None
height_mm: float | None
mural: bool
pattern_match: str
@dataclass
class Layer:
id: str
segment_id: int
kind: str # "wall" | "floor"
tile: TileRef
rgb: np.ndarray # uint8 (H, W, 3): the wallpaper as the browser's shader lit it, on the support
support: np.ndarray # bool (H, W): where the browser rendered it (mask + repair band)
coverage: np.ndarray # float32 0..1 (H, W): the editor's own coverage
planes: np.ndarray # uint8 (H, W): the mapping plane per support pixel, 255 = none
def _disc(radius: int) -> np.ndarray:
return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1))
def enclosed_holes(mask: np.ndarray, max_area: float = MAX_HOLE_AREA) -> np.ndarray:
"""Small regions fully enclosed by the mask (wall seen between chair backs, behind a frame)."""
count, labels, stats, _ = cv2.connectedComponentsWithStats((~mask).astype(np.uint8), connectivity=4)
height, width = mask.shape
keep = np.zeros(count, bool)
for i in range(1, count):
left, top, w, h, area = stats[i]
if area < max_area * mask.size and left > 0 and top > 0 and left + w < width and top + h < height:
keep[i] = True
return keep[labels]
def _decode_png(data: bytes, mode: str, size: tuple[int, int], name: str) -> np.ndarray:
try:
with Image.open(io.BytesIO(data)) as opened:
if opened.format != "PNG":
raise LayerRejected("BAD_LAYER", f"{name} must be a PNG.")
if opened.size != size:
raise LayerRejected("SIZE_MISMATCH", f"{name} is {opened.size[0]}x{opened.size[1]}, expected {size[0]}x{size[1]}.")
return np.asarray(opened.convert(mode))
except LayerRejected:
raise
except Exception as exc:
raise LayerRejected("BAD_LAYER", f"{name} is not a readable PNG.") from exc
def _number(value) -> float | None:
return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 else None
def _text(value, limit: int) -> str:
return value.strip()[:limit] if isinstance(value, str) else ""
def parse_layers(manifest: dict, files: dict[str, bytes], context: JobContext) -> list[Layer]:
"""The manifest's layers with their decoded PNGs, each checked against the job (raises LayerRejected).
The manifest lists layers in the editor's drawing order (bottom first): where two overlap,
the later one is the one shown."""
width, height = context.size
if manifest.get("width") != width or manifest.get("height") != height:
raise LayerRejected("SIZE_MISMATCH", "The layers were made for a different photo size.")
items = manifest.get("layers")
if not isinstance(items, list) or not items:
raise LayerRejected("EMPTY_LAYER", "Apply a material before enhancing.")
if len(items) > MAX_LAYERS:
raise LayerRejected("BAD_LAYER", f"At most {MAX_LAYERS} surfaces can be enhanced at once.")
layers: list[Layer] = []
seen_segments: set[int] = set()
for item in items:
if not isinstance(item, dict):
raise LayerRejected("BAD_LAYER", "Malformed layer.")
layer_id = _text(item.get("id"), 16)
if not layer_id.isalnum():
raise LayerRejected("BAD_LAYER", "Malformed layer id.")
segment_id = item.get("segmentId")
segment = context.segments.get(segment_id) if isinstance(segment_id, int) else None
if segment is None:
raise LayerRejected("UNKNOWN_SEGMENT", "A layer refers to a surface this room does not have.")
kind = SURFACE_KINDS.get(item.get("kind"))
if kind is None or kind != segment.class_name:
raise LayerRejected("UNKNOWN_SEGMENT", "A layer's surface type does not match the room.")
if segment_id in seen_segments:
raise LayerRejected("LAYER_OVERLAP", "Two layers cover the same surface.")
seen_segments.add(segment_id)
tile = item.get("tile") if isinstance(item.get("tile"), dict) else {}
missing = [name for name in (f"layer.{layer_id}", f"coverage.{layer_id}", f"planes.{layer_id}") if name not in files]
if missing:
raise LayerRejected("BAD_LAYER", f"Missing {', '.join(missing)}.")
rgba = _decode_png(files[f"layer.{layer_id}"], "RGBA", (width, height), f"layer.{layer_id}")
coverage = _decode_png(files[f"coverage.{layer_id}"], "L", (width, height), f"coverage.{layer_id}")
planes = _decode_png(files[f"planes.{layer_id}"], "L", (width, height), f"planes.{layer_id}")
layer = Layer(
id=layer_id,
segment_id=segment_id,
kind=kind,
tile=TileRef(
slug=_text(tile.get("slug"), 120),
name=_text(tile.get("name"), 200) or "the material",
image_url=_text(tile.get("imageUrl"), 2000) or None,
width_mm=_number(tile.get("widthMm")),
height_mm=_number(tile.get("heightMm")),
mural=tile.get("mural") is True,
pattern_match="half-drop" if tile.get("patternMatch") == "half-drop" else "straight",
),
rgb=np.ascontiguousarray(rgba[..., :3]),
support=rgba[..., 3] > 127,
coverage=coverage.astype(np.float32) / 255.0,
planes=planes,
)
check_layer(layer, context)
layers.append(layer)
check_overlaps(layers, context)
return layers
def check_layer(layer: Layer, context: JobContext) -> None:
segment = context.segments[layer.segment_id]
expected = segment.mask & ~segment.occlusion
covered = layer.coverage > 0
if not covered.any() or not expected.any():
raise LayerRejected("EMPTY_LAYER", "A layer covers nothing.")
union = int((covered | expected).sum())
iou = int((covered & expected).sum()) / max(union, 1)
if iou < MIN_COVERAGE_IOU:
raise LayerRejected("COVERAGE_MISMATCH", f"A layer does not match its surface (overlap {iou:.3f}).")
contained = int((layer.support & covered).sum()) / max(int(covered.sum()), 1)
if contained < MIN_SUPPORT_CONTAINS_COVERAGE:
raise LayerRejected("COVERAGE_MISMATCH", "A layer was not rendered everywhere it is shown.")
reach = max(1, round(MAX_SUPPORT_REACH * min(context.size)))
allowed = cv2.dilate(segment.mask.astype(np.uint8), _disc(reach)).astype(bool) | enclosed_holes(segment.mask)
if (layer.support & ~allowed).any():
raise LayerRejected("SUPPORT_OUT_OF_BOUNDS", "A layer reaches beyond its surface.")
shown = layer.rgb[covered]
if shown.size == 0 or float(shown.std()) < 0.5:
raise LayerRejected("BAD_LAYER", "A layer's pixels are blank (the browser export failed).")
def check_overlaps(layers: list[Layer], context: JobContext) -> None:
"""Coverage shared by two layers must already be shared by the job's own masks (the room's
surfaces can overlap; the editor then shows the later layer on top). Anything more is a mismatch."""
for i, a in enumerate(layers):
for b in layers[i + 1:]:
ca, cb = a.coverage > 0, b.coverage > 0
shared_masks = context.segments[a.segment_id].mask & context.segments[b.segment_id].mask
excess = int((ca & cb & ~shared_masks).sum()) / max(1, min(int(ca.sum()), int(cb.sum())))
if excess > MAX_LAYER_OVERLAP:
raise LayerRejected("LAYER_OVERLAP", "Two layers cover the same pixels.")
|