"""Pinned TRAIN-only background admission with fixed existing window mass.""" import hashlib import numpy as np from condition_inventory import raster from PIL import Image, ImageFilter def add_background(sample, review, target, protected): if sample["split"] != "train" or review["name"] != sample["name"]: raise ValueError("Pinned TRAIN sample required") if ( target.dtype != np.uint8 or target.ndim != 2 or list(target.shape[::-1]) != sample["size"] or not np.isin(target, [0, 1, 255]).all() or protected.dtype != bool or protected.shape != target.shape or np.any(protected & (target != 255)) ): raise ValueError("Aligned labels and unknown-only protected mask required") for key, actual in [ ("target_sha256", hashlib.sha256(target.tobytes()).hexdigest()), ("protected_sha256", hashlib.sha256(protected.tobytes()).hexdigest()), ("rgb_sha256", sample["rgb_sha256"]), ]: if review[key] != actual or sample[key] != actual: raise ValueError("Pinned source or target changed") if review["boundary_ignore_px"] != 2 or not isinstance(review["regions"], list): raise ValueError("Explicit two-native-pixel uncertainty margin required") if len(review["regions"]) > 32: raise ValueError("Bounded reviewed regions required") added = np.zeros(target.shape, dtype=bool) audit, seen = [], set() for region in review["regions"]: if not region["reason"].strip() or not region["id"] or region["id"] in seen: raise ValueError("Unique region identity and visible-source reason required") seen.add(region["id"]) mask = raster(region["polygon"], sample["size"]) core = ( np.asarray(Image.fromarray(mask.astype("uint8") * 255).filter(ImageFilter.MinFilter(5))) > 0 ) if np.any(core & (target == 1)): raise ValueError("Reviewed background conflicts with accepted paint") fresh = core & (target == 255) & ~protected if np.any(fresh & added): raise ValueError("Overlapping added-background interiors") added |= fresh audit.append( dict( id=region["id"], new_pixels=int(fresh.sum()), known_background=int((core & (target == 0)).sum()), protected_excluded=int((core & protected).sum()), ) ) out = target.copy() out[added] = 0 return out, added, audit def prepare_background(records, weights): """Keep positive weights exact; redistribute each window's existing BG mass. New negatives may enter only windows already containing reviewed background. Empty additions are an exact identity, including dtype and sample order. """ if not records or set(weights) != {r["name"] for r in records}: raise ValueError("Matching nonempty records and weights required") output, result, seen = [], {}, set() for r in records: name = r["name"] if r["split"] != "train" or name in seen: raise ValueError("Unique TRAIN records required") seen.add(name) target, added, w = r["target"], r["added_background"], weights[name] if ( target.dtype != np.uint8 or target.ndim != 2 or not np.isin(target, [0, 1, 255]).all() or added.dtype != bool or added.shape != target.shape or w.shape != target.shape or w.dtype.kind != "f" or not np.isfinite(w).all() or np.any(w < 0) or np.any(w[target == 255] != 0) or np.any(added & (target != 255)) ): raise ValueError("Invalid labels, admitted background or weights") t, ww = target.copy(), w.copy() nadd = int(added.sum()) if nadd: existing = target == 0 nold = int(existing.sum()) if not nold or np.any(w[existing] <= 0): raise ValueError("Existing positive background mass required in each added window") mass = float(w[existing].sum(dtype=np.float64)) ww[existing] *= nold / (nold + nadd) ww[added] = mass / (nold + nadd) t[added] = 0 output.append(dict(r, target=t)) result[name] = ww return output, result