Repository navigation
Expand file tree
/
Copy pathtask_workflows.py
More file actions
1692 lines (1481 loc) · 63.3 KB
/
Copy pathtask_workflows.py
File metadata and controls
1692 lines (1481 loc) · 63.3 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
#!/usr/bin/env python3
"""One complete path per labeling task, ending in a tool that is not VisionSet.
Nine tasks, and a tenth run of detection that augments, one workspace, one
lifecycle. Each gets its own project and walks the same stages:
generated media -> ingest under capture groups -> author -> review (one label
sent back and corrected) -> accept -> promote -> quality report -> curate
(one asset removed) -> correction batch -> publish with a grouped split ->
verify -> pre-processing recipe where the task allows one -> preflight ->
export -> an independent consumer reads it
The media is generated at run time: stills for the image tasks, frames of a
short clip for tracking (posted the way the browser posts the frames it
decoded), and PCD scans with a car-sized cluster of points for the 3D task.
Nothing is downloaded and nothing is committed.
``augmentation`` is detection again, imbalanced on purpose, exported through
the ``detection`` preset behind an ``object_safe_crop`` and a ``uniform``
balance: refused without consent, then written with exactly the consent the
preflight asked for, its held-out folds byte-identical to a plain export, its
variants where the preflight planned them, and its report replayed.
Labels are written through the SDK, the route every surface shares. Keypoints,
masks and scans have no browser editor for some steps and the SDK (or REST or
MCP) is their real route; boxes, polygons, oriented boxes, polylines, tags,
tracks and cuboids can also be drawn in the browser.
**Consumers.** Each export is read by something other than VisionSet's own
importer. Where a third-party library is installed it is used, and the run
records how deep it went: ``loaded`` (the library parsed the layout),
``scored`` (it computed a metric over it) or ``trained`` (a short CPU training
step finished with a finite loss). Where no third-party tool exists the
example parses the published layout itself and records ``parsed (example
reader)``, which is weaker evidence and says so. A missing library is
``skipped``, unless ``VISIONSET_REQUIRE_READERS=1`` is set, which turns every
skip into a failure.
python examples/task_workflows.py [DESTINATION] [--train] [--only TASK,...]
``--train`` adds the training steps (ultralytics on CPU for one epoch, and a
small torch loop over the semantic masks). The readers come from the ``yolo``,
``coco`` and ``mot`` dependency groups; ``pykitti`` is optional and not in any
group.
"""
from __future__ import annotations
import argparse
import contextlib
import json
import math
import os
import shutil
import struct
import sys
import xml.etree.ElementTree as ElementTree
from collections.abc import Callable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from io import BytesIO
from pathlib import Path
from typing import Any
from uuid import UUID
from PIL import Image
from visionset import __version__
from visionset.formats import registry
from visionset.kernel.domain import (
Annotation,
AnnotationJob,
Asset,
AssetProgress,
AugmentOp,
AugmentStep,
BalancePolicy,
BboxGeometry,
ClassBalance,
ClassificationGeometry,
Cuboid3DGeometry,
ExportReport,
GeometryType,
IncomingFrame,
KeypointsGeometry,
KeypointSpec,
LabelClass,
ObbGeometry,
PolygonGeometry,
PolylineGeometry,
RecipeAssessment,
RecipeSpec,
Release,
ReplayOutcome,
ResizeStep,
ResizeStrategy,
ScanFrame,
SplitAssignment,
SplitGrouping,
SplitRecipe,
VertexVisibility,
VideoMetadata,
mask_from_bitmap,
read_export_report,
recipe_preset,
replay_export_report,
)
from visionset.kernel.errors import LossyExportNotConsented, VisionSetError
from visionset.kernel.ports import resolve_target
from visionset.kernel.services import (
AnnotationService,
BatchService,
DatasetService,
IngestService,
JobService,
PreprocessingRecipeService,
ProjectService,
QualityService,
ReleaseService,
SchemaService,
SourceService,
TrackService,
VideoImportService,
WorkspaceService,
export_environment,
)
from visionset.preprocessing import registry as preprocessing_registry
DEFAULT_DEST = Path(__file__).resolve().parent / "workspace-data" / "task-workflows"
REQUIRE_ENV = "VISIONSET_REQUIRE_READERS"
SIZE = 64
GROUPS = ("scene-a", "scene-b", "scene-c", "scene-d")
PER_GROUP = 3
#: Four capture groups under 0.5/0.25/0.25 land two, one and one whole groups per fold.
SPLIT = SplitRecipe(train=0.5, val=0.25, test=0.25, seed=7, group_by=SplitGrouping.GROUP_LABEL)
TASKS = (
"classification",
"detection",
"instance-segmentation",
"semantic-segmentation",
"obb",
"pose",
"lanes",
"tracking",
"point-cloud",
"augmentation",
)
# --- evidence ---------------------------------------------------------------
@dataclass(frozen=True)
class Evidence:
task: str
output: str
consumer: str
depth: str
detail: str
@dataclass
class Run:
dest: Path
train: bool
evidence: list[Evidence] = field(default_factory=list)
releases: dict[str, Release] = field(default_factory=dict)
def record(self, task: str, output: str, consumer: str, depth: str, detail: str) -> None:
self.evidence.append(Evidence(task, output, consumer, depth, detail))
print(f" [{depth}] {output} <- {consumer}: {detail}", flush=True)
class ReaderMissing(Exception):
"""A consumer's library is not installed."""
def _require(module: str, group: str) -> Any:
try:
return __import__(module, fromlist=["_"])
except ImportError:
raise ReaderMissing(f"{module} is not installed ({group})") from None
@contextlib.contextmanager
def consumer(run: Run, task: str, output: str, name: str) -> Iterator[None]:
"""Run one consumer; a missing library is a skip unless the readers are required."""
try:
yield
except ReaderMissing as missing:
if os.environ.get(REQUIRE_ENV) == "1":
raise SystemExit(f"{task}: {missing}, and {REQUIRE_ENV}=1 is set") from None
run.record(task, output, name, "skipped", str(missing))
# --- media -------------------------------------------------------------------
def write_stills(directory: Path, first: int, count: int) -> Path:
directory.mkdir(parents=True, exist_ok=True)
for index in range(first, first + count):
pixels = bytes(
channel
for y in range(SIZE)
for x in range(SIZE)
for channel in (
(x * 3 + index * 41) % 256,
(y * 3 + index * 17) % 256,
(index * 53) % 256,
)
)
Image.frombytes("RGB", (SIZE, SIZE), pixels).save(directory / f"still-{index:03d}.png")
return directory
def car_boxes(position: int) -> tuple[tuple[float, float], ...]:
"""Where the clip's two cars are at a frame: one drives right, one left."""
return ((4.0 + 8 * position, 12.0), (44.0 - 8 * position, 40.0))
def jpeg_frame(seed: int, position: int) -> bytes:
image = Image.new("RGB", (SIZE, SIZE), ((seed * 31) % 256, 90, 120))
for left, top in car_boxes(position):
for x in range(int(left), int(left) + 16):
for y in range(int(top), int(top) + 12):
image.putpixel((x, y), (230, 40, 40))
buffer = BytesIO()
image.save(buffer, format="JPEG", quality=90)
return buffer.getvalue()
#: The car every scan holds, in the lidar's forward-left-up frame: centre, (l, w, h), yaw.
CAR = ((8.0, 1.5, -0.9), (4.0, 1.8, 1.5), 0.4)
def pcd_scan(seed: int) -> bytes:
"""A binary PCD: a ground grid and a car-shaped block of points inside :data:`CAR`."""
points: list[tuple[float, float, float, float]] = []
for gx in range(-10, 30, 2):
for gy in range(-10, 10, 2):
points.append((gx + 0.1 * seed, float(gy), -1.7, 0.2))
(cx, cy, cz), (length, width, height), yaw = CAR
cos, sin = math.cos(yaw), math.sin(yaw)
for i in range(6):
for j in range(4):
for k in range(3):
u = (i + 0.5) / 6 * length * 0.9 - length * 0.45
v = (j + 0.5) / 4 * width * 0.9 - width * 0.45
w = (k + 0.5) / 3 * height * 0.9 - height * 0.45
points.append((cx + u * cos - v * sin, cy + u * sin + v * cos, cz + w, 0.8))
header = (
"# .PCD v0.7\nVERSION 0.7\nFIELDS x y z intensity\nSIZE 4 4 4 4\nTYPE F F F F\n"
f"COUNT 1 1 1 1\nWIDTH {len(points)}\nHEIGHT 1\nVIEWPOINT 0 0 0 1 0 0 0\n"
f"POINTS {len(points)}\nDATA binary\n"
).encode("ascii")
return header + b"".join(struct.pack("<ffff", *point) for point in points)
# --- the lifecycle -------------------------------------------------------------
Annotate = Callable[[AnnotationJob, list[Asset]], None]
Correct = Callable[[Annotation], Annotation]
@dataclass(frozen=True)
class Lifecycle:
project_id: UUID
release: Release
removed: UUID
def lifecycle(
workspace: WorkspaceService,
name: str,
classes: Sequence[LabelClass],
gather: Callable[[UUID], UUID],
annotate: Annotate,
correct: Correct,
) -> Lifecycle:
"""Drive one project from its media to a verified, grouped release."""
projects = ProjectService(workspace)
batches = BatchService(workspace)
jobs = JobService(workspace)
annotations = AnnotationService(workspace)
datasets = DatasetService(workspace)
releases = ReleaseService(workspace)
project = projects.create(name)
SchemaService(workspace).create_version(project.id, list(classes))
batch_id = gather(project.id)
batches.approve(batch_id)
batches.start(batch_id)
(job,) = batches.jobs(batch_id)
jobs.start(job.id)
assets = batches.assets(batch_id)
annotate(job, assets)
for asset in assets:
jobs.mark(job.id, asset.id, AssetProgress.REVIEW_PENDING)
sent_back = assets[0]
jobs.mark(job.id, sent_back.id, AssetProgress.ANNOTATED)
first = annotations.for_asset(job.id, sent_back.id)[0]
annotations.update(job.id, [correct(first)])
jobs.mark(job.id, sent_back.id, AssetProgress.REVIEW_PENDING)
for asset in assets:
jobs.mark(job.id, asset.id, AssetProgress.ACCEPTED)
jobs.complete(job.id)
batches.complete(batch_id)
datasets.promote(batch_id)
dataset = projects.get_dataset(project.id)
report = QualityService(workspace).assess_dataset(dataset.id)
blocking = [issue for issue in report.issues if issue.severity == "blocking"]
if blocking:
raise SystemExit(f"{name}: the quality report blocks publishing: {blocking}")
removed = assets[-1].id
if not datasets.remove_asset(dataset.id, removed):
raise SystemExit(f"{name}: curation removed nothing")
corrected = assets[1].id
fix = batches.create_correction(batch_id, f"{name}-correction", [corrected])
batches.approve(fix.id)
batches.start(fix.id)
(fix_job,) = batches.jobs(fix.id)
jobs.start(fix_job.id)
label = annotations.for_asset(fix_job.id, corrected)[0]
annotations.update(fix_job.id, [correct(label)])
jobs.mark(fix_job.id, corrected, AssetProgress.REVIEW_PENDING)
jobs.mark(fix_job.id, corrected, AssetProgress.ACCEPTED)
jobs.complete(fix_job.id)
batches.complete(fix.id)
datasets.promote(fix.id)
release = releases.publish(dataset.id, "v1", split=SPLIT)
if not releases.verify(release.id).ok:
raise SystemExit(f"{name}: the release does not verify")
folds = releases.assignment(release.id)
print(
f" released {release.asset_count} assets, {release.annotation_count} labels; "
f"folds {_fold_sizes(folds)}; quality: {report.assets} assets, "
f"{len(report.issues)} issue(s)",
flush=True,
)
return Lifecycle(project.id, release, removed)
def _fold_sizes(assignment: SplitAssignment) -> str:
return f"train={len(assignment.train)}, val={len(assignment.val)}, test={len(assignment.test)}"
def gather_stills(workspace: WorkspaceService, dest: Path, name: str) -> Callable[[UUID], UUID]:
"""Ingest one folder per capture group into one draft batch."""
def gather(project_id: UUID) -> UUID:
sources, ingest = SourceService(workspace), IngestService(workspace)
batch_id: UUID | None = None
for position, group in enumerate(GROUPS):
folder = write_stills(
dest / "incoming" / name / group,
position * PER_GROUP + 100 * TASKS.index(name),
PER_GROUP,
)
source = sources.register_images(project_id, folder)
run = ingest.ingest(
source.id,
batch_id=batch_id,
batch_name=None if batch_id else name,
group_label=group,
)
if run.failed or run.batch_id is None:
raise SystemExit(f"{name}: ingest failed: {run.failures}")
batch_id = run.batch_id
assert batch_id is not None
return batch_id
return gather
def drawing(workspace: WorkspaceService, draw: Callable[[int, UUID], list[Annotation]]) -> Annotate:
def annotate(job: AnnotationJob, assets: list[Asset]) -> None:
annotations = AnnotationService(workspace)
for index, asset in enumerate(assets):
if drawn := draw(index, asset.id):
annotations.add(job.id, drawn)
else:
JobService(workspace).mark(job.id, asset.id, AssetProgress.ANNOTATED)
return annotate
def label(asset_id: UUID, label_class: str, geometry: Any) -> Annotation:
return Annotation(
asset_id=asset_id,
label_class=label_class,
schema_version=1,
geometry=geometry,
provenance="human",
)
def moved(annotation: Annotation, **changes: Any) -> Annotation:
geometry = annotation.geometry.model_copy(update=changes)
return annotation.model_copy(
update={"geometry": type(geometry).model_validate(geometry.model_dump())}
)
# --- export ---------------------------------------------------------------------
def export(
run: Run,
workspace: WorkspaceService,
task: str,
release: Release,
name: str,
*,
target: bool = False,
recipe: tuple[str, RecipeSpec] | None = None,
project_id: UUID | None = None,
folder: str | None = None,
) -> Path:
"""Preflight, then export with consent given only for what the preflight reported."""
installed = registry.exporters()
if target:
plugin, addressed = resolve_target(installed, name)
else:
plugin, addressed = registry.pick(installed, name)[0], None
releases = ReleaseService(workspace)
spec = None
drivers = None
if recipe is not None:
assert project_id is not None
recipes = PreprocessingRecipeService(workspace)
if recipe[0] not in {saved.name for saved in recipes.list(project_id)}:
recipes.create(project_id, recipe[0], recipe[1])
spec = recipes.for_release(release.id, recipe[0]).spec
drivers = preprocessing_registry.drivers()
report = releases.check_export(
release.id, plugin, target=addressed, recipe=spec, drivers=drivers
)
print(
f" preflight {name}{' + ' + recipe[0] if recipe else ''}: "
f"consent_required={report.consent_required}, excluded={report.excluded_annotations}, "
f"degraded={report.degraded_annotations}",
flush=True,
)
out = run.dest / "exports" / task / (folder or name)
result = releases.export(
release.id,
plugin,
out,
allow_lossy=report.consent_required,
target=addressed,
recipe=spec,
recipe_name=None if recipe is None else recipe[0],
drivers=drivers,
)
if recipe is not None:
print(
f" {name}: {result.source_file_count} source and "
f"{result.augmented_file_count} augmented file(s)",
flush=True,
)
return result.directory
FLIP = AugmentStep(op=AugmentOp.HFLIP)
def flip_recipe(*, resize: bool) -> RecipeSpec:
steps: tuple[Any, ...] = (FLIP,)
if resize:
steps = (ResizeStep(strategy=ResizeStrategy.LETTERBOX, width=SIZE, height=SIZE), FLIP)
return RecipeSpec(target=None, steps=steps, variants_per_asset=1)
# --- shared consumers -------------------------------------------------------------
def ultralytics_load(run: Run, task: str, output: str, data: Path, kind: str) -> None:
with consumer(run, task, output, "ultralytics"):
os.environ.setdefault("YOLO_OFFLINE", "true")
utils = _require("ultralytics.data.utils", "uv sync --group yolo")
if kind == "classify":
loaded = utils.check_cls_dataset(str(data))
run.record(task, output, "ultralytics", "loaded", f"{loaded['nc']} classes")
return
with contextlib.chdir(data.parent):
loaded = utils.check_det_dataset(data.name, autodownload=False)
run.record(task, output, "ultralytics", "loaded", f"{loaded['nc']} classes")
def ultralytics_train(run: Run, task: str, output: str, data: Path, model_yaml: str) -> None:
if not run.train:
return
with consumer(run, task, output, "ultralytics trainer"):
os.environ.setdefault("YOLO_OFFLINE", "true")
ultralytics = _require("ultralytics", "uv sync --group yolo")
model = ultralytics.YOLO(model_yaml)
workdir = data if data.is_dir() else data.parent
with contextlib.chdir(workdir):
model.train(
data=str(data),
epochs=1,
imgsz=SIZE,
batch=2,
device="cpu",
workers=0,
plots=False,
amp=False,
pretrained=False,
verbose=False,
seed=0,
deterministic=True,
project=str(run.dest / "runs"),
name=f"{task}-{output}",
exist_ok=True,
)
losses = (
{key: float(value) for key, value in model.trainer.tloss.items()}
if isinstance(model.trainer.tloss, dict)
else {"loss": float(model.trainer.tloss.sum())}
)
if not all(math.isfinite(value) for value in losses.values()):
raise SystemExit(f"{task}: training produced a non-finite loss: {losses}")
run.record(
task,
output,
"ultralytics trainer",
"trained",
"one CPU epoch, losses " + ", ".join(f"{k}={v:.3f}" for k, v in losses.items()),
)
def pycocotools_folds(export_dir: Path) -> Iterator[tuple[str, Any]]:
coco = _require("pycocotools.coco", "uv sync --group coco")
for path in sorted((export_dir / "annotations").glob("*.json")):
with contextlib.redirect_stdout(sys.stderr):
yield path.stem, coco.COCO(str(path))
# --- the image tasks --------------------------------------------------------------
def classification(run: Run, workspace: WorkspaceService) -> None:
task = "classification"
classes = (
LabelClass(name="sunny", geometries=(GeometryType.CLASSIFICATION_TAG,)),
LabelClass(name="rainy", geometries=(GeometryType.CLASSIFICATION_TAG,)),
)
def draw(index: int, asset_id: UUID) -> list[Annotation]:
return [label(asset_id, classes[index % 2].name, ClassificationGeometry())]
def correct(annotation: Annotation) -> Annotation:
other = "rainy" if annotation.label_class == "sunny" else "sunny"
return annotation.model_copy(update={"label_class": other})
done = lifecycle(
workspace,
task,
classes,
gather_stills(workspace, run.dest, task),
drawing(workspace, draw),
correct,
)
tree = export(
run,
workspace,
task,
done.release,
"classification-dir",
recipe=("flip", flip_recipe(resize=True)),
project_id=done.project_id,
)
ultralytics_load(run, task, "classification-dir", tree, "classify")
ultralytics_train(run, task, "classification-dir", tree, "yolo11n-cls.yaml")
yolo = export(run, workspace, task, done.release, "yolo11", target=True)
ultralytics_load(run, task, "yolo11 (classify)", yolo, "classify")
def detection(run: Run, workspace: WorkspaceService) -> None:
task = "detection"
classes = (
LabelClass(name="car", geometries=(GeometryType.BBOX,)),
LabelClass(name="sign", geometries=(GeometryType.BBOX,)),
)
def draw(index: int, asset_id: UUID) -> list[Annotation]:
shift = float(index % 4) * 3
return [
label(asset_id, "car", BboxGeometry(x=6.0 + shift, y=30.0, width=24.0, height=16.0)),
label(asset_id, "sign", BboxGeometry(x=40.0, y=6.0 + shift, width=10.0, height=14.0)),
]
def correct(annotation: Annotation) -> Annotation:
return moved(annotation, x=annotation.geometry.x + 1.0) # type: ignore[union-attr]
done = lifecycle(
workspace,
task,
classes,
gather_stills(workspace, run.dest, task),
drawing(workspace, draw),
correct,
)
coco = export(run, workspace, task, done.release, "coco")
with consumer(run, task, "coco", "pycocotools"):
counts = {fold: len(api.getAnnIds()) for fold, api in pycocotools_folds(coco)}
if sum(counts.values()) != done.release.annotation_count:
raise SystemExit(
f"{task}: pycocotools found {counts}, not {done.release.annotation_count}"
)
run.record(task, "coco", "pycocotools", "loaded", f"boxes per fold {counts}")
yolo = export(
run,
workspace,
task,
done.release,
"yolo11",
target=True,
recipe=("letterbox-flip", flip_recipe(resize=True)),
project_id=done.project_id,
)
ultralytics_load(run, task, "yolo11 (detect)", yolo / "data.yaml", "detect")
ultralytics_train(run, task, "yolo11 (detect)", yolo / "data.yaml", "yolo11n.yaml")
def instance_segmentation(run: Run, workspace: WorkspaceService) -> None:
task = "instance-segmentation"
classes = (
LabelClass(name="car", geometries=(GeometryType.POLYGON,)),
LabelClass(name="puddle", geometries=(GeometryType.MASK,)),
)
def draw(index: int, asset_id: UUID) -> list[Annotation]:
shift = float(index % 4) * 3
car = PolygonGeometry(
points=[(6 + shift, 30), (34 + shift, 30), (30 + shift, 46), (8 + shift, 46)]
)
bitmap = bytearray(SIZE * SIZE)
for y in range(48, 60):
for x in range(36, 58):
bitmap[y * SIZE + x] = 1
puddle = mask_from_bitmap(bytes(bitmap), height=SIZE, width=SIZE)
return [label(asset_id, "car", car), label(asset_id, "puddle", puddle)]
def correct(annotation: Annotation) -> Annotation:
if annotation.geometry.type is GeometryType.POLYGON:
points = [(x + 1.0, y) for x, y in annotation.geometry.points] # type: ignore[union-attr]
return moved(annotation, points=points)
return annotation
done = lifecycle(
workspace,
task,
classes,
gather_stills(workspace, run.dest, task),
drawing(workspace, draw),
correct,
)
coco = export(run, workspace, task, done.release, "coco")
with consumer(run, task, "coco", "pycocotools"):
areas: dict[str, int] = {}
for _fold, api in pycocotools_folds(coco):
names = {c["id"]: c["name"] for c in api.loadCats(api.getCatIds())}
for annotation in api.loadAnns(api.getAnnIds()):
pixels = int(api.annToMask(annotation).sum())
if pixels == 0:
raise SystemExit(f"{task}: pycocotools decoded an empty mask")
areas[names[annotation["category_id"]]] = pixels
run.record(
task, "coco", "pycocotools", "loaded", f"decoded masks, pixels per class {areas}"
)
yolo = export(
run,
workspace,
task,
done.release,
"yolo11",
target=True,
recipe=("letterbox-flip", flip_recipe(resize=True)),
project_id=done.project_id,
)
ultralytics_load(run, task, "yolo11 (segment)", yolo / "data.yaml", "segment")
ultralytics_train(run, task, "yolo11 (segment)", yolo / "data.yaml", "yolo11n-seg.yaml")
def semantic_segmentation(run: Run, workspace: WorkspaceService) -> None:
task = "semantic-segmentation"
classes = (
LabelClass(name="road", geometries=(GeometryType.MASK,)),
LabelClass(name="car", geometries=(GeometryType.POLYGON,)),
)
def draw(index: int, asset_id: UUID) -> list[Annotation]:
bitmap = bytearray(SIZE * SIZE)
for y in range(40, SIZE):
for x in range(SIZE):
bitmap[y * SIZE + x] = 1
road = mask_from_bitmap(bytes(bitmap), height=SIZE, width=SIZE)
shift = float(index % 4) * 3
car = PolygonGeometry(
points=[(8 + shift, 20), (30 + shift, 20), (30 + shift, 38), (8 + shift, 38)]
)
return [label(asset_id, "road", road), label(asset_id, "car", car)]
def correct(annotation: Annotation) -> Annotation:
if annotation.geometry.type is GeometryType.POLYGON:
points = [(x, y + 1.0) for x, y in annotation.geometry.points] # type: ignore[union-attr]
return moved(annotation, points=points)
return annotation
done = lifecycle(
workspace,
task,
classes,
gather_stills(workspace, run.dest, task),
drawing(workspace, draw),
correct,
)
out = export(
run,
workspace,
task,
done.release,
"segmentation-png",
recipe=("flip", flip_recipe(resize=False)),
project_id=done.project_id,
)
pairs = _semantic_pairs(out)
ids = sorted(
{
value
for _image, mask in pairs
for _count, value in mask.getcolors(maxcolors=1 << 16) or ()
}
)
if ids != [0, 1, 2]:
raise SystemExit(f"{task}: the masks hold class ids {ids}, not background, road and car")
run.record(
task,
"segmentation-png",
"Pillow",
"parsed (example reader)",
f"{len(pairs)} image/mask pairs, class ids {ids}",
)
if run.train:
with consumer(run, task, "segmentation-png", "torch"):
first, last = _train_semantic(pairs, classes=3)
run.record(
task,
"segmentation-png",
"torch",
"trained",
f"40 steps of a 2-layer conv net, cross-entropy {first:.3f} -> {last:.3f}",
)
def _semantic_pairs(out: Path) -> list[tuple[Image.Image, Image.Image]]:
pairs: list[tuple[Image.Image, Image.Image]] = []
for mask_path in sorted((out / "masks").rglob("*.png")):
fold = mask_path.parent.name
(image_path,) = (out / "images" / fold).glob(mask_path.stem + ".*")
pairs.append((Image.open(image_path).convert("RGB"), Image.open(mask_path)))
return pairs
def _train_semantic(
pairs: list[tuple[Image.Image, Image.Image]], *, classes: int
) -> tuple[float, float]:
torch = _require("torch", "uv sync --group yolo")
numpy = _require("numpy", "numpy")
torch.manual_seed(0)
images = torch.tensor(numpy.stack([numpy.asarray(i, dtype="float32") / 255 for i, _m in pairs]))
targets = torch.tensor(numpy.stack([numpy.asarray(m, dtype="int64") for _i, m in pairs]))
images = images.permute(0, 3, 1, 2)
model = torch.nn.Sequential(
torch.nn.Conv2d(3, 8, 3, padding=1), torch.nn.ReLU(), torch.nn.Conv2d(8, classes, 1)
)
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
losses = []
for _step in range(40):
optimizer.zero_grad()
loss = torch.nn.functional.cross_entropy(model(images), targets)
loss.backward()
optimizer.step()
losses.append(float(loss))
if not (math.isfinite(losses[-1]) and losses[-1] < losses[0]):
raise SystemExit(f"semantic training did not reduce the loss: {losses[0]} -> {losses[-1]}")
return losses[0], losses[-1]
#: The categories ultralytics' DOTA converter knows; a DOTA export must use its names.
DOTA_NAMES = (
"plane",
"ship",
"storage-tank",
"baseball-diamond",
"tennis-court",
"basketball-court",
"ground-track-field",
"harbor",
"bridge",
"large-vehicle",
"small-vehicle",
"helicopter",
"roundabout",
"soccer-ball-field",
"swimming-pool",
"container-crane",
"airport",
"helipad",
)
def obb(run: Run, workspace: WorkspaceService) -> None:
task = "obb"
classes = (
LabelClass(name="ship", geometries=(GeometryType.OBB,)),
LabelClass(name="plane", geometries=(GeometryType.OBB,)),
)
def draw(index: int, asset_id: UUID) -> list[Annotation]:
angle = 0.3 + 0.1 * (index % 3)
return [
label(
asset_id,
"ship",
ObbGeometry(cx=22.0, cy=24.0, width=26.0, height=10.0, angle=angle),
),
label(
asset_id,
"plane",
ObbGeometry(cx=44.0, cy=44.0, width=16.0, height=12.0, angle=-angle),
),
]
def correct(annotation: Annotation) -> Annotation:
return moved(annotation, cx=annotation.geometry.cx + 1.0) # type: ignore[union-attr]
done = lifecycle(
workspace,
task,
classes,
gather_stills(workspace, run.dest, task),
drawing(workspace, draw),
correct,
)
dota = export(
run,
workspace,
task,
done.release,
"dota",
recipe=("flip", flip_recipe(resize=False)),
project_id=done.project_id,
)
yolo = export(run, workspace, task, done.release, "yolo-obb")
ultralytics_load(run, task, "yolo-obb", yolo / "data.yaml", "obb")
with consumer(run, task, "dota", "ultralytics convert_dota_to_yolo_obb"):
converter = _require("ultralytics.data.converter", "uv sync --group yolo")
root = _dota_root(dota, run.dest / "exports" / task / "dota-as-ultralytics")
with contextlib.redirect_stderr(sys.stdout):
converter.convert_dota_to_yolo_obb(str(root))
rows = _compare_dota_with_yolo_obb(root, yolo)
run.record(
task,
"dota",
"ultralytics convert_dota_to_yolo_obb",
"loaded",
f"{rows} boxes converted, each matching the yolo-obb export's corners",
)
ultralytics_train(run, task, "dota (converted)", root / "data.yaml", "yolo11n-obb.yaml")
def _dota_root(dota: Path, root: Path) -> Path:
"""Lay the DOTA export out the way the converter expects; files are copied, not parsed."""
shutil.rmtree(root, ignore_errors=True)
for fold in ("train", "val"):
shutil.copytree(dota / fold / "images", root / "images" / fold)
shutil.copytree(dota / fold / "labelTxt", root / "labels" / f"{fold}_original")
names = "\n".join(f" {index}: {name}" for index, name in enumerate(DOTA_NAMES))
(root / "data.yaml").write_text(
f"path: {root}\ntrain: images/train\nval: images/val\nnames:\n{names}\n", encoding="utf-8"
)
return root
def _compare_dota_with_yolo_obb(root: Path, yolo: Path) -> int:
yolo_names = _data_yaml_names(yolo / "data.yaml")
compared = 0
for converted in sorted((root / "labels" / "val").glob("*.txt")):
theirs = _corner_rows(converted, lambda index: DOTA_NAMES[index])
ours = _corner_rows(
yolo / "labels" / "val" / converted.name, lambda index: yolo_names[index]
)
if sorted(theirs) != sorted(ours):
raise SystemExit(
f"obb: {converted.name}: the converter read {theirs}, yolo-obb wrote {ours}"
)
compared += len(theirs)
if compared == 0:
raise SystemExit("obb: the converter produced no validation labels to compare")
return compared
def _corner_rows(
path: Path, name: Callable[[int], str]
) -> list[tuple[str, tuple[tuple[float, float], ...]]]:
rows = []
for line in path.read_text(encoding="utf-8").splitlines():
index, *values = line.split()
corners = [
(round(float(values[i]), 3), round(float(values[i + 1]), 3)) for i in range(0, 8, 2)
]
rows.append((name(int(index)), tuple(sorted(corners))))
return rows
def _data_yaml_names(data: Path) -> list[str]:
names: list[str] = []
inside = False
for line in data.read_text(encoding="utf-8").splitlines():
if line.startswith("names:"):
inside = True
elif inside and line.startswith(" "):
names.append(line.split(":", 1)[1].strip().strip('"'))
elif inside:
break
return names
def pose(run: Run, workspace: WorkspaceService) -> None:
task = "pose"
classes = (
LabelClass(
name="person",
geometries=(GeometryType.KEYPOINTS,),
keypoints=KeypointSpec(names=("head", "left_hand", "right_hand")),
),
)
def draw(index: int, asset_id: UUID) -> list[Annotation]:
shift = float(index % 4) * 3
points = [(30.0 + shift, 12.0), (18.0 + shift, 32.0), (42.0 + shift, 32.0)]
return [
label(
asset_id,
"person",
KeypointsGeometry(points=points, visibility=(VertexVisibility.VISIBLE,) * 3),
)
]
def correct(annotation: Annotation) -> Annotation:
geometry = annotation.geometry
assert isinstance(geometry, KeypointsGeometry)
return annotation.model_copy(
update={"geometry": geometry.through([(x + 1.0, y) for x, y in geometry.points])}
)
done = lifecycle(
workspace,
task,
classes,
gather_stills(workspace, run.dest, task),
drawing(workspace, draw),
correct,
)
coco = export(run, workspace, task, done.release, "coco")
with consumer(run, task, "coco", "pycocotools COCOeval"):
cocoeval = _require("pycocotools.cocoeval", "uv sync --group coco")
numpy = _require("numpy", "numpy")
scores = {}
for fold, api in pycocotools_folds(coco):
if not api.getAnnIds():
continue
detections = [dict(a, score=1.0) for a in api.loadAnns(api.getAnnIds())]
with contextlib.redirect_stdout(sys.stderr):
evaluation = cocoeval.COCOeval(api, api.loadRes(detections), "keypoints")
evaluation.params.kpt_oks_sigmas = numpy.full(3, 0.05)
evaluation.evaluate()
evaluation.accumulate()
evaluation.summarize()
scores[fold] = round(float(evaluation.stats[0]), 3)
if not scores or any(score != 1.0 for score in scores.values()):
raise SystemExit(f"{task}: COCOeval scored the export against itself as {scores}")
run.record(
task, "coco", "pycocotools COCOeval", "scored", f"keypoint AP against itself {scores}"
)
yolo = export(
run,
workspace,
task,
done.release,
"yolo11",