Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
195 lines
8.0 KiB
Python
195 lines
8.0 KiB
Python
"""RGB adapter uses real pinned stores, native pixels and isolated split readers."""
|
|
import copy
|
|
import importlib.util
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from PIL import Image
|
|
from test_semantic_admission import admission as admission_fixture
|
|
from test_semantic_admission import corpus as corpus_fixture
|
|
from test_semantic_admission import dataset, decision, release
|
|
from test_semantic_corpus import group, opened, plan
|
|
from test_semantic_delivery import ds
|
|
|
|
np = pytest.importorskip("numpy")
|
|
admission = admission_fixture
|
|
corpus = corpus_fixture
|
|
|
|
|
|
@pytest.fixture
|
|
def rgb(admission, monkeypatch):
|
|
monkeypatch.setitem(sys.modules, "admission_store", admission)
|
|
spec = importlib.util.spec_from_file_location(
|
|
"rgb_training_input_test",
|
|
Path(__file__).parents[1] / "simulation/semantic-learning/rgb_training_input.py",
|
|
)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def rgb_dataset(root, name, world, color):
|
|
entry = dataset(root, name, world=world)
|
|
folder = root / entry["path"]
|
|
for view in ["top", "oblique"]:
|
|
Image.new("RGB", (8, 6), color).save(folder / "window" / (view + ".png"))
|
|
path = folder / "dataset.json"
|
|
manifest = json.loads(path.read_text())
|
|
for name in manifest["files"]:
|
|
member = folder / name
|
|
manifest["files"][name] = dict(sha256=ds.checksum(member), bytes=member.stat().st_size)
|
|
ds.write(path, manifest)
|
|
entry["sha256"] = ds.checksum(path)
|
|
return entry
|
|
|
|
|
|
@pytest.fixture
|
|
def admitted(admission, corpus, tmp_path):
|
|
entries = [
|
|
rgb_dataset(tmp_path, "train", "a" * 64, (230, 17, 5)),
|
|
rgb_dataset(tmp_path, "test", "d" * 64, (4, 9, 240)),
|
|
]
|
|
index = corpus.build(
|
|
tmp_path,
|
|
plan(corpus, entries, [group("train-area", "train", "a" * 64),
|
|
group("test-area", "test", "d" * 64)]),
|
|
"corpora/rgb",
|
|
)
|
|
with opened(corpus, tmp_path, index) as reader:
|
|
rr = [r for split in ["train", "test"] for b in reader.batches(split) for r in b]
|
|
admitted, _ = release(admission, tmp_path, index, rr,
|
|
[decision(admission, r) for r in rr])
|
|
return admitted
|
|
|
|
|
|
def reader(admission, root, receipt):
|
|
return admission.Supervision(root, receipt["path"], receipt["sha256"])
|
|
|
|
|
|
def test_pinned_rgb_targets_and_split_isolation(rgb, admission, admitted, tmp_path):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
training = list(rgb.training_frames(source))
|
|
testing = list(rgb.evaluation_frames(source, split="test"))
|
|
assert len(training) == len(testing) == 1
|
|
a, b = training[0], testing[0]
|
|
assert a["metadata"]["split"] == "train" and b["metadata"]["split"] == "test"
|
|
assert a["metadata"]["physical_group"] != b["metadata"]["physical_group"]
|
|
assert a["img"][0, 0].tolist() == [230, 17, 5] # no silent RGB/BGR swap
|
|
assert b["img"][0, 0].tolist() == [4, 9, 240]
|
|
mask = a["target"]
|
|
assert np.count_nonzero(mask == 1) == 3
|
|
assert np.count_nonzero(mask == 0) == 6
|
|
assert np.count_nonzero(mask == 255) == 39
|
|
assert a["metadata"]["input"]["view"] == "top"
|
|
assert a["img"].shape == (6, 8, 3)
|
|
|
|
|
|
def test_hash_failure_precedes_decode(rgb, admission, admitted, tmp_path):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
image = tmp_path / "datasets/train/window/top.png"
|
|
image.write_bytes(image.read_bytes() + b"changed")
|
|
with pytest.raises(ValueError, match="changed"):
|
|
next(rgb.training_frames(source))
|
|
|
|
|
|
def test_loader_does_not_open_next_image_early(rgb, admission, admitted, tmp_path, monkeypatch):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
opened = []
|
|
original = source.open_image
|
|
def tracked(value):
|
|
opened.append(value["sample_id"])
|
|
return original(value)
|
|
monkeypatch.setattr(source, "open_image", tracked)
|
|
iterator = rgb.training_frames(source)
|
|
assert opened == []
|
|
next(iterator)
|
|
assert len(opened) == 1
|
|
iterator.close()
|
|
assert len(opened) == 1
|
|
|
|
|
|
def test_native_crop_padding_and_source_mapping(rgb, admission, admitted, tmp_path):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
frame = next(rgb.training_frames(source))
|
|
original = copy.deepcopy(frame["metadata"])
|
|
cropped = rgb.crop(frame, left=1, top=1, size=8)
|
|
expected = np.full((8, 8), 255, np.uint8)
|
|
expected[:5, :7] = frame["target"][1:, 1:]
|
|
assert np.array_equal(cropped["target"], expected)
|
|
assert np.array_equal(cropped["img"][:5, :7], frame["img"][1:, 1:])
|
|
assert np.all(cropped["img"][5:] == 0)
|
|
assert cropped["metadata"]["crop_to_source_edges"] == [1, 0, 0, 1, 1, 1]
|
|
assert cropped["metadata"]["input"] == original["input"] # no guessed camera rewrite
|
|
assert frame["metadata"] == original
|
|
assert rgb.crop(frame, left=7, top=5, size=4) is None
|
|
cropped["target"][0, 1] = 0
|
|
assert frame["target"][1, 2] == 1
|
|
|
|
|
|
@pytest.mark.parametrize("mutation", [
|
|
lambda e: e.update(split="test", training_eligible=False),
|
|
lambda e: e.update(task="contextual_map"),
|
|
lambda e: e.update(background_from_absence=True),
|
|
lambda e: e["targets"][0].update(ignore_index=0),
|
|
lambda e: e["targets"][0].update(size=[8, 7]),
|
|
])
|
|
def test_invalid_training_contract_refused_before_image(rgb, admission, admitted, tmp_path,
|
|
monkeypatch, mutation):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
example = next(source.training_batches("observed_paint"))[0]
|
|
mutation(example)
|
|
def forbidden(*args):
|
|
raise AssertionError("Unaligned image was opened")
|
|
monkeypatch.setattr(source, "open_image", forbidden)
|
|
with pytest.raises(ValueError):
|
|
rgb.load_frame(source, example, "top", split="train")
|
|
|
|
|
|
def test_all_unknown_does_not_open_media(rgb, admission, admitted, tmp_path, monkeypatch):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
example = next(source.training_batches("observed_paint"))[0]
|
|
example["targets"][0].update(paint=[], background=[], unknown=[])
|
|
def forbidden(*args):
|
|
raise AssertionError("All-ignore sample decoded")
|
|
monkeypatch.setattr(source, "open_image", forbidden)
|
|
assert rgb.load_frame(source, example, "top", split="train") is None
|
|
|
|
|
|
def test_evaluation_cannot_select_train(rgb):
|
|
with pytest.raises(ValueError, match="non-training"):
|
|
next(rgb.evaluation_frames(None, split="train"))
|
|
|
|
|
|
def test_mmseg_input_loss_contract(rgb):
|
|
options = rgb.mmseg_overrides()
|
|
assert options["dataset"] == {"reduce_zero_label": False, "ignore_index": 255}
|
|
head = options["model"]["decode_head"]
|
|
assert head["num_classes"] == head["out_channels"] == 2
|
|
assert head["ignore_index"] == 255
|
|
assert head["loss_decode"]["avg_non_ignore"] is True
|
|
assert options["model"]["data_preprocessor"]["bgr_to_rgb"] is False
|
|
assert options["model"]["data_preprocessor"]["seg_pad_val"] == 255
|
|
|
|
|
|
def test_forged_split_flags_cannot_admit_test_image(rgb, admission, admitted, tmp_path,
|
|
monkeypatch):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
example = next(source.batches("observed_paint", "test"))[0]
|
|
example.update(split="train", training_eligible=True)
|
|
def forbidden(*args):
|
|
raise AssertionError("Test image reached training decode")
|
|
monkeypatch.setattr(source, "open_image", forbidden)
|
|
with pytest.raises(ValueError, match="pinned source split"):
|
|
rgb.load_frame(source, example, "top", split="train")
|
|
|
|
|
|
def test_nested_crop_rejected_instead_of_resetting_source_offset(rgb, admission, admitted,
|
|
tmp_path):
|
|
with reader(admission, tmp_path, admitted) as source:
|
|
frame = next(rgb.training_frames(source))
|
|
first = rgb.crop(frame, left=1, top=1, size=8)
|
|
with pytest.raises(ValueError, match="Nested crop"):
|
|
rgb.crop(first, left=0, top=0, size=4)
|