Skip to content

serializer ¤

Classes:

Name Description
DescriptionSerializer

Description serializer intended for client/server communication, NOT for sharing resource descriptions.

GradioSampleSerializer

Attributes:

Name Type Description
SerializedSampleBlock

SerializedSampleBlock module-attribute ¤

SerializedSampleBlock = Dict[str, JsonValue]

DescriptionSerializer ¤

Description serializer intended for client/server communication, NOT for sharing resource descriptions.

This serializer only includes local files to keep the serialized package small.

Methods:

Name Description
deserialize
deserialize_from_string
serialize
serialize_to_string
serialize_to_string_and_hash

Attributes:

Name Type Description
STRING_ENCODING

STRING_ENCODING class-attribute instance-attribute ¤

STRING_ENCODING = 'ascii'

deserialize staticmethod ¤

deserialize(serialized: bytes) -> ResourceDescr
Source code in src/bioimageio/core/_description_serializer.py
51
52
53
54
55
56
57
@staticmethod
def deserialize(serialized: bytes) -> ResourceDescr:
    descr = load_description(ZipFile(BytesIO(serialized)), perform_io_checks=False)
    if isinstance(descr, InvalidDescr):
        raise ValueError(f"invalid serialized model package: {descr.get_reason()}")

    return descr

deserialize_from_string classmethod ¤

deserialize_from_string(serialized: str) -> ResourceDescr
Source code in src/bioimageio/core/_description_serializer.py
46
47
48
49
@classmethod
def deserialize_from_string(cls, serialized: str) -> ResourceDescr:
    package_bytes = base64.b64decode(serialized.encode(cls.STRING_ENCODING))
    return cls.deserialize(package_bytes)

serialize staticmethod ¤

serialize(rd: ResourceDescr) -> bytes
Source code in src/bioimageio/core/_description_serializer.py
24
25
26
27
28
@staticmethod
def serialize(rd: ResourceDescr) -> bytes:
    stream = save_bioimageio_package_to_stream(rd, local_files_only=True)
    _ = stream.seek(0)
    return stream.read()

serialize_to_string classmethod ¤

serialize_to_string(rd: ResourceDescr) -> str
Source code in src/bioimageio/core/_description_serializer.py
30
31
32
33
34
35
36
37
38
39
40
@classmethod
def serialize_to_string(cls, rd: ResourceDescr) -> str:
    package_bytes = cls.serialize(rd)

    safe_bytes = cls._get_safe_bytes(package_bytes)
    serialized_str = safe_bytes.decode(cls.STRING_ENCODING)
    if len(serialized_str) <= 2083:
        raise RuntimeError(
            "Serialized model description should be longer than 2083 characters to not be treated as a URL on the server side."
        )
    return serialized_str

serialize_to_string_and_hash classmethod ¤

serialize_to_string_and_hash(rd: ResourceDescr) -> Tuple[str, Sha256]
Source code in src/bioimageio/core/_description_serializer.py
59
60
61
62
63
64
65
66
67
68
69
@classmethod
def serialize_to_string_and_hash(cls, rd: ResourceDescr) -> Tuple[str, Sha256]:
    package_bytes = cls.serialize(rd)
    safe_bytes = cls._get_safe_bytes(package_bytes)
    serialized_str = safe_bytes.decode(cls.STRING_ENCODING)
    if len(serialized_str) <= 2083:
        raise RuntimeError(
            "Serialized model description should be longer than 2083 characters to not be treated as a URL on the server side."
        )
    sha256 = Sha256(hashlib.sha256(package_bytes).hexdigest())
    return serialized_str, sha256

GradioSampleSerializer ¤

Bases: SampleSerializer[SerializedSampleBlock]


              flowchart TD
              bioimageio.core.remote_backends.gradio.serializer.GradioSampleSerializer[GradioSampleSerializer]
              bioimageio.core._sample_serializer.SampleSerializer[SampleSerializer]

                              bioimageio.core._sample_serializer.SampleSerializer --> bioimageio.core.remote_backends.gradio.serializer.GradioSampleSerializer
                


              click bioimageio.core.remote_backends.gradio.serializer.GradioSampleSerializer href "" "bioimageio.core.remote_backends.gradio.serializer.GradioSampleSerializer"
              click bioimageio.core._sample_serializer.SampleSerializer href "" "bioimageio.core._sample_serializer.SampleSerializer"
            

Methods:

Name Description
deserialize_sample
deserialize_sample_block

Deserialize a sample block into a new sample or merge it into output_sample if provided.

serialize_sample

Serialize a sample as a single block

serialize_sample_block
serialize_sample_blockwise

Split a sample into blocks according to the model's input specifications and blocksize_parameter and serialize each block.

serialize_sample_with_fixed_blocking

deserialize_sample classmethod ¤

deserialize_sample(serialized: Iterable[SerializedSampleBlockType], fill_value: float = float('nan')) -> Sample
Source code in src/bioimageio/core/_sample_serializer.py
29
30
31
32
33
34
35
36
37
@classmethod
def deserialize_sample(
    cls,
    serialized: Iterable[SerializedSampleBlockType],
    fill_value: float = float("nan"),
) -> Sample:
    return Sample.from_blocks(
        (cls.deserialize_sample_block(s) for s in serialized), fill_value=fill_value
    )

deserialize_sample_block staticmethod ¤

deserialize_sample_block(serialized: SerializedSampleBlock) -> SampleBlock

Deserialize a sample block into a new sample or merge it into output_sample if provided.

Source code in src/bioimageio/core/remote_backends/gradio/serializer.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@staticmethod
def deserialize_sample_block(serialized: SerializedSampleBlock) -> SampleBlock:
    deserializable_sample = _SerializableSampleBlock.model_validate(serialized)
    sample_meta = deserializable_sample.meta
    members = {
        k: Tensor.from_numpy(
            np.load(v if isinstance(v, Path) else v.path),
            dims=list(sample_meta.shape[k]),
        )
        for k, v in deserializable_sample.data.items()
    }
    return SampleBlock.from_meta(
        sample_meta,
        data=members,
        stat=load_stat(deserializable_sample.serialized_stat),
    )

serialize_sample classmethod ¤

serialize_sample(sample: Sample) -> Tuple[SerializedSampleBlockType]

Serialize a sample as a single block

Source code in src/bioimageio/core/_sample_serializer.py
21
22
23
24
25
26
27
@classmethod
def serialize_sample(
    cls,
    sample: Sample,
) -> Tuple[SerializedSampleBlockType]:
    """Serialize a sample as a single block"""
    return (cls.serialize_sample_block(sample.as_single_block()),)

serialize_sample_block staticmethod ¤

serialize_sample_block(sample_block: SampleBlock) -> SerializedSampleBlock
Source code in src/bioimageio/core/remote_backends/gradio/serializer.py
43
44
45
46
47
48
49
50
51
52
53
54
55
@staticmethod
def serialize_sample_block(sample_block: SampleBlock) -> SerializedSampleBlock:
    handled_members: Dict[MemberId, _SerializableBlock] = {}
    for m, t in sample_block.members.items():
        handled_members[m] = _SerializableBlock.from_tensor(t)

    serializable = _SerializableSampleBlock(
        data=handled_members,
        meta=sample_block.get_meta(),
        serialized_stat=serialize_stat(sample_block.stat),
    )
    serialized = serializable.model_dump(mode="json")
    return serialized

serialize_sample_blockwise ¤

serialize_sample_blockwise(sample: Sample, *, model: v0_5.ModelDescr, blocksize_parameter: int, batch_size: int = 1) -> Iterable[SerializedSampleBlockType]

Split a sample into blocks according to the model's input specifications and blocksize_parameter and serialize each block.

Source code in src/bioimageio/core/_sample_serializer.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def serialize_sample_blockwise(
    self,
    sample: Sample,
    *,
    model: v0_5.ModelDescr,
    blocksize_parameter: int,
    batch_size: int = 1,
) -> Iterable[SerializedSampleBlockType]:
    """Split a sample into blocks according to the model's input specifications and `blocksize_parameter` and serialize each block."""

    _n_blocks, blocks = split_sample_into_blocks_for_model(
        sample,
        model=model,
        blocksize_parameter=blocksize_parameter,
        batch_size=batch_size,
    )
    for block in blocks:
        yield self.serialize_sample_block(block)

serialize_sample_with_fixed_blocking classmethod ¤

serialize_sample_with_fixed_blocking(sample: Sample, *, block_shapes: PerMember[PerAxis[int]], halo: PerMember[PerAxis[HaloLike]], pad_mode: Union[PadMode, PerMember[PadMode]] = 'symmetric') -> Iterable[SerializedSampleBlockType]
Source code in src/bioimageio/core/_sample_serializer.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@classmethod
def serialize_sample_with_fixed_blocking(
    cls,
    sample: Sample,
    *,
    block_shapes: PerMember[PerAxis[int]],
    halo: PerMember[PerAxis[HaloLike]],
    pad_mode: Union[PadMode, PerMember[PadMode]] = "symmetric",
) -> Iterable[SerializedSampleBlockType]:

    _n_blocks, input_blocks = sample.split_into_blocks(
        block_shapes=block_shapes,
        halo=halo,
        pad_mode=pad_mode,
    )
    for block in input_blocks:
        yield cls.serialize_sample_block(block)