Cnass commited on
Commit
bf442bf
·
verified ·
1 Parent(s): de08a38

Upload 4 files

Browse files
tests/test_api.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ tests/test_api.py
3
+ ------------------
4
+ HTTP-level tests for the endpoints that carry real logic rather than
5
+ being a one-line pass-through: bulk metadata assignment, duplicate
6
+ collapsing, and the animation frame layout.
7
+
8
+ The DB path is redirected to a throwaway file BEFORE `app` is imported,
9
+ so these never touch the Space's real data.
10
+
11
+ Run with: pytest tests/test_api.py -v
12
+ """
13
+
14
+ import importlib
15
+ import sys
16
+ import tempfile
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
20
+
21
+ _TMP = tempfile.TemporaryDirectory()
22
+ import config # noqa: E402
23
+
24
+ config.DB_PATH = Path(_TMP.name) / "api-test.sqlite3"
25
+
26
+ import database as db # noqa: E402
27
+
28
+ importlib.reload(db)
29
+
30
+ import app as flask_app # noqa: E402
31
+
32
+
33
+ def reset_db():
34
+ if config.DB_PATH.exists():
35
+ config.DB_PATH.unlink()
36
+ for suffix in ("-wal", "-shm"):
37
+ extra = Path(str(config.DB_PATH) + suffix)
38
+ if extra.exists():
39
+ extra.unlink()
40
+ db.init_db()
41
+
42
+
43
+ def client():
44
+ flask_app.app.config["TESTING"] = True
45
+ return flask_app.app.test_client()
46
+
47
+
48
+ def make_sprite(sprite_id, sheet_id="sheet_a", **kwargs):
49
+ db.insert_sprite(
50
+ db.SpriteRecord(
51
+ id=sprite_id,
52
+ sheet_id=sheet_id,
53
+ source_file=f"{sheet_id}.png",
54
+ sprite_index=kwargs.pop("sprite_index", 1),
55
+ x=kwargs.pop("x", 0), y=kwargs.pop("y", 0),
56
+ width=kwargs.pop("width", 16), height=kwargs.pop("height", 16),
57
+ png_path=f"/tmp/{sprite_id}.png",
58
+ png_path_transparent=None,
59
+ sha256=sprite_id, phash="00",
60
+ quality={"overall_quality_score": kwargs.pop("quality", 80.0)},
61
+ confidence=kwargs.pop("confidence", 95.0),
62
+ confidence_reasons=[],
63
+ component_count=1,
64
+ category=kwargs.pop("category", "unknown"),
65
+ style="pixel_art",
66
+ tags=kwargs.pop("tags", []),
67
+ status=kwargs.pop("status", "pending"),
68
+ is_duplicate_of=kwargs.pop("is_duplicate_of", None),
69
+ duplicate_similarity=kwargs.pop("duplicate_similarity", None),
70
+ auto_tagged=kwargs.pop("auto_tagged", False),
71
+ )
72
+ )
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Bulk assignment
77
+ # ---------------------------------------------------------------------------
78
+
79
+ def test_bulk_assign_scoped_to_one_sheet_leaves_others_alone():
80
+ reset_db()
81
+ make_sprite("a", sheet_id="s1")
82
+ make_sprite("b", sheet_id="s1")
83
+ make_sprite("c", sheet_id="s2")
84
+
85
+ res = client().post("/api/batch/assign", json={
86
+ "scope": "sheet", "sheet_id": "s1", "category": "tree", "add_tags": ["forest"],
87
+ })
88
+ assert res.status_code == 200
89
+ assert res.get_json()["updated_count"] == 2
90
+
91
+ assert db.get_sprite("a")["category"] == "tree"
92
+ assert db.get_sprite("c")["category"] == "unknown"
93
+
94
+
95
+ def test_bulk_assign_registers_a_brand_new_category():
96
+ """
97
+ Typing a category that doesn't exist yet must create it, otherwise the
98
+ dropdown can never gain anything the built-in list didn't ship with.
99
+ """
100
+ reset_db()
101
+ make_sprite("a", sheet_id="s1")
102
+ client().post("/api/batch/assign", json={
103
+ "scope": "sheet", "sheet_id": "s1", "category": "Siege Weapon",
104
+ })
105
+ assert "siege_weapon" in db.list_categories("category")
106
+ assert db.get_sprite("a")["category"] == "siege_weapon"
107
+
108
+
109
+ def test_bulk_assign_rejects_an_unknown_scope():
110
+ reset_db()
111
+ res = client().post("/api/batch/assign", json={"scope": "everything", "category": "x"})
112
+ assert res.status_code == 400
113
+
114
+
115
+ def test_bulk_assign_with_nothing_to_change_is_a_no_op():
116
+ reset_db()
117
+ make_sprite("a", sheet_id="s1", tags=["keep"])
118
+ res = client().post("/api/batch/assign", json={"scope": "sheet", "sheet_id": "s1"})
119
+ assert res.status_code == 200
120
+ assert res.get_json()["updated_count"] == 0
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # Duplicate collapsing
125
+ # ---------------------------------------------------------------------------
126
+
127
+ def test_dedupe_keeps_the_best_member_of_each_cluster():
128
+ reset_db()
129
+ make_sprite("low", quality=40, is_duplicate_of=None)
130
+ make_sprite("high", quality=95, is_duplicate_of="low")
131
+ make_sprite("mid", quality=70, is_duplicate_of="high")
132
+
133
+ res = client().post("/api/batch/dedupe-keep-one").get_json()
134
+ assert res["cluster_count"] == 1
135
+ assert res["kept_ids"] == ["high"]
136
+ assert set(res["rejected_ids"]) == {"low", "mid"}
137
+ assert db.get_sprite("high")["status"] == "pending"
138
+ assert db.get_sprite("low")["status"] == "rejected"
139
+
140
+
141
+ def test_dedupe_clears_the_flag_on_the_survivor():
142
+ """
143
+ The kept copy is the only one now, so leaving it flagged would keep it
144
+ out of batch auto-accept for no reason.
145
+ """
146
+ reset_db()
147
+ make_sprite("first", quality=90)
148
+ make_sprite("second", quality=50, is_duplicate_of="first")
149
+ client().post("/api/batch/dedupe-keep-one")
150
+ assert db.get_sprite("first")["is_duplicate_of"] is None
151
+
152
+
153
+ def test_dedupe_does_nothing_without_duplicates():
154
+ reset_db()
155
+ make_sprite("a")
156
+ make_sprite("b")
157
+ res = client().post("/api/batch/dedupe-keep-one").get_json()
158
+ assert res["cluster_count"] == 0
159
+ assert res["rejected_count"] == 0
160
+
161
+
162
+ # ---------------------------------------------------------------------------
163
+ # Animation frames
164
+ # ---------------------------------------------------------------------------
165
+
166
+ def test_animation_frames_are_aligned_to_a_shared_canvas():
167
+ """
168
+ Every sprite is cropped tight to its own content, so playing the crops
169
+ back-to-back makes the animation wobble. Frames therefore come back
170
+ with offsets into one canvas covering all of them.
171
+ """
172
+ reset_db()
173
+ make_sprite("f1", sheet_id="anim", sprite_index=1, x=10, y=20, width=8, height=8)
174
+ make_sprite("f2", sheet_id="anim", sprite_index=2, x=40, y=20, width=12, height=16)
175
+
176
+ data = client().get("/api/animation/frames?sheet_id=anim").get_json()
177
+ assert [f["id"] for f in data["frames"]] == ["f1", "f2"]
178
+ # Origin is the top-left of the union, so the first frame sits at 0,0.
179
+ assert (data["frames"][0]["offset_x"], data["frames"][0]["offset_y"]) == (0, 0)
180
+ assert (data["frames"][1]["offset_x"], data["frames"][1]["offset_y"]) == (30, 0)
181
+ assert data["canvas"] == {"width": 42, "height": 16}
182
+
183
+
184
+ def test_animation_frames_are_ordered_by_sprite_index():
185
+ reset_db()
186
+ make_sprite("c", sheet_id="anim", sprite_index=3)
187
+ make_sprite("a", sheet_id="anim", sprite_index=1)
188
+ make_sprite("b", sheet_id="anim", sprite_index=2)
189
+ data = client().get("/api/animation/frames?sheet_id=anim").get_json()
190
+ assert [f["sprite_index"] for f in data["frames"]] == [1, 2, 3]
191
+
192
+
193
+ def test_animation_skips_rejected_frames():
194
+ reset_db()
195
+ make_sprite("keep", sheet_id="anim", sprite_index=1)
196
+ make_sprite("gone", sheet_id="anim", sprite_index=2, status="rejected")
197
+ data = client().get("/api/animation/frames?sheet_id=anim").get_json()
198
+ assert [f["id"] for f in data["frames"]] == ["keep"]
199
+
200
+
201
+ def test_animation_requires_a_sheet_id():
202
+ reset_db()
203
+ assert client().get("/api/animation/frames").status_code == 400
204
+
205
+
206
+ def test_animation_on_an_empty_sheet_returns_no_frames():
207
+ reset_db()
208
+ data = client().get("/api/animation/frames?sheet_id=nothing").get_json()
209
+ assert data["frames"] == []
210
+
211
+
212
+ # ---------------------------------------------------------------------------
213
+ # Reports
214
+ # ---------------------------------------------------------------------------
215
+
216
+ def test_report_endpoints_respond():
217
+ reset_db()
218
+ make_sprite("a", status="accepted")
219
+ c = client()
220
+ for url in ("/api/dataset/balance", "/api/dataset/calibration", "/api/dataset/split-preview"):
221
+ assert c.get(url).status_code == 200, url
222
+
223
+
224
+ def test_split_preview_warns_when_a_partition_is_empty():
225
+ reset_db()
226
+ for i in range(5):
227
+ make_sprite(f"a{i}", sheet_id="one_sheet", sprite_index=i, status="accepted")
228
+ data = client().get("/api/dataset/split-preview").get_json()
229
+ assert data["total"] == 5
230
+ assert data["grouped_by_sheet"] is True
231
+ assert data["warnings"], "a single sheet cannot fill three partitions"
232
+
233
+
234
+ if __name__ == "__main__":
235
+ import traceback
236
+
237
+ tests = [(n, f) for n, f in list(globals().items()) if n.startswith("test_") and callable(f)]
238
+ passed, failed = 0, 0
239
+ for name, fn in tests:
240
+ try:
241
+ fn()
242
+ print(f"PASS {name}")
243
+ passed += 1
244
+ except Exception:
245
+ print(f"FAIL {name}")
246
+ traceback.print_exc()
247
+ failed += 1
248
+ print(f"\n{passed} passed, {failed} failed")
249
+ sys.exit(1 if failed else 0)
tests/test_auto_tagger.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ tests/test_auto_tagger.py
3
+ --------------------------
4
+ Tests for the heuristic category / style / tag suggester.
5
+
6
+ The point of these is less "does it guess well" (it is a heuristic, not a
7
+ classifier) and more "does it stay honest": provenance facts are used,
8
+ weak colour signals never produce a confident category, and a claim like
9
+ `gameboy` is only made when the pixels actually back it up.
10
+
11
+ Run with: pytest tests/test_auto_tagger.py -v
12
+ """
13
+
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
20
+
21
+ from auto_tagger import suggest_tags
22
+
23
+
24
+ def solid(width, height, color, alpha=255):
25
+ arr = np.zeros((height, width, 4), dtype=np.uint8)
26
+ arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] = color
27
+ arr[:, :, 3] = alpha
28
+ return arr
29
+
30
+
31
+ def test_tile_grid_provenance_gives_a_confident_tile_category():
32
+ """Being cut from a detected tile grid is a fact, not a guess."""
33
+ sprite = solid(16, 16, (120, 90, 70))
34
+ s = suggest_tags(sprite, segmentation_source="tile")
35
+ assert s.category == "tile"
36
+ assert "tileset" in s.tags
37
+ assert s.confidence >= 80
38
+
39
+
40
+ def test_fully_opaque_tile_is_tagged_terrain():
41
+ sprite = solid(16, 16, (80, 70, 60))
42
+ s = suggest_tags(sprite, segmentation_source="tile")
43
+ assert "terrain" in s.tags
44
+
45
+
46
+ def test_animation_strip_member_is_an_effect_frame():
47
+ sprite = solid(32, 32, (250, 220, 120))
48
+ s = suggest_tags(sprite, segmentation_source="separator", sheet_sprite_count=24)
49
+ assert s.category == "effect"
50
+ assert "animation_frame" in s.tags
51
+
52
+
53
+ def test_short_strip_is_not_called_an_animation():
54
+ """Two or three cells is not evidence of an animation."""
55
+ sprite = solid(32, 32, (250, 220, 120))
56
+ s = suggest_tags(sprite, segmentation_source="separator", sheet_sprite_count=2)
57
+ assert "animation_frame" not in s.tags
58
+
59
+
60
+ def test_weak_signals_leave_the_category_unknown():
61
+ """
62
+ A mid-sized, unremarkable, desaturated sprite gives the heuristics
63
+ nothing to go on. It must come back "unknown" rather than guessing --
64
+ a wrong category is worse than a blank one for a training set.
65
+ """
66
+ rng = np.random.default_rng(4)
67
+ sprite = np.zeros((40, 40, 4), dtype=np.uint8)
68
+ sprite[:, :, :3] = rng.integers(90, 130, size=(40, 40, 3), dtype=np.uint16).astype(np.uint8)
69
+ sprite[:, :, 3] = 255
70
+ s = suggest_tags(sprite)
71
+ assert s.category == "unknown"
72
+
73
+
74
+ def test_descriptive_tags_survive_an_unknown_category():
75
+ """
76
+ Tags are cheap when wrong and useful when right, so they are kept even
77
+ when the category is dropped for lack of confidence.
78
+ """
79
+ sprite = np.zeros((80, 8, 4), dtype=np.uint8)
80
+ sprite[:, :, :3] = (110, 110, 115)
81
+ sprite[:, :, 3] = 255
82
+ s = suggest_tags(sprite)
83
+ assert "tall" in s.tags
84
+
85
+
86
+ def test_extreme_aspect_ratio_is_tagged():
87
+ wide = solid(80, 8, (200, 60, 60))
88
+ assert "wide" in suggest_tags(wide).tags
89
+ tall = solid(8, 80, (200, 60, 60))
90
+ assert "tall" in suggest_tags(tall).tags
91
+
92
+
93
+ def test_dominant_colour_is_reported_as_a_tag():
94
+ sprite = solid(24, 24, (40, 190, 60))
95
+ assert "green" in suggest_tags(sprite).tags
96
+
97
+
98
+ def test_gameboy_style_only_claimed_for_a_monochrome_ramp():
99
+ """
100
+ Four colours alone is not Game Boy art -- a four-colour dungeon tile
101
+ is not. The claim requires the palette to actually be monochrome.
102
+ """
103
+ ramp = np.zeros((16, 16, 4), dtype=np.uint8)
104
+ for i, level in enumerate((15, 70, 140, 220)):
105
+ ramp[i * 4:(i + 1) * 4, :, :3] = level
106
+ ramp[:, :, 3] = 255
107
+ assert suggest_tags(ramp).style == "gameboy"
108
+
109
+ colourful = np.zeros((16, 16, 4), dtype=np.uint8)
110
+ for i, colour in enumerate([(200, 40, 40), (40, 200, 40), (40, 40, 200), (200, 200, 40)]):
111
+ colourful[i * 4:(i + 1) * 4, :, :3] = colour
112
+ colourful[:, :, 3] = 255
113
+ assert suggest_tags(colourful).style != "gameboy"
114
+
115
+
116
+ def test_transparent_sprite_does_not_crash_and_reports_nothing_confident():
117
+ sprite = np.zeros((16, 16, 4), dtype=np.uint8)
118
+ s = suggest_tags(sprite)
119
+ assert s.category == "unknown"
120
+
121
+
122
+ def test_zero_sized_sprite_is_handled():
123
+ s = suggest_tags(np.zeros((0, 0, 4), dtype=np.uint8))
124
+ assert s.category == "unknown" and s.tags == []
125
+
126
+
127
+ def test_multi_part_sprites_are_tagged():
128
+ sprite = solid(32, 32, (230, 180, 60))
129
+ s = suggest_tags(sprite, component_count=12)
130
+ assert "multi_part" in s.tags
131
+
132
+
133
+ if __name__ == "__main__":
134
+ import traceback
135
+
136
+ tests = [(n, f) for n, f in list(globals().items()) if n.startswith("test_") and callable(f)]
137
+ passed, failed = 0, 0
138
+ for name, fn in tests:
139
+ try:
140
+ fn()
141
+ print(f"PASS {name}")
142
+ passed += 1
143
+ except Exception:
144
+ print(f"FAIL {name}")
145
+ traceback.print_exc()
146
+ failed += 1
147
+ print(f"\n{passed} passed, {failed} failed")
148
+ sys.exit(1 if failed else 0)
tests/test_dataset.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ tests/test_dataset.py
3
+ ----------------------
4
+ Tests for everything that turns reviewed sprites into a dataset:
5
+ duplicate clustering, bulk metadata assignment, the train/validation/test
6
+ split, and the composition + calibration reports.
7
+
8
+ Every test runs against a throwaway SQLite file so it can't touch the
9
+ Space's real data. `config` is pointed at a temp directory BEFORE the
10
+ modules that read it are imported.
11
+
12
+ Run with: pytest tests/test_dataset.py -v
13
+ """
14
+
15
+ import importlib
16
+ import json
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
22
+
23
+ _TMP = tempfile.TemporaryDirectory()
24
+ import config # noqa: E402
25
+
26
+ config.DB_PATH = Path(_TMP.name) / "test.sqlite3"
27
+
28
+ import database as db # noqa: E402
29
+ import dataset_manager # noqa: E402
30
+ import dataset_report # noqa: E402
31
+
32
+ importlib.reload(db)
33
+ db.DB_PATH = config.DB_PATH
34
+
35
+
36
+ def reset_db():
37
+ if config.DB_PATH.exists():
38
+ config.DB_PATH.unlink()
39
+ for suffix in ("-wal", "-shm"):
40
+ extra = Path(str(config.DB_PATH) + suffix)
41
+ if extra.exists():
42
+ extra.unlink()
43
+ db.init_db()
44
+
45
+
46
+ def make_sprite(sprite_id, sheet_id="sheet_a", quality=80.0, status="pending", **kwargs):
47
+ rec = db.SpriteRecord(
48
+ id=sprite_id,
49
+ sheet_id=sheet_id,
50
+ source_file=f"{sheet_id}.png",
51
+ sprite_index=kwargs.pop("sprite_index", 1),
52
+ x=0, y=0,
53
+ width=kwargs.pop("width", 16),
54
+ height=kwargs.pop("height", 16),
55
+ png_path=f"/tmp/{sprite_id}.png",
56
+ png_path_transparent=None,
57
+ sha256=kwargs.pop("sha256", sprite_id),
58
+ phash="00",
59
+ quality={"overall_quality_score": quality},
60
+ confidence=kwargs.pop("confidence", 95.0),
61
+ confidence_reasons=[],
62
+ component_count=1,
63
+ category=kwargs.pop("category", "unknown"),
64
+ style=kwargs.pop("style", "pixel_art"),
65
+ tags=kwargs.pop("tags", []),
66
+ status=status,
67
+ is_duplicate_of=kwargs.pop("is_duplicate_of", None),
68
+ duplicate_similarity=kwargs.pop("duplicate_similarity", None),
69
+ segmentation_source=kwargs.pop("segmentation_source", "gap"),
70
+ auto_tagged=kwargs.pop("auto_tagged", False),
71
+ auto_tag_confidence=kwargs.pop("auto_tag_confidence", None),
72
+ )
73
+ db.insert_sprite(rec)
74
+ return rec
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Duplicate clustering
79
+ # ---------------------------------------------------------------------------
80
+
81
+ def test_duplicate_chains_collapse_into_one_cluster():
82
+ """
83
+ A repeated tile is flagged against whichever copy was staged first, so
84
+ #3 -> #2 -> #1 is one cluster of three, not two unrelated pairs. Get
85
+ that wrong and "keep one of each" keeps three.
86
+ """
87
+ reset_db()
88
+ make_sprite("a")
89
+ make_sprite("b", is_duplicate_of="a")
90
+ make_sprite("c", is_duplicate_of="b")
91
+ make_sprite("lonely")
92
+
93
+ clusters = db.duplicate_clusters(statuses=("pending",))
94
+ assert len(clusters) == 1
95
+ assert {r["id"] for r in clusters[0]} == {"a", "b", "c"}
96
+
97
+
98
+ def test_duplicate_pointing_at_a_missing_sprite_is_ignored():
99
+ reset_db()
100
+ make_sprite("a", is_duplicate_of="deleted_sprite")
101
+ assert db.duplicate_clusters(statuses=("pending",)) == []
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # Bulk metadata assignment
106
+ # ---------------------------------------------------------------------------
107
+
108
+ def test_bulk_assign_adds_tags_without_wiping_existing_ones():
109
+ """
110
+ The realistic bulk edit is additive: "everything on this sheet is also
111
+ a tree" must not flatten each sprite's own tags.
112
+ """
113
+ reset_db()
114
+ make_sprite("a", tags=["green", "tiny"])
115
+ make_sprite("b", tags=["brown"])
116
+
117
+ db.bulk_update_metadata(["a", "b"], category="tree", add_tags=["forest"])
118
+
119
+ rows = {r["id"]: r for r in db.list_sprites()}
120
+ assert json.loads(rows["a"]["tags"]) == ["green", "tiny", "forest"]
121
+ assert json.loads(rows["b"]["tags"]) == ["brown", "forest"]
122
+ assert rows["a"]["category"] == "tree"
123
+
124
+
125
+ def test_bulk_assign_can_replace_tags_outright():
126
+ reset_db()
127
+ make_sprite("a", tags=["wrong", "bad"])
128
+ db.bulk_update_metadata(["a"], replace_tags=["right"])
129
+ assert json.loads(db.get_sprite("a")["tags"]) == ["right"]
130
+
131
+
132
+ def test_bulk_assign_does_not_duplicate_an_existing_tag():
133
+ reset_db()
134
+ make_sprite("a", tags=["forest"])
135
+ db.bulk_update_metadata(["a"], add_tags=["forest"])
136
+ assert json.loads(db.get_sprite("a")["tags"]) == ["forest"]
137
+
138
+
139
+ def test_bulk_assign_marks_sprites_as_human_reviewed():
140
+ """A machine suggestion a human just overrode is no longer a guess."""
141
+ reset_db()
142
+ make_sprite("a", auto_tagged=True, auto_tag_confidence=45.0)
143
+ assert db.get_sprite("a")["auto_tagged"] == 1
144
+ db.bulk_update_metadata(["a"], category="tree")
145
+ assert db.get_sprite("a")["auto_tagged"] == 0
146
+
147
+
148
+ def test_scope_selection_filters_by_sheet_and_status():
149
+ reset_db()
150
+ make_sprite("a", sheet_id="s1")
151
+ make_sprite("b", sheet_id="s1", status="accepted")
152
+ make_sprite("c", sheet_id="s2")
153
+
154
+ assert set(db.select_sprite_ids(scope="sheet", sheet_id="s1")) == {"a", "b"}
155
+ assert db.select_sprite_ids(scope="sheet", sheet_id="s1", status="pending") == ["a"]
156
+ assert set(db.select_sprite_ids(scope="all")) == {"a", "b", "c"}
157
+ assert db.select_sprite_ids(scope="ids", sprite_ids=["c"]) == ["c"]
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Train / validation / test split
162
+ # ---------------------------------------------------------------------------
163
+
164
+ def test_split_is_deterministic():
165
+ """
166
+ A split that moves between runs silently invalidates every evaluation
167
+ number derived from it.
168
+ """
169
+ first = dataset_manager.assign_split("sprite_1", "sheet_a")
170
+ for _ in range(10):
171
+ assert dataset_manager.assign_split("sprite_1", "sheet_a") == first
172
+
173
+
174
+ def test_split_keeps_a_whole_sheet_together():
175
+ """
176
+ An animation's frames are near-identical images. Splitting per sprite
177
+ puts frame 7 in train and frame 8 in test, and the evaluation then
178
+ measures memorisation rather than generalisation.
179
+ """
180
+ assert config.SPLIT_BY_SHEET, "default must group by sheet"
181
+ splits = {dataset_manager.assign_split(f"sprite_{i}", "sheet_x") for i in range(50)}
182
+ assert len(splits) == 1
183
+
184
+
185
+ def test_split_covers_all_three_partitions_across_many_sheets():
186
+ splits = {dataset_manager.assign_split("s", f"sheet_{i}") for i in range(400)}
187
+ assert splits == {"train", "validation", "test"}
188
+
189
+
190
+ def test_split_roughly_matches_the_configured_ratios():
191
+ assigned = [dataset_manager.assign_split("s", f"sheet_{i}") for i in range(4000)]
192
+ train_share = assigned.count("train") / len(assigned)
193
+ assert abs(train_share - config.SPLIT_TRAIN_RATIO) < 0.05
194
+
195
+
196
+ def test_manifest_carries_split_and_provenance():
197
+ reset_db()
198
+ make_sprite("a", status="accepted", segmentation_source="tile", auto_tagged=True)
199
+ rows = db.list_sprites(status="accepted")
200
+ manifest = dataset_manager.build_manifest(rows, splits={"a": "validation"})
201
+ assert manifest[0]["split"] == "validation"
202
+ assert manifest[0]["segmentation_source"] == "tile"
203
+ assert manifest[0]["auto_tagged"] is True
204
+
205
+
206
+ # ---------------------------------------------------------------------------
207
+ # Composition report
208
+ # ---------------------------------------------------------------------------
209
+
210
+ def test_balance_report_flags_a_dominant_class():
211
+ reset_db()
212
+ for i in range(90):
213
+ make_sprite(f"tile{i}", sheet_id=f"sheet{i % 5}", status="accepted", category="tile")
214
+ for i in range(10):
215
+ make_sprite(f"item{i}", sheet_id=f"sheet{i % 5}", status="accepted", category="item")
216
+
217
+ report = dataset_report.balance_report()
218
+ assert report["total"] == 100
219
+ assert report["by_category"]["tile"] == 90
220
+ assert any("90%" in w and "tile" in w for w in report["warnings"])
221
+
222
+
223
+ def test_balance_report_flags_thin_classes():
224
+ reset_db()
225
+ for i in range(60):
226
+ make_sprite(f"a{i}", sheet_id=f"sheet{i % 4}", status="accepted", category="tile")
227
+ make_sprite("rare", sheet_id="sheet1", status="accepted", category="unicorn")
228
+
229
+ report = dataset_report.balance_report()
230
+ assert any("fewer than" in w and "unicorn" in w for w in report["warnings"])
231
+
232
+
233
+ def test_balance_report_flags_unreviewed_machine_labels():
234
+ reset_db()
235
+ for i in range(30):
236
+ make_sprite(f"a{i}", sheet_id=f"sheet{i % 4}", status="accepted",
237
+ category="tile", auto_tagged=True)
238
+ report = dataset_report.balance_report()
239
+ assert report["auto_tagged_count"] == 30
240
+ assert any("unreviewed machine suggestion" in w for w in report["warnings"])
241
+
242
+
243
+ def test_balance_report_flags_a_single_source_sheet():
244
+ reset_db()
245
+ for i in range(30):
246
+ make_sprite(f"a{i}", sheet_id="only_sheet", status="accepted", category="tile")
247
+ report = dataset_report.balance_report()
248
+ assert any("source sheet" in w for w in report["warnings"])
249
+
250
+
251
+ def test_balance_report_on_an_empty_dataset_says_so():
252
+ reset_db()
253
+ report = dataset_report.balance_report()
254
+ assert report["total"] == 0
255
+ assert report["warnings"]
256
+
257
+
258
+ # ---------------------------------------------------------------------------
259
+ # Quality score calibration
260
+ # ---------------------------------------------------------------------------
261
+
262
+ def test_calibration_refuses_to_recommend_without_enough_history():
263
+ reset_db()
264
+ for i in range(5):
265
+ make_sprite(f"a{i}", status="accepted", quality=95)
266
+ make_sprite(f"r{i}", status="rejected", quality=20)
267
+ result = dataset_report.quality_calibration()
268
+ assert result["separable"] is False
269
+ assert result["suggested_threshold"] is None
270
+ assert "Not enough review history" in result["note"]
271
+
272
+
273
+ def test_calibration_finds_a_threshold_when_the_score_actually_separates():
274
+ reset_db()
275
+ for i in range(40):
276
+ make_sprite(f"a{i}", status="accepted", quality=90 + (i % 5))
277
+ make_sprite(f"r{i}", status="rejected", quality=30 + (i % 5))
278
+ result = dataset_report.quality_calibration()
279
+ assert result["separable"] is True
280
+ assert 35 <= result["suggested_threshold"] <= 90
281
+ assert result["agreement_at_suggested"] > 95
282
+
283
+
284
+ def test_calibration_reports_no_separation_when_the_score_is_useless():
285
+ """
286
+ If accepts and rejects have the same score distribution, the honest
287
+ answer is "this score is not a gate", not a made-up threshold.
288
+ """
289
+ reset_db()
290
+ for i in range(40):
291
+ make_sprite(f"a{i}", status="accepted", quality=60 + (i % 7))
292
+ make_sprite(f"r{i}", status="rejected", quality=60 + (i % 7))
293
+ result = dataset_report.quality_calibration()
294
+ assert result["separable"] is False
295
+ assert "does not separate" in result["note"]
296
+
297
+
298
+ if __name__ == "__main__":
299
+ import traceback
300
+
301
+ tests = [(n, f) for n, f in list(globals().items()) if n.startswith("test_") and callable(f)]
302
+ passed, failed = 0, 0
303
+ for name, fn in tests:
304
+ try:
305
+ fn()
306
+ print(f"PASS {name}")
307
+ passed += 1
308
+ except Exception:
309
+ print(f"FAIL {name}")
310
+ traceback.print_exc()
311
+ failed += 1
312
+ print(f"\n{passed} passed, {failed} failed")
313
+ sys.exit(1 if failed else 0)
tests/test_segmentation.py CHANGED
@@ -13,8 +13,10 @@ import numpy as np
13
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
14
 
15
  from segmentation import (
 
16
  detect_separator_grid,
17
  detect_tile_grid,
 
18
  segment_sheet,
19
  )
20
 
@@ -320,6 +322,67 @@ def test_grid_backed_sprites_are_not_flagged_low_confidence_for_being_sparse():
320
  assert detected and all(d.confidence >= 70 for d in detected)
321
 
322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  if __name__ == "__main__":
324
  # Minimal manual runner for environments without pytest installed.
325
  import traceback
 
13
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
14
 
15
  from segmentation import (
16
+ GridLayout,
17
  detect_separator_grid,
18
  detect_tile_grid,
19
+ segment_grid,
20
  segment_sheet,
21
  )
22
 
 
322
  assert detected and all(d.confidence >= 70 for d in detected)
323
 
324
 
325
+ # ---------------------------------------------------------------------------
326
+ # Composite objects spanning several grid cells
327
+ # ---------------------------------------------------------------------------
328
+
329
+ def test_object_spanning_several_cells_becomes_one_sprite():
330
+ """
331
+ A ladder drawn down three grid cells is ONE object. Cut per cell it
332
+ yields three fragments that mean nothing on their own.
333
+ """
334
+ mask = np.zeros((64, 64), dtype=bool)
335
+ mask[8:56, 20:28] = True # ladder, 3 cells tall
336
+ for (r, c) in [(0, 0), (0, 3), (3, 3)]: # unrelated single tiles
337
+ mask[r * 16 + 3:r * 16 + 13, c * 16 + 3:c * 16 + 13] = True
338
+
339
+ layout = GridLayout(16, 16, 4, 4, 0, 0, 90.0, "tile")
340
+ detected = segment_grid(mask, layout)
341
+ tall = [d for d in detected if d.bbox.height > 20]
342
+ assert len(tall) == 1
343
+ assert tall[0].bbox.height == 48
344
+ assert tall[0].component_count == 4
345
+ assert any("Composite" in r for r in tall[0].confidence_reasons)
346
+ # The unrelated tiles are untouched.
347
+ assert len(detected) == 4
348
+
349
+
350
+ def test_tileable_terrain_is_not_fused_into_one_object():
351
+ """
352
+ A large connected mass of terrain is exactly what the grid cut exists
353
+ to break up. It is connected the same way a composite object is, so
354
+ only its extent can tell them apart -- it must stay per-cell.
355
+ """
356
+ mask = np.zeros((80, 80), dtype=bool)
357
+ mask[0:80, 0:80] = True # 5x5 cells of solid, connected floor
358
+ layout = GridLayout(16, 16, 5, 5, 0, 0, 90.0, "tile")
359
+ detected = segment_grid(mask, layout)
360
+ assert len(detected) == 25
361
+ assert all(d.component_count == 1 for d in detected)
362
+
363
+
364
+ def test_adjacent_flat_tiles_are_not_merged_by_touching_alone():
365
+ """
366
+ Two flat filler tiles touch along their whole shared edge, exactly as a
367
+ composite object's halves do. Keying the merge on connected-component
368
+ identity plus extent is what keeps them apart from a real object --
369
+ here they are part of one big terrain mass.
370
+ """
371
+ mask = np.zeros((48, 96), dtype=bool)
372
+ mask[:, :] = True
373
+ layout = GridLayout(16, 16, 6, 3, 0, 0, 90.0, "tile")
374
+ detected = segment_grid(mask, layout)
375
+ assert len(detected) == 18
376
+
377
+
378
+ def test_composite_merge_can_be_switched_off():
379
+ mask = np.zeros((48, 16), dtype=bool)
380
+ mask[4:44, 4:12] = True
381
+ layout = GridLayout(16, 16, 1, 3, 0, 0, 90.0, "tile")
382
+ assert len(segment_grid(mask, layout)) == 1
383
+ assert len(segment_grid(mask, layout, merge_composites=False)) == 3
384
+
385
+
386
  if __name__ == "__main__":
387
  # Minimal manual runner for environments without pytest installed.
388
  import traceback