-
Notifications
You must be signed in to change notification settings - Fork 1
feat(data): pluggable label-format adapters (COCO/YOLO/VOC ingestion) #342
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
stanlrt
wants to merge
13
commits into
main
Choose a base branch
from
338-label-format-adapters
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
95d3bea
feat(data): add LabelFormat enum and LabelsConfig.format field (refs …
stanlrt d916f4d
refactor(model): extract _align_detection_records from detection load…
stanlrt b9fa7bd
feat(data): add label-format adapter protocol and registry (refs #338)
stanlrt 509040c
feat(data): add COCO label-format adapter (refs #338)
stanlrt 4637748
feat(data): add YOLO label-format adapter (refs #338)
stanlrt ff41664
feat(data): add Pascal-VOC label-format adapter (refs #338)
stanlrt c248cc0
feat(model): dispatch detection labels on data.labels.format (refs #338)
stanlrt 87e5d65
feat(data): dispatch classification labels on data.labels.format (ref…
stanlrt d3510c5
docs: document label-format adapters and data.labels.format (refs #338)
stanlrt 8314068
style(data): satisfy ruff and pyright for label-format adapters (refs…
stanlrt 0494758
docs: note detection label formats match sample_id by exact name (ref…
stanlrt 17a1bd0
docs: fix sphinx cross-ref and heading-level warnings for label forma…
stanlrt a150a60
test(data): use module-qualified load_classification_labels to avoid …
stanlrt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| # pyright: reportUnusedImport=false | ||
| """Imports every in-tree label-format adapter so the decorators fire. | ||
|
|
||
| Imported for its side effects by | ||
| ``raitap.data.label_formats.resolve_label_format_adapter``. Every import in this | ||
| module is intentionally side-effect-only (registers an adapter), so the | ||
| file-level ``reportUnusedImport=false`` above is correct. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from raitap.data.adapters import coco, voc, yolo # noqa: F401 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Built-in label-format adapters (issue #338).""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| """COCO label-format adapter (issue #338).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pathlib import Path | ||
|
|
||
| from raitap.data.label_formats import ( | ||
| ClassificationRecord, | ||
| DetectionRecord, | ||
| label_format, | ||
| ) | ||
| from raitap.data.types import LabelFormat | ||
| from raitap.types import TaskKind | ||
|
|
||
|
|
||
| @label_format | ||
| class CocoAdapter: | ||
| """COCO ``instances.json`` -> native records. | ||
|
|
||
| Detection: ``bbox`` is ``[x, y, w, h]`` -> ``[x1, y1, x2, y2]``; | ||
| ``category_id`` passes through unchanged so labels stay in the model's | ||
| label space. Classification: one label per image (the image's single | ||
| annotation category); images with 0 or >1 categories raise. | ||
| """ | ||
|
|
||
| format = LabelFormat.coco | ||
| supported_tasks = frozenset({TaskKind.detection, TaskKind.classification}) | ||
|
|
||
| def _load(self, source: Path) -> dict[str, Any]: | ||
| with source.open() as fh: | ||
| data = json.load(fh) | ||
| if not isinstance(data, dict) or "images" not in data: | ||
| raise ValueError(f"COCO file {source} must be an object with an 'images' array.") | ||
| return data | ||
|
|
||
| def to_detection_records( | ||
| self, source: Path, *, image_dir: Path | None, class_names: list[str] | None | ||
| ) -> list[DetectionRecord]: | ||
| data = self._load(source) | ||
| file_by_image: dict[int, str] = {img["id"]: img["file_name"] for img in data["images"]} | ||
| boxes: dict[int, list[list[float]]] = {iid: [] for iid in file_by_image} | ||
| labels: dict[int, list[int]] = {iid: [] for iid in file_by_image} | ||
| for ann in data.get("annotations", []): | ||
| iid = ann["image_id"] | ||
| x, y, w, h = ann["bbox"] | ||
| boxes[iid].append([x, y, x + w, y + h]) | ||
| labels[iid].append(int(ann["category_id"])) | ||
| return [ | ||
| {"sample_id": file_by_image[iid], "boxes": boxes[iid], "labels": labels[iid]} | ||
| for iid in file_by_image | ||
| ] | ||
|
|
||
| def to_classification_records(self, source: Path) -> list[ClassificationRecord]: | ||
| data = self._load(source) | ||
| file_by_image: dict[int, str] = {img["id"]: img["file_name"] for img in data["images"]} | ||
| cats: dict[int, set[int]] = {iid: set() for iid in file_by_image} | ||
| for ann in data.get("annotations", []): | ||
| cats[ann["image_id"]].add(int(ann["category_id"])) | ||
| records: list[ClassificationRecord] = [] | ||
| for iid, name in file_by_image.items(): | ||
| cat_set = cats[iid] | ||
| if len(cat_set) != 1: | ||
| raise ValueError( | ||
| f"COCO classification needs exactly one category per image; " | ||
| f"image {name!r} has {len(cat_set)}." | ||
| ) | ||
| records.append({"sample_id": name, "label": next(iter(cat_set))}) | ||
| return records |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| """Pascal-VOC label-format adapter (issue #338).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import xml.etree.ElementTree as ET | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pathlib import Path | ||
|
|
||
| from raitap.data.label_formats import ( | ||
| ClassificationRecord, | ||
| DetectionRecord, | ||
| label_format, | ||
| ) | ||
| from raitap.data.types import LabelFormat | ||
| from raitap.types import TaskKind | ||
|
|
||
| #: Canonical Pascal-VOC class order (index = label id) when no class_names given. | ||
| _VOC_CLASSES = ( | ||
| "aeroplane", | ||
| "bicycle", | ||
| "bird", | ||
| "boat", | ||
| "bottle", | ||
| "bus", | ||
| "car", | ||
| "cat", | ||
| "chair", | ||
| "cow", | ||
| "diningtable", | ||
| "dog", | ||
| "horse", | ||
| "motorbike", | ||
| "person", | ||
| "pottedplant", | ||
| "sheep", | ||
| "sofa", | ||
| "train", | ||
| "tvmonitor", | ||
| ) | ||
|
|
||
|
|
||
| def _coord(box: ET.Element, tag: str, xml_path: Path) -> float: | ||
| text = box.findtext(tag) | ||
| if text is None: | ||
| raise ValueError(f"VOC bndbox in {xml_path.name} missing <{tag}>.") | ||
| return float(text) | ||
|
|
||
|
|
||
| @label_format | ||
| class VocAdapter: | ||
| """Pascal-VOC per-image ``.xml`` -> native detection records. | ||
|
|
||
| Boxes are already ``[xmin, ymin, xmax, ymax]`` pixels. Class names map to | ||
| ids by their position in ``class_names`` (else the standard 20-class VOC | ||
| order). | ||
| """ | ||
|
|
||
| format = LabelFormat.voc | ||
| supported_tasks = frozenset({TaskKind.detection}) | ||
|
|
||
| def to_detection_records( | ||
| self, source: Path, *, image_dir: Path | None, class_names: list[str] | None | ||
| ) -> list[DetectionRecord]: | ||
| name_to_id = { | ||
| name: idx for idx, name in enumerate(class_names if class_names else _VOC_CLASSES) | ||
| } | ||
| records: list[DetectionRecord] = [] | ||
| for xml_path in sorted(source.glob("*.xml")): | ||
| root = ET.parse(xml_path).getroot() | ||
| filename_el = root.find("filename") | ||
| if filename_el is None or not filename_el.text: | ||
| raise ValueError(f"VOC file {xml_path} has no <filename>.") | ||
| boxes: list[list[float]] = [] | ||
| labels: list[int] = [] | ||
| for obj in root.findall("object"): | ||
| name = obj.findtext("name") | ||
| if name not in name_to_id: | ||
| raise ValueError( | ||
| f"VOC class {name!r} in {xml_path.name} is not in the " | ||
| f"class list {sorted(name_to_id)}." | ||
| ) | ||
| box = obj.find("bndbox") | ||
| if box is None: | ||
| raise ValueError(f"VOC object in {xml_path.name} has no <bndbox>.") | ||
| boxes.append( | ||
| [ | ||
| _coord(box, "xmin", xml_path), | ||
| _coord(box, "ymin", xml_path), | ||
| _coord(box, "xmax", xml_path), | ||
| _coord(box, "ymax", xml_path), | ||
| ] | ||
| ) | ||
| labels.append(name_to_id[name]) | ||
| records.append({"sample_id": filename_el.text, "boxes": boxes, "labels": labels}) | ||
| return records | ||
|
|
||
| def to_classification_records(self, source: Path) -> list[ClassificationRecord]: | ||
| raise ValueError("VOC is a detection-only format.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| """YOLO label-format adapter (issue #338).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| from PIL import Image | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pathlib import Path | ||
|
|
||
| from raitap.data.label_formats import ( | ||
| ClassificationRecord, | ||
| DetectionRecord, | ||
| label_format, | ||
| ) | ||
| from raitap.data.types import LabelFormat | ||
| from raitap.types import TaskKind | ||
|
|
||
| _IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".bmp", ".webp") | ||
|
|
||
|
|
||
| @label_format | ||
| class YoloAdapter: | ||
| """YOLO per-image ``.txt`` (``class cx cy w h``, normalised) -> native records. | ||
|
|
||
| Boxes are denormalised with each image's pixel size, read from | ||
| ``image_dir``. Class indices pass through unchanged. | ||
| """ | ||
|
|
||
| format = LabelFormat.yolo | ||
| supported_tasks = frozenset({TaskKind.detection}) | ||
|
|
||
| def _image_for(self, image_dir: Path, stem: str) -> Path: | ||
| for suffix in _IMAGE_SUFFIXES: | ||
| candidate = image_dir / f"{stem}{suffix}" | ||
| if candidate.exists(): | ||
| return candidate | ||
| raise ValueError(f"YOLO adapter found no image for label {stem!r} in {image_dir}.") | ||
|
|
||
| def to_detection_records( | ||
| self, source: Path, *, image_dir: Path | None, class_names: list[str] | None | ||
| ) -> list[DetectionRecord]: | ||
| if image_dir is None: | ||
| raise ValueError( | ||
| "YOLO labels need image_dir to denormalise boxes; " | ||
| "set data.source to the image directory." | ||
| ) | ||
| records: list[DetectionRecord] = [] | ||
| for txt in sorted(source.glob("*.txt")): | ||
| image_path = self._image_for(image_dir, txt.stem) | ||
| with Image.open(image_path) as im: | ||
| width, height = im.size | ||
| boxes: list[list[float]] = [] | ||
| labels: list[int] = [] | ||
| for line in txt.read_text().splitlines(): | ||
| parts = line.split() | ||
| if not parts: | ||
| continue | ||
| cls, cx, cy, bw, bh = (float(p) for p in parts[:5]) | ||
| x1 = (cx - bw / 2) * width | ||
| y1 = (cy - bh / 2) * height | ||
| x2 = (cx + bw / 2) * width | ||
| y2 = (cy + bh / 2) * height | ||
| boxes.append([x1, y1, x2, y2]) | ||
| labels.append(int(cls)) | ||
| records.append({"sample_id": image_path.name, "boxes": boxes, "labels": labels}) | ||
| return records | ||
|
|
||
| def to_classification_records(self, source: Path) -> list[ClassificationRecord]: | ||
| raise ValueError("YOLO is a detection-only format.") |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.