Spaces:
Paused
Paused
Download apps/renderer/services/enhance/validate.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 8.72 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/enhance/validate.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/services/enhance/validate.py
-
curl -L -o validate.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/enhance/validate.py
8.72 kB
| """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 | |
| class TileRef: | |
| slug: str | |
| name: str | |
| image_url: str | None | |
| width_mm: float | None | |
| height_mm: float | None | |
| mural: bool | |
| pattern_match: str | |
| 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.") | |