Source code for PartSegImage.channel_class

from typing import Union

from pydantic_core import core_schema


def check_type(value):  # type: ignore [misc]
    if isinstance(value, Channel):
        return value
    if value.__class__.__module__.startswith("napari"):
        value = value.name
    if not isinstance(value, (str, int)):  # pragma: no cover
        raise ValueError(f"Channel need to be int or str, provided {type(value)}")
    if isinstance(value, str) and not value:
        raise ValueError("Channel name can not be empty string")
    return Channel(value)


[docs] class Channel: """ This class is introduced to distinguish numerical algorithm parameter from choose channel. In autogenerated interface field with this type limits input values to number of current image channels """ def __init__(self, value: Union[str, int, "Channel"]): if isinstance(value, Channel): value = value.value if not isinstance(value, (str, int)): raise TypeError(f"wrong type {value} {type(value)}") # pragma: no cover self._value: str | int = value @property def value(self) -> str | int: """Value stored in this class""" return self._value def __str__(self): return str(self._value + 1) if isinstance(self._value, int) else self._value def __repr__(self): return f"<{self.__class__.__module__}.{self.__class__.__name__}(value={self._value!r})>" def __eq__(self, other): return isinstance(other, Channel) and self._value == other.value def __hash__(self): return hash(self._value) def as_dict(self): return {"value": self._value} @classmethod def validate(cls, value: "int | str | Channel") -> "Channel": return cls(check_type(value)) @classmethod def __get_pydantic_core_schema__(cls, source_type, handler): value_schema = core_schema.union_schema( [ core_schema.int_schema(), core_schema.str_schema(min_length=1), ] ) return core_schema.no_info_plain_validator_function( cls.validate, serialization=core_schema.plain_serializer_function_ser_schema( lambda value: value.value, return_schema=value_schema, ), ) @classmethod def __get_pydantic_json_schema__(cls, schema, handler): json_schema = handler( core_schema.union_schema( [ core_schema.int_schema(), core_schema.str_schema(min_length=1), ] ) ) json_schema.update( title="Channel", description="Image channel index or channel name. Accepts an integer or any non-empty string.", examples=[0, "nucleus"], ) return json_schema