Repository navigation
Expand file tree
/
Copy pathtest_report_agreement.py
More file actions
1062 lines (868 loc) · 42.9 KB
/
Copy pathtest_report_agreement.py
File metadata and controls
1062 lines (868 loc) · 42.9 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""The export report against the bytes on disk, for every installed exporter.
A file of its own rather than three more tests in ``test_yolo.py``, because the
defect it guards is not an exporter doing the wrong thing — YOLO's own
``test_a_polygon_is_written_as_its_bounding_box`` passes either way, since writing
the box is what that exporter is *for*. The defect is that nothing compares the
report to the output, so the two can describe the same release differently and
every test agrees with the half it is looking at.
**Every count here is read back out of the written artifacts.** Nothing asserts
"the report says 1 and 1 is what we expect"; it asserts "the report says 1, and
counting the rows in the label files finds exactly the annotations it did not
claim". That is the only shape of test that catches this class of defect.
The dispatch table is the fifth criterion: a fourth exporter registering into the
``visionset.formats`` group either lands a counter here or is declared as one
that writes nothing, and ``test_every_installed_exporter_is_accounted_for``
fails until somebody chooses. A format cannot be added and quietly skipped.
"""
from __future__ import annotations
import csv
import json
import xml.etree.ElementTree as ElementTree
from collections import Counter
from collections.abc import Callable
from pathlib import Path
from uuid import UUID, uuid4
import pytest
from PIL import Image
from tests.fixtures.exporting import export_or_refused
from tests.formats.test_kitti_export import Released
from tests.formats.test_tfrecord import _parse_example, _parse_records
from tests.formats.test_ultralytics import CLASSES, Fixture, _box
from visionset.formats.classification import LABELS_FILENAME as CLASSIFICATION_LABELS
from visionset.formats.coco import ANNOTATIONS_DIRNAME as COCO_ANNOTATIONS_DIRNAME
from visionset.formats.coco_panoptic import read_segment_map
from visionset.formats.createml import ANNOTATIONS_FILENAME as CREATEML_ANNOTATIONS
from visionset.formats.lanes import LABELS_DIRNAME as LANE_LABELS_DIRNAME
from visionset.formats.open_images import DESCRIPTIONS_FILENAME as OPEN_IMAGES_DESCRIPTIONS
from visionset.formats.registry import exporters
from visionset.formats.segmentation_png import DESCRIPTOR_FILENAME as SEGMENTATION_DESCRIPTOR
from visionset.formats.ultralytics import DATA_FILENAME, LABELS_DIRNAME
from visionset.formats.voc import ANNOTATIONS_DIRNAME as VOC_ANNOTATIONS_DIRNAME
from visionset.kernel.domain import (
Annotation,
ClassExportStatus,
ClassificationGeometry,
ExportCompatibility,
GeometryType,
LabelClass,
PolygonGeometry,
PolylineGeometry,
)
from visionset.kernel.errors import ExportSourceUnreadable
from visionset.kernel.ports import Exporter, resolve_target
#: Formats that write no annotations at all, and are therefore outside the
#: report-versus-output comparison.
#:
#: Named rather than skipped by a heuristic. ``DummyExporter`` exists to prove
#: entry-point discovery works and writes nothing; it also declares every
#: geometry supported, so its report promises everything and its output holds
#: nothing. That is a contradiction the comparison below would catch, and it is
#: not a defect — it is what "no-op" means. An exporter joins this set only by
#: somebody deciding it should.
NON_WRITING = frozenset({"dummy"})
def _polygon(points: list[tuple[float, float]] | None = None) -> Annotation:
return Annotation(
asset_id=uuid4(),
label_class="lane",
schema_version=1,
geometry=PolygonGeometry(points=points or [(8.0, 12.0), (24.0, 12.0), (8.0, 36.0)]),
provenance="human",
)
def _tag() -> Annotation:
return Annotation(
asset_id=uuid4(),
label_class="weather",
schema_version=1,
geometry=ClassificationGeometry(),
provenance="human",
)
#: The release every test here exports: three boxes, two polygons, one tag,
#: spread over three assets so ``assets`` counts differ from ``annotations``.
#:
#: The shape the report and the output are most likely to disagree over: three
#: annotations reported excluded against four rows on disk where two were
#: expected.
DRAWING: dict[int, list[Annotation]] = {
0: [_box(x=8, y=6, width=20, height=22), _polygon()],
1: [_box(x=2, y=2, width=10, height=10), _polygon([(30.0, 4.0), (44.0, 4.0), (44.0, 20.0)])],
2: [_box(x=1, y=1, width=8, height=8), _tag()],
}
def _yolo_counts(root: Path) -> Counter[str]:
"""Every label row, by class name, resolved through ``data.yaml``'s own index.
Through the index rather than by position, because reading the file the way
a trainer reads it is the point: a row's meaning is ``names[index]``, and a
test that assumed the schema order would agree with a wrong export. Both
spellings of ``names`` are read — the ``ultralytics`` mapping and the
``yolov5-yaml`` list — so one counter serves both dialects.
"""
names: dict[int, str] = {}
for line in (root / DATA_FILENAME).read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if stripped.startswith("names: ["):
names = dict(enumerate(json.loads(stripped.removeprefix("names:").strip())))
elif stripped[:1].isdigit() and ":" in stripped:
index, name = stripped.split(":", 1)
names[int(index)] = json.loads(name.strip())
found: Counter[str] = Counter()
for path in sorted((root / LABELS_DIRNAME).rglob("*.txt")):
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
found[names[int(line.split()[0])]] += 1
return found
def _darknet_counts(root: Path) -> Counter[str]:
"""Every label row, by the line of ``obj.names`` its index points at."""
names = (root / "obj.names").read_text(encoding="utf-8").splitlines()
found: Counter[str] = Counter()
for path in sorted((root / LABELS_DIRNAME).rglob("*.txt")):
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
found[names[int(line.split()[0])]] += 1
return found
def _voc_counts(root: Path) -> Counter[str]:
"""Every ``<object>``, by the ``<name>`` a devkit consumer reads it under."""
found: Counter[str] = Counter()
for path in sorted((root / VOC_ANNOTATIONS_DIRNAME).rglob("*.xml")):
for element in ElementTree.parse(path).getroot().findall("object"):
name = element.findtext("name")
assert name is not None
found[name] += 1
return found
def _coco_counts(root: Path) -> Counter[str]:
"""Every instance, by the category name its ``category_id`` points at."""
found: Counter[str] = Counter()
for path in sorted((root / COCO_ANNOTATIONS_DIRNAME).rglob("*.json")):
document = json.loads(path.read_text(encoding="utf-8"))
names = {one["id"]: one["name"] for one in document["categories"]}
for annotation in document["annotations"]:
found[names[annotation["category_id"]]] += 1
return found
def _classification_counts(root: Path) -> Counter[str]:
"""Every label row, by the class name in its own column.
Read with ``csv`` rather than split on commas, for the reason the exporter
writes with it: a class name may hold one.
"""
with (root / CLASSIFICATION_LABELS).open(encoding="utf-8", newline="") as handle:
return Counter(row["class"] for row in csv.DictReader(handle))
def _classification_dir_counts(root: Path) -> Counter[str]:
"""Every picture, by the class directory it sits in under its fold."""
return Counter(path.parent.name for path in root.glob("*/*/*") if path.is_file())
def _mot_counts(root: Path) -> Counter[str]:
"""Every ``gt.txt`` row, by the line of its sequence's ``labels.txt`` its class points at.
``DRAWING`` holds no track, so this one finds nothing and the report must
call every box dropped; ``test_mot.py`` compares a tracked release.
"""
found: Counter[str] = Counter()
for path in sorted(root.glob("*/gt/gt.txt")):
names = (path.parent / "labels.txt").read_text(encoding="utf-8").splitlines()
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
found[names[int(line.split(",")[7]) - 1]] += 1
return found
def _cvat_images_counts(root: Path) -> Counter[str]:
"""Every shape and tag under an ``<image>``, by its ``label``."""
found: Counter[str] = Counter()
for image in ElementTree.parse(root / "annotations.xml").getroot().findall("image"):
for shape in image:
found[shape.attrib["label"]] += 1
return found
def _cvat_video_counts(root: Path) -> Counter[str]:
"""Every shape a track holds inside its object, by the track's ``label``.
``DRAWING`` holds no track, so this one finds nothing, as for ``mot``.
"""
found: Counter[str] = Counter()
for path in sorted(root.glob("*/annotations.xml")):
for track in ElementTree.parse(path).getroot().findall("track"):
found[track.attrib["label"]] += sum(
1 for shape in track if shape.attrib.get("outside") == "0"
)
return found
def _dota_counts(root: Path) -> Counter[str]:
"""Every ``labelTxt`` row, by the category token that names its class."""
found: Counter[str] = Counter()
for path in sorted(root.glob("*/labelTxt/*.txt")):
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
found[line.split()[8]] += 1
return found
def _labelme_counts(root: Path) -> Counter[str]:
"""Every shape in a LabelMe document, by its ``label``; other JSON is not a document."""
found: Counter[str] = Counter()
for path in sorted(root.rglob("*.json")):
document = json.loads(path.read_text(encoding="utf-8"))
if isinstance(document, dict) and "shapes" in document:
found.update(shape["label"] for shape in document["shapes"])
return found
def _createml_counts(root: Path) -> Counter[str]:
"""Every annotation in a Create ML array, by its ``label``; other JSON is not a document."""
found: Counter[str] = Counter()
for path in sorted(root.rglob(CREATEML_ANNOTATIONS)):
for entry in json.loads(path.read_text(encoding="utf-8")):
found.update(annotation["label"] for annotation in entry["annotations"])
return found
def _coco_panoptic_counts(root: Path) -> Counter[str]:
"""Every ``segments_info`` entry, by its category's name, each one a segment of the PNG."""
found: Counter[str] = Counter()
for path in sorted((root / COCO_ANNOTATIONS_DIRNAME).glob("panoptic_*.json")):
document = json.loads(path.read_text(encoding="utf-8"))
names = {one["id"]: one["name"] for one in document["categories"]}
for annotation in document["annotations"]:
_, _, values = read_segment_map(
path.parent / path.stem / annotation["file_name"], annotation["file_name"]
)
present = set(values)
found.update(
names[one["category_id"]]
for one in annotation["segments_info"]
if one["id"] in present
)
return found
def _open_images_counts(root: Path) -> Counter[str]:
"""Every box row of every split's CSV, by the ``DisplayName`` its ``LabelName`` maps to."""
with (root / OPEN_IMAGES_DESCRIPTIONS).open(newline="", encoding="utf-8") as handle:
names = {row["LabelName"]: row["DisplayName"] for row in csv.DictReader(handle)}
found: Counter[str] = Counter()
for path in sorted(root.glob("*-annotations-bbox.csv")):
with path.open(newline="", encoding="utf-8") as handle:
found.update(names[row["LabelName"]] for row in csv.DictReader(handle))
return found
def _tfrecord_counts(root: Path) -> Counter[str]:
"""Every box of every split's records, by its ``image/object/class/text``."""
found: Counter[str] = Counter()
for path in sorted(root.glob("*.tfrecord")):
for record in _parse_records(path.read_bytes()):
_, texts = _parse_example(record)["image/object/class/text"]
found.update(text.decode("utf-8") for text in texts)
return found
def _segmentation_png_counts(root: Path) -> Counter[str]:
"""Every class present in a mask, once per mask, by the name the descriptor gives its id.
A class map cannot tell two instances of one class apart, so this counts what
it can: each class a picture's mask holds. ``DRAWING`` puts at most one
polygon of a class on a picture, so that equals the annotations written.
"""
descriptor = json.loads((root / SEGMENTATION_DESCRIPTOR).read_text(encoding="utf-8"))
names = {int(key): name for key, name in descriptor["classes"].items()}
found: Counter[str] = Counter()
for path in sorted((root / descriptor["masks"]).rglob("*.png")):
with Image.open(path) as image:
present = set(image.tobytes())
found.update(names[value] for value in present if value in names)
return found
#: How to count what each format actually wrote, keyed by ``format_name``.
COUNTERS: dict[str, Callable[[Path], Counter[str]]] = {
"ultralytics": _yolo_counts,
"yolov5-yaml": _yolo_counts,
"darknet": _darknet_counts,
"yolo-obb": _yolo_counts,
"dota": _dota_counts,
"voc": _voc_counts,
"coco": _coco_counts,
"coco-panoptic": _coco_panoptic_counts,
"classification": _classification_counts,
"classification-dir": _classification_dir_counts,
"mot": _mot_counts,
"cvat-images": _cvat_images_counts,
"cvat-video": _cvat_video_counts,
"segmentation-png": _segmentation_png_counts,
"labelme": _labelme_counts,
"createml": _createml_counts,
"open-images": _open_images_counts,
"tfrecord": _tfrecord_counts,
}
#: Formats whose layout depends on what the release holds, and are therefore
#: compared per layout rather than against ``DRAWING``.
#:
#: The ``ultralytics`` dialect derives its task from the manifest: any polygon
#: makes a segment export, tags with no located label make a class tree, and
#: anything else is detect. Its geometry declarations are what each layout
#: carries intact, so ``DRAWING`` — a tag beside boxes — is the one shape whose
#: report cannot be read off those declarations: the tag is dropped by the
#: derivation while the declaration calls it supported. That shape is pinned
#: below as what it is; the per-layout comparisons follow it.
TASK_SWITCHING = frozenset({"ultralytics"})
#: The formats ``DRAWING`` is compared against in the parametrized tests.
STATIC = sorted(set(COUNTERS) - TASK_SWITCHING)
def _installed() -> dict[str, Exporter]:
return exporters()
def _export(
fixture: Fixture, release_id: UUID, plugin: Exporter, dest: Path
) -> ExportCompatibility:
return export_or_refused(fixture.releases, release_id, plugin, dest)
def _count(counter: Callable[[Path], Counter[str]], dest: Path) -> Counter[str]:
"""What a format wrote, by class; nothing where the export was refused."""
return counter(dest) if dest.exists() else Counter()
@pytest.fixture
def labelled(tmp_path: Path) -> Fixture:
fixture = Fixture(tmp_path)
fixture.label(DRAWING)
return fixture
# --- the guard ----------------------------------------------------------------
def test_every_installed_exporter_is_accounted_for() -> None:
"""A fourth format cannot disagree with its own report by not being looked at.
The one assertion here that is about this file rather than about the code: a
new exporter either gets a counter and is compared against its own output, or
is declared non-writing on purpose. Silence is not an option.
"""
assert (
set(_installed()) == set(COUNTERS) | set(LANE_COUNTERS) | set(SCAN_COUNTERS) | NON_WRITING
)
def test_a_non_writing_exporter_really_writes_nothing(tmp_path: Path, labelled: Fixture) -> None:
"""The exemption above, checked rather than trusted."""
release_id = labelled.publish()
for name in NON_WRITING:
dest = tmp_path / f"out-{name}"
_export(labelled, release_id, _installed()[name], dest)
# The kernel's own report is the one file in there, and it is written
# after the plugin runs.
assert [path.name for path in dest.iterdir()] == ["visionset-export-report.json"]
labelled.close()
@pytest.mark.parametrize("format_name", STATIC)
def test_the_report_agrees_with_what_the_format_wrote(
tmp_path: Path, labelled: Fixture, format_name: str
) -> None:
"""Report versus artifact, per class, for every writing format.
Three claims, each read off the bytes:
- a **dropped** class contributes nothing to the output;
- a **degraded** class contributes every one of its annotations, because it
is converted rather than removed — this is exactly the row YOLO and VOC
used to write while the report called it excluded;
- a **supported** class contributes every one of its annotations too.
"""
release_id = labelled.publish()
dest = tmp_path / f"out-{format_name}"
report = _export(labelled, release_id, _installed()[format_name], dest)
written = _count(COUNTERS[format_name], dest)
labelled.close()
for declared in report.classes:
expected = 0 if declared.status is ClassExportStatus.DROPPED else declared.annotations
assert written[declared.label_class] == expected, (
f"{format_name} reports {declared.label_class!r} as {declared.status.value} "
f"with {declared.annotations} annotation(s), and wrote "
f"{written[declared.label_class]}"
)
# Nothing appeared under a name the report never mentioned.
assert set(written) <= {one.label_class for one in report.classes}
@pytest.mark.parametrize("format_name", STATIC)
def test_excluded_annotations_is_exactly_what_is_missing_from_the_output(
tmp_path: Path, labelled: Fixture, format_name: str
) -> None:
"""The count, checked rather than restated.
The number a caller consents to losing is checked against the arithmetic of
the artifact: everything the release held, minus everything on disk. A
two-valued model answers 3 here where the subtraction gives 1.
"""
release_id = labelled.publish()
dest = tmp_path / f"out-{format_name}"
report = _export(labelled, release_id, _installed()[format_name], dest)
written = _count(COUNTERS[format_name], dest)
held = sum(one.annotations for one in report.classes)
labelled.close()
assert report.excluded_annotations == held - sum(written.values())
@pytest.mark.parametrize("format_name", STATIC)
def test_a_reason_says_what_actually_happens_to_that_class(
tmp_path: Path, labelled: Fixture, format_name: str
) -> None:
"""A written class's reason must not deny being written."""
release_id = labelled.publish()
report = _export(labelled, release_id, _installed()[format_name], tmp_path / "out")
labelled.close()
for declared in report.classes:
if declared.status is ClassExportStatus.SUPPORTED:
assert declared.reason is None
continue
assert declared.reason is not None
if declared.status is ClassExportStatus.DEGRADED:
# It is written, so nothing here may say it cannot be.
assert "cannot" not in declared.reason
assert "lost" in declared.reason
else:
assert "drops it" in declared.reason
# --- the two formats the defect was found in ----------------------------------
def test_yolov5_yaml_reports_the_polygon_it_writes_as_degraded_not_excluded(
tmp_path: Path, labelled: Fixture
) -> None:
"""The reproduction, in the numbers a two-valued model disagrees about."""
release_id = labelled.publish()
dest = tmp_path / "out"
report = _export(labelled, release_id, _installed()["yolov5-yaml"], dest)
written = _yolo_counts(dest)
labelled.close()
# Three boxes and two polygons reach the label files; only the tag does not.
assert written == Counter({"sign": 3, "lane": 2})
assert (report.excluded_annotations, report.degraded_annotations) == (1, 2)
assert [one.label_class for one in report.excluded] == ["weather"]
assert [one.label_class for one in report.degraded] == ["lane"]
# Still not compatible, and still asking for consent: a polygon flattened to
# a box has lost its shape. Only the accounting moved.
assert not report.compatible
def test_voc_reports_the_polygon_it_writes_as_degraded_not_excluded(
tmp_path: Path, labelled: Fixture
) -> None:
release_id = labelled.publish()
dest = tmp_path / "out"
report = _export(labelled, release_id, _installed()["voc"], dest)
written = _voc_counts(dest)
labelled.close()
assert written == Counter({"sign": 3, "lane": 2})
assert (report.excluded_annotations, report.degraded_annotations) == (1, 2)
assert not report.compatible
def test_coco_is_unchanged_because_it_reduces_nothing(tmp_path: Path, labelled: Fixture) -> None:
"""COCO writes a polygon as a polygon, so it degrades nothing."""
release_id = labelled.publish()
dest = tmp_path / "out"
report = _export(labelled, release_id, _installed()["coco"], dest)
written = _coco_counts(dest)
labelled.close()
assert written == Counter({"sign": 3, "lane": 2})
assert (report.excluded_annotations, report.degraded_annotations) == (1, 0)
assert report.degraded == ()
assert [one.label_class for one in report.excluded] == ["weather"]
def test_classification_writes_the_tag_and_reports_everything_else_dropped(
tmp_path: Path, labelled: Fixture
) -> None:
"""The mirror image of the three formats above.
``DRAWING`` holds three boxes, two polygons and one tag. Every other
installed format writes the boxes and drops the tag; this one writes the tag
and drops the rest, which is what makes the pair of assertions worth having
in the same file.
"""
release_id = labelled.publish()
dest = tmp_path / "out"
report = _export(labelled, release_id, _installed()["classification"], dest)
written = _classification_counts(dest)
labelled.close()
assert written == Counter({"weather": 1})
assert (report.excluded_annotations, report.degraded_annotations) == (5, 0)
assert sorted(one.label_class for one in report.excluded) == ["lane", "sign"]
assert not report.compatible
# --- the lane family ----------------------------------------------------------
#
# Five more installed exporters, and none of them can be counted the way the
# three above are. A YOLO row starts with a class index, a VOC `<object>` has a
# `<name>` and a COCO instance has a `category_id` — so "what did this format
# write, per class" is a question their artifacts answer. A lane file does not:
# TuSimple and CurveLanes and CULane record no class at all, and BDD100K and
# OpenLane record their *own* category derived from style and colour. That is a
# property of single-purpose formats, not an oversight.
#
# So they are compared at the granularity their output supports — every lane on
# disk against every lane the report did not call dropped — which keeps the
# guarantee (the report is checked against the bytes) without inventing a class
# attribution the files do not carry.
def _polyline(points: list[tuple[float, float]] | None = None) -> Annotation:
"""One lane. Y-ascending, because TuSimple refuses anything else."""
return Annotation(
asset_id=uuid4(),
label_class="centerline",
schema_version=1,
geometry=PolylineGeometry(points=points or [(6.0, 4.0), (18.0, 22.0), (30.0, 44.0)]),
provenance="human",
)
#: The same shape as ``DRAWING``, plus three lanes. Kept separate rather than
#: folded in, because the three reproduction tests above assert exact counters
#: chosen to make a report disagree, and widening their release would rewrite the
#: reproduction they exist to preserve.
LANE_DRAWING: dict[int, list[Annotation]] = {
0: [_box(x=8, y=6, width=20, height=22), _polyline()],
1: [
_polyline([(2.0, 2.0), (10.0, 20.0), (16.0, 46.0)]),
_polyline([(40.0, 3.0), (48.0, 25.0), (56.0, 45.0)]),
],
2: [_box(x=1, y=1, width=8, height=8), _tag()],
}
LANE_CLASSES = (*CLASSES, LabelClass(name="centerline", geometries=(GeometryType.POLYLINE,)))
def _tusimple_lanes(root: Path) -> int:
total = 0
for path in sorted(root.glob("label_data_*.json")):
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
total += len(json.loads(line)["lanes"])
return total
def _curvelanes_lanes(root: Path) -> int:
return sum(
len(json.loads(path.read_text(encoding="utf-8"))["Lines"])
for path in sorted((root / LANE_LABELS_DIRNAME).rglob("*.lines.json"))
)
def _bdd100k_lanes(root: Path) -> int:
return sum(
len(json.loads(path.read_text(encoding="utf-8"))["labels"])
for path in sorted((root / LANE_LABELS_DIRNAME).rglob("*.json"))
)
def _culane_lanes(root: Path) -> int:
return sum(
len([line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()])
for path in sorted((root / LANE_LABELS_DIRNAME).rglob("*.lines.txt"))
)
def _openlane_lanes(root: Path) -> int:
return sum(
len(json.loads(path.read_text(encoding="utf-8"))["lane_lines"])
for path in sorted((root / LANE_LABELS_DIRNAME).rglob("*.json"))
)
#: How to count the lanes each lane format wrote, keyed by ``format_name``.
LANE_COUNTERS: dict[str, Callable[[Path], int]] = {
"tusimple": _tusimple_lanes,
"curvelanes": _curvelanes_lanes,
"bdd100k-lane": _bdd100k_lanes,
"culane": _culane_lanes,
"openlane-2d": _openlane_lanes,
}
@pytest.fixture
def laned(tmp_path: Path) -> Fixture:
fixture = Fixture(tmp_path, classes=LANE_CLASSES)
fixture.label(LANE_DRAWING)
return fixture
@pytest.mark.parametrize("format_name", sorted(LANE_COUNTERS))
def test_a_lane_format_writes_exactly_the_lanes_it_did_not_call_dropped(
tmp_path: Path, laned: Fixture, format_name: str
) -> None:
"""Report versus artifact for the class-blind formats.
The three lanes in ``LANE_DRAWING`` are the only thing any of these can hold,
so this is also the assertion that a lane format does **not** quietly write a
box or a tag it declared dropped.
"""
release_id = laned.publish()
dest = tmp_path / f"out-{format_name}"
report = _export(laned, release_id, _installed()[format_name], dest)
written = LANE_COUNTERS[format_name](dest)
laned.close()
kept = sum(
one.annotations for one in report.classes if one.status is not ClassExportStatus.DROPPED
)
assert written == kept == 3
assert report.excluded_annotations == 3 # two boxes and a tag
assert sorted(one.label_class for one in report.excluded) == ["sign", "weather"]
def test_tusimple_calls_the_lane_it_resamples_degraded_and_the_others_do_not(
tmp_path: Path, laned: Fixture
) -> None:
"""The one geometry declaration that differs across the five, asserted as such.
TuSimple writes X-at-each-row and not the vertices it was given, so its lanes
are ``DEGRADED``; the other four write the vertices, so theirs are
``SUPPORTED``. Every one of the five is still ``lossy`` — which is a different
question, and the reason both fields exist.
"""
release_id = laned.publish()
reports = {
name: _export(laned, release_id, _installed()[name], tmp_path / f"out-{name}")
for name in sorted(LANE_COUNTERS)
}
laned.close()
for name, report in reports.items():
(lane,) = [one for one in report.classes if one.label_class == "centerline"]
expected = ClassExportStatus.DEGRADED if name == "tusimple" else ClassExportStatus.SUPPORTED
assert lane.status is expected, f"{name} declares centerline {lane.status.value}"
assert not report.compatible # a box and a tag are still dropped
assert _installed()[name].lossy
@pytest.mark.parametrize("format_name", ["ultralytics", "yolov5-yaml", "darknet", "coco", "voc"])
def test_the_general_formats_declare_polyline_truthfully(
tmp_path: Path, laned: Fixture, format_name: str
) -> None:
"""What the YOLO dialects, COCO and VOC can genuinely do with an open path.
The answer, verified against the bytes rather than assumed: **nothing**, and
all three already said so. YOLO and VOC are box formats and reduce a *polygon*
to its bounds, which is defensible because a polygon encloses an area a box
can approximate; an open path encloses nothing, so a box drawn round it is an
invention rather than a reduction. COCO's ``segmentation`` is a closed ring
and it has no open-path primitive at all.
So ``polyline`` is in neither ``supported_geometries`` nor
``degraded_geometries`` for the three, the report calls the class dropped, and
the label files contain no trace of it. Nothing changed in those exporters —
this test is the verification the issue asked for.
"""
release_id = laned.publish()
dest = tmp_path / f"out-{format_name}"
report = _export(laned, release_id, _installed()[format_name], dest)
written = _count(COUNTERS[format_name], dest)
laned.close()
plugin = _installed()[format_name]
assert GeometryType.POLYLINE not in plugin.supported_geometries
assert GeometryType.POLYLINE not in plugin.degraded_geometries
(lane,) = [one for one in report.classes if one.label_class == "centerline"]
assert lane.status is ClassExportStatus.DROPPED
assert lane.annotations == 3
assert written["centerline"] == 0
# --- one class, two shapes ----------------------------------------------------
#: A single class labelled both ways, which is what #584 made expressible. YOLO
#: writes the boxes whole and reduces the polygons; COCO carries both intact.
MIXED_CLASSES = (LabelClass(name="sign", geometries=(GeometryType.BBOX, GeometryType.POLYGON)),)
#: Two boxes and one polygon, all under ``sign``, on two assets.
MIXED_DRAWING: dict[int, list[Annotation]] = {
0: [_box(x=8, y=6, width=20, height=22), _polygon()],
1: [_box(x=2, y=2, width=10, height=10)],
}
@pytest.fixture
def mixed(tmp_path: Path) -> Fixture:
fixture = Fixture(tmp_path, classes=MIXED_CLASSES)
fixture.label(
{
position: [one.model_copy(update={"label_class": "sign"}) for one in drawn]
for position, drawn in MIXED_DRAWING.items()
}
)
return fixture
@pytest.mark.parametrize("format_name", STATIC)
def test_a_class_labelled_two_ways_gets_a_report_row_for_each(
tmp_path: Path, mixed: Fixture, format_name: str
) -> None:
"""The defect a per-class report cannot express, and the reason it is per shape.
Under YOLO one class here is two different answers at once — the boxes are
written whole, the polygons are written as their bounding box and lose their
shape. A report with one row per class could carry only one of those verdicts,
and would describe half its own output wrongly whichever it picked.
The counts are read off the artifact, like every other test in this file: the
rows a format wrote under the class name must equal the sum of the rows it did
not report as dropped.
"""
release_id = mixed.publish()
dest = tmp_path / f"out-{format_name}"
report = _export(mixed, release_id, _installed()[format_name], dest)
written = _count(COUNTERS[format_name], dest)
mixed.close()
rows = [one for one in report.classes if one.label_class == "sign"]
assert {one.geometry for one in rows} == {GeometryType.BBOX, GeometryType.POLYGON}
assert sum(one.annotations for one in rows) == 3
carried = sum(one.annotations for one in rows if one.status is not ClassExportStatus.DROPPED)
assert written["sign"] == carried, (
f"{format_name} reports {[(one.geometry.value, one.status.value) for one in rows]} "
f"and wrote {written['sign']} row(s)"
)
def test_yolov5_yaml_splits_one_mixed_class_into_a_whole_half_and_a_degraded_half(
tmp_path: Path, mixed: Fixture
) -> None:
"""The verdicts themselves, named — the parametrized test above only compares counts.
Written against ``yolov5-yaml`` specifically because it is the format whose
two answers differ: ``supported_geometries`` is ``{bbox}`` and
``degraded_geometries`` is ``{polygon}``, so one class produces one of each.
COCO carries both and would make the assertion vacuous.
"""
release_id = mixed.publish()
report = _export(mixed, release_id, _installed()["yolov5-yaml"], tmp_path / "out")
mixed.close()
verdicts = {one.geometry: one.status for one in report.classes if one.label_class == "sign"}
assert verdicts == {
GeometryType.BBOX: ClassExportStatus.SUPPORTED,
GeometryType.POLYGON: ClassExportStatus.DEGRADED,
}
# Nothing is lost, so consent is still asked for — a degraded export is not a
# compatible one, which is the call `_compatibility` already made.
assert report.excluded_annotations == 0
assert report.degraded_annotations == 1
assert report.compatible is False
# --- the task-switching dialect ----------------------------------------------
#
# ``ultralytics`` is compared per layout: the report is read off static
# declarations and the layout is derived from the release, so the comparison
# holds a release at a time. Three releases, one per task, and then the one
# shape the declarations cannot describe.
#: Boxes and polygons and nothing else: a segment export.
LOCATED_DRAWING: dict[int, list[Annotation]] = {
0: [_box(x=8, y=6, width=20, height=22), _polygon()],
1: [_box(x=2, y=2, width=10, height=10), _polygon([(30.0, 4.0), (44.0, 4.0), (44.0, 20.0)])],
2: [_box(x=1, y=1, width=8, height=8)],
}
#: Tags and nothing else: a class tree.
TAGGED_DRAWING: dict[int, list[Annotation]] = {0: [_tag()], 1: [_tag()], 2: [_tag()]}
def _class_tree_counts(root: Path) -> Counter[str]:
"""Every image under every ``<fold>/<class>`` directory, by the class the directory names."""
found: Counter[str] = Counter()
for fold in ("train", "val", "test"):
if not (root / fold).is_dir():
continue
for class_dir in (root / fold).iterdir():
found[class_dir.name] += sum(1 for _ in class_dir.iterdir())
return found
def _assert_agrees(report: ExportCompatibility, written: Counter[str]) -> None:
for declared in report.classes:
expected = 0 if declared.status is ClassExportStatus.DROPPED else declared.annotations
assert written[declared.label_class] == expected, (
f"ultralytics reports {declared.label_class!r} as {declared.status.value} "
f"with {declared.annotations} annotation(s), and wrote "
f"{written[declared.label_class]}"
)
assert set(written) <= {one.label_class for one in report.classes}
held = sum(one.annotations for one in report.classes)
assert report.excluded_annotations == held - sum(written.values())
def test_ultralytics_segment_export_agrees_with_its_report(tmp_path: Path) -> None:
"""Boxes and polygons both arrive intact, and the report says so."""
fixture = Fixture(tmp_path)
fixture.label(LOCATED_DRAWING)
release_id = fixture.publish()
dest = tmp_path / "out"
report = _export(fixture, release_id, _installed()["ultralytics"], dest)
written = _yolo_counts(dest)
fixture.close()
assert written == Counter({"sign": 3, "lane": 2})
assert (report.excluded_annotations, report.degraded_annotations) == (0, 0)
_assert_agrees(report, written)
def test_ultralytics_detect_export_agrees_with_its_report(tmp_path: Path) -> None:
fixture = Fixture(tmp_path)
fixture.label(
{0: [_box(x=8, y=6, width=20, height=22)], 1: [_box(x=2, y=2, width=10, height=10)]}
)
release_id = fixture.publish()
dest = tmp_path / "out"
report = _export(fixture, release_id, _installed()["ultralytics"], dest)
written = _yolo_counts(dest)
fixture.close()
assert written == Counter({"sign": 2})
_assert_agrees(report, written)
def test_ultralytics_classify_export_agrees_with_its_report(tmp_path: Path) -> None:
"""One image per tag under the class directory, so the tree counts annotations."""
fixture = Fixture(tmp_path)
fixture.label(TAGGED_DRAWING)
release_id = fixture.publish()
dest = tmp_path / "out"
report = _export(fixture, release_id, _installed()["ultralytics"], dest)
written = _class_tree_counts(dest)
fixture.close()
assert written == Counter({"weather": 3})
_assert_agrees(report, written)
def test_ultralytics_reports_a_tag_beside_a_box_as_dropped(
tmp_path: Path, labelled: Fixture
) -> None:
"""A tag beside located labels has no layout to land in, and the report says so."""
release_id = labelled.publish()
dest = tmp_path / "out"
report = _export(labelled, release_id, _installed()["ultralytics"], dest)
written = _yolo_counts(dest)
labelled.close()
assert written == Counter({"sign": 3, "lane": 2})
(tag,) = [one for one in report.classes if one.label_class == "weather"]
assert tag.status is ClassExportStatus.DROPPED
assert tag.reason is not None and "nothing else" in tag.reason
assert not report.compatible
_assert_agrees(report, written)
def test_a_target_keeping_tags_reports_the_same_drop(tmp_path: Path, labelled: Fixture) -> None:
installed = _installed()
plugin, target = resolve_target(installed, "yolo11")
release_id = labelled.publish()
report = labelled.releases.check_export(release_id, plugin, target=target)
labelled.close()
(tag,) = [one for one in report.classes if one.label_class == "weather"]
assert tag.status is ClassExportStatus.DROPPED
@pytest.mark.parametrize("name", ["yolov4", "voc"])
def test_a_target_not_carrying_a_shape_its_format_reduces_drops_it_and_refuses_alone(
tmp_path: Path, name: str
) -> None:
"""The format writes a polygon as its box; the target carries boxes only and is handed none."""
fixture = Fixture(tmp_path)
fixture.label({0: [_polygon()]})
release_id = fixture.publish()
plugin, target = resolve_target(_installed(), name)
by_format = fixture.releases.check_export(release_id, plugin)
by_target = fixture.releases.check_export(release_id, plugin, target=target)
with pytest.raises(ExportSourceUnreadable, match="would write none of the 1 label"):
fixture.releases.export(
release_id, plugin, tmp_path / "out", allow_lossy=True, target=target
)
fixture.close()
((_, by_format_status),) = [
(one.label_class, one.status) for one in by_format.classes if one.annotations
]
(lane,) = [one for one in by_target.classes if one.annotations]
assert by_format_status is ClassExportStatus.DEGRADED
assert lane.status is ClassExportStatus.DROPPED
assert not (tmp_path / "out").exists()
# --- a recipe at export ---------------------------------------------------------
#
# The accounting a recipe adds: every fold's images and labels on disk are the
# fold's source files plus the augmented variants the recipe made for it, and
# the report's mapping traces each one. Real pixels, through the installed
# Pillow drivers, because the seam's own tests use a marking double.
def _fold_files(root: Path, fold: str, suffix: str) -> list[Path]:
return (
sorted((root / "images" / fold).glob(f"*{suffix}"))
if suffix != ".txt"
else sorted((root / LABELS_DIRNAME / fold).glob("*.txt"))
)
def test_written_files_are_source_plus_augmented_per_fold(
tmp_path: Path, labelled: Fixture
) -> None:
from PIL import Image
from visionset.kernel.domain import (
AugmentOp,
AugmentStep,
RecipeSpec,
ResizeStep,
ResizeStrategy,
SplitRecipe,
source_of_content_hash,
)
from visionset.preprocessing.registry import drivers
release_id = labelled.publish(split=SplitRecipe(train=0.6, val=0.2, test=0.2, seed=3))
folds = labelled.releases.assignment(release_id)
recipe = RecipeSpec(
target="yolo11",
steps=(
ResizeStep(strategy=ResizeStrategy.LETTERBOX, width=64, height=64),
AugmentStep(op=AugmentOp.HFLIP),
),
variants_per_asset=1,
)
dest = tmp_path / "out"
result = labelled.releases.export(
release_id,
_installed()["ultralytics"],
dest,
allow_lossy=True,
recipe=recipe,
recipe_name="flip",
drivers=drivers(),
)
labelled.close()
per_fold = {"train": len(folds.train), "val": len(folds.val), "test": len(folds.test)}
assert result.source_file_count == sum(per_fold.values()) == 3
assert result.augmented_file_count == per_fold["train"]
for fold, sources in per_fold.items():
augmented = sources if fold == "train" else 0
images = _fold_files(dest, fold, ".png")