detection-dataset-contract 1.0.1__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sv-vibe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: detection-dataset-contract
3
+ Version: 1.0.1
4
+ Summary: Published detection dataset CSV and bundle format v1
5
+ Keywords: dataset,object-detection,csv,validation
6
+ Author: Buckanov Nikita
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
13
+ Requires-Python: >=3.12
14
+ Project-URL: Repository, https://github.com/sv-vibe/detection-dataset-contract
15
+ Project-URL: Issues, https://github.com/sv-vibe/detection-dataset-contract/issues
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Контракт наборов данных для детекции
19
+
20
+ Пакет `detection-dataset-contract` определяет формат опубликованных аннотаций v1 для cveta2 и clearml-yolo и ставится с [PyPI](https://pypi.org/project/detection-dataset-contract/).
21
+
22
+ ```bash
23
+ python -m pip install detection-dataset-contract
24
+ ```
25
+
26
+ Функция `classify_inventory` принимает полный перечень относительных имён файлов. Поддерживаются отдельный `dataset.csv`, комплект с `dataset.yaml` и `tasks.yaml`, а также тот же комплект с `sources.tar.gz`. Для комплектов передайте разобранный исходный YAML в `validate_bundle_version`. Обязательное поле верхнего уровня `schema_version` содержит целое число 1.
27
+
28
+ Функция `validate_rows` принимает заголовок и строки из `csv.reader`. Обязательные поля перечислены в `REQUIRED_COLUMNS`. Дополнительные именованные столбцы разрешены. Передавайте идентификаторы и координаты исходными строками. Координаты задают углы рамки в пикселях. Фон обозначается пустой меткой и четырьмя пустыми координатами. Итоговые выборки — `train`, `val`, `test`.
29
+
30
+ Приложение передаёт в `resolve_path` функцию разрешения путей относительно исходного CSV и при необходимости — `image_size`, возвращающую пару «ширина, высота» для разрешённого пути. Без этих аргументов проверяются лексические POSIX-пути и геометрия рамок без верхней границы изображения. Нарушение формата вызывает `ContractError`. Проверки готовности к обучению, чтение изображений и исправление исходных данных выполняются в приложениях.
31
+
32
+ Корпус примеров входит в пакет как `corpus.json`. Для каждого случая указаны назначение на этапе подготовки и ожидаемый итог проверки при публикации.
33
+ Для воспроизведения проверки границ возьмите размеры из поля `image_sizes` примера. Ключом служит POSIX-путь из CSV, значением — пара целых чисел «ширина, высота».
@@ -0,0 +1,16 @@
1
+ # Контракт наборов данных для детекции
2
+
3
+ Пакет `detection-dataset-contract` определяет формат опубликованных аннотаций v1 для cveta2 и clearml-yolo и ставится с [PyPI](https://pypi.org/project/detection-dataset-contract/).
4
+
5
+ ```bash
6
+ python -m pip install detection-dataset-contract
7
+ ```
8
+
9
+ Функция `classify_inventory` принимает полный перечень относительных имён файлов. Поддерживаются отдельный `dataset.csv`, комплект с `dataset.yaml` и `tasks.yaml`, а также тот же комплект с `sources.tar.gz`. Для комплектов передайте разобранный исходный YAML в `validate_bundle_version`. Обязательное поле верхнего уровня `schema_version` содержит целое число 1.
10
+
11
+ Функция `validate_rows` принимает заголовок и строки из `csv.reader`. Обязательные поля перечислены в `REQUIRED_COLUMNS`. Дополнительные именованные столбцы разрешены. Передавайте идентификаторы и координаты исходными строками. Координаты задают углы рамки в пикселях. Фон обозначается пустой меткой и четырьмя пустыми координатами. Итоговые выборки — `train`, `val`, `test`.
12
+
13
+ Приложение передаёт в `resolve_path` функцию разрешения путей относительно исходного CSV и при необходимости — `image_size`, возвращающую пару «ширина, высота» для разрешённого пути. Без этих аргументов проверяются лексические POSIX-пути и геометрия рамок без верхней границы изображения. Нарушение формата вызывает `ContractError`. Проверки готовности к обучению, чтение изображений и исправление исходных данных выполняются в приложениях.
14
+
15
+ Корпус примеров входит в пакет как `corpus.json`. Для каждого случая указаны назначение на этапе подготовки и ожидаемый итог проверки при публикации.
16
+ Для воспроизведения проверки границ возьмите размеры из поля `image_sizes` примера. Ключом служит POSIX-путь из CSV, значением — пара целых чисел «ширина, высота».
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.32,<0.12"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "detection-dataset-contract"
7
+ version = "1.0.1"
8
+ description = "Published detection dataset CSV and bundle format v1"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ dependencies = []
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ authors = [{ name = "Buckanov Nikita" }]
15
+ keywords = ["dataset", "object-detection", "csv", "validation"]
16
+ classifiers = [
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Topic :: Scientific/Engineering :: Image Recognition",
21
+ ]
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/sv-vibe/detection-dataset-contract"
25
+ Issues = "https://github.com/sv-vibe/detection-dataset-contract/issues"
@@ -0,0 +1,119 @@
1
+ """Version 1 of the published detection dataset format. All operations are pure."""
2
+
3
+ from collections import Counter
4
+ from collections.abc import Callable, Iterable, Mapping, Sequence
5
+ from math import isfinite
6
+ from pathlib import PurePath, PurePosixPath
7
+ from typing import Literal
8
+
9
+ SCHEMA_VERSION = 1
10
+ REQUIRED_COLUMNS = (
11
+ "image_name",
12
+ "image_path",
13
+ "instance_label",
14
+ "bbox_x_tl",
15
+ "bbox_y_tl",
16
+ "bbox_x_br",
17
+ "bbox_y_br",
18
+ "split",
19
+ )
20
+ Inventory = Literal["csv", "managed", "upload"]
21
+ _MANAGED = frozenset({"dataset.csv", "dataset.yaml", "tasks.yaml"})
22
+ _INVENTORIES: dict[frozenset[str], Inventory] = {
23
+ frozenset({"dataset.csv"}): "csv",
24
+ _MANAGED: "managed",
25
+ _MANAGED | {"sources.tar.gz"}: "upload",
26
+ }
27
+
28
+
29
+ class ContractError(ValueError):
30
+ """An inventory, format version or CSV record violates the wire contract."""
31
+
32
+
33
+ def classify_inventory(names: Iterable[str]) -> Inventory:
34
+ """Match complete root-relative names, including any nested or unexpected files."""
35
+ entries = tuple(names)
36
+ inventory = frozenset(entries)
37
+ if len(entries) != len(inventory) or inventory not in _INVENTORIES:
38
+ raise ContractError(f"Unsupported dataset inventory: {sorted(entries)!r}")
39
+ return _INVENTORIES[inventory]
40
+
41
+
42
+ def validate_bundle_version(metadata: object) -> None:
43
+ """Require the physically present integer field from decoded dataset.yaml."""
44
+ value = metadata.get("schema_version") if isinstance(metadata, Mapping) else None
45
+ if type(value) is not int or value != SCHEMA_VERSION:
46
+ raise ContractError(f"Missing or unsupported dataset schema_version: {value!r}")
47
+
48
+
49
+ def _annotation(label: str, cells: Sequence[str], size: tuple[int, int] | None) -> tuple[float, ...] | None:
50
+ if label == "" and all(cell == "" for cell in cells):
51
+ return None
52
+ if label == "background":
53
+ raise ContractError("reserved label 'background'")
54
+ if label == "" or any(cell == "" for cell in cells):
55
+ raise ContractError("incomplete box or missing label")
56
+ try:
57
+ box = tuple(float(cell) for cell in cells)
58
+ except ValueError as error:
59
+ raise ContractError("box coordinates must be numeric") from error
60
+ x1, y1, x2, y2 = box
61
+ if not all(map(isfinite, box)) or x2 <= x1 or y2 <= y1:
62
+ raise ContractError("box must have finite coordinates and positive area")
63
+ if min(x1, y1) < 0 or (size is not None and (x2 > size[0] or y2 > size[1])):
64
+ raise ContractError("coordinates outside image bounds")
65
+ return box
66
+
67
+
68
+ def validate_rows(
69
+ header: Sequence[str],
70
+ rows: Iterable[Sequence[str]],
71
+ *,
72
+ resolve_path: Callable[[str], PurePath] = PurePosixPath,
73
+ image_size: Callable[[PurePath], tuple[int, int] | None] | None = None,
74
+ ) -> None:
75
+ """Validate uncoerced CSV cells. Callers supply canonical media paths and known sizes.
76
+
77
+ Header order and extra named columns do not affect validation. Box coordinates
78
+ are parsed for checks only. Callers retain ownership of the original bytes.
79
+ """
80
+ duplicates = [name for name, count in Counter(header).items() if count > 1]
81
+ if duplicates:
82
+ raise ContractError(f"duplicate CSV headers: {duplicates}")
83
+ missing = set(REQUIRED_COLUMNS).difference(header)
84
+ if missing:
85
+ raise ContractError(f"missing required columns: {sorted(missing)}")
86
+ indices = [header.index(column) for column in REQUIRED_COLUMNS]
87
+ owners: dict[str, tuple[PurePath, str]] = {}
88
+ path_owners: dict[PurePath, str] = {}
89
+ annotations: dict[str, set[tuple[str, tuple[float, ...] | None]]] = {}
90
+ for number, row in enumerate(rows, start=2):
91
+ if not row:
92
+ continue
93
+ values = [row[i] if i < len(row) else "" for i in indices]
94
+ name, raw_path, label, *cells, split = values
95
+ if not all(isinstance(cell, str) for cell in values):
96
+ raise ContractError(f"CSV row {number}: required cells must be literal strings")
97
+ if not name or not raw_path:
98
+ raise ContractError(f"CSV row {number}: missing image name or path")
99
+ path = resolve_path(raw_path)
100
+ if path.name != name:
101
+ raise ContractError(f"CSV row {number}: image name {name!r} differs from basename {path.name!r}")
102
+ if split not in ("train", "val", "test"):
103
+ raise ContractError(f"CSV row {number}: invalid final split {split!r}")
104
+ if owners.setdefault(name, (path, split)) != (path, split):
105
+ raise ContractError(f"CSV row {number}: conflicting path or split for {name!r}")
106
+ if path_owners.setdefault(path, name) != name:
107
+ raise ContractError(f"CSV row {number}: canonical path {path} identifies multiple image names")
108
+ try:
109
+ box = _annotation(label, cells, image_size(path) if image_size else None)
110
+ except ContractError as error:
111
+ raise ContractError(f"CSV row {number}: {error}") from error
112
+ seen = annotations.setdefault(name, set())
113
+ if (label, box) in seen:
114
+ raise ContractError(f"CSV row {number}: duplicate annotation or background for {name!r}")
115
+ if seen and (box is None or ("", None) in seen):
116
+ raise ContractError(f"CSV row {number}: mixed annotation and background for {name!r}")
117
+ seen.add((label, box))
118
+ if not owners:
119
+ raise ContractError("CSV contains no data rows")
@@ -0,0 +1,439 @@
1
+ [
2
+ {
3
+ "name": "literal numeric-looking class and image boundary",
4
+ "preparation": "retain literal cells",
5
+ "published": "accept",
6
+ "rows": [
7
+ [
8
+ "001.png",
9
+ "a/001.png",
10
+ "001",
11
+ "0.000000",
12
+ "0",
13
+ "32",
14
+ "32",
15
+ "train"
16
+ ]
17
+ ],
18
+ "image_sizes": {
19
+ "a/001.png": [
20
+ 32,
21
+ 32
22
+ ]
23
+ }
24
+ },
25
+ {
26
+ "name": "empty background",
27
+ "preparation": "retain image",
28
+ "published": "accept",
29
+ "rows": [
30
+ [
31
+ "001.png",
32
+ "a/001.png",
33
+ "",
34
+ "",
35
+ "",
36
+ "",
37
+ "",
38
+ "val"
39
+ ]
40
+ ]
41
+ },
42
+ {
43
+ "name": "reserved label",
44
+ "preparation": "resolve class identity before publication",
45
+ "published": "reject",
46
+ "rows": [
47
+ [
48
+ "001.png",
49
+ "a/001.png",
50
+ "background",
51
+ "0.000000",
52
+ "0",
53
+ "32",
54
+ "32",
55
+ "train"
56
+ ]
57
+ ],
58
+ "error": "reserved"
59
+ },
60
+ {
61
+ "name": "name claimed by two paths",
62
+ "preparation": "resolve path ownership",
63
+ "published": "reject",
64
+ "rows": [
65
+ [
66
+ "001.png",
67
+ "a/001.png",
68
+ "001",
69
+ "0.000000",
70
+ "0",
71
+ "32",
72
+ "32",
73
+ "train"
74
+ ],
75
+ [
76
+ "001.png",
77
+ "b/001.png",
78
+ "001",
79
+ "0.000000",
80
+ "0",
81
+ "32",
82
+ "32",
83
+ "train"
84
+ ]
85
+ ],
86
+ "error": "conflicting"
87
+ },
88
+ {
89
+ "name": "image in two splits",
90
+ "preparation": "reconcile split assignment",
91
+ "published": "reject",
92
+ "rows": [
93
+ [
94
+ "001.png",
95
+ "a/001.png",
96
+ "001",
97
+ "0.000000",
98
+ "0",
99
+ "32",
100
+ "32",
101
+ "train"
102
+ ],
103
+ [
104
+ "001.png",
105
+ "a/001.png",
106
+ "001",
107
+ "0.000000",
108
+ "0",
109
+ "32",
110
+ "32",
111
+ "test"
112
+ ]
113
+ ],
114
+ "error": "conflicting"
115
+ },
116
+ {
117
+ "name": "pending assignment",
118
+ "preparation": "allow pending assignment during preparation",
119
+ "published": "reject",
120
+ "rows": [
121
+ [
122
+ "001.png",
123
+ "a/001.png",
124
+ "001",
125
+ "0.000000",
126
+ "0",
127
+ "32",
128
+ "32",
129
+ ""
130
+ ]
131
+ ],
132
+ "error": "final split"
133
+ },
134
+ {
135
+ "name": "unknown final split",
136
+ "preparation": "correct split",
137
+ "published": "reject",
138
+ "rows": [
139
+ [
140
+ "001.png",
141
+ "a/001.png",
142
+ "001",
143
+ "0.000000",
144
+ "0",
145
+ "32",
146
+ "32",
147
+ "validation"
148
+ ]
149
+ ],
150
+ "error": "final split"
151
+ },
152
+ {
153
+ "name": "incomplete box",
154
+ "preparation": "repair or remove invalid box",
155
+ "published": "reject",
156
+ "rows": [
157
+ [
158
+ "001.png",
159
+ "a/001.png",
160
+ "001",
161
+ "0.000000",
162
+ "",
163
+ "32",
164
+ "32",
165
+ "train"
166
+ ]
167
+ ],
168
+ "error": "incomplete"
169
+ },
170
+ {
171
+ "name": "duplicate header",
172
+ "preparation": "resolve ambiguous header",
173
+ "published": "reject",
174
+ "rows": [
175
+ [
176
+ "001.png",
177
+ "a/001.png",
178
+ "001",
179
+ "0.000000",
180
+ "0",
181
+ "32",
182
+ "32",
183
+ "train",
184
+ "other"
185
+ ]
186
+ ],
187
+ "error": "duplicate",
188
+ "headers": [
189
+ "image_name",
190
+ "image_path",
191
+ "instance_label",
192
+ "bbox_x_tl",
193
+ "bbox_y_tl",
194
+ "bbox_x_br",
195
+ "bbox_y_br",
196
+ "split",
197
+ "image_name"
198
+ ]
199
+ },
200
+ {
201
+ "name": "second object with high precision",
202
+ "preparation": "retain exporter precision",
203
+ "published": "accept",
204
+ "rows": [
205
+ [
206
+ "001.png",
207
+ "a/001.png",
208
+ "001",
209
+ "0.000000",
210
+ "0",
211
+ "32",
212
+ "32",
213
+ "train"
214
+ ],
215
+ [
216
+ "001.png",
217
+ "a/001.png",
218
+ "NA",
219
+ "1.0000000000000002",
220
+ "1",
221
+ "2",
222
+ "2",
223
+ "train"
224
+ ]
225
+ ]
226
+ },
227
+ {
228
+ "name": "duplicate numeric box",
229
+ "preparation": "deduplicate annotation",
230
+ "published": "reject",
231
+ "rows": [
232
+ [
233
+ "001.png",
234
+ "a/001.png",
235
+ "001",
236
+ "0.000000",
237
+ "0",
238
+ "32",
239
+ "32",
240
+ "train"
241
+ ],
242
+ [
243
+ "001.png",
244
+ "a/001.png",
245
+ "001",
246
+ "0",
247
+ "0",
248
+ "32",
249
+ "32",
250
+ "train"
251
+ ]
252
+ ],
253
+ "error": "duplicate"
254
+ },
255
+ {
256
+ "name": "duplicate background",
257
+ "preparation": "deduplicate background",
258
+ "published": "reject",
259
+ "rows": [
260
+ [
261
+ "001.png",
262
+ "a/001.png",
263
+ "",
264
+ "",
265
+ "",
266
+ "",
267
+ "",
268
+ "val"
269
+ ],
270
+ [
271
+ "001.png",
272
+ "a/001.png",
273
+ "",
274
+ "",
275
+ "",
276
+ "",
277
+ "",
278
+ "val"
279
+ ]
280
+ ],
281
+ "error": "duplicate"
282
+ },
283
+ {
284
+ "name": "background and box on same image",
285
+ "preparation": "reconcile background with annotations",
286
+ "published": "reject",
287
+ "rows": [
288
+ [
289
+ "001.png",
290
+ "a/001.png",
291
+ "001",
292
+ "0.000000",
293
+ "0",
294
+ "32",
295
+ "32",
296
+ "train"
297
+ ],
298
+ [
299
+ "001.png",
300
+ "a/001.png",
301
+ "",
302
+ "",
303
+ "",
304
+ "",
305
+ "",
306
+ "train"
307
+ ]
308
+ ],
309
+ "error": "mixed"
310
+ },
311
+ {
312
+ "name": "outside supplied width",
313
+ "preparation": "clip or remove before publication",
314
+ "published": "reject",
315
+ "rows": [
316
+ [
317
+ "001.png",
318
+ "a/001.png",
319
+ "001",
320
+ "0.000000",
321
+ "0",
322
+ "33",
323
+ "32",
324
+ "train"
325
+ ]
326
+ ],
327
+ "error": "bounds",
328
+ "image_sizes": {
329
+ "a/001.png": [
330
+ 32,
331
+ 32
332
+ ]
333
+ }
334
+ },
335
+ {
336
+ "name": "non-finite coordinate",
337
+ "preparation": "repair or remove invalid box",
338
+ "published": "reject",
339
+ "rows": [
340
+ [
341
+ "001.png",
342
+ "a/001.png",
343
+ "001",
344
+ "0.000000",
345
+ "0",
346
+ "inf",
347
+ "32",
348
+ "train"
349
+ ]
350
+ ],
351
+ "error": "finite"
352
+ },
353
+ {
354
+ "name": "collapsed box",
355
+ "preparation": "repair or remove invalid box",
356
+ "published": "reject",
357
+ "rows": [
358
+ [
359
+ "001.png",
360
+ "a/001.png",
361
+ "001",
362
+ "0.000000",
363
+ "0",
364
+ "0",
365
+ "32",
366
+ "train"
367
+ ]
368
+ ],
369
+ "error": "positive area"
370
+ },
371
+ {
372
+ "name": "empty dataset",
373
+ "preparation": "supply records",
374
+ "published": "reject",
375
+ "rows": [],
376
+ "error": "no data"
377
+ },
378
+ {
379
+ "name": "missing column",
380
+ "preparation": "restore split column",
381
+ "published": "reject",
382
+ "rows": [
383
+ [
384
+ "001.png",
385
+ "a/001.png",
386
+ "001",
387
+ "0.000000",
388
+ "0",
389
+ "32",
390
+ "32"
391
+ ]
392
+ ],
393
+ "error": "missing required",
394
+ "headers": [
395
+ "image_name",
396
+ "image_path",
397
+ "instance_label",
398
+ "bbox_x_tl",
399
+ "bbox_y_tl",
400
+ "bbox_x_br",
401
+ "bbox_y_br"
402
+ ]
403
+ },
404
+ {
405
+ "name": "short row",
406
+ "preparation": "supply missing cell",
407
+ "published": "reject",
408
+ "rows": [
409
+ [
410
+ "001.png",
411
+ "a/001.png",
412
+ "001",
413
+ "0.000000",
414
+ "0",
415
+ "32",
416
+ "32"
417
+ ]
418
+ ],
419
+ "error": "final split"
420
+ },
421
+ {
422
+ "name": "basename mismatch",
423
+ "preparation": "reconcile image reference",
424
+ "published": "reject",
425
+ "rows": [
426
+ [
427
+ "001.png",
428
+ "a/002.png",
429
+ "001",
430
+ "0.000000",
431
+ "0",
432
+ "32",
433
+ "32",
434
+ "train"
435
+ ]
436
+ ],
437
+ "error": "basename"
438
+ }
439
+ ]