From 4f40c9b9311384f961f2990fd8410294f03c626f Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 10:37:37 +0100 Subject: [PATCH 1/3] Copy labeled-data vocabulary --- dlccore/io/labeled_data/model.py | 48 +++++++++ dlccore/io/labeled_data/wide/__init__.py | 4 + dlccore/io/labeled_data/wide/header.py | 113 ++++++++++++++++++++++ dlccore/io/labeled_data/wide/row_index.py | 101 +++++++++++++++++++ 4 files changed, 266 insertions(+) create mode 100644 dlccore/io/labeled_data/model.py create mode 100644 dlccore/io/labeled_data/wide/__init__.py create mode 100644 dlccore/io/labeled_data/wide/header.py create mode 100644 dlccore/io/labeled_data/wide/row_index.py diff --git a/dlccore/io/labeled_data/model.py b/dlccore/io/labeled_data/model.py new file mode 100644 index 0000000..35f2d87 --- /dev/null +++ b/dlccore/io/labeled_data/model.py @@ -0,0 +1,48 @@ +"""DeepLabCut's labeled-data model: what is true in any file format.""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + +# Keypoint data: always x and y, and a likelihood for models +# NOTE: 3D support is obviously missing +POSITION_COORDS = ("x", "y") +LIKELIHOOD_COORD = "likelihood" + +# In multi-animal project, this denotes keypoints that do not belong to any individual. +# Extra caution is needed as this is a sentinel value, make sure to treat it accordingly. +# TODO: needs improvement in handling as this is a major source of confusion and potential bugs. +# It should not be used in any other format than the wide table "legacy" format. +UNIQUE_BODYPARTS_INDIVIDUAL = "single" + +FramePath = tuple[str, ...] +"""A frame's path components as stored, e.g. ``("labeled-data", "session-01", "img000.png")``.""" + + +class BodypartScope(str, Enum): + """Whether a bodypart is labeled once per individual, or once per frame as DeepLabCut's ``uniquebodyparts``.""" + + INDIVIDUAL = "individual" + UNIQUE = "unique" + + +@dataclass(frozen=True) +class Keypoint: + """Which keypoint: one bodypart, of one individual or unique, from one scorer. + + Attributes: + scorer: As stored. + individual: As stored; ``None`` when the source names no individual. + bodypart: As stored. + """ + + scorer: str + individual: str | None + bodypart: str + + @property + def scope(self) -> BodypartScope: + """``UNIQUE`` exactly when the individual is DeepLabCut's unique-bodyparts bucket.""" + + return BodypartScope.UNIQUE if self.individual == UNIQUE_BODYPARTS_INDIVIDUAL else BodypartScope.INDIVIDUAL diff --git a/dlccore/io/labeled_data/wide/__init__.py b/dlccore/io/labeled_data/wide/__init__.py new file mode 100644 index 0000000..9d9d73f --- /dev/null +++ b/dlccore/io/labeled_data/wide/__init__.py @@ -0,0 +1,4 @@ +"""DeepLabCut's wide labeled-data table: its header, its row index, and the containers that store it. + +Imports nothing eagerly: ``h5`` loads pandas and PyTables, so import it explicitly. +""" diff --git a/dlccore/io/labeled_data/wide/header.py b/dlccore/io/labeled_data/wide/header.py new file mode 100644 index 0000000..540d369 --- /dev/null +++ b/dlccore/io/labeled_data/wide/header.py @@ -0,0 +1,113 @@ +"""DeepLabCut's wide labeled-data column header, classified by keypoint without loss.""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass +from enum import Enum + +from dlc_octopus.io.labeled_data.model import Keypoint + +SINGLE_ANIMAL_LEVELS = ("scorer", "bodyparts", "coords") +MULTI_ANIMAL_LEVELS = ("scorer", "individuals", "bodyparts", "coords") + + +class LabeledDataHeaderShape(str, Enum): + """The stored column levels""" + + SINGLE_ANIMAL = "single_animal" + MULTI_ANIMAL = "multi_animal" + UNRECOGNISED = "unrecognised" + + +_HEADER_SHAPES: dict[tuple[str | None, ...], LabeledDataHeaderShape] = { + SINGLE_ANIMAL_LEVELS: LabeledDataHeaderShape.SINGLE_ANIMAL, + MULTI_ANIMAL_LEVELS: LabeledDataHeaderShape.MULTI_ANIMAL, +} + + +@dataclass(frozen=True) +class KeypointColumns: + """Where one keypoint sits in a wide header. + + Attributes: + keypoint:Individual is ``None`` if no individuals level, and its scope is + ``UNIQUE`` exactly when the individual is ``"single"``. + coords: The coordinate of each column, in column order, duplicates kept. + positions: Each column's position in the header, aligned with ``coords``. + """ + + keypoint: Keypoint + coords: tuple[str, ...] + positions: tuple[int, ...] + + +@dataclass(frozen=True) +class LabeledDataHeader: + """A labeled-data column header. + + Attributes: + level_names: The level names. + shape: Which header DeepLabCut writes these level names match. + keypoints: In order of first appearance; empty when ``shape`` is ``UNRECOGNISED``. + columns: The stored column tuples, kept only when ``shape`` is ``UNRECOGNISED``. + """ + + level_names: tuple[str | None, ...] + shape: LabeledDataHeaderShape + keypoints: tuple[KeypointColumns, ...] = () + columns: tuple[tuple[str, ...], ...] = () + + +HEADER_DEPTHS: tuple[int, ...] = tuple(sorted({len(level_names) for level_names in _HEADER_SHAPES}, reverse=True)) + + +def header_shape(level_names: Iterable[str | None]) -> LabeledDataHeaderShape: + """Return which header DeepLabCut writes these level names are, or ``UNRECOGNISED``.""" + + return _HEADER_SHAPES.get(tuple(level_names), LabeledDataHeaderShape.UNRECOGNISED) + + +def classify_labeled_data_header( + level_names: Iterable[str | None], + columns: Iterable[tuple[str, ...]], +) -> LabeledDataHeader: + """Classify a column header by keypoint, read by name, never as a grid of distinct level values. + + Columns are grouped by (scorer, individual, bodypart). + Reordered headers give the same keypoints at other positions, + any missing pair is omitted rather than padded, and duplicated columns are kept. + + Args: + level_names: The header's level names, outermost first. + columns: One tuple per column, aligned with ``level_names``. + """ + + level_names = tuple(level_names) + columns = tuple(tuple(column) for column in columns) + shape = header_shape(level_names) + + if shape is LabeledDataHeaderShape.UNRECOGNISED: + return LabeledDataHeader(level_names=level_names, shape=shape, columns=columns) + + groups: dict[tuple[str, str | None, str], list[tuple[str, int]]] = {} + + for position, column in enumerate(columns): + if shape is LabeledDataHeaderShape.SINGLE_ANIMAL: + scorer, bodypart, coord = column + individual = None + else: + scorer, individual, bodypart, coord = column + + groups.setdefault((scorer, individual, bodypart), []).append((coord, position)) + + keypoints = tuple( + KeypointColumns( + keypoint=Keypoint(scorer=scorer, individual=individual, bodypart=bodypart), + coords=tuple(coord for coord, _position in members), + positions=tuple(position for _coord, position in members), + ) + for (scorer, individual, bodypart), members in groups.items() + ) + + return LabeledDataHeader(level_names=level_names, shape=shape, keypoints=keypoints) diff --git a/dlccore/io/labeled_data/wide/row_index.py b/dlccore/io/labeled_data/wide/row_index.py new file mode 100644 index 0000000..e3323f0 --- /dev/null +++ b/dlccore/io/labeled_data/wide/row_index.py @@ -0,0 +1,101 @@ +"""Frame paths of labeled data: DeepLabCut's row index, split into path components as stored.""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass +from enum import Enum +from numbers import Integral + + +class RowIndexShape(str, Enum): + """The stored row index: path components, path strings, no entries (whatever the index type), or unrecognised.""" + + PATH_PARTS = "path_parts" + FLAT_PATHS = "flat_paths" + EMPTY = "empty" + UNRECOGNISED = "unrecognised" + + +@dataclass(frozen=True) +class LabeledDataRowIndex: + """A labeled-data row index. + + Attributes: + shape: How the frame paths are stored. + names: The stored level names, unmodified; ``None`` for each unnamed level. + entries: The stored entries, unmodified. + frames: The path components of each entry, as stored; ragged depths stay ragged. Empty when ``shape`` + is ``EMPTY`` or ``UNRECOGNISED``. + """ + + shape: RowIndexShape + names: tuple[object, ...] + entries: tuple[object, ...] + frames: tuple[tuple[object, ...], ...] = () + + +# Frame identity rather than wide storage: moves to ``model`` once a second format needs it. +def split_frame_path(entry: str) -> tuple[str, ...]: + """Split a labeled-data row-index entry into its path components. + + Splits; does not validate. Empty and repeated separators yield empty components rather than being dropped. + + Args: + entry: A row-index entry, e.g. ``labeled-data/vid1/img1.png``. Either path separator is accepted. + """ + + return tuple(entry.replace("\\", "/").split("/")) + + +def frame_part_as_text(part: object) -> str | None: + """Return a frame part as the name it stands for, or ``None`` when no name can be given without inventing one. + + Text is kept. An integer becomes its digits: pandas infers one for a folder named by a number, and DeepLabCut's + ``guarantee_multiindex_rows`` casts it back the same way. A float or bool would name a folder that never existed. + """ + + if isinstance(part, str): + return part + if isinstance(part, Integral) and not isinstance(part, bool): + return str(part) + return None + + +def classify_labeled_data_row_index( + names: Iterable[object], + entries: Iterable[object], + *, + is_multi_index: bool, +) -> LabeledDataRowIndex: + """Classify a row index by how its frame paths are stored, splitting path strings without normalising them. + + Args: + names: The row index's level names + entries: The row-index entries, in order; tuples for a MultiIndex + is_multi_index: Whether the entries came from a MultiIndex + """ + + names = tuple(names) + entries = tuple(entries) + + if not entries: + return LabeledDataRowIndex(shape=RowIndexShape.EMPTY, names=names, entries=entries) + + if is_multi_index: + return LabeledDataRowIndex( + shape=RowIndexShape.PATH_PARTS, + names=names, + entries=entries, + frames=tuple(tuple(entry) for entry in entries), + ) + + if all(isinstance(entry, str) for entry in entries): + return LabeledDataRowIndex( + shape=RowIndexShape.FLAT_PATHS, + names=names, + entries=entries, + frames=tuple(split_frame_path(entry) for entry in entries), + ) + + return LabeledDataRowIndex(shape=RowIndexShape.UNRECOGNISED, names=names, entries=entries) From 22366e3ffbad8e0157021946e394482c7b7296f6 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 10:52:48 +0100 Subject: [PATCH 2/3] Adapt labeled-data vocabulary to dlccore - Rename the package to dlccore.io and add the dlccore license header - Add labeled_data/__init__.py so the package ships in the wheel; it re-exports nothing until the readers land - Reword the header and row-index docstrings --- dlccore/io/labeled_data/__init__.py | 15 +++++++ dlccore/io/labeled_data/model.py | 11 +++++ dlccore/io/labeled_data/wide/__init__.py | 11 +++++ dlccore/io/labeled_data/wide/header.py | 44 ++++++++++++------- dlccore/io/labeled_data/wide/row_index.py | 52 ++++++++++++++++------- 5 files changed, 101 insertions(+), 32 deletions(-) create mode 100644 dlccore/io/labeled_data/__init__.py diff --git a/dlccore/io/labeled_data/__init__.py b/dlccore/io/labeled_data/__init__.py new file mode 100644 index 0000000..6ce0188 --- /dev/null +++ b/dlccore/io/labeled_data/__init__.py @@ -0,0 +1,15 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Labeled-data files: ``model`` holds what is true in any format, and each table format is a subpackage. + +Imports no format eagerly, so no format's dependencies load until that format is imported. +""" diff --git a/dlccore/io/labeled_data/model.py b/dlccore/io/labeled_data/model.py index 35f2d87..34f1ace 100644 --- a/dlccore/io/labeled_data/model.py +++ b/dlccore/io/labeled_data/model.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """DeepLabCut's labeled-data model: what is true in any file format.""" from __future__ import annotations diff --git a/dlccore/io/labeled_data/wide/__init__.py b/dlccore/io/labeled_data/wide/__init__.py index 9d9d73f..199a413 100644 --- a/dlccore/io/labeled_data/wide/__init__.py +++ b/dlccore/io/labeled_data/wide/__init__.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """DeepLabCut's wide labeled-data table: its header, its row index, and the containers that store it. Imports nothing eagerly: ``h5`` loads pandas and PyTables, so import it explicitly. diff --git a/dlccore/io/labeled_data/wide/header.py b/dlccore/io/labeled_data/wide/header.py index 540d369..f3cd765 100644 --- a/dlccore/io/labeled_data/wide/header.py +++ b/dlccore/io/labeled_data/wide/header.py @@ -1,4 +1,15 @@ -"""DeepLabCut's wide labeled-data column header, classified by keypoint without loss.""" +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""DeepLabCut's wide labeled-data column header, grouped into keypoints without dropping any column.""" from __future__ import annotations @@ -6,14 +17,14 @@ from dataclasses import dataclass from enum import Enum -from dlc_octopus.io.labeled_data.model import Keypoint +from dlccore.io.labeled_data.model import Keypoint SINGLE_ANIMAL_LEVELS = ("scorer", "bodyparts", "coords") MULTI_ANIMAL_LEVELS = ("scorer", "individuals", "bodyparts", "coords") class LabeledDataHeaderShape(str, Enum): - """The stored column levels""" + """Column layouts used by a header, if recognised.""" SINGLE_ANIMAL = "single_animal" MULTI_ANIMAL = "multi_animal" @@ -28,13 +39,13 @@ class LabeledDataHeaderShape(str, Enum): @dataclass(frozen=True) class KeypointColumns: - """Where one keypoint sits in a wide header. + """The columns of one keypoint in a wide header. Attributes: - keypoint:Individual is ``None`` if no individuals level, and its scope is - ``UNIQUE`` exactly when the individual is ``"single"``. - coords: The coordinate of each column, in column order, duplicates kept. - positions: Each column's position in the header, aligned with ``coords``. + keypoint: The keypoint. The individual is ``None`` in a single-animal header, and the scope is + ``UNIQUE`` only when the individual is ``"single"``. + coords: The coordinate name of each column (e.g. ``"x"``), in column order, duplicates kept. + positions: Each column's index in the header, aligned with ``coords``. """ keypoint: Keypoint @@ -44,13 +55,13 @@ class KeypointColumns: @dataclass(frozen=True) class LabeledDataHeader: - """A labeled-data column header. + """A wide labeled-data column header, classified. Attributes: - level_names: The level names. - shape: Which header DeepLabCut writes these level names match. - keypoints: In order of first appearance; empty when ``shape`` is ``UNRECOGNISED``. - columns: The stored column tuples, kept only when ``shape`` is ``UNRECOGNISED``. + level_names: The header's level names, as stored. + shape: The DeepLabCut layout these level names match, or ``UNRECOGNISED``. + keypoints: The keypoints, in order of first appearance; empty when ``shape`` is ``UNRECOGNISED``. + columns: The raw column tuples, kept only when ``shape`` is ``UNRECOGNISED`` so that nothing is lost. """ level_names: tuple[str | None, ...] @@ -63,7 +74,7 @@ class LabeledDataHeader: def header_shape(level_names: Iterable[str | None]) -> LabeledDataHeaderShape: - """Return which header DeepLabCut writes these level names are, or ``UNRECOGNISED``.""" + """Return the DeepLabCut layout these level names match, or ``UNRECOGNISED``.""" return _HEADER_SHAPES.get(tuple(level_names), LabeledDataHeaderShape.UNRECOGNISED) @@ -72,9 +83,10 @@ def classify_labeled_data_header( level_names: Iterable[str | None], columns: Iterable[tuple[str, ...]], ) -> LabeledDataHeader: - """Classify a column header by keypoint, read by name, never as a grid of distinct level values. + """Group a wide header's columns into keypoints. + Each column is read on its own and grouped by (scorer, individual, bodypart). The header is never expanded + from its per-level values (a MultiIndex's ``levels``), which would add keypoints that have no column. - Columns are grouped by (scorer, individual, bodypart). Reordered headers give the same keypoints at other positions, any missing pair is omitted rather than padded, and duplicated columns are kept. diff --git a/dlccore/io/labeled_data/wide/row_index.py b/dlccore/io/labeled_data/wide/row_index.py index e3323f0..2d592f6 100644 --- a/dlccore/io/labeled_data/wide/row_index.py +++ b/dlccore/io/labeled_data/wide/row_index.py @@ -1,4 +1,15 @@ -"""Frame paths of labeled data: DeepLabCut's row index, split into path components as stored.""" +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""DeepLabCut's labeled-data row index: each row's frame path, split into path components as stored.""" from __future__ import annotations @@ -9,7 +20,11 @@ class RowIndexShape(str, Enum): - """The stored row index: path components, path strings, no entries (whatever the index type), or unrecognised.""" + """How a row index stores its frame paths. + + ``PATH_PARTS``: a MultiIndex, one level per path component. ``FLAT_PATHS``: one path string per row. + ``EMPTY``: no rows, whatever the index type. ``UNRECOGNISED``: anything else. + """ PATH_PARTS = "path_parts" FLAT_PATHS = "flat_paths" @@ -19,14 +34,14 @@ class RowIndexShape(str, Enum): @dataclass(frozen=True) class LabeledDataRowIndex: - """A labeled-data row index. + """A labeled-data row index, classified. Attributes: shape: How the frame paths are stored. - names: The stored level names, unmodified; ``None`` for each unnamed level. - entries: The stored entries, unmodified. - frames: The path components of each entry, as stored; ragged depths stay ragged. Empty when ``shape`` - is ``EMPTY`` or ``UNRECOGNISED``. + names: The level names as stored; ``None`` for each unnamed level. + entries: The entries as stored. + frames: Each entry's path components as stored. Entries of different depths keep their own length. + Empty when ``shape`` is ``EMPTY`` or ``UNRECOGNISED``. """ shape: RowIndexShape @@ -39,20 +54,25 @@ class LabeledDataRowIndex: def split_frame_path(entry: str) -> tuple[str, ...]: """Split a labeled-data row-index entry into its path components. - Splits; does not validate. Empty and repeated separators yield empty components rather than being dropped. + Does not validate: empty and repeated separators give empty components instead of being dropped. Args: - entry: A row-index entry, e.g. ``labeled-data/vid1/img1.png``. Either path separator is accepted. + entry: A row-index entry, e.g. ``labeled-data/vid1/img1.png``. Forward slashes and backslashes both separate. """ return tuple(entry.replace("\\", "/").split("/")) def frame_part_as_text(part: object) -> str | None: - """Return a frame part as the name it stands for, or ``None`` when no name can be given without inventing one. + """Return a row-index part as the folder or file name it stands for. + + A string is returned unchanged. An integer is converted with ``str()``: when a video folder's name is a + number (e.g. ``labeled-data/123/``), pandas may read that level back as an integer, and DeepLabCut's + ``guarantee_multiindex_rows`` converts it to a string the same way. - Text is kept. An integer becomes its digits: pandas infers one for a folder named by a number, and DeepLabCut's - ``guarantee_multiindex_rows`` casts it back the same way. A float or bool would name a folder that never existed. + Returns: + The name, or ``None`` for any other type. A float or bool cannot be turned back into the original + name (``1.0`` vs ``"1"``), so no guessing is involved. """ if isinstance(part, str): @@ -68,12 +88,12 @@ def classify_labeled_data_row_index( *, is_multi_index: bool, ) -> LabeledDataRowIndex: - """Classify a row index by how its frame paths are stored, splitting path strings without normalising them. + """Classify a row index by how it stores frame paths. Path strings are split but not normalised. Args: - names: The row index's level names - entries: The row-index entries, in order; tuples for a MultiIndex - is_multi_index: Whether the entries came from a MultiIndex + names: The row index's level names. + entries: The row-index entries, in order; tuples for a MultiIndex. + is_multi_index: Whether the entries came from a MultiIndex. """ names = tuple(names) From 68b3a9c986a849ce5ffc52f2deafd97e60047151 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 17:30:06 +0100 Subject: [PATCH 3/3] pre-commit --- dlccore/io/labeled_data/wide/header.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dlccore/io/labeled_data/wide/header.py b/dlccore/io/labeled_data/wide/header.py index f3cd765..042ee07 100644 --- a/dlccore/io/labeled_data/wide/header.py +++ b/dlccore/io/labeled_data/wide/header.py @@ -84,10 +84,11 @@ def classify_labeled_data_header( columns: Iterable[tuple[str, ...]], ) -> LabeledDataHeader: """Group a wide header's columns into keypoints. + Each column is read on its own and grouped by (scorer, individual, bodypart). The header is never expanded from its per-level values (a MultiIndex's ``levels``), which would add keypoints that have no column. - Reordered headers give the same keypoints at other positions, + Reordered headers give the same keypoints at other positions, any missing pair is omitted rather than padded, and duplicated columns are kept. Args: