"""The codec interface. See DESIGN.md, "Codec interface"."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import ClassVar, Literal
from pydantic import BaseModel
from jabara.types import DTYPE_ITEMSIZE, TensorMeta
[docs]
class NoParams(BaseModel, frozen=True, extra="forbid"):
"""The parameters of a codec that takes none."""
[docs]
class Work(BaseModel, frozen=True, extra="forbid"):
"""A paper, a specification, or a library."""
kind: Literal["paper", "specification", "implementation"]
title: str
#: As the source lists them, in its order; for a library, its author or owner as its own page names them.
authors: tuple[str, ...]
#: The year of the publication, or of the release of a library that jabara uses.
year: int
url: str
[docs]
class Reference(BaseModel, frozen=True, extra="forbid"):
"""A work a codec builds on, and how. `jabara codecs` and the codec reference list them."""
#: "wraps": the codec calls this library. "describes": the work describes the method or the format of a library
#: the codec wraps. "related": the work has the same idea; the codec is this project's own and does not reproduce
#: the work's method.
relation: Literal["wraps", "describes", "related"]
work: Work
[docs]
class Codec(ABC):
"""Base class of every codec. A subclass sets `id` and `lossless`, optionally `needs_ref`, `Params`, `dtypes`,
`extra` and `references`, and implements `encode` and `decode` for one chunk of one tensor. A codec with threads
of its own also overrides `with_threads`. The first sentence of the class docstring is the codec's one-line
description in `jabara codecs --long`.
"""
#: `<name>/<version>`, the key in the registry and in the archive index. Change the version when the payload
#: format changes.
id: ClassVar[str]
#: True when `decode(encode(x))` returns `x` byte for byte for every chunk.
lossless: ClassVar[bool]
#: True for a delta codec: `encode` and `decode` then receive the same chunk of the base tensor as `ref`.
needs_ref: ClassVar[bool] = False
#: The pydantic model of the codec's parameters (frozen, `extra="forbid"`). `NoParams` for a codec without any.
Params: ClassVar[type[BaseModel]] = NoParams
#: The dtypes the codec encodes; any other raises `UnsupportedDtypeError`. Every dtype unless a subclass narrows it.
dtypes: ClassVar[frozenset[str]] = frozenset(DTYPE_ITEMSIZE)
#: The jabara extra that installs the package the codec imports on first use, or None. The package's top-level
#: module has the extra's name.
extra: ClassVar[str | None] = None
#: What the codec builds on. Empty for a codec that cites nothing.
references: ClassVar[tuple[Reference, ...]] = ()
def __init__(self, params: BaseModel | None = None) -> None:
self.params = params or self.Params()
[docs]
@abstractmethod
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return the encoded bytes of one chunk. `ref` is the same chunk of the base tensor; only a codec with
`needs_ref` reads it.
"""
[docs]
@abstractmethod
def decode(
self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None
) -> bytes | bytearray | memoryview:
"""Return the `raw_length` bytes that were encoded, as `bytes`, as a new `bytearray`, or as a memoryview of
unsigned bytes (format `B`, one contiguous dimension) over a new buffer, which the caller then owns. A codec
whose library returns a `bytearray`, or that builds its output in a NumPy array, needs no copy. The container
checks the type where it takes the result and raises `TypeError` naming the codec for anything else: a view
of a float32 array (`arr.data`), a two-dimensional view, and a strided view are all errors; use `.cast("B")`
on a contiguous view of another format, and `.reshape(-1)` before `.data`. A lossless codec returns its input
byte for byte. A lossy codec returns the same bytes every time for the same payload.
"""
[docs]
def with_threads(self, threads: int) -> Codec | None:
"""Return a copy of this codec that codes one chunk with at most `threads` threads of its own, or None for a
codec that has none (the default). The container then codes the chunks one after another with the copy
instead of on its thread pool. The copy must be the same class with the same `id` and `params` (the container
raises `TypeError` otherwise), encode every chunk to the same payload, and decode every payload to the same
bytes, so neither an archive's bytes nor whether it reads back depend on `threads`. Override it for a codec
that holds the GIL while it works, because a pool cannot run such a codec in parallel.
"""
return None