"""Explicit TRAIN-only paint additions over immutable labels; never infer background.""" import hashlib import numpy as np from condition_inventory import raster from PIL import Image, ImageFilter def add_fragments(sample, review, old, approved_roi): if sample["split"] != "train" or review["name"] != sample["name"]: raise ValueError("Pinned TRAIN sample required") if review["input_sha256"] != sample["rgb_sha256"]: raise ValueError("Image identity changed") if old.dtype != np.uint8 or list(old.shape[::-1]) != sample["size"]: raise ValueError("Invalid target shape/type") if not np.isin(old, [0, 1, 255]).all(): raise ValueError("Invalid target classes") expected = sample["target_sha256"] if sample["kind"] == "existing": if expected is None or hashlib.sha256(old.tobytes()).hexdigest() != expected: raise ValueError("Existing target changed") elif sample["kind"] != "candidate" or expected is not None or np.any(old != 255): raise ValueError("Candidate already has unbound labels") if review["target_sha256"] != expected or review["boundary_ignore_px"] != 1: raise ValueError("Pinned target/uncertainty policy required") polygons = review["paint_fragments"] if not isinstance(polygons, list) or not 1 <= len(polygons) <= 64: raise ValueError("Bounded explicit fragments required") mask = np.zeros(old.shape, dtype=bool) roi = raster(approved_roi, sample["size"]) for polygon in polygons: part = raster(polygon, sample["size"]) if np.any(part & ~roi): raise ValueError("Fragment escaped prereviewed region") mask |= part core = ( np.array(Image.fromarray(mask.astype("uint8") * 255).filter(ImageFilter.MinFilter(3))) > 0 ) if np.any(core & (old == 0)): raise ValueError("Paint conflicts with accepted background") added = core & (old == 255) if not added.any(): raise ValueError("No new visible paint survived uncertainty erosion") result = old.copy() result[added] = 1 return result, added def runs(target): result = dict(view="top", paint=[], background=[], unknown=[]) for name, label in [("paint", 1), ("background", 0)]: for y, row in enumerate(target == label): edges = np.diff(np.pad(row.astype("int8"), (1, 1))) result[name].extend( [ [y, int(a), int(b)] for a, b in zip( np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True ) ] ) return result