Files
NODEDC_MISSION_CORE/simulation/semantic-learning/boundary_review.py
T
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

239 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Portable, explicitly reviewed boundary evidence; no implicit pixel/background truth.
Run on Worker. A reviewer selects a rectangle in an existing orthographic image.
The target is a range on the original stored polyline, never a refitted curve.
Only an explicit relative preference is eligible for the first ranking trial.
"""
import argparse
import math
import shutil
from pathlib import Path
from dataset_store import checksum, confined, digest, read, review_samples, write
SCHEMA = "missioncore.boundary-review-pack/v1"
LIMIT = 96 * 1024**2
def clipped_range(a, b, rect):
"""Liang–Barsky parameters on the unchanged source segment (pixel centres)."""
lo, hi = 0.0, 1.0
for axis in (0, 1):
delta = b[axis] - a[axis]
if delta == 0:
if not rect[axis] <= a[axis] <= rect[axis + 2]:
return None
else:
x, y = sorted(((rect[axis] - a[axis]) / delta, (rect[axis + 2] - a[axis]) / delta))
lo, hi = max(lo, x), min(hi, y)
return [lo, hi] if hi > lo else None
def compile_record(labels, cameras, decision):
if decision["evidence"] not in {"visible", "context", "uncertain"}:
raise ValueError("Unknown evidence category")
if not decision.get("reviewer") or not decision.get("reason"):
raise ValueError("Explicit reviewer and reason required")
feature = next(f for f in labels["proposed_element"] if f["id"] == decision["feature_id"])
if (
feature["properties"]["class"] != "road_boundary"
or feature["properties"].get("review_status") == "rejected"
or feature["geometry"]["type"] != "LineString"
):
raise ValueError("Expected an active road boundary LineString")
camera = next(c for c in cameras["views"] if c["id"] == decision["view"])
if camera["projection"] != "ortho":
raise ValueError("Review ranges currently require orthographic projection")
rect = decision["rect_px"]
if (
len(rect) != 4
or not all(math.isfinite(x) for x in rect)
or not 0 <= rect[0] < rect[2] < camera["size"][0]
or not 0 <= rect[1] < rect[3] < camera["size"][1]
):
raise ValueError("Review rectangle outside image")
projections = [
p for p in labels["projections"][decision["view"]] if p["feature_id"] == feature["id"]
]
if len(projections) != 1:
raise ValueError("Ambiguous source path")
projection = projections[0]
points = feature["geometry"]["coordinates"]
uv = projection["uv"]
if len(points) != len(uv) or len(points) != len(projection["in_front"]):
raise ValueError("Projection/path identity mismatch")
ranges = []
for i, (a, b) in enumerate(zip(uv, uv[1:], strict=False)):
if not all(math.isfinite(v) for v in (*a, *b, *points[i], *points[i + 1])):
raise ValueError("Non-finite observation")
span = clipped_range(a, b, rect)
if span and projection["in_front"][i] and projection["in_front"][i + 1]:
ranges.append(dict(segment=i, t=span))
if not ranges:
raise ValueError("Review rectangle contains no source segment")
original = next((f for f in labels["original_element"] if f["id"] == feature["id"]), None)
preference = decision.get("preference")
if preference not in {None, "edited-better-than-original"}:
raise ValueError("Unknown ranking preference")
eligible = preference is not None and decision["evidence"] == "visible"
if preference and (
not eligible or original is None or original["geometry"] == feature["geometry"]
):
raise ValueError("Preference requires visible evidence and distinct source candidates")
return dict(
**decision,
geometry_sha256=digest(feature["geometry"]),
original_geometry_sha256=digest(original["geometry"]) if original else None,
camera_sha256=digest(camera),
path=0,
segment_ranges=ranges,
ranking_trial_eligible=eligible,
metric_ground_truth=False,
dense_segmentation_eligible=False,
background_targets=[],
complete_regions=[],
human_approved=False,
)
def check_control(control, train_world):
if (
control.get("schema_version") != "missioncore.boundary-control/v1"
or control.get("role") != "held-out-scene"
or control.get("world_sha256") == train_world
or control.get("training_eligible") is not False
or not control.get("windows")
or not control.get("frozen_utc")
):
raise ValueError("A distinct frozen control scene is required")
for key in ("world_sha256", "model_sha256"):
value = control.get(key, "")
if len(value) != 64 or any(c not in "0123456789abcdef" for c in value):
raise ValueError("Control source identity required")
def verify_pack(root):
root = Path(root)
manifest = read(root / "pack.json")
if manifest["schema_version"] != SCHEMA:
raise ValueError("Unsupported boundary pack")
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(manifest["files"]) | {"pack.json"}:
raise ValueError("Unexpected pack member")
total = 0
for name, spec in manifest["files"].items():
path = confined(root, name)
total += path.stat().st_size
if path.stat().st_size != spec["bytes"] or checksum(path) != spec["sha256"]:
raise ValueError("Pack member changed: " + name)
if total > LIMIT:
raise ValueError("Boundary pack exceeds bounded size")
decisions = read(root / "decisions.json")
check_control(read(root / "control.json"), manifest["source"]["world_sha256"])
records = []
for decision in decisions["records"]:
folder = Path("observations") / Path(decision["sample"]).parent
labels = read(confined(root, (folder / "labels.json").as_posix()))
cameras = read(confined(root, (folder / "cameras.json").as_posix()))
records.append(compile_record(labels, cameras, decision))
if records != read(root / "records.json"):
raise ValueError("Admission differs from reviewed evidence")
return dict(
sha256=checksum(root / "pack.json"),
bytes=total,
records=len(records),
ranking_pairs=sum(r["ranking_trial_eligible"] for r in records),
)
def build_pack(source, decisions, control, destination):
source, destination = Path(source), Path(destination)
if destination.exists() or destination.resolve().is_relative_to(source.resolve()):
raise ValueError("Use a new destination outside the immutable source dataset")
if checksum(source / "dataset.json") != decisions["dataset_sha256"]:
raise ValueError("Reviewed collection changed")
if not 1 <= len(decisions["records"]) <= 12:
raise ValueError("First review pack is bounded to twelve decisions")
if len({r["id"] for r in decisions["records"]}) != len(decisions["records"]):
raise ValueError("Duplicate review identity")
wanted = {d["sample"] for d in decisions["records"]}
# This verifies the complete immutable collection before selecting a small subset.
rows = {row["sample"]: row for row in review_samples(source) if row["sample"] in wanted}
if set(rows) != wanted:
raise ValueError("Unknown reviewed sample")
identity = next(iter(rows.values()))["source"]
if any(r["source"] != identity for r in rows.values()):
raise ValueError("Mixed source revisions")
check_control(control, identity["world_sha256"])
files = {"provenance/collection.json": source / "dataset.json"}
records = []
for d in decisions["records"]:
sample = confined(source, d["sample"])
folder = sample.parent
labels, cameras = read(folder / "labels.json"), read(folder / "cameras.json")
records.append(compile_record(labels, cameras, d))
shard = read(folder.parent / "dataset.json")
part = folder.parent.name
files[f"provenance/{part}.json"] = folder.parent / "dataset.json"
files["provenance/annotation.json"] = folder.parent / "annotation.json"
for name in read(sample)["members"] + [folder.name + "/sample.json"]:
member = confined(folder.parent, name)
if name not in shard["files"]:
raise ValueError("Unbound observation")
files[f"observations/{part}/{name}"] = member
if sum(p.stat().st_size for p in files.values()) > LIMIT - 1024**2:
raise ValueError("Selected observations exceed size budget")
destination.parent.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(destination.parent).free < 12 * 1024**3 + LIMIT:
raise ValueError("Worker disk reserve would be exceeded")
staging = destination.with_name(destination.name + ".partial")
staging.mkdir() # No overwrite of another attempt.
for name, origin in files.items():
target = staging / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(origin, target)
if checksum(target) != checksum(origin):
raise ValueError("Observation copy changed")
for name, value in (
("decisions.json", decisions),
("control.json", control),
("records.json", records),
):
write(staging / name, value)
# A standalone stdlib reader travels with the pack.
for script in (Path(__file__), Path(__file__).with_name("dataset_store.py")):
shutil.copyfile(script, staging / script.name)
write(
staging / "pack.json",
dict(
schema_version=SCHEMA,
source=identity,
source_collection_sha256=decisions["dataset_sha256"],
usage="local-boundary-ranking-trial",
dense_segmentation_eligible=False,
files={
p.relative_to(staging).as_posix(): dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(staging.rglob("*"))
if p.is_file()
},
),
)
result = verify_pack(staging)
staging.rename(destination)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
parser.add_argument("--decisions", type=Path)
parser.add_argument("--control", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.output:
result = build_pack(args.root, read(args.decisions), read(args.control), args.output)
else:
result = verify_pack(args.root)
print(result)