Skip to content

unaiverse.streams.dataprops

A stream carries samples of one kind: text, images, tensors or files. Before a sample reaches a processor the node must know what to expect, how to turn the sample into a tensor and how to turn the output of the processor back into a sample that can be sent over the network. This module holds that description. A developer writes it when declaring the inputs and outputs of a processor (proc_inputs and proc_outputs of an agent) or when building a stream by hand. The node reads it to check every sample, to convert it and to name the stream on the network. The narrative guide is Data streams.

Object Role
StreamType What a developer writes in proc_inputs and proc_outputs. It builds one DataProps for the world network and one for the public network from the same arguments.
DataProps The description of the data of one stream: type, shape, dtype, labels, transforms, pace (delta), broadcast (pubsub) and network (public). Every Stream owns one in stream.props.
TensorLabels The names of the components of a flat tensor and the rule that turns a tensor into one or more of these names. A DataProps creates it from tensor_labels.
FileContainer A sample of a stream of type file. It holds the bytes of a file or the path of a file on disk together with its name and MIME type.

StreamType takes the arguments of DataProps except public. A typical classifier reads images and writes the name of a class. Its declaration is the following:

import torch
from unaiverse.modules.utils import transforms_factory
from unaiverse.streams.dataprops import StreamType

classes = ["cat", "dog", "horse"]
proc_inputs = [StreamType(data_type="img", stream_to_proc_transforms=transforms_factory("rgb224"))]
proc_outputs = [StreamType(data_type="tensor", tensor_shape=(1, 3), tensor_dtype=torch.float32,
                           tensor_labels=classes)]

With these declarations the node accepts a PIL.Image.Image on the input stream, converts it to a (1, 3, 224, 224) float tensor for the processor and checks that the processor returns a (1, 3) float tensor. DataProps.to_text then reads such an output as the label with the largest score ("dog" for instance).

All the checks of this module are assert statements. A wrong argument raises AssertionError with a short message and Python skips every check when it runs with -O.

FileContainer

FileContainer(content: bytes | str | None = None, filename: str = 'file', mime_type: str = 'application/octet-stream', path: str | None = None)
Source code in unaiverse/streams/dataprops.py
def __init__(self, content: bytes | str | None = None, filename: str = "file",
             mime_type: str = "application/octet-stream", path: str | None = None) -> None:
    """Initializes the container.

    Args:
        content: The bytes (or text) of the file, or None for a path-backed container.
        filename: The name of the file.
        mime_type: Its MIME type.
        path: The file on disk of a path-backed container.

    Raises:
        ValueError: If neither content nor path is given.
    """
    if content is None and path is None:
        raise ValueError("A FileContainer needs its content or its path")
    self._content = content
    self.filename = filename
    self.mime_type = mime_type
    self.path = path

A sample of a stream of type file. The class exists to tell a file apart from a generic bytes or str sample. A container is backed either by its content (bytes or a string held in memory) or by a path on disk. A path-backed container reads the file only at the first access to its content property. Because the node sends such a container straight from the disk to a peer that accepts file messages, a file of any size never has to fit in memory. A received file arrives as a path-backed container that points into ~/.unaiverse/Downloads/ (see Networking).

Argument Type Default Meaning
content bytes, str or None None The content of the file. None builds a path-backed container.
filename str "file" The name of the file that the receiver sees.
mime_type str "application/octet-stream" The MIME type of the content.
path str or None None The file on disk of a path-backed container.

The constructor raises ValueError("A FileContainer needs its content or its path") when both content and path are None. When both are given, content returns the content in memory and the path is only kept as an attribute.

Two containers compare equal (==) when their filename, mime_type and content are equal. The comparison therefore reads a path-backed file from disk. repr never prints the bytes:

>>> FileContainer(content=b"abc", filename="a.bin")
FileContainer(filename='a.bin', mime_type='application/octet-stream', 3 bytes)

from_path classmethod

from_path(file_path: str) -> FileContainer
Source code in unaiverse/streams/dataprops.py
@classmethod
def from_path(cls, file_path: str) -> 'FileContainer':
    """Create a path-backed FileContainer for the given file, which is not read here.

    Args:
        file_path: Absolute or relative path to the file.

    Returns:
        A FileContainer for the file, with its name and guessed MIME type.

    Raises:
        FileNotFoundError: If there is no such file.
    """
    if not os.path.isfile(file_path):
        raise FileNotFoundError(file_path)

    # Guess MIME type based on extension
    mime_type, _ = mimetypes.guess_type(file_path)
    if mime_type is None:
        mime_type = "application/octet-stream"  # Safe fallback for binary
    return cls(filename=os.path.basename(file_path), mime_type=mime_type, path=os.path.abspath(file_path))

Builds a path-backed container for the file at file_path without reading it. The filename is the base name of the path, the MIME type is guessed from the extension with mimetypes.guess_type ("application/octet-stream" when the extension is unknown) and the stored path is absolute. It raises FileNotFoundError when file_path is not an existing file.

>>> f = FileContainer.from_path("report.csv")
>>> f
FileContainer(filename='report.csv', mime_type='text/csv', path='/home/me/report.csv')
>>> f.has_content
False

content property writable

content: bytes | str

The content of the file (bytes or str). On a path-backed container the first read opens the file in binary mode and keeps its bytes in memory. Later reads do not touch the disk and has_content becomes True. Assigning a new value replaces the content in memory and leaves path untouched.

has_content property

has_content: bool

True when the content is in memory. It is always True for a container built with content and False for a path-backed one until content is read.

size property

size: int

The size of the file in bytes (int). A path-backed container that has not loaded its content takes the size from the file system without reading the file. A str content is measured on its UTF-8 encoding.

StreamType

StreamType(*args: object, private_only: bool = False, **kwargs: object)
Source code in unaiverse/streams/dataprops.py
def __init__(self, *args: object, private_only: bool = False, **kwargs: object) -> None:
    """Initializes a `Stream` object, which is a container for one or two `DataProps` instances. It creates a
     `DataProps` object for a private stream and, optionally, a public stream.

    Args:
        *args: Variable length argument list to be passed to the `DataProps` constructor.
        private_only: If True, only a private stream's `DataProps` is created.
        **kwargs: Arbitrary keyword arguments passed to the `DataProps` constructor.

    Raises:
        ValueError: If the 'public' argument is passed directly (it is a `DataProps` argument).
    """
    self.props = []

    if 'public' in kwargs:
        raise ValueError("Invalid argument was provided to Stream: 'public' (it is an argument of DataProps)")

    # Shorthand creation: Stream("text")
    if len(args) == 1 and len(kwargs) == 0:
        kwargs['data_type'] = args[0]
        args = []

    kwargs['public'] = False
    self.props.append(DataProps(*args, **kwargs))
    if not private_only:
        kwargs['public'] = True
        self.props.append(DataProps(*args, **kwargs))

The object that a developer writes in proc_inputs and proc_outputs. An agent offers each processor stream twice: once on the private network of the world it joins and once on the public network. StreamType therefore builds two DataProps from the same arguments and keeps them in the list props. props[0] has public=False and props[1] has public=True.

Argument Type Default Meaning
*args any Positional arguments of DataProps. A single positional argument with no keyword argument is the data type (StreamType("text") is StreamType(data_type="text")).
private_only bool False Keyword only. True builds only the private DataProps and makes the processor unreachable from the public network through this input or output.
**kwargs any Keyword arguments of DataProps (see the table of DataProps).

Passing public raises ValueError("Invalid argument was provided to Stream: 'public' (it is an argument of DataProps)") because StreamType chooses that value itself. A plain string in proc_inputs or proc_outputs ("img") is read by the agent as StreamType("img").

StreamType forwards the access to every other attribute to its descriptions in two ways:

  1. A name that starts with set_ returns a function that calls that setter on every DataProps of the list. st.set_name("feat") therefore renames both descriptions.
  2. Any other name is read from props[0]. st.data_type, st.is_text() and st.tensor_shape return the values of the private description.
>>> st = StreamType(data_type="tensor", tensor_shape=(1, 3), tensor_dtype="torch.float32")
>>> [p.public for p in st.props]
[False, True]
>>> st.set_name("features")
>>> [p.name for p in st.props]
['features', 'features']
>>> st.is_tensor()
True

str(st) lists the number of descriptions and the dictionary of each one.

to_list_of_dicts

to_list_of_dicts() -> list[dict]
Source code in unaiverse/streams/dataprops.py
def to_list_of_dicts(self) -> list[dict]:
    """Converts the contained `DataProps` objects into a list of dictionaries. Each dictionary represents the
    properties of a single data stream.

    Returns:
        A list of dictionaries, where each dictionary holds the properties of a `DataProps` object.
    """
    return [props.to_dict() for props in self.props]

Returns the list [p.to_dict() for p in props] with one dictionary per description in the order of props (see DataProps.to_dict).

to_dict

to_dict() -> None
Source code in unaiverse/streams/dataprops.py
def to_dict(self) -> None:
    """Raises a `RuntimeError` because this method is intended for a single `DataProps` object, not for the
    container class `Stream` which can hold multiple properties.

    Raises:
        RuntimeError: Always, as this method is not supported.
    """
    raise RuntimeError("This method can only be called on a DataProps object and not on Stream")

Always raises RuntimeError("This method can only be called on a DataProps object and not on Stream"). A StreamType holds up to two descriptions and has no single dictionary. Use to_list_of_dicts or call to_dict on one element of props.

from_dict

from_dict() -> None
Source code in unaiverse/streams/dataprops.py
def from_dict(self) -> None:
    """Raises a `RuntimeError` because this method is intended for a single `DataProps` object, not for the
    container class `Stream` which can hold multiple properties.

    Raises:
        RuntimeError: Always, as this method is not supported.
    """
    raise RuntimeError("This method can only be called on a DataProps object and not on Stream")

Always raises RuntimeError with the same message as to_dict. Rebuild a description with DataProps.from_dict.

clone

clone() -> StreamType
Source code in unaiverse/streams/dataprops.py
def clone(self) -> 'StreamType':
    """Creates and returns a deep copy of the `Stream` object.

    Returns:
        A new `Stream` object that is a clone of the original.
    """
    ret = StreamType()
    ret.props = []
    for p in self.props:
        ret.props.append(p.clone())
    return ret

Returns a new StreamType whose props holds a clone of each description. The clones keep the transforms as they were given (an "AutoTokenizer:..." string is resolved again).

is_public

is_public() -> None
Source code in unaiverse/streams/dataprops.py
def is_public(self) -> None:
    """Raises a `RuntimeError` because this method is intended for a single `DataProps` object, not for the
    container class `Stream` which can hold multiple properties.

    Raises:
        RuntimeError: Always, as this method is not supported.
    """
    raise RuntimeError("This method can only be called on a DataProps object and not on Stream")

Always raises RuntimeError with the same message as to_dict. The two descriptions give different answers because one is private and the other public. Ask props[0].is_public() or props[1].is_public().

DataProps

DataProps(name: str = 'unk', group: str = 'none', data_type: str = 'text', data_desc: str = 'unk', tensor_shape: tuple[int | None, ...] | None = None, tensor_labels: list[str] | str | None = None, tensor_dtype: dtype | str | None = None, tensor_labeling_rule: str = 'max', stream_to_proc_transforms: Callable[..., Any] | PreTrainedTokenizerBase | str | dict | tuple[dict | Callable[..., Any] | PreTrainedTokenizerBase | str | None, dict | Callable[..., Any] | PreTrainedTokenizerBase | str | None] | list | None = None, proc_to_stream_transforms: Callable[..., Any] | PreTrainedTokenizerBase | str | list | None = None, delta: float = -1, pubsub: bool = False, public: bool = False)
Source code in unaiverse/streams/dataprops.py
def __init__(self,
             name: str = "unk",
             group: str = "none",
             data_type: str = "text",  # Do not set tensor as default
             data_desc: str = "unk",
             tensor_shape: tuple[int | None, ...] | None = None,
             tensor_labels: list[str] | str | None = None,
             tensor_dtype: torch.dtype | str | None = None,
             tensor_labeling_rule: str = "max",
             stream_to_proc_transforms: Callable[..., Any] | PreTrainedTokenizerBase | str | dict | tuple[
                 dict | Callable[..., Any] | PreTrainedTokenizerBase | str | None,
                 dict | Callable[..., Any] | PreTrainedTokenizerBase | str | None] | list | None = None,
             proc_to_stream_transforms: Callable[..., Any] | PreTrainedTokenizerBase | str | list | None = None,
             delta: float = -1,
             pubsub: bool = False,
             public: bool = False):
    """Initializes a DataProps instance.

    Args:
        name (str): Name of the data (default is "unk").
        group (str): Name of the group to which this DataProps belong (default: "none").
        data_type (str): The type of data ('tensor', 'img', or 'text').
        data_desc (str): Description of the data (default is "unk").
        tensor_shape (tuple[int | None] or None): Shape of the tensor data (e.g., (3, 224, 224) or (3, None, None)
            for tensors that are variable size images). It is None for non-tensor data.
        tensor_labels (list[str] or "AutoTokenizer:<tokenizer_model_id>" or None):
            List of labels for the components (features) of tensor data. It can be a string representing the ID of a
            tokenizer which is valid in AutoTokenizer (with prefix "AutoTokenizer:").
        tensor_dtype (torch.dtype or str or None): The string representing the PyTorch dtype of the tensor data.
        tensor_labeling_rule (str): The labeling rule for tensor data ('max' or 'geq-X' where -X is a number).
        stream_to_proc_transforms (callable or PreTrainedTokenizerBase or str or dict or a list* or None):
            A callable stream format to tensor format conversion fcn (any callable thing, torchvision transforms, a
            pretrained tokenizer, or the model ID from which it can be downloaded (it must have prefix
            "AutoTokenizer:"), or a vocabulary str->int). It is None for already-tensorial data.
            *If you need to distinguish the transform applied to the inputs and to targets, you can pass a list of
            two elements like the just described ones - one for input, one for targets, respectively.
        proc_to_stream_transforms (callable or PreTrainedTokenizerBase or str or list or None): A callable tensor
            to stream format function (any callable thing, torchvision transforms, a Pretrained tokenizer (HF),
            or the model ID from which it can be downloaded, (it must have prefix "AutoTokenizer:"), or a
            vocabulary int->str). It is None for non text data.
        delta (float): Time interval between consecutive data samples (<= 0 for real-time data).
        pubsub (bool): If the stream is supposed to be sent to/received from a Pub/Sub topic.
        public (bool): If the stream is supposed to be accessed through the public net or through the private one.

    Returns:
        None
    """

    # Checking data type
    assert data_type in DataProps.VALID_DATA_TYPES, "Invalid data type"
    assert isinstance(data_desc, str), "Invalid data description"

    # Checking transformations
    assert (stream_to_proc_transforms is None or
            isinstance(stream_to_proc_transforms, str) or
            isinstance(stream_to_proc_transforms, PreTrainedTokenizerBase) or
            callable(stream_to_proc_transforms) or
            isinstance(stream_to_proc_transforms, dict) or
            isinstance(stream_to_proc_transforms, tuple) or
            isinstance(stream_to_proc_transforms, list)), \
        "Invalid stream to processor transforms"

    self.__original_stream_to_proc_transforms = None
    self.__original_proc_to_stream_transforms = None

    if stream_to_proc_transforms is not None:
        if not isinstance(stream_to_proc_transforms, list) and not isinstance(stream_to_proc_transforms, tuple):
            self.stream_to_proc_transforms = [stream_to_proc_transforms, stream_to_proc_transforms]
        else:
            assert len(stream_to_proc_transforms) == 2, \
                "Expected a list with two sets of transforms (input, target)"
            self.stream_to_proc_transforms = stream_to_proc_transforms
        self.__original_stream_to_proc_transforms = stream_to_proc_transforms
    else:
        self.stream_to_proc_transforms = None
        self.__original_stream_to_proc_transforms = None

    assert (proc_to_stream_transforms is None or
            isinstance(proc_to_stream_transforms, str) or
            isinstance(proc_to_stream_transforms, PreTrainedTokenizerBase) or
            callable(proc_to_stream_transforms) or
            isinstance(proc_to_stream_transforms, list)), \
        "Invalid stream to processor transforms"

    self.proc_to_stream_transforms = proc_to_stream_transforms
    self.__original_proc_to_stream_transforms = proc_to_stream_transforms

    # Setting data type and description
    self.data_type = data_type
    self.data_desc = data_desc

    # Setting empty attributes
    self.tensor_shape = None
    self.tensor_dtype = None
    self.tensor_labels: TensorLabels | None = None

    # Checking data in function of its type
    if self.is_tensor():

        # A shape or labels that came as another kind of sequence (in the browser, a JS array that Pyodide
        # proxies, e.g. from the profile of a peer) are taken as a list
        tensor_shape = DataProps._as_list(tensor_shape)
        tensor_labels = DataProps._as_list(tensor_labels)

        # Checking shape
        assert (tensor_shape is not None and
                isinstance(tensor_shape, (tuple, list))), f"Invalid shape for DataProps: {tensor_shape}"
        assert all(x is None or isinstance(x, int) for x in tensor_shape), \
            f"Invalid shape for DataProps: {tensor_shape}"

        # Setting shape
        self.tensor_shape = tuple(tensor_shape)  # Forcing (important)

        # Checking dtype
        assert (tensor_dtype is not None and
                (isinstance(tensor_dtype, torch.dtype) or isinstance(tensor_dtype, str)
                 and tensor_dtype.startswith("torch."))), \
            f"Invalid tensor type: {tensor_dtype}"

        # Setting dtype
        if isinstance(tensor_dtype, torch.dtype):
            self.tensor_dtype = tensor_dtype
        else:
            assert (isinstance(tensor_dtype, str) and tensor_dtype.startswith("torch.") and
                    "." not in tensor_dtype[6:])
            self.tensor_dtype = eval(tensor_dtype)
            assert isinstance(self.tensor_dtype, torch.dtype)

        # Checking labels
        assert tensor_labels is None or (isinstance(tensor_labels, list) or
                                         (isinstance(tensor_labels, str) and
                                          tensor_labels.startswith("AutoTokenizer:"))), \
            f"Invalid tensor labels: {tensor_labels}"

        # Setting labels
        if tensor_labels is not None:
            if not (isinstance(tensor_labels, str) and tensor_labels.startswith("AutoTokenizer:")):
                tensor_labels: list[str]
                self.tensor_labels = TensorLabels(self, labels=tensor_labels, labeling_rule=tensor_labeling_rule)
            else:
                self.set_tensor_labels_from_auto_tokenizer(tensor_labels.split(":")[1])

    elif self.is_img():

        # Ensuring other type-related tools are not set
        assert tensor_shape is None and tensor_labels is None and tensor_dtype is None, \
            f"Tensor-related arguments must be None when using a DataProps of type {data_type}"
        assert (self.stream_to_proc_transforms is None or (not isinstance(self.stream_to_proc_transforms, str)
                                                           and not isinstance(self.stream_to_proc_transforms,
                                                                              PreTrainedTokenizerBase))), \
            "Non-image-related transforms were selected"
        assert (self.proc_to_stream_transforms is None or (not isinstance(self.proc_to_stream_transforms, str)
                                                           and not isinstance(self.proc_to_stream_transforms,
                                                                              PreTrainedTokenizerBase)
                                                           and not isinstance(self.proc_to_stream_transforms,
                                                                              list))), \
            "Non-image-related transforms were selected"

    elif self.is_text():

        # Ensuring other type-related tools are not set
        assert tensor_shape is None and tensor_labels is None and tensor_dtype is None, \
            f"Tensor/image-related arguments must be None when using a DataProps of type {data_type}"

        # Setting text to tensor transform (tokenizer in encode mode) (if given)
        if self.stream_to_proc_transforms is not None:
            assert isinstance(self.stream_to_proc_transforms, list)
            for j, _tttt in enumerate(self.stream_to_proc_transforms):
                assert ((isinstance(_tttt, str) and _tttt.startswith("AutoTokenizer:")) or
                        isinstance(_tttt, PreTrainedTokenizerBase) or
                        isinstance(_tttt, dict) or
                        callable(_tttt)), \
                    ("Invalid text tokenizer: expected object of type PreTrainedTokenizerBase or a "
                     "string starting with 'AutoTokenizer:' or a callable object or a dictionary "
                     "(vocabulary str->int)")
                if isinstance(_tttt, str) and _tttt.startswith("AutoTokenizer:"):
                    self.stream_to_proc_transforms[j] = AutoTokenizer.from_pretrained(_tttt.split(":")[1])

        # Setting tensor to text transform (tokenizer in decode mode OR a given vocabulary int->str) (if given)
        if self.proc_to_stream_transforms is not None:
            assert ((isinstance(self.proc_to_stream_transforms, str) and
                     self.proc_to_stream_transforms.startswith("AutoTokenizer:")) or
                    isinstance(self.proc_to_stream_transforms, PreTrainedTokenizerBase) or
                    isinstance(self.proc_to_stream_transforms, list) or
                    callable(self.proc_to_stream_transforms)), \
                ("Invalid text tokenizer: expected object of type PreTrainedTokenizerBase or a "
                 "string starting with 'AutoTokenizer:' or a callable object or a dictionary "
                 "(vocabulary int->str)")
            if (isinstance(self.proc_to_stream_transforms, str) and
                    self.proc_to_stream_transforms.startswith("AutoTokenizer:")):
                self.proc_to_stream_transforms = (
                    AutoTokenizer.from_pretrained(self.proc_to_stream_transforms.split(":")[1]))

    elif self.is_file():
        # Ensuring other type-related tools are not set
        assert tensor_shape is None and tensor_labels is None and tensor_dtype is None, \
            f"Tensor-related arguments must be None when using a DataProps of type {data_type}"

        # Files usually don't use standard transforms, but we allow custom callables if needed.
        # We strictly forbid PreTrainedTokenizerBase as it makes no sense for binary files.
        assert (self.stream_to_proc_transforms is None or 
                (not isinstance(self.stream_to_proc_transforms, PreTrainedTokenizerBase) and 
                 not isinstance(self.stream_to_proc_transforms, str))), \
            "Tokenizers cannot be used as transforms for file streams"

    # Checking name and group
    assert "~" not in name, "Invalid chars in stream name"
    assert "~" not in group, "Invalid chars in group name"

    # Initialize properties
    self.name = name
    self.group = group
    self.delta = delta
    self.pubsub = pubsub
    self.public = public

The description of the data of one stream. Every Stream holds one in stream.props and every StreamType holds one or two. The node uses it in four places: (1) it checks each sample that enters a processor with check_and_preprocess and each output with check_and_postprocess, (2) it converts samples with the transforms, (3) it names the stream on the network with net_hash and user_hash and (4) it publishes to_dict() in the profile of the node so that other agents can tell whether their streams are compatible (see is_compatible).

Argument Type Default Meaning
name str "unk" The name of the stream. It must not contain ~. The agent renames unnamed processor streams proc_input_<j> and proc_output_<j>.
group str "none" A group that collects related streams, for example the image and the label of one dataset. It must not contain ~. "none" means no group. When a group is present the network channel is named after the group (see name_or_group).
data_type str "text" One of the values of VALID_DATA_TYPES: "tensor", "img", "text", "file" or "all". Any other value fails with AssertionError("Invalid data type").
data_desc str "unk" A free description. A value that is not a str fails an assertion.
tensor_shape tuple[int \| None, ...], a list of the same entries or None None Required for "tensor" and forbidden for the other types. Each entry is an int or None. A None entry accepts any size in that position. The first entry is the batch dimension. (1, 10) is one vector of 10 features and (None, 3, None, None) is a batch of RGB images of any size. A list is stored as a tuple.
tensor_dtype torch.dtype, str or None None Required for "tensor" and forbidden for the other types. A string must start with "torch." and name one attribute of torch, for example "torch.float32" or "torch.long". The string is converted to the matching dtype object.
tensor_labels list[str], str or None None Only for "tensor". A list names each component of a flat tensor (the classes of a classifier for instance) and requires a shape of two entries (batch and features). The string "AutoTokenizer:<model id>" downloads that tokenizer and uses its vocabulary in id order as labels. Any other string fails an assertion.
tensor_labeling_rule str "max" The rule that to_text uses to read a tensor as labels. "max" picks the component with the largest value and "geq<x>" (for example "geq0.5") picks every component at least equal to x. It is read only when tensor_labels is a list.
stream_to_proc_transforms callable, tokenizer, str, dict, list, tuple or None None The conversion from a stream sample to a processor input (see Transforms).
proc_to_stream_transforms callable, tokenizer, str, list or None None The conversion from a processor output to a stream sample (see Transforms).
delta float -1 The minimum time in seconds between two accepted samples of the stream. A value of zero or less means no pacing. The check is done by Stream.set.
pubsub bool False True broadcasts the stream on a channel that every subscriber reads. False sends it to one peer at a time.
public bool False True serves the stream on the public network and False on the private network of the world. StreamType chooses this value itself.

The constructor validates the arguments against the type:

  • "tensor" requires a shape and a dtype. The labels are a list or an "AutoTokenizer:..." string. A list needs a shape of length 2 (AssertionError("Data attribute labels can only be specified for 2d arrays (batch size + data features)")).
  • "img", "text" and "file" require tensor_shape, tensor_labels and tensor_dtype to be None.
  • "text" resolves every "AutoTokenizer:<model id>" transform into the tokenizer object when the description is built. Building the description therefore downloads the tokenizer.
  • "all" accepts any sample and checks nothing.

A shape or a label list that arrives as another iterable (for example an array in the profile of a peer that runs in the browser) is converted to a list before the checks.

>>> p = DataProps(name="temperature", data_type="tensor", tensor_shape=(1, 1), tensor_dtype="torch.float32",
...               delta=1.0, pubsub=True)
>>> p.to_dict()
{'name': 'temperature', 'group': 'none', 'data_type': 'tensor', 'data_desc': 'unk', 'tensor_shape': (1, 1),
 'tensor_dtype': 'torch.float32', 'tensor_labels': None, 'delta': 1.0, 'pubsub': True, 'public': False}

str(p) is str(p.to_dict()).

Transforms

A stream carries data in a form that can be sent over the network (a string, an image). A processor works on tensors. The two transform arguments convert between the two forms.

stream_to_proc_transforms turns a sample into a processor input. It accepts:

  1. A callable such as a torchvision pipeline or a lambda.
  2. A tokenizer of Hugging Face (PreTrainedTokenizerBase) or the string "AutoTokenizer:<model id>" that downloads one (text streams only).
  3. A dict vocabulary from str to int.
  4. A list or tuple of exactly two of the above. The first converts the inputs and the second the targets of learning (targets=True in check_and_preprocess).

A single transform t is stored as [t, t] and serves both inputs and targets. A list or tuple of another length fails with AssertionError("Expected a list with two sets of transforms (input, target)").

proc_to_stream_transforms turns a processor output into a sample. It accepts a callable, a tokenizer, the string "AutoTokenizer:<model id>" (resolved for text streams) or a list that maps ids to strings (a vocabulary). A dict fails the assertion although the assertion message lists it among the accepted types.

Three behaviors of the current version matter when choosing a transform:

  • A dict vocabulary looks up the whole sample string as one key. "the cat" is not split into words. A string that is not a key gets the id len(vocabulary).
  • The checks that refuse a tokenizer on "img" and "file" streams never fire for stream_to_proc_transforms because the transform is already wrapped in the list [t, t] when they run. DataProps(data_type="img", stream_to_proc_transforms="AutoTokenizer:gpt2") is accepted and keeps the string.
  • to_text calls a list vocabulary of a text stream as a function and raises TypeError: 'list' object is not callable. check_and_postprocess handles the same list correctly.

Ready-made image pipelines come from transforms_factory in unaiverse.modules.utils. The function returns a torchvision.transforms.Compose:

Name Pipeline
"rgb<N>", "gray<N>" Convert to RGB or to one gray channel, resize and center-crop to N pixels, convert to a float tensor in [0, 1] and normalize (ImageNet statistics for RGB, mean 0.45 and std 0.225 for gray). "rgb224" fits most ImageNet models.
"rgb-no_norm<N>", "gray-no_norm<N>" Resize and center-crop to N pixels into a uint8 tensor in [0, 255] with no normalization.
"rgb", "gray" The full image, normalized.
"rgb-no_norm", "gray-no_norm" The full image as a uint8 tensor.
"gray_mnist" One gray channel of 28 by 28 pixels normalized with the MNIST statistics (mean 0.1307 and std 0.3081).

transforms_factory(trans_type, add_batch_dim=True, return_inverse=False) appends a step that adds the batch dimension when add_batch_dim is True. With it "rgb224" produces a (1, 3, 224, 224) tensor. With return_inverse=True it returns the inverse pipeline. That pipeline removes the batch dimension, undoes the normalization and returns a PIL.Image.Image. It is therefore the natural proc_to_stream_transforms of an image output. Although the docstring of the function says that an unknown name returns None, the function raises ValueError.

VALID_DATA_TYPES class-attribute instance-attribute

VALID_DATA_TYPES = ('tensor', 'img', 'text', 'file', 'all')

The tuple ('tensor', 'img', 'text', 'file', 'all') of the accepted values of data_type. The samples of the five types are respectively a torch.Tensor, a PIL.Image.Image, a str, a FileContainer and any object. The docstring of the class mentions a type 'tensor_token_id' that does not exist.

to_dict

to_dict() -> dict
Source code in unaiverse/streams/dataprops.py
def to_dict(self) -> dict:
    """Serializes the `DataProps` object into a dictionary, making it suitable for transmission or storage.
    It converts complex types like `torch.dtype` and `TensorLabels` into simple, serializable formats.

    Returns:
        A dictionary representation of the object's properties.
    """
    return {
        'name': self.name,
        'group': self.group,
        'data_type': self.data_type,
        'data_desc': self.data_desc,
        'tensor_shape': self.tensor_shape,
        'tensor_dtype': str(self.tensor_dtype) if self.tensor_dtype is not None else None,
        'tensor_labels': self.tensor_labels.to_dict() if self.tensor_labels is not None else None,
        'delta': self.delta,
        'pubsub': self.pubsub,
        'public': self.public
    }

Returns the description as a plain dictionary that can travel in the profile of a node. The keys are name, group, data_type, data_desc, tensor_shape (a tuple or None), tensor_dtype (a string such as "torch.float32" or None), tensor_labels (the dictionary of TensorLabels.to_dict or None), delta, pubsub and public. The transforms are not included because they are code and the profile carries only data.

from_dict staticmethod

from_dict(d_props: dict) -> DataProps
Source code in unaiverse/streams/dataprops.py
@staticmethod
def from_dict(d_props: dict) -> 'DataProps':
    """A static method that deserializes a dictionary into a `DataProps` object.

    Args:
        d_props: The dictionary containing the object's properties.

    Returns:
        A new `DataProps` object.
    """
    d_labels = d_props['tensor_labels']
    return DataProps(name=d_props['name'],
                     group=d_props['group'],
                     data_type=d_props['data_type'],
                     data_desc=d_props['data_desc'],
                     tensor_shape=d_props['tensor_shape'],
                     tensor_dtype=d_props['tensor_dtype'],
                     tensor_labels=d_labels['labels'] if d_labels is not None else None,
                     tensor_labeling_rule=d_labels['labeling_rule'] if d_labels is not None else "max",
                     delta=d_props['delta'],
                     pubsub=d_props['pubsub'],
                     public=d_props['public'])

A static method that rebuilds a DataProps from the dictionary of to_dict. Every key of to_dict must be present (KeyError otherwise). The labels and the original labeling rule come from the nested tensor_labels dictionary. The result has no transforms. The node calls it on the stream descriptions found in the profile of another peer.

clone

clone() -> DataProps
Source code in unaiverse/streams/dataprops.py
def clone(self) -> 'DataProps':
    """Creates and returns a deep copy of the `DataProps` instance.
    It preserves the original transformation objects rather than re-evaluating them.

    Returns:
        A new `DataProps` object that is a clone of the original.
    """
    return DataProps(name=self.name,
                     group=self.group,
                     data_type=self.data_type,
                     data_desc=self.data_desc,
                     tensor_shape=self.tensor_shape,
                     tensor_dtype=self.tensor_dtype,
                     tensor_labels=list(self.tensor_labels.labels)
                     if self.tensor_labels is not None and self.tensor_labels.labels is not None else None,
                     tensor_labeling_rule=self.tensor_labels.original_labeling_rule
                     if self.tensor_labels is not None else "max",
                     stream_to_proc_transforms=self.__original_stream_to_proc_transforms,
                     proc_to_stream_transforms=self.__original_proc_to_stream_transforms,
                     delta=self.delta,
                     pubsub=self.pubsub,
                     public=self.public)

Returns a new DataProps with the same arguments. The labels are copied into a new list and the transforms are the ones originally given to the constructor (or to the set_*_transforms methods). A tokenizer string is therefore resolved again. The clone does not carry over the changes made by interleave_with. It gets the current label list and no indices.

get_name

get_name() -> str
Source code in unaiverse/streams/dataprops.py
def get_name(self) -> str:
    """Retrieves the name of the data stream.

    Returns:
        A string representing the stream's name.
    """

    return self.name

Returns name (str).

get_group

get_group() -> str
Source code in unaiverse/streams/dataprops.py
def get_group(self) -> str:
    """Retrieves the name of the group to which the data stream belongs.

    Returns:
        A string representing the group name.
    """

    return self.group

Returns group (str). "none" means that the stream belongs to no group.

get_description

get_description() -> str
Source code in unaiverse/streams/dataprops.py
def get_description(self) -> str:
    """Retrieves the description of the data.

    Returns:
        A string with the data description.
    """
    return self.data_desc

Returns data_desc (str).

get_tensor_labels

get_tensor_labels() -> list[str] | None
Source code in unaiverse/streams/dataprops.py
def get_tensor_labels(self) -> list[str] | None:
    """Retrieves the list of tensor labels, if they exist.

    Returns:
        A list of strings or None.
    """
    return self.tensor_labels.labels if self.tensor_labels is not None else None

Returns the list of labels of a tensor stream. It returns None when the stream has no labels.

set_name

set_name(name: str) -> None
Source code in unaiverse/streams/dataprops.py
def set_name(self, name: str) -> None:
    """Sets a new name for the stream, with a check for invalid characters.

    Args:
        name: The new name as a string.
    """
    assert "~" not in name, "Invalid chars in stream name"
    self.name = name

Replaces name. A name that contains ~ fails with AssertionError("Invalid chars in stream name"). The character ~ is reserved for the net hashes of direct channels (see normalize_net_hash).

set_group

set_group(group: str) -> None
Source code in unaiverse/streams/dataprops.py
def set_group(self, group: str) -> None:
    """Sets a new group name for the stream, with a check for invalid characters.

    Args:
        group: The new group name as a string.
    """
    assert "~" not in group, "Invalid chars in group name"
    self.group = group

Replaces group. A group that contains ~ fails with AssertionError("Invalid chars in group name").

set_description

set_description(desc: str) -> None
Source code in unaiverse/streams/dataprops.py
def set_description(self, desc: str) -> None:
    """Sets a new description for the data.

    Args:
        desc: The new description as a string.
    """
    self.data_desc = desc

Replaces data_desc with desc. The value is not checked.

set_public

set_public(public: bool) -> None
Source code in unaiverse/streams/dataprops.py
def set_public(self, public: bool) -> None:
    """Sets whether the stream is public or not.

    Args:
        public: A boolean value.
    """
    self.public = public

Replaces public with the given bool. It changes only the description and a stream that the node already serves keeps its channel.

set_pubsub

set_pubsub(pubsub: bool) -> None
Source code in unaiverse/streams/dataprops.py
def set_pubsub(self, pubsub: bool) -> None:
    """Sets whether the stream uses Pub/Sub or direct messaging.

    Args:
        pubsub: A boolean value.
    """
    self.pubsub = pubsub

Replaces pubsub with the given bool. As with set_public, a stream that the node already serves keeps its channel.

set_delta

set_delta(delta: float) -> None
Source code in unaiverse/streams/dataprops.py
def set_delta(self, delta: float) -> None:
    """Sets a new delta (offset between two consecutive 'set'-like operations) for the stream.

    Args:
        delta: The new delta (float).
    """
    self.delta = delta

Replaces delta, the minimum time in seconds between two accepted samples. A value of zero or less disables the pacing.

set_stream_to_proc_transforms

set_stream_to_proc_transforms(t)
Source code in unaiverse/streams/dataprops.py
def set_stream_to_proc_transforms(self, t):
    self.stream_to_proc_transforms = t
    self.__original_stream_to_proc_transforms = t

Replaces stream_to_proc_transforms with t and remembers t for clone. Unlike the constructor, it validates nothing, does not wrap a single transform into [t, t] and does not resolve an "AutoTokenizer:..." string. Pass a list of two transforms because check_and_preprocess indexes the stored value with 0 or 1. The image models of unaiverse.modules.networks call it on their descriptions with pipelines such as transforms_factory("gray_mnist").

set_proc_to_stream_transforms

set_proc_to_stream_transforms(t)
Source code in unaiverse/streams/dataprops.py
def set_proc_to_stream_transforms(self, t):
    self.proc_to_stream_transforms = t
    self.__original_proc_to_stream_transforms = t

Replaces proc_to_stream_transforms with t and remembers t for clone. Nothing is validated or resolved.

is_tensor

is_tensor() -> bool
Source code in unaiverse/streams/dataprops.py
def is_tensor(self) -> bool:
    """Checks if the data type is 'tensor'.

    Returns:
        True if the type is 'tensor', False otherwise.
    """
    return self.data_type == "tensor"

True when data_type is "tensor".

is_img

is_img() -> bool
Source code in unaiverse/streams/dataprops.py
def is_img(self) -> bool:
    """Checks if the data type is 'img'.

    Returns:
        True if the type is 'img', False otherwise.
    """
    return self.data_type == "img"

True when data_type is "img".

is_text

is_text() -> bool
Source code in unaiverse/streams/dataprops.py
def is_text(self) -> bool:
    """Checks if the data type is 'text'.

    Returns:
        True if the type is 'text', False otherwise.
    """
    return self.data_type == "text"

True when data_type is "text".

is_file

is_file() -> bool
Source code in unaiverse/streams/dataprops.py
def is_file(self) -> bool:
    """Checks if the data type is 'file'.

    Returns:
        True if the type is 'file', False otherwise.
    """
    return self.data_type == "file"

True when data_type is "file".

is_tensor_long

is_tensor_long() -> bool
Source code in unaiverse/streams/dataprops.py
def is_tensor_long(self) -> bool:
    """Checks if the tensor's data type is `torch.long`.

    Returns:
        True if the dtype is `torch.long`, False otherwise.
    """
    return self.tensor_dtype == torch.long if self.tensor_dtype is not None else False

True when tensor_dtype is torch.long (torch.int64). False for a stream without a dtype.

is_tensor_float

is_tensor_float() -> bool
Source code in unaiverse/streams/dataprops.py
def is_tensor_float(self) -> bool:
    """Checks if the tensor's data type is a float type (e.g., `torch.float32`).

    Returns:
        True if the dtype is a float type, False otherwise.
    """
    return str(self.tensor_dtype).startswith("torch.float") if self.tensor_dtype is not None else False

True when the string of tensor_dtype starts with "torch.float" (torch.float16, torch.float32, torch.float64). torch.half prints as torch.float16 and counts as float. torch.bfloat16 does not.

is_tensor_img

is_tensor_img() -> bool
Source code in unaiverse/streams/dataprops.py
def is_tensor_img(self) -> bool:
    """Checks if the tensor's shape corresponds to a typical image format (4D, with 1 or 3 channels).

    Returns:
        True if the shape matches, False otherwise.
    """
    return len(self.tensor_shape) == 4 and (self.tensor_shape[1] == 1 or self.tensor_shape[1] == 3) \
        if self.tensor_shape is not None else False

True when the shape has four entries and the second (the channels) is 1 or 3 as in (1, 3, 224, 224). The dtype is not checked.

is_tensor_token_ids

is_tensor_token_ids() -> bool
Source code in unaiverse/streams/dataprops.py
def is_tensor_token_ids(self) -> bool:
    """Checks if the tensor represents token IDs, which is indicated by `torch.long` data type and a 2D shape
    suitable for sequences.

    Returns:
        True if it matches, False otherwise.
    """
    # noinspection PyTypeChecker
    return ((self.tensor_dtype == torch.long and
            len(self.tensor_shape) == 2 and (self.tensor_shape[1] is None or cast(int, self.tensor_shape[1]) >= 1))
        if self.tensor_shape is not None else False)  # noqa

True for a sequence of token ids. The dtype must be torch.long and the shape must have two entries whose second is None or at least 1 (for example (1, None)). to_text then reads each id as a label.

is_tensor_target_id

is_tensor_target_id() -> bool
Source code in unaiverse/streams/dataprops.py
def is_tensor_target_id(self) -> bool:
    """Checks if the tensor represents a single target ID, indicated by `torch.long` data type and a 1D shape.

    Returns:
        True if it matches, False otherwise.
    """
    return (self.tensor_dtype == torch.long and
            len(self.tensor_shape) == 1) \
        if self.tensor_shape is not None else False

True for a batch of class ids used as targets. The dtype must be torch.long and the shape must have one entry (for example (None,)).

is_all

is_all() -> bool
Source code in unaiverse/streams/dataprops.py
def is_all(self) -> bool:
    """Checks if the data type is 'all', which is a wildcard type.

    Returns:
        True if the type is 'all', False otherwise.
    """
    return self.data_type == "all"

True when data_type is "all". This type accepts any sample.

net_hash

net_hash(prefix: str) -> str
Source code in unaiverse/streams/dataprops.py
def net_hash(self, prefix: str) -> str:
    """Generates a unique network hash for the stream using a provided prefix, Pub/Sub status, and name/group.

    Args:
        prefix: The prefix, typically the peer ID.

    Returns:
        A string representing the network hash.
    """
    return DataProps.build_net_hash(prefix, self.pubsub, self.name_or_group())

Returns the net hash of the stream for the peer id prefix. The net hash is the name of the network channel that carries the samples of the stream. It is "<prefix>::ps:<name or group>" for a broadcast stream and "<prefix>::dm:<name or group>" for a stream sent to one peer at a time. The last part comes from name_or_group. Streams of one group therefore share one channel.

>>> DataProps(name="x").net_hash("PEER")
'PEER::dm:x'

user_hash

user_hash(prefix: str) -> str
Source code in unaiverse/streams/dataprops.py
def user_hash(self, prefix: str) -> str:
    """Generates a unique user hash for the stream using a provided prefix and name.

    Args:
        prefix: The prefix, typically the peer ID.

    Returns:
        A string representing the user hash.
    """
    return DataProps.build_user_hash(prefix, self.name)

Returns the user hash "<prefix>:<name>". It names the stream on the side of its owner and is unique per stream even inside a group. DataProps(name="x").user_hash("PEER") is 'PEER:x'.

peer_id_from_net_hash staticmethod

peer_id_from_net_hash(net_hash: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def peer_id_from_net_hash(net_hash: str) -> str:
    """A static method to extract the peer ID from a network hash.

    Args:
        net_hash: The network hash string.

    Returns:
        A string representing the peer ID.
    """
    return net_hash.split("::")[0]

A static method that returns the part of a net hash before the first :: (the peer id). "PEER::ps:cams" gives "PEER".

peer_id_from_user_hash staticmethod

peer_id_from_user_hash(user_hash: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def peer_id_from_user_hash(user_hash: str) -> str:
    """A static method to extract the peer ID from a user hash.

    Args:
        user_hash: The user hash string.

    Returns:
        A string representing the peer ID.
    """
    return user_hash.rsplit(":", 1)[0]

A static method that returns the part of a user hash before the last : (the peer id). "PEER:front@cams" gives "PEER".

name_or_group_from_net_hash staticmethod

name_or_group_from_net_hash(net_hash: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def name_or_group_from_net_hash(net_hash: str) -> str:
    """A static method to extract the name or group from a network hash.

    Args:
        net_hash: The network hash string.

    Returns:
        A string representing the name or group.
    """
    return net_hash.split("::ps:")[1] if DataProps.is_pubsub_from_net_hash(net_hash) else net_hash.split("::dm:")[1]

A static method that returns the part of a net hash after ::ps: or ::dm:. "PEER::ps:cams" gives "cams". A string without either marker raises IndexError.

name_from_user_hash staticmethod

name_from_user_hash(user_hash: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def name_from_user_hash(user_hash: str) -> str:
    """A static method to extract the name from a user hash.

    Args:
        user_hash: The user hash string.

    Returns:
        A string representing the name or group.
    """
    return user_hash.rsplit(":", 1)[1]

A static method that returns the part of a user hash after the last : (the stream name). "PEER:front@cams" gives "front@cams".

is_pubsub_from_net_hash staticmethod

is_pubsub_from_net_hash(net_hash: str) -> bool
Source code in unaiverse/streams/dataprops.py
@staticmethod
def is_pubsub_from_net_hash(net_hash: str) -> bool:
    """A static method to check if a network hash belongs to a Pub/Sub stream.

    Args:
        net_hash: The network hash string.

    Returns:
        True if the hash is for a Pub/Sub stream, False otherwise.
    """
    return "::ps:" in net_hash

A static method that returns True when the net hash contains ::ps: (the mark of a broadcast channel).

name_or_group

name_or_group() -> str
Source code in unaiverse/streams/dataprops.py
def name_or_group(self) -> str:
    """Retrieves the group name if it's set, otherwise defaults to the stream name.

    Returns:
        A string representing the name or group.
    """
    group = self.get_group()
    return group if group != 'none' else self.get_name()

Returns the group when it is not "none" and the name otherwise. This is the last part of the net hash.

build_net_hash staticmethod

build_net_hash(prefix: str, pubsub: bool, name_or_group: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def build_net_hash(prefix: str, pubsub: bool, name_or_group: str) -> str:
    """A static method to construct a complete network hash from a prefix, Pub/Sub status, and name/group.

    Args:
        prefix: The peer ID prefix.
        pubsub: The Pub/Sub status.
        name_or_group: The name or group of the stream.

    Returns:
        The constructed network hash string.
    """
    if pubsub:
        return f"{prefix}::ps:{name_or_group}"
    else:
        return f"{prefix}::dm:{name_or_group}"

A static method that builds "<prefix>::ps:<name_or_group>" when pubsub is True and "<prefix>::dm:<name_or_group>" otherwise. net_hash calls it.

build_user_hash staticmethod

build_user_hash(prefix: str, name: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def build_user_hash(prefix: str, name: str) -> str:
    """A static method to construct a complete user hash from a prefix and name.

    Args:
        prefix: The peer ID prefix.
        name: The name of the stream.

    Returns:
        The constructed user hash string.
    """
    return f"{prefix}:{name}"

A static method that builds "<prefix>:<name>". user_hash calls it.

user_hash_from_net_hash staticmethod

user_hash_from_net_hash(net_hash: str, name: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def user_hash_from_net_hash(net_hash: str, name: str) -> str:
    """Generates a unique user hash for the stream using a provided network hash

    Args:
        net_hash: The network hash.
        name: Stream name.

    Returns:
        A string representing the user hash.
    """
    prefix = DataProps.peer_id_from_net_hash(net_hash)
    return DataProps.build_user_hash(prefix, name)

A static method that combines the peer id of net_hash with name into a user hash. ("PEER::ps:cams", "front@cams") gives "PEER:front@cams".

normalize_net_hash staticmethod

normalize_net_hash(not_normalized_net_hash: str) -> str
Source code in unaiverse/streams/dataprops.py
@staticmethod
def normalize_net_hash(not_normalized_net_hash: str) -> str:
    """A static method that cleans up or normalizes a network hash string to a canonical format, particularly
    for direct messages.

    Args:
        not_normalized_net_hash: The network hash to normalize.

    Returns:
        The normalized network hash string.
    """
    if not DataProps.is_pubsub_from_net_hash(not_normalized_net_hash):
        if "~" in not_normalized_net_hash:
            return not_normalized_net_hash.split("::dm:")[0] + "::dm:" + not_normalized_net_hash.split("~")[1]
        else:
            parts = not_normalized_net_hash.split("::dm:")
            return parts[0] + "::dm:" + parts[1].split("-")[1]
    else:
        return not_normalized_net_hash

A static method that the node applies to the net hashes of direct channels. The last part of such a hash can start with a prefix added by the connection. A broadcast hash is returned unchanged. For a direct hash that contains ~ the method keeps what follows the ~. Otherwise it keeps the part of the name after the first -:

>>> DataProps.normalize_net_hash("PEER::dm:abc~feat")
'PEER::dm:feat'
>>> DataProps.normalize_net_hash("PEER::dm:abc-feat")
'PEER::dm:feat'

The second form keeps only the text between the first and the second -. "PEER::dm:abc-my-feat" therefore gives "PEER::dm:my". A direct hash with neither ~ nor - raises IndexError.

is_pubsub

is_pubsub() -> bool
Source code in unaiverse/streams/dataprops.py
def is_pubsub(self) -> bool:
    """Checks if the stream is set to use Pub/Sub.

    Returns:
        True if it's a Pub/Sub stream, False otherwise.
    """
    return self.pubsub

Returns pubsub.

is_public

is_public() -> bool
Source code in unaiverse/streams/dataprops.py
def is_public(self) -> bool:
    """Checks if the stream is set to be public.

    Returns:
        True if it's a public stream, False otherwise.
    """
    return self.public

Returns public.

set_tensor_labels_from_auto_tokenizer

set_tensor_labels_from_auto_tokenizer(model_id: str) -> None
Source code in unaiverse/streams/dataprops.py
def set_tensor_labels_from_auto_tokenizer(self, model_id: str) -> None:
    """Initializes and sets the tensor labels by fetching the vocabulary from a Hugging Face `AutoTokenizer`
    model ID.

    Args:
        model_id: The ID of the tokenizer model.
    """
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    vocab_size = len(tokenizer.vocab)
    reverse_vocab_list: list = [None] * vocab_size
    for i in range(vocab_size):
        reverse_vocab_list[i] = tokenizer.convert_ids_to_tokens(i)
    self.set_tensor_labels(reverse_vocab_list)

Downloads the tokenizer model_id with AutoTokenizer.from_pretrained and replaces the labels with its vocabulary in id order (label i is the token with id i). The labeling rule becomes "max". The constructor calls it for tensor_labels="AutoTokenizer:<model id>" and ignores tensor_labeling_rule in that case. The stream must be a tensor stream with a shape of two entries.

set_tensor_labels

set_tensor_labels(labels: list[str] | None, labeling_rule: str = 'max')
Source code in unaiverse/streams/dataprops.py
def set_tensor_labels(self, labels: list[str] | None, labeling_rule: str = "max"):
    """Sets the labels for the data.

    Args:
        labels (list[str] or None): List of labels to associate with the data.
        labeling_rule (str): The labeling rule for the labels.

    Returns:
        None
    """
    self.tensor_labels = TensorLabels(self, labels=labels, labeling_rule=labeling_rule)

Replaces the labels with a new TensorLabels built from labels (list[str] or None) and labeling_rule ("max" by default). The checks of TensorLabels apply. The stream must be a tensor stream and a non-empty list needs a shape of two entries.

adapt_tensor_to_tensor_labels

adapt_tensor_to_tensor_labels(data)
Source code in unaiverse/streams/dataprops.py
def adapt_tensor_to_tensor_labels(self, data):
    """Interleaves data in function of its corresponding labels and the current super-set labels.

    Args:
        data: The data tensor to interleave.

    Returns:
        The interleaved data tensor (or the data as it was, if not a tensor).
    """
    if self.is_tensor():
        num_labels = len(self.tensor_labels) if self.tensor_labels is not None else 0
        if self.tensor_labels is not None and data.shape[1] < num_labels and self.tensor_labels.indices is not None:
            data_padded = torch.zeros((data.shape[0], num_labels), device=data.device, dtype=data.dtype)
            data_padded[:, self.tensor_labels.indices] = data
            return data_padded
        else:
            return data  # Do nothing
    else:
        return data  # Do nothing

Expands a tensor to a larger label set after TensorLabels.interleave_with has mapped the labels of this stream into a superset. When the stream is a tensor stream with labels and indices and the second dimension of data is smaller than the number of labels, the method returns a zero tensor of shape (batch, number of labels) and copies the columns of data into the columns given by the indices. In every other case it returns data unchanged. Stream.set calls it on every sample.

>>> p = DataProps(data_type="tensor", tensor_shape=(1, 2), tensor_dtype=torch.float32, tensor_labels=["b", "a"])
>>> p.tensor_labels.interleave_with(["a", "c", "b"])
>>> p.adapt_tensor_to_tensor_labels(torch.tensor([[0.3, 0.7]]))
tensor([[0.7000, 0.0000, 0.3000]])

clear_label_adaptation

clear_label_adaptation(data: Tensor)
Source code in unaiverse/streams/dataprops.py
def clear_label_adaptation(self, data: torch.Tensor):
    """Removes the padding and returns the original data from an adapted tensor.

    Args:
        data: The adapted tensor.

    Returns:
        The original, un-padded tensor.
    """
    return data[:, self.tensor_labels.indices] \
        if self.tensor_labels is not None and self.tensor_labels.indices is not None else data

The inverse of adapt_tensor_to_tensor_labels. It returns data[:, indices] when the labels carry indices and data otherwise. On the example above it gives back tensor([[0.3000, 0.7000]]).

is_flat_tensor_with_labels

is_flat_tensor_with_labels() -> bool
Source code in unaiverse/streams/dataprops.py
def is_flat_tensor_with_labels(self) -> bool:
    """Checks if the tensor is a 2D array and has labels, which is a common structure for general feature data.

    Returns:
        True if it is, False otherwise.
    """
    return (self.is_tensor() and self.tensor_shape is not None and len(self.tensor_shape) == 2 and
            self.has_tensor_labels())

True for a tensor stream with a shape of two entries and at least one label. A stream of token ids with labels counts too (a (1, None) shape with a vocabulary). Stream.create and BufferedStream.set use it to decide whether a sample has a text form.

has_tensor_labels

has_tensor_labels() -> bool
Source code in unaiverse/streams/dataprops.py
def has_tensor_labels(self) -> bool:
    """Checks if any tensor labels are associated with the stream.

    Returns:
        True if labels exist, False otherwise.
    """
    return self.tensor_labels is not None and len(self.tensor_labels) > 0

True when the description has a non-empty label set.

to_text

to_text(data: Tensor | Image | str, ignore_raw_tensors: bool = False)
Source code in unaiverse/streams/dataprops.py
def to_text(self, data: torch.Tensor | Image.Image | str, ignore_raw_tensors: bool = False):
    """Converts the tensor data into a text-based representation exploiting the given labels and the labeling rule.

    Args:
        data (torch.Tensor or Image.Image or str): The data to convert into text (if a string, then pass-through).
        ignore_raw_tensors (bool): Default False. If True, only tensor with labels will be considered.

    Returns:
        str or None: The corresponding text representation of the data.

    Raises:
        ValueError: If the data type is not supported for conversion.
    """
    if isinstance(data, str):
        return data
    elif not isinstance(data, torch.Tensor):
        return '<non-tensor and non-text>' if data is not None else None

    if self.is_tensor():
        if not self.has_tensor_labels():
            if ignore_raw_tensors:
                return None
            str_rep = f"{'x'.join(map(str, data.shape))} tensor ({data.dtype})\n{data.detach().cpu().numpy()}"
            if len(str_rep) > 110:
                str_rep = str_rep[0:(110-3)] + "..."
            return str_rep

        if len(data.shape) > 2:  # Can only print 1d data (recall that 1d data has 2 dimensions, due to batch size)
            return None

        if data.shape[0] != 1:
            return None  # Code designed for a batch of only 1 element

        if self.is_tensor_token_ids():
            if self.tensor_labels is None:
                return None

            # This is the case in which we assume to have a vector of token IDs
            text = ""
            for i in range(0, data.shape[1]):
                if i > 0:
                    text += " "
                text += self.tensor_labels[int(data[0][i].item())]
            return text

        elif self.is_tensor_float():
            if self.tensor_labels is None:
                return None

            # This is the generic case of a 1d tensor
            if self.tensor_labels.labeling_rule == "max":
                j = torch.argmax(data, dim=1)
                return self.tensor_labels[int(j.item())]
            elif self.tensor_labels.labeling_rule == "geq":

                # Warning: does not work for mini-batches
                jj = torch.where(data >= self.tensor_labels.labeling_rule_thres)[1]
                return ", ".join(self.tensor_labels[j] for j in jj.tolist())
            else:
                return None
        return None

    elif self.is_text():
        if self.proc_to_stream_transforms is None:
            return None
        if isinstance(self.proc_to_stream_transforms, PreTrainedTokenizerBase):
            return self.proc_to_stream_transforms.decode(data[0])
        elif isinstance(self.proc_to_stream_transforms, dict):
            if data.dtype != torch.long:

                # This is the case of probabilities
                j = torch.argmax(data, dim=1)  # Warning: does not work for mini-batches
                return self.proc_to_stream_transforms[j.item()]
            else:

                # This is the case in which we assume to have a vector of token IDs
                text = ""
                for i in range(0, data.shape[1]):
                    if i > 0:
                        text += " "
                    text += self.proc_to_stream_transforms[data[0][i].item()]
                return text
        else:
            return self.proc_to_stream_transforms(data)
    else:
        return None

Returns a readable text for one sample. The logs, the text buffer of a BufferedStream and the agent (when it shows data to a person) use it.

Argument Type Default Meaning
data torch.Tensor, PIL.Image.Image, str or None The sample.
ignore_raw_tensors bool False True returns None for a tensor stream without labels instead of printing the tensor.

The result depends on the sample and on the stream:

  1. A str is returned as it is and None gives None. Any other object that is not a tensor gives '<non-tensor and non-text>'.
  2. On a tensor stream without labels, the result is the shape, the dtype and the values truncated to 110 characters and ending with ...: '1x3 tensor (torch.float32)\n[[1. 2. 3.]]'.
  3. On a tensor stream with labels the method reads only a two-dimensional tensor with one row and returns None for any other shape. Token ids are joined with spaces (tensor([[0, 1, 2]]) with labels ["the", "cat", "sat"] gives 'the cat sat'). A float tensor with rule "max" gives the label of the largest value and with rule "geq<x>" the labels of the values at least x joined by ", ". Other dtypes give None.
  4. On a text stream the tensor is decoded with proc_to_stream_transforms. A tokenizer decodes the first row and a callable is called on the tensor. Without a transform the result is None.
  5. Images and files give None.
>>> p = DataProps(data_type="tensor", tensor_shape=(1, 3), tensor_dtype=torch.float32,
...               tensor_labels=["a", "b", "c"], tensor_labeling_rule="geq0.5")
>>> p.to_text(torch.tensor([[0.7, 0.1, 0.6]]))
'a, c'

Two inputs raise errors in the current version. The rule "geq" without a number leaves the threshold at None and the comparison raises TypeError. A list vocabulary of a text stream is called as a function and raises TypeError (see Transforms).

check_and_preprocess

check_and_preprocess(data: str | Image | Tensor | None, allow_class_ids: bool = False, targets: bool = False, device: device = device('cpu'))
Source code in unaiverse/streams/dataprops.py
def check_and_preprocess(self, data: str | Image.Image | torch.Tensor | None,
                         allow_class_ids: bool = False, targets: bool = False,
                         device: torch.device = torch.device("cpu")):
    """Prepares incoming data for a processor by validating its type and applying necessary transformations.
    It handles different data types, including tensors, text (strings), and images, raising `ValueError` if
    the data type is unexpected or incompatible with the stream's properties. For text and images, it can apply a
    pre-configured transformation (like a tokenizer or a standard image transform) to convert the data into a
    tensor format suitable for processing. For tensors, it performs validation on shape and data type.

    Args:
        data: The data sample to check and preprocess.
        allow_class_ids: A boolean to allow single-element long tensors, typically for class IDs.
        targets: A boolean to indicate if the data is a target (used to select the correct transformation in a
            dual-transform setup).
        device: The PyTorch device (e.g., 'cpu' or 'cuda') to which the tensor should be moved.

    Returns:
        The preprocessed data, typically a tensor on the specified device.
    """
    if data is None:
        return data

    if self.is_tensor():
        if isinstance(data, torch.Tensor):

            # Skipping all checks, it is enough to know it is a tensor
            if allow_class_ids and data.dtype == torch.long and len(data.shape) == 1:
                return data.to(device)

            # Checking dtype
            if self.tensor_dtype != data.dtype:
                raise ValueError(f"Expected data of type {self.tensor_dtype}, got {data.dtype} ("
                                 f"shape {data.shape})")

            # Checking shape
            if self.tensor_shape is None or len(self.tensor_shape) != len(data.shape):
                raise ValueError(f"Expected data with shape {self.tensor_shape}, got {data.shape}")
            for i, s in enumerate(self.tensor_shape):
                if s is not None:
                    if s != data.shape[i]:
                        raise ValueError(f"Expected data with shape {self.tensor_shape}, got {data.shape}")

            # Checking labels
            if self.has_tensor_labels():
                assert self.tensor_labels is not None
                if data.ndim != 2:
                    raise ValueError("Only 2d tensors are expected for "
                                     "labeled attributes (1st dimension is batch dim)")
                if not (self.is_tensor_token_ids() or data.shape[1] == len(self.tensor_labels)):
                    raise ValueError(f"Expected data with {len(self.tensor_labels)} "
                                     f"components (ignoring the 1st dimension), "
                                     f"got {data[0].numel()}")

            return data.to(device)
        else:
            raise ValueError(f"Expecting tensor data, got {type(data)}")
    elif self.is_text():
        if isinstance(data, str):
            if self.stream_to_proc_transforms is not None:
                text_to_tensor_transform = self.stream_to_proc_transforms[int(targets)]
                if text_to_tensor_transform is not None:
                    if isinstance(text_to_tensor_transform, PreTrainedTokenizerBase):
                        return text_to_tensor_transform(data, return_tensors='pt')['input_ids'].to(device)  # noqa
                    elif isinstance(text_to_tensor_transform, dict):
                        tensor = torch.tensor(
                            text_to_tensor_transform[data] if data in text_to_tensor_transform else len(
                                text_to_tensor_transform), dtype=torch.long, device=device)
                        if not targets or tensor.ndim > 1:
                            return tensor.view(1, -1)  # Warning batch size 1
                        else:
                            return tensor.view(-1)  # No batch size for targets, just a 1D vector with IDS
                    else:
                        return text_to_tensor_transform(data).to(device)  # Custom callable function
                else:
                    return data
            else:
                return data
        else:
            raise ValueError(f"Expecting text (string) data, got {type(data)}")
    elif self.is_img():
        if isinstance(data, Image.Image):
            if self.stream_to_proc_transforms is not None:
                img_to_tensor_transform = self.stream_to_proc_transforms[int(targets)]
                if img_to_tensor_transform is not None:
                    img_to_tensor_transform: Callable
                    return img_to_tensor_transform(data).to(device)
                else:
                    return data
            else:
                return data
        else:
            raise ValueError(f"Expecting image (PIL.Image) data, got {type(data)}")
    elif self.is_file():
        if isinstance(data, FileContainer):
            return data

        elif isinstance(data, str):
            return FileContainer.from_path(data)

        elif isinstance(data, bytes):
            return FileContainer(content=data, filename="raw_bytes", mime_type="application/octet-stream")

        # Fallback if FileContainer is not imported but the object looks like one (duck typing)
        elif hasattr(data, 'content') and hasattr(data, 'filename') and hasattr(data, 'mime_type'):
            return data

        else:
            raise ValueError(f"Expecting FileContainer, str (path), or bytes for file stream, got {type(data)}")
    elif self.is_all():
        return data
    else:
        raise ValueError(f"Unexpected data type, {self.data_type}")

Checks a sample that is about to enter a processor and converts it into the form that the processor expects. The agent calls it on each input before running the processor.

Argument Type Default Meaning
data str, PIL.Image.Image, torch.Tensor, FileContainer, bytes or None The sample. None is returned as it is.
allow_class_ids bool False True accepts a one-dimensional torch.long tensor (class ids) on a tensor stream without any further check.
targets bool False True uses the second transform of the pair (the one for targets).
device torch.device torch.device("cpu") The device of the returned tensor.

What happens by type:

  • tensor: a non-tensor raises ValueError. The dtype must equal tensor_dtype and the shape must have the same length as tensor_shape and match every entry that is not None (ValueError("Expected data with shape (None, 3), got torch.Size([5, 4])")). With labels the tensor must have two dimensions. Its second dimension must equal the number of labels unless the stream holds token ids. The tensor is moved to device.
  • text: a non-string raises ValueError. Without a transform the string is returned. A tokenizer returns input_ids of shape (1, length). A dict vocabulary returns the id of the whole string as a torch.long tensor of shape (1, 1) ((1,) for targets) and gives an unknown string the id len(vocabulary). A callable is called on the string and its result is moved to device.
  • img: a non-image raises ValueError. The transform, if any, is applied and its result moved to device. Without a transform the image is returned.
  • file: a FileContainer is returned, a str is taken as a path and wrapped with FileContainer.from_path, bytes become a container named "raw_bytes" and an object with content, filename and mime_type attributes is accepted as it is. Anything else raises ValueError.
  • all: the sample is returned as it is.
>>> t = DataProps(data_type="text", stream_to_proc_transforms={"hi": 0, "yo": 1})
>>> t.check_and_preprocess("yo"), t.check_and_preprocess("zz"), t.check_and_preprocess("yo", targets=True)
(tensor([[1]]), tensor([[2]]), tensor([1]))

check_and_postprocess

check_and_postprocess(data: str | Image | Tensor | None)
Source code in unaiverse/streams/dataprops.py
def check_and_postprocess(self, data: str | Image.Image | torch.Tensor | None):
    """Takes a processor's output and validates it before converting it back into a stream-compatible format.
    It handles `torch.Tensor` data, applying a `proc_to_stream_transform` (if one exists) to convert the tensor
    into an appropriate format for the stream, such as a string for text or a PIL `Image` for images. It performs
    a final check on the data's format (shape, dtype, etc.) to ensure consistency with the stream's properties.

    Args:
        data: The output from the processor, typically a tensor.

    Returns:
        The post-processed data, in a stream-compatible format (e.g., a string, image, or CPU tensor).
    """
    if data is None:
        return None

    if self.is_tensor():
        if isinstance(data, torch.Tensor):
            if self.proc_to_stream_transforms is not None:
                data = self.proc_to_stream_transforms(data)  # noqa
            data = data.cpu()

            # Checking dtype
            if self.tensor_dtype != data.dtype:
                raise ValueError(f"Expected data of type {self.tensor_dtype}, got {data.dtype}")

            # Checking shape
            assert self.tensor_shape is not None
            if len(self.tensor_shape) != len(data.shape):
                raise ValueError(f"Expected data with shape {self.tensor_shape}, got {data.shape}")
            for i, s in enumerate(self.tensor_shape):
                if s is not None:
                    if s != data.shape[i]:
                        raise ValueError(f"Expected data with shape {self.tensor_shape}, got {data.shape}")

            # Checking labels
            if self.has_tensor_labels():
                assert self.tensor_labels is not None

                if data.ndim != 2:
                    raise ValueError("Only 2d tensors are expected for "
                                     "labeled attributes (1st dimension is batch dim)")
                if not (self.is_tensor_token_ids() or data.shape[1] == len(self.tensor_labels)):
                    raise ValueError(f"Expected data with {len(self.tensor_labels)} "
                                     f"components (ignoring the 1st dimension), "
                                     f"got {data[0].numel()}")

            return data
        else:
            raise ValueError(f"Expecting tensor data, got {type(data)}")
    elif self.is_text():
        if isinstance(data, str):
            return data
        elif isinstance(data, torch.Tensor):
            data = data.cpu()
            if self.proc_to_stream_transforms is not None:
                assert data.shape[0] == 1, f"Code designed for a batch of only 1 element, got {data.shape[0]}"
                if isinstance(self.proc_to_stream_transforms, PreTrainedTokenizerBase):
                    return self.proc_to_stream_transforms.decode(data[0])  # Tokenizer
                elif isinstance(self.proc_to_stream_transforms, list):
                    if data.dtype != torch.long:

                        # This is the case of probabilities
                        j = torch.argmax(data, dim=1)  # Warning: does not work for mini-batches
                        return self.proc_to_stream_transforms[int(j.item())]
                    else:

                        # This is the case in which we assume to have a vector of token IDs
                        text = ""
                        for i in range(0, data.shape[1]):
                            if i > 0:
                                text += " "
                            text += self.proc_to_stream_transforms[int(data[0][i].item())]
                        return text
                else:
                    return self.proc_to_stream_transforms(data)  # Custom callable function
            else:
                raise ValueError(f"Cannot decode torch.Tensor to text, since text_to_tensor_inv_transform is None")
        else:
            raise ValueError(f"Expecting text (string) or tensor data, got {type(data).__name__}")
    elif self.is_img():
        if isinstance(data, Image.Image):
            return data
        elif isinstance(data, torch.Tensor):
            data = data.cpu()
            if self.proc_to_stream_transforms is not None:
                return self.proc_to_stream_transforms(data)  # noqa
            else:
                raise ValueError(f"Cannot convert a tensor to PIL.Image, since img_to_tensor_inv_transform is None")
        else:
            raise ValueError(f"Expecting image (PIL.Image) data or torch.Tensor, got {type(data).__name__}")
    elif self.is_file():
        if isinstance(data, FileContainer) or \
           (hasattr(data, 'content') and hasattr(data, 'filename') and hasattr(data, 'mime_type')):
            return data
        else:
            raise ValueError(f"Expecting FileContainer for file stream output, got {type(data)}")
    elif self.is_all():
        return data
    else:
        raise ValueError(f"Unexpected data type, {self.data_type}")

Converts the output of a processor into a sample of the stream and checks it. The agent calls it on each output before writing it on the output stream. None is returned as it is.

  • tensor: a non-tensor raises ValueError. Any output transform is applied first. The result is moved to the CPU and checked like an input (dtype, shape, labels).
  • text: a str is returned. A tensor (moved to the CPU) needs a transform (ValueError otherwise) and a batch of exactly one row (AssertionError otherwise). A tokenizer decodes the row. A list vocabulary reads a non-long tensor as scores and returns the label of the largest one. It reads a long tensor as token ids joined with spaces. A callable is called on the tensor.
  • img: an image is returned. A tensor needs a transform that produces the image and raises ValueError without one.
  • file: a FileContainer or an object with its three attributes is returned and anything else raises ValueError.
  • all: the output is returned as it is.
>>> t = DataProps(data_type="text", proc_to_stream_transforms=["hi", "yo"])
>>> t.check_and_postprocess(torch.tensor([[1, 0]])), t.check_and_postprocess(torch.tensor([[0.1, 0.9]]))
('yo hi', 'yo')

is_compatible

is_compatible(props_to_compare: DataProps) -> bool
Source code in unaiverse/streams/dataprops.py
def is_compatible(self, props_to_compare: 'DataProps') -> bool:
    """Checks if the current DataProps instance is compatible with another DataProps instance.
    Checks include data type, shape, and labels.

    Args:
        props_to_compare (DataProps): The DataProps instance to check compatibility with.

    Returns:
        bool: True if compatible, False otherwise.
    """

    # Checking data type
    if self.data_type != props_to_compare.data_type and self.data_type != "all":
        return False

    # In the case of tensors...
    if self.is_tensor():

        # Checking shape
        if (self.tensor_shape is not None and props_to_compare.tensor_shape is not None
                and len(self.tensor_shape) == len(props_to_compare.tensor_shape)):
            for s, p in zip(self.tensor_shape, props_to_compare.tensor_shape):
                if s is not None and p is not None and s != p:
                    return False
        else:
            return False

        # Checking labels (if possible)
        if (not self.has_tensor_labels()) or (not props_to_compare.has_tensor_labels()):
            return True
        else:
            return self.tensor_labels == props_to_compare.tensor_labels
    else:
        return True

Returns True when the samples described by props_to_compare fit this description. The agent uses it to match its streams with the streams of another peer. The rules are:

  1. The data types must be equal unless this description is "all". The test is not symmetric: DataProps(data_type="all").is_compatible(img) is True and img.is_compatible(all_props) is False.
  2. For tensors both shapes must exist with the same length. Each pair of entries that are both not None must be equal.
  3. When both tensor descriptions have labels, the labels must be equal in the same order (see TensorLabels). A description without labels matches any labels.

The dtype is not compared. A (None, 3) float description is therefore compatible with a (2, 3) long one. Types other than tensors are compatible as soon as rule 1 passes.

TensorLabels

TensorLabels(data_props: DataProps, labels: list[str] | None, labeling_rule: str = 'max')
Source code in unaiverse/streams/dataprops.py
def __init__(self, data_props: DataProps, labels: list[str] | None, labeling_rule: str = "max"):
    """Initializes the TensorLabels instance.

    Args:
        data_props (DataProps): The DataProps instance that owns these labels.
        labels (list[str] or None): List of labels.
        labeling_rule (str): The rule for labeling (either 'max' or 'geq-X', where -X is a number).

    Returns:
        None

    Raises:
        AssertionError: If the labels or labeling_rule are invalid.
    """
    assert data_props.is_tensor(), "Tensor labels can only be attached to tensor data properties"
    assert data_props.tensor_shape is not None
    num_labels = len(labels) if labels is not None else 0
    assert num_labels == 0 or (data_props.is_tensor() and len(data_props.tensor_shape) == 2), \
        "Data attribute labels can only be specified for 2d arrays (batch size + data features)"
    assert len(labeling_rule) >= 3 and labeling_rule[0:3] in TensorLabels.VALID_LABELING_RULES, \
        "Invalid labeling rule"
    try:
        original_labeling_rule = labeling_rule
        if len(labeling_rule) > 3:
            labeling_rule_thres = float(labeling_rule[3:])
            labeling_rule = labeling_rule[0:3]
        else:
            labeling_rule_thres = None
    except ValueError:
        assert False, "Invalid labeling rule"

    # Basic attributes
    self.data_props = data_props
    self.labels = labels
    self.labeling_rule = labeling_rule
    self.labeling_rule_thres = labeling_rule_thres
    self.original_labeling_rule = original_labeling_rule

    # These are mostly operational stuff, similar to private info (but it could be useful to expose them)
    self.num_labels = num_labels
    self.indices = None

The labels of a flat tensor stream. The class holds one name per component of the second dimension and the rule that reads a tensor as labels. A DataProps creates it from tensor_labels. A developer reads it through props.tensor_labels or props.get_tensor_labels().

Argument Type Default Meaning
data_props DataProps The owner. It must be a tensor description with a shape.
labels list[str] or None The names, in component order. A non-empty list requires a shape of two entries.
labeling_rule str "max" "max" or "geq" followed by a number. The first three characters must be one of VALID_LABELING_RULES and what follows them is parsed as a float threshold (AssertionError("Invalid labeling rule") when it is not a number).

The attributes are labels (the list), labeling_rule ("max" or "geq"), labeling_rule_thres (the float, or None), original_labeling_rule (the string as given), num_labels and indices (a torch.long tensor after interleave_with, None otherwise).

The threshold is everything after the first three characters. The docstrings write the rule as "geq-X". In the current version "geq-0.5" gives the threshold -0.5 and then every component is selected. Write "geq0.5". A number after "max" is parsed and never used.

The object behaves like a sequence. len(labels) is num_labels and iteration yields the labels (nothing when they are None). labels[i] returns one label and raises ValueError for an index outside 0 to num_labels - 1 or when there are no labels. labels[i] = "name" replaces one label, raises TypeError for a value that is not a str and clears indices. Two TensorLabels are equal (==) when they hold the same labels in the same order. The rules are not compared. str prints the labels, the rule and the indices.

VALID_LABELING_RULES class-attribute instance-attribute

VALID_LABELING_RULES = ('max', 'geq')

The tuple ('max', 'geq') of the accepted rule prefixes.

to_dict

to_dict() -> dict
Source code in unaiverse/streams/dataprops.py
def to_dict(self) -> dict:
    """Serializes the `TensorLabels` instance into a dictionary, which includes the list of labels and the original
    labeling rule.

    Returns:
        A dictionary containing the labels and the original labeling rule.
    """
    return {
        'labels': self.labels,
        'labeling_rule': self.original_labeling_rule
    }

Returns the dictionary {"labels": labels, "labeling_rule": original_labeling_rule} that DataProps.to_dict embeds.

clear_indices

clear_indices() -> None
Source code in unaiverse/streams/dataprops.py
def clear_indices(self) -> None:
    """Resets the internal `indices` attribute to `None`. This effectively clears any previous label adaptation
    that was performed and allows the object to revert to its original, non-interleaved state.
    """
    self.indices = None

Clears indices (back to None). The labels remain the superset installed by interleave_with but the tensors are no longer expanded onto it.

interleave_with

interleave_with(superset_labels: list[str]) -> None
Source code in unaiverse/streams/dataprops.py
def interleave_with(self, superset_labels: list[str]) -> None:
    """Interleaves the current labels with a super-set of labels, determining how to index them.

    Args:
        superset_labels: The super-set of labels to interleave with.

    Raises:
        AssertionError: If the super-set of labels is not compatible.
    """
    assert superset_labels is not None and self.labels is not None, \
        f"Can only interleave non-empty sets of attribute labels"
    assert len(superset_labels) >= len(self), f"You must provide a super-set of attribute labels"

    # Ensuring it is a super-set of the current labels and finding its position
    if self.indices is not None:
        labels = []
        indices_list = self.indices.tolist()
        for i in indices_list:
            labels.append(self.labels[i])
    else:
        labels = self.labels

    indices = []
    for label in labels:
        assert label in superset_labels, \
            f"Cannot find attribute label {label} in (expected) super-set {superset_labels}"
        indices.append(superset_labels.index(label))

    if len(indices) == len(superset_labels):
        same_labels_and_order = True
        for j, i in enumerate(indices):
            if j != i:
                same_labels_and_order = False
                break
    else:
        same_labels_and_order = False

    if not same_labels_and_order:
        self.labels = superset_labels
        self.num_labels = len(self.labels)
        self.indices = torch.tensor(indices, dtype=torch.long)

        # Altering shape
        assert self.data_props.tensor_shape is not None
        self.data_props.tensor_shape = (self.data_props.tensor_shape[0], self.num_labels)
    else:
        self.indices = None

Maps the labels of this stream into superset_labels, a list that contains each of them. The agent uses it when it merges streams whose classes are a subset of a larger class list. Every current label must appear in the superset and the superset must be at least as long as the labels (AssertionError otherwise). When the superset holds the same labels in the same order the method only clears indices. Otherwise it replaces labels with the superset, stores in indices the position of each original label in it and widens the shape of the owner to (shape[0], len(superset_labels)). From then on DataProps.adapt_tensor_to_tensor_labels expands each sample onto the superset. A second call starts from the original labels recovered through the indices.

>>> p = DataProps(data_type="tensor", tensor_shape=(1, 2), tensor_dtype=torch.float32, tensor_labels=["b", "a"])
>>> p.tensor_labels.interleave_with(["a", "c", "b"])
>>> p.tensor_labels.labels, p.tensor_labels.indices, p.tensor_shape
(['a', 'c', 'b'], tensor([2, 0]), (1, 3))