Files
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00

90 lines
4.4 KiB
Python

"""Source-local scoring of observed paint; unknown is never ground truth.
Instance polygons only identify observed cores. Gap contamination is not a
merge verdict; uncertainty prevents topology/physical-boundary claims.
"""
import hashlib
import numpy as np
from PIL import Image, ImageDraw
from scipy.spatial import ConvexHull
def array_sha(value):
return hashlib.sha256(value.tobytes()).hexdigest()
def polygon_mask(points, shape):
image = Image.new("1", (shape[1], shape[0]))
ImageDraw.Draw(image).polygon([tuple(p) for p in points], fill=1)
return np.array(image, dtype=bool)
def support(target, instances):
if target.ndim != 2 or target.dtype != np.uint8 or not np.isin(target, [0, 1, 255]).all():
raise ValueError("Native uint8 0/1/255 target required")
cores, gaps, rows = [], [], []
for obj in instances:
core = polygon_mask(obj["outline_native_pixels"], target.shape) & (target == 1)
if int(core.sum()) != obj["final_paint_pixels"] or not core.any():
raise ValueError("Reviewed visible core differs: " + obj["id"])
if any((core & other).any() for other in cores):
raise ValueError("Overlapping instance cores")
cores.append(core)
rows.append(dict(id=obj["id"], visibility=obj["visibility"],
core_pixels=int(core.sum()), core_sha256=array_sha(core)))
if cores and not np.array_equal(np.logical_or.reduce(cores), target == 1):
raise ValueError("Instance observations do not cover exactly the reviewed paint")
# Annotation order is frozen. Only adjacent members of the same crossing
# have a declared between-bars region; partial line fragments do not.
for left, right in zip(instances, instances[1:], strict=False):
if (left["kind"] != "observed_crosswalk_bar"
or right["kind"] != "observed_crosswalk_bar"
or left.get("semantic_group") != right.get("semantic_group")):
continue
pts = np.asarray(left["outline_native_pixels"] + right["outline_native_pixels"])
hull = pts[ConvexHull(pts).vertices]
mask = polygon_mask(hull, target.shape) & (target == 0)
mask &= ~polygon_mask(left["outline_native_pixels"], target.shape)
mask &= ~polygon_mask(right["outline_native_pixels"], target.shape)
gaps.append((dict(pair=[left["id"], right["id"]],
background_pixels=int(mask.sum()), mask_sha256=array_sha(mask)), mask))
return cores, rows, gaps
def score(probability, target, instances):
if (probability.shape != target.shape or not np.isfinite(probability).all()
or not ((probability >= 0) & (probability <= 1)).all()):
raise ValueError("Finite native-grid probabilities required")
pred = probability >= .5
pos, neg = target == 1, target == 0
cores, rows, gaps = support(target, instances)
tp, fn = int((pred & pos).sum()), int((~pred & pos).sum())
fp, tn = int((pred & neg).sum()), int((~pred & neg).sum())
return dict(
prediction_sha256=array_sha(probability), target_sha256=array_sha(target),
tp=tp, fn=fn, fp=fp, tn=tn, paint_pixels=tp+fn, background_pixels=fp+tn,
unknown_pixels=int((target == 255).sum()),
fnr=fn/(tp+fn) if tp+fn else None, fpr=fp/(fp+tn) if fp+tn else None,
observations=[dict(row, tp=int((pred & core).sum()),
fn=int((~pred & core).sum()),
recall=float((pred & core).sum()/core.sum()),
missed_core=not bool((pred & core).any()))
for row, core in zip(rows, cores, strict=True)],
gaps=[dict(row, fp=int((pred & mask).sum()),
fpr=float((pred & mask).sum()/mask.sum()) if mask.any() else None,
assessed=bool(mask.any())) for row, mask in gaps],
not_assessed=["full_window_recall", "whole_crossing_count", "holes",
"physical_boundary_accuracy", "instance_merge_split"],
)
def paired_changes(candidate, baseline, target):
a, b = candidate >= .5, baseline >= .5
if a.shape != target.shape or b.shape != target.shape:
raise ValueError("Paired native shapes differ")
return dict(new_fn=int((~a & b & (target == 1)).sum()),
recovered_fn=int((a & ~b & (target == 1)).sum()),
new_fp=int((a & ~b & (target == 0)).sum()),
removed_fp=int((~a & b & (target == 0)).sum()))