Skip to content

category

sleap_io.model.category

Category data structure for ground-truth class membership of detections.

Classes:

Name Description
Category

Ground-truth class membership of a detection (e.g. species, sex, condition).

Functions:

Name Description
to_category

Coerce a category-like value to a Category (or None).

Attributes:

Name Type Description
__cached__

str(object='') -> str

__doc__

str(object='') -> str

__file__

str(object='') -> str

__name__

str(object='') -> str

__package__

str(object='') -> str

__cached__ = '/home/runner/work/sleap-io/sleap-io/sleap_io/model/__pycache__/category.cpython-313.pyc' module-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__doc__ = 'Category data structure for ground-truth class membership of detections.' module-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__file__ = '/home/runner/work/sleap-io/sleap-io/sleap_io/model/category.py' module-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__name__ = 'sleap_io.model.category' module-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__package__ = 'sleap_io.model' module-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

Category

Ground-truth class membership of a detection (e.g. species, sex, condition).

Where Track is an ephemeral temporal trajectory within a single video and Identity names a specific individual across videos, Category names the class an individual belongs to -- a group of individuals that share some attribute, typically assigned by classification or retrieved via re-ID (e.g. "female_fly", "fur_shaved", "mouse"). The per-detection binding is stored on Instance.category (and the analogous slot on the other detection modalities), alongside an optional category_score (assignment confidence) and category_embedding (the appearance vector it was classified from).

Attributes:

Name Type Description
name

Human-readable name for this category (e.g., "female_fly"). Not required to be unique, but name is how categories are matched across separately-loaded files and merges.

metadata

Arbitrary string-keyed, string-valued metadata (e.g. {"color": "#e6194b", "supercategory": "insect"}). Empty by default.

Notes

Category objects use object-identity equality (eq=False), matching Track and Identity. Use matches() (default method="name") to compare categories across files, where Python object identity is not meaningful.

Methods:

Name Description
__init__

Method generated by attrs for class Category.

__repr__

Return a readable string representation.

__setattr__

Method generated by attrs for class Category.

matches

Check if this category matches another category.

Source code in sleap_io/model/category.py
@define(eq=False)
class Category:
    """Ground-truth class membership of a detection (e.g. species, sex, condition).

    Where `Track` is an ephemeral temporal trajectory within a single video and
    `Identity` names a specific individual across videos, `Category` names the
    *class* an individual belongs to -- a group of individuals that share some
    attribute, typically assigned by classification or retrieved via re-ID (e.g.
    ``"female_fly"``, ``"fur_shaved"``, ``"mouse"``). The per-detection binding is
    stored on ``Instance.category`` (and the analogous slot on the other detection
    modalities), alongside an optional ``category_score`` (assignment confidence)
    and ``category_embedding`` (the appearance vector it was classified from).

    Attributes:
        name: Human-readable name for this category (e.g., ``"female_fly"``). Not
            required to be unique, but ``name`` is how categories are matched
            across separately-loaded files and merges.
        metadata: Arbitrary string-keyed, string-valued metadata (e.g.
            ``{"color": "#e6194b", "supercategory": "insect"}``). Empty by default.

    Notes:
        `Category` objects use object-identity equality (``eq=False``), matching
        `Track` and `Identity`. Use `matches()` (default ``method="name"``) to
        compare categories across files, where Python object identity is not
        meaningful.
    """

    name: str = field(default="", validator=instance_of(str))
    metadata: dict[str, str] = field(factory=dict, validator=instance_of(dict))

    def matches(self, other: "Category", method: str = "name") -> bool:
        """Check if this category matches another category.

        Args:
            other: Another category to compare with.
            method: Matching method:

                - ``"name"`` (default): match by the `name` attribute, which
                  survives serialization and cross-file merges.
                - ``"identity"``: match by Python object identity (same object).

        Returns:
            True if the categories match according to the specified method.

        Raises:
            ValueError: If `method` is not one of the supported values.
        """
        if method == "name":
            return self.name == other.name
        elif method == "identity":
            return self is other
        else:
            raise ValueError(f"Unknown matching method: {method}")

    def __repr__(self) -> str:
        """Return a readable string representation."""
        return f'Category(name="{self.name}")'

__annotations__ = {'name': 'str', 'metadata': 'dict[str, str]'} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=False, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'Ground-truth class membership of a detection (e.g. species, sex, condition).\n\nWhere `Track` is an ephemeral temporal trajectory within a single video and\n`Identity` names a specific individual across videos, `Category` names the\n*class* an individual belongs to -- a group of individuals that share some\nattribute, typically assigned by classification or retrieved via re-ID (e.g.\n``"female_fly"``, ``"fur_shaved"``, ``"mouse"``). The per-detection binding is\nstored on ``Instance.category`` (and the analogous slot on the other detection\nmodalities), alongside an optional ``category_score`` (assignment confidence)\nand ``category_embedding`` (the appearance vector it was classified from).\n\nAttributes:\n name: Human-readable name for this category (e.g., ``"female_fly"``). Not\n required to be unique, but ``name`` is how categories are matched\n across separately-loaded files and merges.\n metadata: Arbitrary string-keyed, string-valued metadata (e.g.\n ``{"color": "#e6194b", "supercategory": "insect"}``). Empty by default.\n\nNotes:\n `Category` objects use object-identity equality (``eq=False``), matching\n `Track` and `Identity`. Use `matches()` (default ``method="name"``) to\n compare categories across files, where Python object identity is not\n meaningful.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 9 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('name', 'metadata') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.category' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = ('name', 'metadata', '__weakref__') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property

list of weak references to the object

__init__(name='', metadata=NOTHING)

Method generated by attrs for class Category.

Source code in sleap_io/model/category.py
"""Category data structure for ground-truth class membership of detections."""

from __future__ import annotations

from attrs import define, field
from attrs.validators import instance_of


@define(eq=False)
class Category:

__repr__()

Return a readable string representation.

Source code in sleap_io/model/category.py
def __repr__(self) -> str:
    """Return a readable string representation."""
    return f'Category(name="{self.name}")'

__setattr__(name, val)

Method generated by attrs for class Category.

matches(other, method='name')

Check if this category matches another category.

Parameters:

Name Type Description Default
other Category

Another category to compare with.

required
method str

Matching method:

  • "name" (default): match by the name attribute, which survives serialization and cross-file merges.
  • "identity": match by Python object identity (same object).
'name'

Returns:

Type Description
bool

True if the categories match according to the specified method.

Raises:

Type Description
ValueError

If method is not one of the supported values.

Source code in sleap_io/model/category.py
def matches(self, other: "Category", method: str = "name") -> bool:
    """Check if this category matches another category.

    Args:
        other: Another category to compare with.
        method: Matching method:

            - ``"name"`` (default): match by the `name` attribute, which
              survives serialization and cross-file merges.
            - ``"identity"``: match by Python object identity (same object).

    Returns:
        True if the categories match according to the specified method.

    Raises:
        ValueError: If `method` is not one of the supported values.
    """
    if method == "name":
        return self.name == other.name
    elif method == "identity":
        return self is other
    else:
        raise ValueError(f"Unknown matching method: {method}")

to_category(value)

Coerce a category-like value to a Category (or None).

Promotes the legacy free-form category: str field (the object-detection class label) to a first-class Category, keeping existing category="mouse" call sites working:

  • None or the empty string "" (the old "unset" sentinel) -> None.
  • a non-empty str -> Category(name=value).
  • an existing Category -> returned unchanged.

Parameters:

Name Type Description Default
value Category | str | None

A Category, a class-label string, "", or None.

required

Returns:

Type Description
Category | None

A Category, or None if the input was None / "".

Raises:

Type Description
TypeError

If value is not a Category, str, or None.

Source code in sleap_io/model/category.py
def to_category(value: "Category | str | None") -> "Category | None":
    """Coerce a category-like value to a `Category` (or ``None``).

    Promotes the legacy free-form ``category: str`` field (the object-detection
    class label) to a first-class `Category`, keeping existing ``category="mouse"``
    call sites working:

    - ``None`` or the empty string ``""`` (the old "unset" sentinel) -> ``None``.
    - a non-empty ``str`` -> ``Category(name=value)``.
    - an existing `Category` -> returned unchanged.

    Args:
        value: A `Category`, a class-label string, ``""``, or ``None``.

    Returns:
        A `Category`, or ``None`` if the input was ``None`` / ``""``.

    Raises:
        TypeError: If `value` is not a `Category`, `str`, or ``None``.
    """
    if value is None:
        return None
    if isinstance(value, Category):
        return value
    if isinstance(value, str):
        if value == "":
            return None
        return Category(name=value)
    raise TypeError(
        f"category must be a Category, str, or None, got {type(value).__name__}."
    )