File size: 12,008 Bytes
3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 3726258 3f3fbe2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | """CPU tests of the scene-specification, render and build helpers (no models).
"""
import csv, json, pathlib, subprocess, sys
import numpy as np
import pytest
from strangebench.generation import coco_class_prompts as ccp
from strangebench.scene_specs import layout_solver as ls
from strangebench.audit.audit_diffusion_scenes import dedup_cross_class
from strangebench.generation import gen_sd35l_e2e as gen
ROOT = pathlib.Path(__file__).resolve().parents[1]
def test_choose_attempt_first_complete_wins():
assert gen.choose_attempt([2, 3, 3], 3) == 1
assert gen.choose_attempt([3], 3) == 0
assert gen.choose_attempt([1, 4, 3], 3) == 1
def test_choose_attempt_most_found_first_on_ties():
assert gen.choose_attempt([1, 2, 2, 1], 3) == 1
assert gen.choose_attempt([0, 0], 2) == 0
with pytest.raises(ValueError):
gen.choose_attempt([], 2)
CATS = {1: "a", 2: "b"}
def _ann(aid, cid, bbox, score):
return dict(id=aid, image_id=1, category_id=cid, bbox=bbox, score=score)
def test_dedup_keeps_intended_class_drops_other():
anns = [_ann(1, 1, [0, 0, 100, 100], 0.4), _ann(2, 2, [0, 0, 100, 90], 0.95)]
dropped, flag = dedup_cross_class(anns, {"a"}, CATS, iou_thr=0.5)
assert [d["ann_id"] for d in dropped] == [2]
assert dropped[0]["kept_ann_id"] == 1 and dropped[0]["kept_class"] == "a"
assert dropped[0]["iou"] == pytest.approx(0.9, abs=1e-3)
assert dropped[0]["dropped_intended"] is False and flag is False
def test_dedup_both_intended_keeps_higher_score_and_flags_scene():
anns = [_ann(1, 1, [0, 0, 100, 100], 0.6), _ann(2, 2, [0, 0, 100, 90], 0.8)]
dropped, flag = dedup_cross_class(anns, {"a", "b"}, CATS, iou_thr=0.5)
assert [d["ann_id"] for d in dropped] == [1] and flag is True
def test_dedup_ignores_low_iou_same_class_and_off():
far = [_ann(1, 1, [0, 0, 100, 100], 0.6), _ann(2, 2, [500, 500, 100, 100], 0.8)]
assert dedup_cross_class(far, {"a", "b"}, CATS, 0.5) == ([], False)
same = [_ann(1, 1, [0, 0, 100, 100], 0.6), _ann(2, 1, [0, 0, 100, 90], 0.8)]
assert dedup_cross_class(same, {"a"}, CATS, 0.5) == ([], False)
anns = [_ann(1, 1, [0, 0, 100, 100], 0.6), _ann(2, 2, [0, 0, 100, 90], 0.8)]
assert dedup_cross_class(anns, {"a"}, CATS, 0.0) == ([], False)
def test_size_word_thresholds():
lo, hi = ccp.SIZE_WORD_THRESHOLDS
assert ccp.size_word(lo / 2) == "small"
assert ccp.size_word(lo) == "medium" and ccp.size_word((lo + hi) / 2) == "medium"
assert ccp.size_word(hi) == "large" and ccp.size_word(0.9) == "large"
assert ccp.rel_box_area([0, 0, 512, 512], 1024) == pytest.approx(0.25)
assert ccp.size_word_for_box([24, 24, 1000, 1000]) == "large"
assert ccp.size_word_for_box([0, 0, 100, 100]) == "small"
SCENE = dict(scene_id="tier2_1atypical__a064_s0000", sub_tier="tier2_1atypical", n_partners=1,
labels=["mouse", "cow"], layout_boxes=[[100, 100, 300, 300], [700, 700, 1000, 1000]],
img_size=1024, prompt="A photorealistic photo of a mouse and a cow, in an unusual setting")
def _v1_objects_block(scene):
return "\n".join(f" - {l} → {gen.bbox_to_position(bb)} of the image → {ccp.describe(l)}"
for l, bb in zip(scene["labels"], scene["layout_boxes"]))
def test_display_name_override():
assert ccp.display_name("mouse") == "computer mouse"
assert ccp.display_name("keyboard") == "computer keyboard"
assert ccp.display_name("mouse", overrides=False) == "mouse"
assert ccp.display_name("cow") == "cow"
block = gen.make_objects_block(SCENE)
assert block.startswith(" - computer mouse → ") and " - cow → " in block
assert gen.caption_names(["mouse", "cow"]) == ["computer mouse", "cow"]
assert gen.caption_names(["mouse", "cow"], display_names=False) == ["mouse", "cow"]
fixed = gen.apply_display_names(SCENE["prompt"], SCENE["labels"])
assert fixed == "A photorealistic photo of a computer mouse and a cow, in an unusual setting"
assert gen.apply_display_names(fixed, SCENE["labels"]) == fixed
def test_v1_wording_byte_identical_when_overrides_and_visibility_off():
ctx, phrase = gen.tier_descriptor(SCENE)
expected = gen.SPATIAL_PROMPT_TEMPLATE.format(context_label=ctx, tier_phrase=phrase,
objects_block=_v1_objects_block(SCENE))
assert gen.build_user_prompt(SCENE, visibility=False, display_names=False) == expected
assert gen.make_objects_block(SCENE, display_names=False) == _v1_objects_block(SCENE)
assert " - mouse → " in expected and " - computer mouse → " not in expected
def test_visibility_prompt_adds_bullet_and_size_words():
p = gen.build_user_prompt(SCENE, visibility=True)
assert "FULLY VISIBLE and unoccluded" in p and "size in the frame" in p
assert " - computer mouse → top left of the image → small in the frame → " in p
assert " - cow → bottom right of the image → medium in the frame → " in p
assert gen.SPATIAL_PROMPT_TEMPLATE_VISIBILITY.endswith(gen.VISIBILITY_BULLET)
assert "\\" not in p and p.count("\n- ") == 7
assert gen.SPATIAL_PROMPT_TEMPLATE not in (gen.SPATIAL_PROMPT_TEMPLATE_VISIBILITY,)
v1 = gen.build_user_prompt(SCENE, visibility=False)
assert "in the frame" not in v1
def test_sam3_prompts_for():
prim = {"keyboard": "a computer keyboard", "bed": "a picture of a {category}"}
sec = {"keyboard": "a keyboard"}
assert gen.sam3_prompts_for("cow", prim, sec) == ["a cow"]
assert gen.sam3_prompts_for("cow", prim, sec, union=True) == ["a cow", "cow"]
assert gen.sam3_prompts_for("keyboard", prim, sec, union=True) == ["a computer keyboard", "a keyboard"]
assert gen.sam3_prompts_for("bed", prim, sec, union=True) == ["a picture of a bed", "bed"]
def _mask(x0, x1):
m = np.zeros((64, 64), dtype=np.uint8)
m[16:48, x0:x1] = 255
return m
def test_merge_prompt_results():
assert gen.merge_prompt_results([]) is None
same, same2, other = _mask(10, 40), _mask(12, 42), _mask(50, 60)
m, s, hits = gen.merge_prompt_results([(same, 0.7, "a cow"), (same2, 0.9, "cow")], iou_thr=0.5)
assert s == 0.9 and hits == ["cow", "a cow"]
assert m[20, 11] == 255 and m[20, 41] == 255
m, s, hits = gen.merge_prompt_results([(same, 0.7, "a cow"), (other, 0.6, "cow")], iou_thr=0.5)
assert s == 0.7 and hits == ["a cow"] and m[20, 55] == 0
m, s, hits = gen.merge_prompt_results([(same, 0.7, "a cow"), (same2, 0.7, "cow")])
assert hits[0] == "a cow"
K6 = ["person", "dog", "bench", "kite", "bottle", "airplane"]
@pytest.fixture(scope="module")
def priors():
assert ls.DEFAULT_PRIORS_PATH.exists(), ls.DEFAULT_PRIORS_PATH
p = ls.load_size_priors()
assert len(p) == 80
return p
@pytest.mark.parametrize("area_scale", [1.0, 3.0])
def test_solver_k6_non_overlap_and_margins(priors, area_scale):
cfg = ls.SolverConfig()
for seed in range(10):
info = ls.solve_layout(K6, priors, 1024, seed=seed, area_scale=area_scale)
assert info["layout_source"] == "solver", (seed, info)
boxes = info["layout_boxes"]
assert len(boxes) == 6 and ls.check_layout(boxes, K6) == []
for x1, y1, x2, y2 in boxes:
assert cfg.margin <= x1 < x2 <= 1024 - cfg.margin and cfg.margin <= y1 < y2 <= 1024 - cfg.margin
assert min(x2 - x1, y2 - y1) >= cfg.min_short_side
assert (x2 - x1) * (y2 - y1) <= cfg.max_rel_area * 1024 * 1024 + 1
for i in range(6):
for j in range(i + 1, 6):
assert ls.box_iou(boxes[i], boxes[j]) <= cfg.max_iou
for lbl, b in zip(K6, boxes):
if lbl in ls.GROUND_CONTACT_CLASSES:
assert b[3] >= 0.4 * 1024
a = ls.solve_layout(K6, priors, 1024, seed=7, area_scale=area_scale)
assert a == ls.solve_layout(K6, priors, 1024, seed=7, area_scale=area_scale)
assert a["layout_boxes"] != ls.solve_layout(K6, priors, 1024, seed=8, area_scale=area_scale)["layout_boxes"]
def test_stage1_solver_seed_is_process_independent():
from strangebench.scene_specs.select_scenes_and_layouts import solver_seed, solver_layout
assert solver_seed(42, "tier5_4typical__a001_s0000") == solver_seed(42, "tier5_4typical__a001_s0000")
assert solver_seed(42, "x") != solver_seed(43, "x")
info = solver_layout(K6, 1024, {}, seed=1, area_scale=3.0)
assert info["layout_source"] == "solver" and info["layout_attempts"] == 0
assert info["solver_attempts"] > 0 and info["solver_area_scale"] == 3.0
fb = solver_layout(K6, 1024, {}, seed=1, area_scale=3.0, source="solver_fallback", llm_attempts=3)
assert fb["layout_source"] == "solver_fallback" and fb["layout_attempts"] == 3
def _run(args, cwd):
r = subprocess.run([sys.executable] + args, capture_output=True, text=True, cwd=str(cwd))
assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-2000:]
return r
def test_fragment_to_manifest_lever_columns(tmp_path):
from PIL import Image
raw = tmp_path / "raw"
tier = raw / "tier2_1atypical"
(tier / "raw").mkdir(parents=True)
Image.new("RGB", (8, 8)).save(tier / "raw" / "v2_s1.png")
Image.new("RGB", (8, 8)).save(tier / "raw" / "v2_s2.png")
base = dict(sub_tier="tier2_1atypical", labels=["mouse", "cow"])
(tier / "v2_s1_anns.json").write_text(json.dumps(dict(base, scene_id="v2_s1",
annotations=[dict(category_name="mouse", bbox=[1, 1, 3, 3], score=0.9),
dict(category_name="cow", bbox=[4, 4, 3, 3], score=0.8)],
render_attempts=2, attempt_seeds=[10, 11], chosen_attempt=1, complete_at_render=True,
n_found_per_attempt=[1, 2], visibility_prompt=True, sam3_prompt_union=False)))
(tier / "v2_s2_anns.json").write_text(json.dumps(dict(base, scene_id="v2_s2",
annotations=[dict(category_name="cow", bbox=[4, 4, 3, 3], score=0.8)])))
cats = tmp_path / "categories.json"
cats.write_text(json.dumps(dict(idx_to_name={"0": "mouse", "1": "cow"}, id_to_idx={"74": 0, "21": 1})))
_run(["strangebench/audit/merge_per_scene_anns.py", "--out-root", str(raw), "--categories-json", str(cats)], ROOT)
coco = json.load(open(tier / "annotations.json"))
by_sid = {im["scene_id"]: im for im in coco["images"]}
assert by_sid["v2_s1"]["render_attempts"] == 2 and by_sid["v2_s1"]["visibility_prompt"] is True
assert by_sid["v2_s1"]["complete_at_render"] is True and by_sid["v2_s1"]["attempt_seeds"] == [10, 11]
assert "render_attempts" not in by_sid["v2_s2"]
clean = tmp_path / "clean" / "tier2_1atypical"
(clean / "images").mkdir(parents=True)
for sid in ("v2_s1", "v2_s2"):
(clean / "images" / f"{sid}.png").write_bytes((tier / "raw" / f"{sid}.png").read_bytes())
json.dump(coco, open(clean / "annotations.json", "w"))
specs = tmp_path / "scene_specs.json"
json.dump([dict(scene_id="v2_s1", anchor={"idx": 64, "name": "mouse"}, partners=[{"idx": 19, "name": "cow"}],
sub_tier="tier2_1atypical", layout_source="solver", variant="k56"),
dict(scene_id="v2_s2", anchor={"idx": 64, "name": "mouse"}, partners=[{"idx": 19, "name": "cow"}],
sub_tier="tier2_1atypical", layout_source="qwen")], open(specs, "w"))
dst = tmp_path / "v2"
_run(["strangebench/strict/build_dataset.py", "--source", "v2", str(tmp_path / "clean"), str(specs),
"--dst", str(dst)], ROOT)
rows = {r["scene_id"]: r for r in csv.DictReader(open(dst / "tier_manifest.csv"))}
assert set(rows) == {"v2_s1", "v2_s2"}
assert rows["v2_s1"]["variant"] == "k56" and rows["v2_s1"]["layout_source"] == "solver"
assert rows["v2_s1"]["render_attempts"] == "2" and rows["v2_s1"]["visibility_prompt"] == "1"
assert rows["v2_s2"]["layout_source"] == "qwen" and rows["v2_s2"]["variant"] == ""
assert rows["v2_s2"]["render_attempts"] == "" and rows["v2_s2"]["visibility_prompt"] == ""
assert rows["v2_s1"]["complete"] == "1" and rows["v2_s2"]["complete"] == "0"
|