Skip to content

pixano_inference.schemas.nd_array

Pydantic models for N-dimensional arrays.

This is a core, framework-agnostic wire type. It converts to and from numpy.ndarray only; conversions to framework tensors live in the model packages (e.g. pixano_inference_torch for PyTorch), so the core does not privilege any one framework.

Arrays serialize as {shape, dtype, data} where data is the base64-encoded raw bytes of the array (compact and cheap to parse, unlike a JSON list of floats — important for SAM2-scale embeddings).

NDArray(**data)

Bases: BaseModel, Generic[T], ABC

Represents an N-dimensional array serialized as base64-encoded raw bytes.

Attributes:

Name Type Description
shape list[int]

The shape of the array.

dtype str

The numpy dtype name (informational; the concrete subclass fixes it).

data str

Base64-encoded raw bytes of the (C-contiguous) array.

Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            f'See the `model_validator` docs (https://pydantic.dev/docs/validation/{version_short()}/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

from_numpy(arr) classmethod

Create an instance from a NumPy array (cast to the subclass dtype).

Parameters:

Name Type Description Default
arr ndarray

The NumPy array to convert.

required

Returns:

Type Description
Self

An instance holding the array's shape and base64-encoded bytes.

Source code in pixano_inference/schemas/nd_array.py
@classmethod
def from_numpy(cls, arr: np.ndarray) -> Self:
    """Create an instance from a NumPy array (cast to the subclass dtype).

    Args:
        arr: The NumPy array to convert.

    Returns:
        An instance holding the array's shape and base64-encoded bytes.
    """
    contiguous = np.ascontiguousarray(arr.astype(cls.np_dtype))
    return cls(
        shape=list(arr.shape),
        dtype=str(cls.np_dtype),
        data=base64.b64encode(contiguous.tobytes()).decode("ascii"),
    )

to_numpy()

Convert the instance to a NumPy array.

Returns:

Type Description
ndarray

A NumPy array with the stored shape and dtype.

Source code in pixano_inference/schemas/nd_array.py
def to_numpy(self) -> np.ndarray:
    """Convert the instance to a NumPy array.

    Returns:
        A NumPy array with the stored shape and dtype.
    """
    # bytearray (rather than bytes) yields a writable array, avoiding a torch warning.
    buffer = bytearray(base64.b64decode(self.data))
    return np.frombuffer(buffer, dtype=self.np_dtype).reshape(self.shape)

NDArrayFloat(**data)

Bases: NDArray[float]

An N-dimensional array of 32-bit floating-point values.

Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            f'See the `model_validator` docs (https://pydantic.dev/docs/validation/{version_short()}/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )