easyannotate 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. data_factory/__init__.py +82 -0
  2. data_factory/__main__.py +6 -0
  3. data_factory/annotate/__init__.py +15 -0
  4. data_factory/annotate/attach.py +398 -0
  5. data_factory/annotate/demo.py +161 -0
  6. data_factory/annotate/images.py +443 -0
  7. data_factory/annotate/labels.py +399 -0
  8. data_factory/annotate/loop.py +359 -0
  9. data_factory/annotate/projects.py +207 -0
  10. data_factory/annotate/review.py +471 -0
  11. data_factory/annotate/schema.sql +171 -0
  12. data_factory/annotate/shapes.py +488 -0
  13. data_factory/annotate/store.py +292 -0
  14. data_factory/annotate/tools/__init__.py +39 -0
  15. data_factory/annotate/tools/fake.py +170 -0
  16. data_factory/annotate/tools/install.py +254 -0
  17. data_factory/annotate/tools/local.py +389 -0
  18. data_factory/annotate/tools/postprocess.py +175 -0
  19. data_factory/annotate/tools/protocol.py +238 -0
  20. data_factory/annotate/tools/registry.py +196 -0
  21. data_factory/annotate/tools/results.py +83 -0
  22. data_factory/annotate/tools/serve.py +106 -0
  23. data_factory/cli/__init__.py +21 -0
  24. data_factory/cli/main.py +837 -0
  25. data_factory/cli/menu.py +173 -0
  26. data_factory/cli/render.py +158 -0
  27. data_factory/core/__init__.py +11 -0
  28. data_factory/core/annotations/__init__.py +5 -0
  29. data_factory/core/annotations/coco.py +394 -0
  30. data_factory/core/annotations/csvfmt.py +174 -0
  31. data_factory/core/annotations/dota.py +98 -0
  32. data_factory/core/annotations/formats.py +626 -0
  33. data_factory/core/annotations/labelme.py +153 -0
  34. data_factory/core/annotations/model.py +334 -0
  35. data_factory/core/annotations/voc.py +231 -0
  36. data_factory/core/annotations/yolo.py +283 -0
  37. data_factory/core/bktree.py +89 -0
  38. data_factory/core/fs.py +245 -0
  39. data_factory/core/imaging.py +626 -0
  40. data_factory/core/ops/__init__.py +44 -0
  41. data_factory/core/ops/analyze.py +383 -0
  42. data_factory/core/ops/annotate_export.py +326 -0
  43. data_factory/core/ops/audit.py +274 -0
  44. data_factory/core/ops/augment.py +454 -0
  45. data_factory/core/ops/collect.py +241 -0
  46. data_factory/core/ops/combine.py +582 -0
  47. data_factory/core/ops/convert.py +212 -0
  48. data_factory/core/ops/dataset.py +246 -0
  49. data_factory/core/ops/dedup.py +235 -0
  50. data_factory/core/ops/export.py +168 -0
  51. data_factory/core/ops/image.py +407 -0
  52. data_factory/core/ops/labels.py +215 -0
  53. data_factory/core/ops/pairing.py +133 -0
  54. data_factory/core/ops/rename.py +154 -0
  55. data_factory/core/ops/report.py +323 -0
  56. data_factory/core/ops/visualize.py +164 -0
  57. data_factory/core/pairs.py +144 -0
  58. data_factory/core/parallel.py +191 -0
  59. data_factory/core/provenance.py +136 -0
  60. data_factory/core/registry.py +339 -0
  61. data_factory/core/stats.py +403 -0
  62. data_factory/core/types.py +148 -0
  63. data_factory/core/writer.py +194 -0
  64. data_factory/desktop.py +207 -0
  65. data_factory/hardware.py +243 -0
  66. data_factory/pipeline.py +192 -0
  67. data_factory/py.typed +0 -0
  68. data_factory/service/__init__.py +26 -0
  69. data_factory/service/app.py +483 -0
  70. data_factory/service/binding.py +174 -0
  71. data_factory/service/deps.py +133 -0
  72. data_factory/service/jobs.py +177 -0
  73. data_factory/service/limits.py +71 -0
  74. data_factory/service/routers/__init__.py +11 -0
  75. data_factory/service/routers/annotate.py +582 -0
  76. data_factory/service/routers/local.py +464 -0
  77. data_factory/service/routers/media.py +154 -0
  78. data_factory/service/routers/predictions.py +116 -0
  79. data_factory/service/routers/promote.py +182 -0
  80. data_factory/service/routers/tools.py +308 -0
  81. data_factory/service/static/annotate/api.js +246 -0
  82. data_factory/service/static/annotate/app.js +1696 -0
  83. data_factory/service/static/annotate/assist.js +106 -0
  84. data_factory/service/static/annotate/filmstrip.js +286 -0
  85. data_factory/service/static/annotate/hit.js +146 -0
  86. data_factory/service/static/annotate/labels.js +197 -0
  87. data_factory/service/static/annotate/render.js +286 -0
  88. data_factory/service/static/annotate/scene.js +277 -0
  89. data_factory/service/static/annotate/shapelist.js +72 -0
  90. data_factory/service/static/annotate/tools/box.js +96 -0
  91. data_factory/service/static/annotate/tools/line.js +96 -0
  92. data_factory/service/static/annotate/tools/obb.js +88 -0
  93. data_factory/service/static/annotate/tools/point.js +49 -0
  94. data_factory/service/static/annotate/tools/polygon.js +110 -0
  95. data_factory/service/static/annotate/tools/select.js +227 -0
  96. data_factory/service/static/annotate/undo.js +176 -0
  97. data_factory/service/static/annotate/viewport.js +156 -0
  98. data_factory/service/static/annotate.html +390 -0
  99. data_factory/service/static/index.html +632 -0
  100. data_factory/service/workspace.py +244 -0
  101. easyannotate/__init__.py +64 -0
  102. easyannotate/__main__.py +5 -0
  103. easyannotate/project.py +181 -0
  104. easyannotate/py.typed +0 -0
  105. easyannotate-0.4.0.dist-info/METADATA +767 -0
  106. easyannotate-0.4.0.dist-info/RECORD +109 -0
  107. easyannotate-0.4.0.dist-info/WHEEL +4 -0
  108. easyannotate-0.4.0.dist-info/entry_points.txt +4 -0
  109. easyannotate-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,153 @@
1
+ """LabelMe JSON reading and writing.
2
+
3
+ LabelMe sidecars are the lingua franca of hand-drawn polygons -- the SAM and
4
+ polygon annotators in this repository both descend from that lineage, and most
5
+ academic segmentation datasets ship in it. One ``.json`` per image, absolute
6
+ float coordinates, and a ``shape_type`` naming the geometry.
7
+
8
+ We read ``polygon``, ``rectangle``, ``linestrip`` and ``point``; anything else
9
+ (circles, masks) is reported rather than silently dropped, because a segmenter
10
+ losing half its objects to an unhandled shape type is the kind of failure that
11
+ only shows up as poor accuracy weeks later.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from ..fs import write_text_atomic
21
+ from .model import Annotation, AnnotationError, Point, Shape
22
+
23
+ #: Shape types we can faithfully represent as a bbox and optional polygon.
24
+ SUPPORTED_SHAPES = ("polygon", "rectangle", "linestrip", "line", "point", "rotation")
25
+
26
+
27
+ def read(
28
+ path: Path, *, strict: bool = False, skipped_out: list[str] | None = None
29
+ ) -> Annotation:
30
+ """Parse a LabelMe ``.json``.
31
+
32
+ Unhandled shape types are appended to ``skipped_out`` when one is given, so
33
+ a converter can warn about them; :class:`Annotation` is a slots dataclass
34
+ and deliberately has nowhere to stash out-of-band notes.
35
+ """
36
+ try:
37
+ document: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
38
+ except (OSError, json.JSONDecodeError) as exc:
39
+ raise AnnotationError(f"{path.name}: cannot parse ({exc})") from exc
40
+
41
+ width = int(document.get("imageWidth") or 0)
42
+ height = int(document.get("imageHeight") or 0)
43
+ filename = str(document.get("imagePath") or path.with_suffix(".jpg").name)
44
+ # imagePath is often a relative path like "../images/x.jpg"; we only ever
45
+ # want the basename, since pairing is by stem.
46
+ filename = Path(filename.replace("\\", "/")).name
47
+
48
+ shapes: list[Shape] = []
49
+ skipped: list[str] = []
50
+ for raw in document.get("shapes", []):
51
+ shape = _read_shape(raw, path, skipped)
52
+ if shape is not None:
53
+ shapes.append(shape)
54
+
55
+ if skipped and strict:
56
+ raise AnnotationError(
57
+ f"{path.name}: unsupported shape type(s): {', '.join(sorted(set(skipped)))}"
58
+ )
59
+
60
+ if (width <= 0 or height <= 0) and shapes:
61
+ width = max(s.bbox[2] for s in shapes) + 1
62
+ height = max(s.bbox[3] for s in shapes) + 1
63
+
64
+ if skipped and skipped_out is not None:
65
+ skipped_out.extend(sorted(set(skipped)))
66
+
67
+ return Annotation(
68
+ filename=filename,
69
+ width=width,
70
+ height=height,
71
+ shapes=shapes,
72
+ source_path=path,
73
+ )
74
+
75
+
76
+ def _read_shape(raw: dict[str, Any], path: Path, skipped: list[str]) -> Shape | None:
77
+ label = str(raw.get("label") or "").strip()
78
+ kind = str(raw.get("shape_type") or "polygon").lower()
79
+ points_raw = raw.get("points") or []
80
+ if not label or not points_raw:
81
+ return None
82
+ if kind not in SUPPORTED_SHAPES:
83
+ skipped.append(kind)
84
+ return None
85
+
86
+ try:
87
+ points: list[Point] = [(int(round(float(p[0]))), int(round(float(p[1])))) for p in points_raw]
88
+ except (TypeError, ValueError, IndexError) as exc:
89
+ raise AnnotationError(f"{path.name}: bad point list for {label!r}") from exc
90
+
91
+ xs = [p[0] for p in points]
92
+ ys = [p[1] for p in points]
93
+ bbox = (min(xs), min(ys), max(xs), max(ys))
94
+
95
+ # Boxes and polygons keep an empty kind: the historical rule infers them,
96
+ # and stamping them would make every old equality test lie about change.
97
+ if kind == "polygon" and len(points) >= 3:
98
+ return Shape(label=label, bbox=bbox, polygon=points)
99
+ if kind == "rotation" and len(points) == 4:
100
+ # LabelMe 5's rotated box: four corners, in order.
101
+ return Shape(label=label, bbox=bbox, polygon=points, kind="obb")
102
+ if kind in ("linestrip", "line") and len(points) >= 2:
103
+ return Shape(label=label, bbox=bbox, polygon=points, kind="line")
104
+ if kind == "point":
105
+ x, y = points[0]
106
+ return Shape(label=label, bbox=(x, y, x, y), kind="point")
107
+ # A rectangle is stored as its two opposite corners, so it has no outline.
108
+ return Shape(label=label, bbox=bbox)
109
+
110
+
111
+ def write(annotation: Annotation, path: Path, *, image_path: str | None = None) -> Path:
112
+ """Serialise to LabelMe JSON."""
113
+ shapes: list[dict[str, Any]] = []
114
+ for shape in annotation.shapes:
115
+ if shape.is_point:
116
+ x, y = shape.bbox[:2]
117
+ points = [[int(x), int(y)]]
118
+ shape_type = "point"
119
+ elif shape.is_line and shape.polygon:
120
+ points = [[int(x), int(y)] for x, y in shape.polygon]
121
+ shape_type = "linestrip"
122
+ elif shape.has_polygon:
123
+ assert shape.polygon is not None
124
+ points = [[int(x), int(y)] for x, y in shape.polygon]
125
+ shape_type = "rotation" if shape.shape_kind == "obb" and len(points) == 4 else "polygon"
126
+ else:
127
+ xmin, ymin, xmax, ymax = shape.bbox
128
+ points = [[int(xmin), int(ymin)], [int(xmax), int(ymax)]]
129
+ shape_type = "rectangle"
130
+ shapes.append(
131
+ {
132
+ "label": shape.label,
133
+ "points": points,
134
+ "group_id": None,
135
+ "shape_type": shape_type,
136
+ "flags": {},
137
+ }
138
+ )
139
+
140
+ document = {
141
+ "version": "5.3.1",
142
+ "flags": {},
143
+ "shapes": shapes,
144
+ "imagePath": image_path or annotation.filename,
145
+ # imageData is where LabelMe embeds a base64 copy of the whole image.
146
+ # Omitting it keeps label files small and diffable; LabelMe reloads the
147
+ # pixels from imagePath instead.
148
+ "imageData": None,
149
+ "imageHeight": annotation.height,
150
+ "imageWidth": annotation.width,
151
+ }
152
+ write_text_atomic(path, json.dumps(document, indent=2))
153
+ return path
@@ -0,0 +1,334 @@
1
+ """A format-neutral annotation model.
2
+
3
+ Readers parse into these types and writers serialise out of them. Keeping a
4
+ neutral middle means adding YOLO or CreateML later costs one reader and one
5
+ writer, not a new converter for every existing pair of formats.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ Point = tuple[int, int]
15
+
16
+ #: What a shape's geometry means. ``box`` and ``polygon`` are the originals;
17
+ #: ``line`` is an open polyline (vertices in ``polygon``, no area); ``point``
18
+ #: is one location (a degenerate ``bbox``); ``obb`` is a rotated box, stored as
19
+ #: its four corners in ``polygon`` -- which is exactly what YOLO-OBB and DOTA
20
+ #: write, so the export is a copy rather than a conversion.
21
+ KINDS = ("box", "polygon", "line", "point", "obb")
22
+
23
+ #: Version of the JSON shape/annotation form. Bump when a change would stop an
24
+ #: older build reading a newer payload; ``Annotation.from_dict`` refuses
25
+ #: anything newer than it understands rather than dropping fields silently.
26
+ WIRE_VERSION = 1
27
+
28
+
29
+ class AnnotationError(Exception):
30
+ """Raised when a label file cannot be parsed or is structurally invalid."""
31
+
32
+
33
+ @dataclass(slots=True)
34
+ class Shape:
35
+ """One annotated object.
36
+
37
+ Every shape has a bounding box; a polygon is optional. A polygon-only
38
+ source still yields a bbox because we derive it from the outline, which is
39
+ what lets detection and segmentation datasets come out of the same file.
40
+ """
41
+
42
+ label: str
43
+ bbox: tuple[int, int, int, int]
44
+ polygon: list[Point] | None = None
45
+ pose: str = "Unspecified"
46
+ truncated: int = 0
47
+ difficult: int = 0
48
+ occluded: int = 0
49
+
50
+ #: Detector score, when this shape came from a model rather than a person.
51
+ #: ``None`` for anything hand-drawn -- which is how the review UI tells a
52
+ #: prediction from a human label, and what a confidence filter reads.
53
+ confidence: float | None = None
54
+
55
+ #: One of :data:`KINDS`, or empty for the historical rule: a polygon if
56
+ #: there is an outline of three or more points, else a box. Readers that
57
+ #: predate kinds leave it empty and lose nothing.
58
+ kind: str = ""
59
+
60
+ @property
61
+ def shape_kind(self) -> str:
62
+ if self.kind:
63
+ return self.kind
64
+ return "polygon" if self.polygon is not None and len(self.polygon) >= 3 else "box"
65
+
66
+ @property
67
+ def has_polygon(self) -> bool:
68
+ """Whether the outline encloses an area a mask could be made from.
69
+
70
+ Fewer than three points cannot, and COCO rejects a segmentation with
71
+ under six numbers, so those are bbox-only. A polyline has vertices but
72
+ no area, so it is *not* a polygon here -- that keeps every
73
+ segmentation writer from turning a lane marking into a sliver mask.
74
+ """
75
+ return (
76
+ self.polygon is not None
77
+ and len(self.polygon) >= 3
78
+ and self.shape_kind in ("polygon", "obb")
79
+ )
80
+
81
+ @property
82
+ def is_point(self) -> bool:
83
+ return self.shape_kind == "point"
84
+
85
+ @property
86
+ def is_line(self) -> bool:
87
+ return self.shape_kind == "line"
88
+
89
+ @property
90
+ def width(self) -> int:
91
+ return max(0, self.bbox[2] - self.bbox[0])
92
+
93
+ @property
94
+ def height(self) -> int:
95
+ return max(0, self.bbox[3] - self.bbox[1])
96
+
97
+ @property
98
+ def bbox_area(self) -> int:
99
+ return self.width * self.height
100
+
101
+ def polygon_area(self) -> float:
102
+ """Shoelace area of the outline, falling back to the box."""
103
+ if self.shape_kind in ("point", "line"):
104
+ return 0.0
105
+ if not self.has_polygon:
106
+ return float(self.bbox_area)
107
+ assert self.polygon is not None
108
+ total = 0.0
109
+ count = len(self.polygon)
110
+ for i in range(count):
111
+ x1, y1 = self.polygon[i]
112
+ x2, y2 = self.polygon[(i + 1) % count]
113
+ total += x1 * y2 - x2 * y1
114
+ return abs(total) / 2.0
115
+
116
+ def flat_polygon(self) -> list[int]:
117
+ """``[x1, y1, x2, y2, ...]`` as COCO segmentation wants it."""
118
+ if not self.has_polygon:
119
+ return []
120
+ assert self.polygon is not None
121
+ flat: list[int] = []
122
+ for x, y in self.polygon:
123
+ flat.extend((int(x), int(y)))
124
+ return flat
125
+
126
+ def clamped(self, width: int, height: int) -> Shape:
127
+ """Return a copy with all coordinates inside the image bounds."""
128
+
129
+ def clamp_x(value: int) -> int:
130
+ return max(0, min(int(value), max(0, width - 1)))
131
+
132
+ def clamp_y(value: int) -> int:
133
+ return max(0, min(int(value), max(0, height - 1)))
134
+
135
+ xmin, ymin, xmax, ymax = self.bbox
136
+ polygon = (
137
+ [(clamp_x(x), clamp_y(y)) for x, y in self.polygon] if self.polygon else None
138
+ )
139
+ return Shape(
140
+ label=self.label,
141
+ bbox=(clamp_x(xmin), clamp_y(ymin), clamp_x(xmax), clamp_y(ymax)),
142
+ polygon=polygon,
143
+ pose=self.pose,
144
+ truncated=self.truncated,
145
+ difficult=self.difficult,
146
+ occluded=self.occluded,
147
+ confidence=self.confidence,
148
+ kind=self.kind,
149
+ )
150
+
151
+ # -- wire format -------------------------------------------------------
152
+ def as_dict(self) -> dict[str, Any]:
153
+ """Lossless, JSON-safe form. ``from_dict`` reverses it exactly.
154
+
155
+ This is what crosses the wire to the annotation editor and what is
156
+ stored per shape. Every field round-trips, including the flags a
157
+ detection format would drop -- losing ``difficult`` on a save because
158
+ the browser never knew about it is the kind of quiet damage that only
159
+ shows up in a training run weeks later.
160
+ """
161
+ return {
162
+ "label": self.label,
163
+ "bbox": list(self.bbox),
164
+ "polygon": [[int(x), int(y)] for x, y in self.polygon] if self.polygon else None,
165
+ "pose": self.pose,
166
+ "truncated": self.truncated,
167
+ "difficult": self.difficult,
168
+ "occluded": self.occluded,
169
+ "confidence": self.confidence,
170
+ "kind": self.shape_kind,
171
+ }
172
+
173
+ @classmethod
174
+ def from_dict(cls, raw: dict[str, Any]) -> Shape:
175
+ """Rebuild a shape from its wire form, validating as we go.
176
+
177
+ Raises :class:`AnnotationError` rather than letting a malformed
178
+ payload become a half-built shape -- this parses untrusted input from
179
+ a browser, so it fails loudly and specifically.
180
+ """
181
+ if not isinstance(raw, dict):
182
+ raise AnnotationError(f"a shape must be an object, got {type(raw).__name__}")
183
+
184
+ label = str(raw.get("label") or "").strip()
185
+ if not label:
186
+ raise AnnotationError("a shape needs a non-empty label")
187
+
188
+ bbox = raw.get("bbox")
189
+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
190
+ raise AnnotationError(f"{label}: bbox must be four numbers, got {bbox!r}")
191
+ try:
192
+ xmin, ymin, xmax, ymax = (int(round(float(v))) for v in bbox)
193
+ except (TypeError, ValueError) as exc:
194
+ raise AnnotationError(f"{label}: bbox holds a non-number") from exc
195
+ # Normalise rather than reject: a box dragged up-and-left is a normal
196
+ # thing to do with a mouse, and the corners simply arrive swapped.
197
+ if xmax < xmin:
198
+ xmin, xmax = xmax, xmin
199
+ if ymax < ymin:
200
+ ymin, ymax = ymax, ymin
201
+
202
+ polygon = _points_from(raw.get("polygon"), label)
203
+ kind = str(raw.get("kind") or "").strip().lower()
204
+ if kind and kind not in KINDS:
205
+ raise AnnotationError(f"{label}: unknown shape kind {kind!r}; known: {', '.join(KINDS)}")
206
+ if kind == "line" and (polygon is None or len(polygon) < 2):
207
+ raise AnnotationError(f"{label}: a line needs at least two points")
208
+ if kind == "obb" and (polygon is None or len(polygon) != 4):
209
+ raise AnnotationError(f"{label}: a rotated box needs exactly four corners")
210
+ if kind == "point":
211
+ polygon = None
212
+ # The two historical kinds are inferred from the geometry, so they are
213
+ # stored as empty: a shape must round-trip to *equal* itself.
214
+ if kind in ("box", "polygon"):
215
+ kind = ""
216
+ confidence = raw.get("confidence")
217
+ if confidence is not None:
218
+ try:
219
+ confidence = float(confidence)
220
+ except (TypeError, ValueError) as exc:
221
+ raise AnnotationError(f"{label}: confidence must be a number") from exc
222
+
223
+ return cls(
224
+ label=label,
225
+ bbox=(xmin, ymin, xmax, ymax),
226
+ polygon=polygon,
227
+ pose=str(raw.get("pose") or "Unspecified"),
228
+ truncated=_flag(raw.get("truncated")),
229
+ difficult=_flag(raw.get("difficult")),
230
+ occluded=_flag(raw.get("occluded")),
231
+ confidence=confidence,
232
+ kind=kind,
233
+ )
234
+
235
+
236
+ @dataclass(slots=True)
237
+ class Annotation:
238
+ """Everything one label file says about one image."""
239
+
240
+ filename: str
241
+ width: int
242
+ height: int
243
+ depth: int = 3
244
+ shapes: list[Shape] = field(default_factory=list)
245
+ folder: str = "images"
246
+ source_path: Path | None = None
247
+
248
+ @property
249
+ def is_background(self) -> bool:
250
+ """A deliberate hard negative: valid file, zero objects."""
251
+ return not self.shapes
252
+
253
+ @property
254
+ def labels(self) -> list[str]:
255
+ return [s.label for s in self.shapes]
256
+
257
+ @property
258
+ def label_set(self) -> set[str]:
259
+ return {s.label for s in self.shapes}
260
+
261
+ @property
262
+ def has_polygons(self) -> bool:
263
+ return any(s.has_polygon for s in self.shapes)
264
+
265
+ def as_dict(self) -> dict[str, Any]:
266
+ """Lossless, JSON-safe form.
267
+
268
+ The previous version of this method reported ``polygon_points`` as a
269
+ *count*, which made it useless for anything but a glance -- you could
270
+ not reconstruct the annotation from it. It had no callers. This one
271
+ round-trips.
272
+ """
273
+ return {
274
+ "wire": WIRE_VERSION,
275
+ "filename": self.filename,
276
+ "width": self.width,
277
+ "height": self.height,
278
+ "depth": self.depth,
279
+ "folder": self.folder,
280
+ "shapes": [s.as_dict() for s in self.shapes],
281
+ }
282
+
283
+ @classmethod
284
+ def from_dict(cls, raw: dict[str, Any]) -> Annotation:
285
+ if not isinstance(raw, dict):
286
+ raise AnnotationError(f"an annotation must be an object, got {type(raw).__name__}")
287
+ version = int(raw.get("wire", WIRE_VERSION) or WIRE_VERSION)
288
+ if version > WIRE_VERSION:
289
+ raise AnnotationError(
290
+ f"this annotation is wire version {version}; this build understands "
291
+ f"up to {WIRE_VERSION}. Upgrade Data Factory to read it."
292
+ )
293
+ shapes = raw.get("shapes") or []
294
+ if not isinstance(shapes, list):
295
+ raise AnnotationError("shapes must be a list")
296
+ return cls(
297
+ filename=str(raw.get("filename") or ""),
298
+ width=int(raw.get("width") or 0),
299
+ height=int(raw.get("height") or 0),
300
+ depth=int(raw.get("depth") or 3),
301
+ shapes=[Shape.from_dict(s) for s in shapes],
302
+ folder=str(raw.get("folder") or "images"),
303
+ )
304
+
305
+
306
+ def _flag(value: Any) -> int:
307
+ """VOC's 0/1 attributes, tolerant of the bools a browser will send."""
308
+ if value is None:
309
+ return 0
310
+ if isinstance(value, bool):
311
+ return int(value)
312
+ try:
313
+ return 1 if int(value) else 0
314
+ except (TypeError, ValueError):
315
+ return 0
316
+
317
+
318
+ def _points_from(raw: Any, label: str) -> list[Point] | None:
319
+ """Parse ``[[x, y], ...]``, rejecting anything that is not a point list."""
320
+ if raw is None:
321
+ return None
322
+ if not isinstance(raw, (list, tuple)):
323
+ raise AnnotationError(f"{label}: polygon must be a list of points")
324
+ points: list[Point] = []
325
+ for pair in raw:
326
+ if not isinstance(pair, (list, tuple)) or len(pair) != 2:
327
+ raise AnnotationError(f"{label}: each polygon point must be [x, y], got {pair!r}")
328
+ try:
329
+ points.append((int(round(float(pair[0]))), int(round(float(pair[1])))))
330
+ except (TypeError, ValueError) as exc:
331
+ raise AnnotationError(f"{label}: polygon holds a non-number") from exc
332
+ # An empty list and a one-point list both mean "no outline"; normalising to
333
+ # None here keeps `has_polygon` the single place that defines the rule.
334
+ return points or None