Skip to content

common ¤

Common nodes and field types of bioimage.io specifications.

Classes:

Name Description
BytesReader
FileDescr

A file description

HttpUrl

A URL with the HTTP or HTTPS scheme.

InvalidDescr

A representation of an invalid resource description

ProgressbarLike

Progressbar protocol modeled after tqdm

RelativeFilePath

A path relative to the rdf.yaml file (also if the RDF source is a URL).

RootHttpUrl

An untested HTTP URL, possibly a 'URL folder' or an invalid HTTP URL

Sha256

A SHA-256 hash value

Attributes:

Name Type Description
AbsoluteDirectory
AbsoluteFilePath
BioimageioYamlContent
BioimageioYamlSource
FileName
FilePath
FileSource
PermissiveFileSource TypeAlias
YamlValue TypeAlias
ZipPath

AbsoluteDirectory module-attribute ¤

AbsoluteDirectory = Annotated[
    pydantic.DirectoryPath,
    Predicate(Path.is_absolute),
    pydantic.Field(title="AbsoluteDirectory"),
]

AbsoluteFilePath module-attribute ¤

AbsoluteFilePath = Annotated[
    pydantic.FilePath,
    Predicate(Path.is_absolute),
    pydantic.Field(title="AbsoluteFilePath"),
]

BioimageioYamlContent module-attribute ¤

BioimageioYamlContent = Dict[str, YamlValue]

BioimageioYamlSource module-attribute ¤

BioimageioYamlSource = Union[
    PermissiveFileSource,
    ZipFile,
    BioimageioYamlContent,
    BioimageioYamlContentView,
]

FilePath module-attribute ¤

FilePath = Annotated[
    pydantic.FilePath, pydantic.Field(title="FilePath")
]

FileSource module-attribute ¤

FileSource = Annotated[
    Union[HttpUrl, RelativeFilePath, FilePath],
    Field(union_mode="left_to_right"),
]

YamlValue module-attribute ¤

YamlValue: TypeAlias = Union[
    YamlLeafValue,
    List["YamlValue"],
    Dict[YamlKey, "YamlValue"],
]

BytesReader ¤

BytesReader(
    reader: BytesReaderP | BytesReaderIntoP,
    *,
    sha256: Sha256 | None,
    suffix: Suffix,
    original_file_name: FileName,
    original_root: RootHttpUrl
    | AbsoluteDirectory
    | ZipFile,
    is_zipfile: bool | None,
)

Bases: BytesReaderP


              flowchart TD
              bioimageio.spec.common.BytesReader[BytesReader]
              bioimageio.spec._internal.io_basics.BytesReaderP[BytesReaderP]

                              bioimageio.spec._internal.io_basics.BytesReaderP --> bioimageio.spec.common.BytesReader
                


              click bioimageio.spec.common.BytesReader href "" "bioimageio.spec.common.BytesReader"
              click bioimageio.spec._internal.io_basics.BytesReaderP href "" "bioimageio.spec._internal.io_basics.BytesReaderP"
            

Methods:

Name Description
read
read_text
readable
seek
seekable
tell

Attributes:

Name Type Description
closed bool
is_zipfile bool
original_file_name FileName
original_root RootHttpUrl | AbsoluteDirectory | ZipFile
sha256 Sha256
suffix Suffix
Source code in src/bioimageio/spec/_internal/io_basics.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def __init__(
    self,
    /,
    reader: BytesReaderP | BytesReaderIntoP,
    *,
    sha256: Sha256 | None,
    suffix: Suffix,
    original_file_name: FileName,
    original_root: RootHttpUrl | AbsoluteDirectory | ZipFile,
    is_zipfile: bool | None,
) -> None:
    self._reader = reader
    self._sha256 = sha256
    self._suffix = suffix
    self._original_file_name = original_file_name
    self._original_root = original_root
    self._is_zipfile = is_zipfile
    super().__init__()

closed property ¤

closed: bool

is_zipfile property ¤

is_zipfile: bool

original_file_name property ¤

original_file_name: FileName

original_root property ¤

original_root: RootHttpUrl | AbsoluteDirectory | ZipFile

sha256 property ¤

sha256: Sha256

suffix property ¤

suffix: Suffix

read ¤

read(size: int = -1) -> bytes
Source code in src/bioimageio/spec/_internal/io_basics.py
128
129
def read(self, size: int = -1, /) -> bytes:
    return self._reader.read(size)

read_text ¤

read_text(encoding: str = 'utf-8') -> str
Source code in src/bioimageio/spec/_internal/io_basics.py
131
132
def read_text(self, encoding: str = "utf-8") -> str:
    return self._reader.read().decode(encoding)

readable ¤

readable() -> bool
Source code in src/bioimageio/spec/_internal/io_basics.py
134
135
def readable(self) -> bool:
    return True

seek ¤

seek(offset: int, whence: int = os.SEEK_SET) -> int
Source code in src/bioimageio/spec/_internal/io_basics.py
137
138
def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int:
    return self._reader.seek(offset, whence)

seekable ¤

seekable() -> bool
Source code in src/bioimageio/spec/_internal/io_basics.py
140
141
def seekable(self) -> bool:
    return True

tell ¤

tell() -> int
Source code in src/bioimageio/spec/_internal/io_basics.py
143
144
def tell(self) -> int:
    return self._reader.tell()

FileDescr pydantic-model ¤

Bases: Node

A file description

Show JSON schema:
{
  "$defs": {
    "RelativeFilePath": {
      "description": "A path relative to the `rdf.yaml` file (also if the RDF source is a URL).",
      "format": "path",
      "title": "RelativeFilePath",
      "type": "string"
    }
  },
  "additionalProperties": false,
  "description": "A file description",
  "properties": {
    "source": {
      "anyOf": [
        {
          "description": "A URL with the HTTP or HTTPS scheme.",
          "format": "uri",
          "maxLength": 2083,
          "minLength": 1,
          "title": "HttpUrl",
          "type": "string"
        },
        {
          "$ref": "#/$defs/RelativeFilePath"
        },
        {
          "format": "file-path",
          "title": "FilePath",
          "type": "string"
        }
      ],
      "description": "File source",
      "title": "Source"
    },
    "sha256": {
      "anyOf": [
        {
          "description": "A SHA-256 hash value",
          "maxLength": 64,
          "minLength": 64,
          "title": "Sha256",
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "SHA256 hash value of the **source** file.",
      "title": "Sha256"
    }
  },
  "required": [
    "source"
  ],
  "title": "_internal.io.FileDescr",
  "type": "object"
}

Fields:

Validators:

  • _validate_sha256

sha256 pydantic-field ¤

sha256: Sha256 | None = None

SHA256 hash value of the source file.

source pydantic-field ¤

source: FileSource

File source

suffix property ¤

suffix: str

dict_from_kwargs classmethod ¤

dict_from_kwargs(
    *args: P.args, **kwargs: P.kwargs
) -> dict[str, Any]
Source code in src/bioimageio/spec/_internal/node.py
93
94
95
96
97
98
@classmethod
def dict_from_kwargs(
    cls: Callable[P, T], *args: P.args, **kwargs: P.kwargs
) -> dict[str, Any]:
    assert not args, "Did not expected any args"
    return dict(kwargs)

download ¤

download(
    *,
    progressbar: ProgressbarLike
    | Callable[[], ProgressbarLike]
    | bool
    | None = None,
)

alias for .get_reader

Source code in src/bioimageio/spec/_internal/io.py
317
318
319
320
321
322
323
324
325
326
def download(
    self,
    *,
    progressbar: ProgressbarLike
    | Callable[[], ProgressbarLike]
    | bool
    | None = None,
):
    """alias for `.get_reader`"""
    return get_reader(self.source, progressbar=progressbar, sha256=self.sha256)

get_reader ¤

get_reader(
    *,
    progressbar: ProgressbarLike
    | Callable[[], ProgressbarLike]
    | bool
    | None = None,
)

open the file source (download if needed)

Source code in src/bioimageio/spec/_internal/io.py
306
307
308
309
310
311
312
313
314
315
def get_reader(
    self,
    *,
    progressbar: ProgressbarLike
    | Callable[[], ProgressbarLike]
    | bool
    | None = None,
):
    """open the file source (download if needed)"""
    return get_reader(self.source, progressbar=progressbar, sha256=self.sha256)

model_validate classmethod ¤

model_validate(
    obj: Any | Mapping[str, Any],
    *,
    strict: bool | None = None,
    extra: Literal["allow", "ignore", "forbid"]
    | None = None,
    from_attributes: bool | None = None,
    context: ValidationContext
    | Mapping[str, Any]
    | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self

Validate a pydantic model instance.

Parameters:

Name Type Description Default

obj ¤

Any | Mapping[str, Any]

The object to validate.

required

strict ¤

bool | None

Whether to raise an exception on invalid fields.

None

from_attributes ¤

bool | None

Whether to extract data from object attributes.

None

context ¤

ValidationContext | Mapping[str, Any] | None

Additional context to pass to the validator.

None

Raises:

Type Description
ValidationError

If the object failed validation.

Returns:

Type Description
Self

The validated description instance.

Source code in src/bioimageio/spec/_internal/node.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@classmethod
def model_validate(
    cls,
    obj: Any | Mapping[str, Any],
    *,
    strict: bool | None = None,
    extra: Literal["allow", "ignore", "forbid"] | None = None,
    from_attributes: bool | None = None,
    context: ValidationContext | Mapping[str, Any] | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to raise an exception on invalid fields.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.

    Raises:
        ValidationError: If the object failed validation.

    Returns:
        The validated description instance.
    """
    __tracebackhide__ = True

    if context is None:
        context = get_validation_context()
    elif isinstance(context, collections.abc.Mapping):
        context = ValidationContext(**context)

    assert not isinstance(obj, collections.abc.Mapping) or is_kwargs(obj), obj

    # TODO: pass on extra with pydantic >=2.12
    if extra is not None:
        warnings.warn("`extra` argument is currently ignored")

    with context:
        # use validation context as context manager for equal behavior of __init__ and model_validate
        return super().model_validate(
            obj, strict=strict, from_attributes=from_attributes
        )

validate_sha256 ¤

validate_sha256(force_recompute: bool = False) -> None

validate the sha256 hash value of the source file

Source code in src/bioimageio/spec/_internal/io.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def validate_sha256(self, force_recompute: bool = False) -> None:
    """validate the sha256 hash value of the **source** file"""
    context = get_validation_context()
    src_str = str(self.source)
    if force_recompute:
        actual_sha = None
    else:
        actual_sha = context.known_files.get(src_str)

    if actual_sha is None:
        if context.perform_io_checks or force_recompute:
            reader = get_reader(self.source, sha256=self.sha256)
            if force_recompute:
                actual_sha = get_sha256(reader)
            else:
                actual_sha = reader.sha256

            context.known_files[src_str] = actual_sha
        elif context.known_files and src_str not in context.known_files:
            # perform_io_checks is False, but known files were given,
            # so we expect all file references to be in there
            raise ValueError(f"File {src_str} not found in `known_files`.")

    if actual_sha is None or self.sha256 == actual_sha:
        return
    elif self.sha256 is None or context.update_hashes:
        self.sha256 = actual_sha
    elif self.sha256 != actual_sha:
        raise ValueError(
            f"Sha256 mismatch for {self.source}. Expected {self.sha256}, got "
            + f"{actual_sha}. Update expected `sha256` or point to the matching "
            + "file."
        )

HttpUrl ¤

Bases: RootHttpUrl


              flowchart TD
              bioimageio.spec.common.HttpUrl[HttpUrl]
              bioimageio.spec._internal.root_url.RootHttpUrl[RootHttpUrl]
              bioimageio.spec._internal.validated_string.ValidatedString[ValidatedString]

                              bioimageio.spec._internal.root_url.RootHttpUrl --> bioimageio.spec.common.HttpUrl
                                bioimageio.spec._internal.validated_string.ValidatedString --> bioimageio.spec._internal.root_url.RootHttpUrl
                



              click bioimageio.spec.common.HttpUrl href "" "bioimageio.spec.common.HttpUrl"
              click bioimageio.spec._internal.root_url.RootHttpUrl href "" "bioimageio.spec._internal.root_url.RootHttpUrl"
              click bioimageio.spec._internal.validated_string.ValidatedString href "" "bioimageio.spec._internal.validated_string.ValidatedString"
            

A URL with the HTTP or HTTPS scheme.

Methods:

Name Description
__get_pydantic_core_schema__
__get_pydantic_json_schema__
__new__
__truediv__
absolute

analog to absolute method of pathlib.

exists

True if URL is available

Attributes:

Name Type Description
host str | None
parent RootHttpUrl
parents Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path str | None
root_model type[RootModel[Any]]

the pydantic root model to validate the string

scheme str
suffix str

host property ¤

host: str | None

parent property ¤

parent: RootHttpUrl

parents property ¤

parents: Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path property ¤

path: str | None

root_model class-attribute ¤

root_model: type[RootModel[Any]] = RootModel[
    pydantic.HttpUrl
]

the pydantic root model to validate the string

scheme property ¤

scheme: str

suffix property ¤

suffix: str

__get_pydantic_core_schema__ classmethod ¤

__get_pydantic_core_schema__(
    source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema
Source code in src/bioimageio/spec/_internal/validated_string.py
31
32
33
34
35
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    return no_info_after_validator_function(cls, handler(str))

__get_pydantic_json_schema__ classmethod ¤

__get_pydantic_json_schema__(
    core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue
Source code in src/bioimageio/spec/_internal/validated_string.py
37
38
39
40
41
42
43
44
45
46
@classmethod
def __get_pydantic_json_schema__(
    cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    json_schema = cls.root_model.model_json_schema(mode=handler.mode)
    json_schema["title"] = cls.__name__.strip("_")
    if cls.__doc__:
        json_schema["description"] = cls.__doc__

    return json_schema

__new__ ¤

__new__(object: object)
Source code in src/bioimageio/spec/_internal/validated_string.py
21
22
23
24
25
def __new__(cls, object: object):
    _validated = cls.root_model.model_validate(object).root
    self = super().__new__(cls, _validated)
    self._validated = _validated
    return self._after_validator()

__truediv__ ¤

__truediv__(other: str) -> RootHttpUrl
Source code in src/bioimageio/spec/_internal/root_url.py
75
76
77
78
79
80
81
82
83
84
85
86
87
def __truediv__(self, other: str) -> RootHttpUrl:
    parsed = urlsplit(str(self))
    return RootHttpUrl(
        urlunsplit(
            (
                parsed.scheme,
                parsed.netloc,
                f"{parsed.path.strip('/')}/{other.strip('/')}",
                parsed.query,
                parsed.fragment,
            )
        )
    )

absolute ¤

absolute()

analog to absolute method of pathlib.

Source code in src/bioimageio/spec/_internal/root_url.py
19
20
21
def absolute(self):
    """analog to `absolute` method of pathlib."""
    return self

exists ¤

exists()

True if URL is available

Source code in src/bioimageio/spec/_internal/url.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def exists(self):
    """True if URL is available"""
    if self._exists is None:
        ctxt = get_validation_context()
        try:
            with ctxt.replace(warning_level=warning_levels.WARNING):
                self._validated = _validate_url(self._validated)
        except Exception as e:
            if ctxt.log_warnings:
                logger.info(e)

            self._exists = False
        else:
            self._exists = True

    return self._exists

InvalidDescr pydantic-model ¤

Bases: ResourceDescrBase

A representation of an invalid resource description

Show JSON schema:
{
  "additionalProperties": true,
  "description": "A representation of an invalid resource description",
  "properties": {
    "type": {
      "title": "Type"
    },
    "format_version": {
      "title": "Format Version"
    }
  },
  "required": [
    "type",
    "format_version"
  ],
  "title": "An invalid resource description",
  "type": "object"
}

Fields:

file_name property ¤

file_name: FileName | None

File name of the bioimageio.yaml file the description was loaded from.

format_version pydantic-field ¤

format_version: Any = 'unknown'

implemented_format_version class-attribute ¤

implemented_format_version: Literal['unknown'] = 'unknown'

implemented_format_version_tuple class-attribute ¤

implemented_format_version_tuple: tuple[int, int, int]

implemented_type class-attribute ¤

implemented_type: Literal['unknown'] = 'unknown'

root property ¤

root: RootHttpUrl | DirectoryPath | ZipFile

The URL/Path prefix to resolve any relative paths with.

type pydantic-field ¤

type: Any = 'unknown'

validation_summary property ¤

validation_summary: ValidationSummary

__pydantic_init_subclass__ classmethod ¤

__pydantic_init_subclass__(**kwargs: Any)
Source code in src/bioimageio/spec/_internal/common_nodes.py
201
202
203
204
205
206
207
208
209
210
211
212
213
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any):
    super().__pydantic_init_subclass__(**kwargs)
    # set classvar implemented_format_version_tuple
    if "format_version" in cls.model_fields:
        if "." not in cls.implemented_format_version:
            cls.implemented_format_version_tuple = (0, 0, 0)
        else:
            fv_tuple = get_format_version_tuple(cls.implemented_format_version)
            assert fv_tuple is not None, (
                f"failed to cast '{cls.implemented_format_version}' to tuple"
            )
            cls.implemented_format_version_tuple = fv_tuple

dict_from_kwargs classmethod ¤

dict_from_kwargs(
    *args: P.args, **kwargs: P.kwargs
) -> dict[str, Any]
Source code in src/bioimageio/spec/_internal/node.py
93
94
95
96
97
98
@classmethod
def dict_from_kwargs(
    cls: Callable[P, T], *args: P.args, **kwargs: P.kwargs
) -> dict[str, Any]:
    assert not args, "Did not expected any args"
    return dict(kwargs)

get_package_content ¤

get_package_content(
    local_files_only: bool = False,
) -> dict[FileName, FileDescr | BioimageioYamlContent]

Returns package content without creating the package.

Source code in src/bioimageio/spec/_internal/common_nodes.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def get_package_content(
    self, local_files_only: bool = False
) -> dict[FileName, FileDescr | BioimageioYamlContent]:
    """Returns package content without creating the package."""
    content: dict[FileName, FileDescr] = {}
    with PackagingContext(
        bioimageio_yaml_file_name=BIOIMAGEIO_YAML,
        file_sources=content,
        local_files_only=local_files_only,
    ):
        rdf_content: BioimageioYamlContent = self.model_dump(
            mode="json", exclude_unset=True
        )

    _ = rdf_content.pop("rdf_source", None)

    return {**content, BIOIMAGEIO_YAML: rdf_content}

get_reason ¤

get_reason() -> str | None

Get the reason why the description is invalid, if available.

Source code in src/bioimageio/spec/_internal/common_nodes.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def get_reason(self) -> str | None:
    """Get the reason why the description is invalid, if available."""
    reasons: list[str] = []
    if self.validation_summary and self.validation_summary.details:
        for detail in self.validation_summary.details:
            if detail.status == "failed" and detail.errors:
                reasons.extend(
                    f"{loc}: {msg}"
                    for loc, msg in (
                        (
                            ".".join(map(str, error.loc)),
                            error.msg.replace("\n", " "),
                        )
                        for error in detail.errors
                    )
                )

    return "\n- ".join(reasons) if reasons else None

load classmethod ¤

load(
    data: IncompleteDescrView,
    context: ValidationContext | None = None,
) -> Self | InvalidDescr

factory method to create a resource description object

Source code in src/bioimageio/spec/_internal/common_nodes.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
@classmethod
def load(
    cls,
    data: IncompleteDescrView,
    context: ValidationContext | None = None,
) -> Self | InvalidDescr:
    """factory method to create a resource description object"""

    context = context or get_validation_context()
    if context.perform_io_checks:
        file_descrs = extract_file_descrs(data)
        populate_cache(file_descrs)  # TODO: add progress bar

    with context.replace(log_warnings=context.warning_level <= INFO):
        rd, errors, val_warnings = cls._load_impl(deepcopy_incomplete_descr(data))

    if context.warning_level > INFO:
        all_warnings_context = context.replace(
            warning_level=INFO, log_warnings=False, raise_errors=False
        )
        # raise all validation warnings by reloading
        with all_warnings_context:
            _, _, val_warnings = cls._load_impl(deepcopy_incomplete_descr(data))

    format_status = "failed" if errors else "passed"
    rd.validation_summary.add_detail(
        ValidationDetail(
            errors=errors,
            name=(
                "bioimageio.spec format validation"
                f" {rd.type} {cls.implemented_format_version}"
            ),
            status=format_status,
            warnings=val_warnings,
        ),
        update_status=False,  # this special validation detail needs manual format updating below
    )
    assert format_status != "failed" or isinstance(rd, InvalidDescr)

    return rd

load_from_kwargs classmethod ¤

load_from_kwargs(
    context: ValidationContext | None = None,
    *args: P.args,
    **kwargs: P.kwargs,
) -> T | InvalidDescr
Source code in src/bioimageio/spec/_internal/common_nodes.py
215
216
217
218
219
220
221
222
223
224
@classmethod
def load_from_kwargs(
    cls: Callable[P, T],
    context: ValidationContext | None = None,
    *args: P.args,
    **kwargs: P.kwargs,
) -> T | InvalidDescr:
    sig = signature(cls)
    bound = sig.bind_partial(*args, **kwargs)
    return cls.load(dict(bound.arguments), context=context)  # pyright: ignore[reportFunctionMemberAccess]

model_validate classmethod ¤

model_validate(
    obj: Any | Mapping[str, Any],
    *,
    strict: bool | None = None,
    extra: Literal["allow", "ignore", "forbid"]
    | None = None,
    from_attributes: bool | None = None,
    context: ValidationContext
    | Mapping[str, Any]
    | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self

Validate a pydantic model instance.

Parameters:

Name Type Description Default

obj ¤

Any | Mapping[str, Any]

The object to validate.

required

strict ¤

bool | None

Whether to raise an exception on invalid fields.

None

from_attributes ¤

bool | None

Whether to extract data from object attributes.

None

context ¤

ValidationContext | Mapping[str, Any] | None

Additional context to pass to the validator.

None

Raises:

Type Description
ValidationError

If the object failed validation.

Returns:

Type Description
Self

The validated description instance.

Source code in src/bioimageio/spec/_internal/node.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@classmethod
def model_validate(
    cls,
    obj: Any | Mapping[str, Any],
    *,
    strict: bool | None = None,
    extra: Literal["allow", "ignore", "forbid"] | None = None,
    from_attributes: bool | None = None,
    context: ValidationContext | Mapping[str, Any] | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to raise an exception on invalid fields.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.

    Raises:
        ValidationError: If the object failed validation.

    Returns:
        The validated description instance.
    """
    __tracebackhide__ = True

    if context is None:
        context = get_validation_context()
    elif isinstance(context, collections.abc.Mapping):
        context = ValidationContext(**context)

    assert not isinstance(obj, collections.abc.Mapping) or is_kwargs(obj), obj

    # TODO: pass on extra with pydantic >=2.12
    if extra is not None:
        warnings.warn("`extra` argument is currently ignored")

    with context:
        # use validation context as context manager for equal behavior of __init__ and model_validate
        return super().model_validate(
            obj, strict=strict, from_attributes=from_attributes
        )

package ¤

package(
    dest: ZipFile | IO[bytes] | Path | str | None = None,
    /,
    local_files_only: bool = False,
) -> ZipFile

package the described resource as a zip archive

Parameters:

Name Type Description Default

dest ¤

ZipFile | IO[bytes] | Path | str | None

(path/bytes stream of) destination zipfile

None
Source code in src/bioimageio/spec/_internal/common_nodes.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def package(
    self,
    dest: ZipFile | IO[bytes] | Path | str | None = None,
    /,
    local_files_only: bool = False,
) -> ZipFile:
    """package the described resource as a zip archive

    Args:
        dest: (path/bytes stream of) destination zipfile
    """
    if dest is None:
        dest = BytesIO()

    if isinstance(dest, ZipFile):
        zip = dest
        if "r" in zip.mode:
            raise ValueError(
                f"zip file {dest} opened in '{zip.mode}' mode,"
                + " but write access is needed for packaging."
            )
    else:
        zip = ZipFile(dest, mode="w")

    if zip.filename is None:
        zip.filename = (
            str(getattr(self, "id", getattr(self, "name", "bioimageio"))) + ".zip"
        )

    content = self.get_package_content(local_files_only=local_files_only)
    write_content_to_zip(content, zip)
    return zip

ProgressbarLike ¤

Bases: Protocol


              flowchart TD
              bioimageio.spec.common.ProgressbarLike[ProgressbarLike]

              

              click bioimageio.spec.common.ProgressbarLike href "" "bioimageio.spec.common.ProgressbarLike"
            

Progressbar protocol modeled after tqdm

Methods:

Name Description
close
reset
set_description
update

Attributes:

Name Type Description
total int | None

total instance-attribute ¤

total: int | None

close abstractmethod ¤

close()
Source code in src/bioimageio/spec/_internal/progress.py
20
21
@abstractmethod
def close(self): ...

reset abstractmethod ¤

reset()
Source code in src/bioimageio/spec/_internal/progress.py
17
18
@abstractmethod
def reset(self): ...

set_description abstractmethod ¤

set_description(description: str, /, refresh: bool = True)
Source code in src/bioimageio/spec/_internal/progress.py
23
24
@abstractmethod
def set_description(self, description: str, /, refresh: bool = True): ...

update abstractmethod ¤

update(increment: int) -> Any
Source code in src/bioimageio/spec/_internal/progress.py
14
15
@abstractmethod
def update(self, increment: int, /) -> Any: ...

RelativeFilePath ¤

Bases: RelativePathBase[Union[AbsoluteFilePath, HttpUrl, ZipPath]]


              flowchart TD
              bioimageio.spec.common.RelativeFilePath[RelativeFilePath]
              bioimageio.spec._internal.io.RelativePathBase[RelativePathBase]

                              bioimageio.spec._internal.io.RelativePathBase --> bioimageio.spec.common.RelativeFilePath
                


              click bioimageio.spec.common.RelativeFilePath href "" "bioimageio.spec.common.RelativeFilePath"
              click bioimageio.spec._internal.io.RelativePathBase href "" "bioimageio.spec._internal.io.RelativePathBase"
            

A path relative to the rdf.yaml file (also if the RDF source is a URL).

Methods:

Name Description
__repr__
__str__
absolute

get the absolute path/url

format
get_absolute
model_post_init

add validation @private

Attributes:

Name Type Description
path PurePath
suffix

path property ¤

path: PurePath

suffix property ¤

suffix

__repr__ ¤

__repr__() -> str
Source code in src/bioimageio/spec/_internal/io.py
151
152
def __repr__(self) -> str:
    return f"RelativePath('{self}')"

__str__ ¤

__str__() -> str
Source code in src/bioimageio/spec/_internal/io.py
148
149
def __str__(self) -> str:
    return self.root.as_posix()

absolute ¤

absolute() -> AbsolutePathT

get the absolute path/url

(resolved at time of initialization with the root of the ValidationContext)

Source code in src/bioimageio/spec/_internal/io.py
126
127
128
129
130
131
132
133
def absolute(  # method not property analog to `pathlib.Path.absolute()`
    self,
) -> AbsolutePathT:
    """get the absolute path/url

    (resolved at time of initialization with the root of the ValidationContext)
    """
    return self._absolute

format ¤

format() -> str
Source code in src/bioimageio/spec/_internal/io.py
154
155
156
@model_serializer()
def format(self) -> str:
    return str(self)

get_absolute ¤

get_absolute(
    root: RootHttpUrl | Path | AnyUrl | ZipFile,
) -> AbsoluteFilePath | HttpUrl | ZipPath
Source code in src/bioimageio/spec/_internal/io.py
216
217
218
219
220
221
222
223
224
225
226
227
228
def get_absolute(
    self, root: RootHttpUrl | Path | AnyUrl | ZipFile
) -> AbsoluteFilePath | HttpUrl | ZipPath:
    absolute = self._get_absolute_impl(root)
    if (
        isinstance(absolute, Path)
        and (context := get_validation_context()).perform_io_checks
        and str(self.root) not in context.known_files
        and not absolute.is_file()
    ):
        raise ValueError(f"{absolute} does not point to an existing file")

    return absolute

model_post_init ¤

model_post_init(__context: Any) -> None

add validation @private

Source code in src/bioimageio/spec/_internal/io.py
209
210
211
212
213
214
def model_post_init(self, __context: Any, /) -> None:
    """add validation @private"""
    if not self.root.parts:  # an empty path can only be a directory
        raise ValueError(f"{self.root} is not a valid file path.")

    super().model_post_init(__context)

RootHttpUrl ¤

Bases: ValidatedString


              flowchart TD
              bioimageio.spec.common.RootHttpUrl[RootHttpUrl]
              bioimageio.spec._internal.validated_string.ValidatedString[ValidatedString]

                              bioimageio.spec._internal.validated_string.ValidatedString --> bioimageio.spec.common.RootHttpUrl
                


              click bioimageio.spec.common.RootHttpUrl href "" "bioimageio.spec.common.RootHttpUrl"
              click bioimageio.spec._internal.validated_string.ValidatedString href "" "bioimageio.spec._internal.validated_string.ValidatedString"
            

An untested HTTP URL, possibly a 'URL folder' or an invalid HTTP URL

Methods:

Name Description
__get_pydantic_core_schema__
__get_pydantic_json_schema__
__new__
__truediv__
absolute

analog to absolute method of pathlib.

Attributes:

Name Type Description
host str | None
parent RootHttpUrl
parents Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path str | None
root_model type[RootModel[Any]]

the pydantic root model to validate the string

scheme str
suffix str

host property ¤

host: str | None

parent property ¤

parent: RootHttpUrl

parents property ¤

parents: Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path property ¤

path: str | None

root_model class-attribute ¤

root_model: type[RootModel[Any]] = RootModel[
    pydantic.HttpUrl
]

the pydantic root model to validate the string

scheme property ¤

scheme: str

suffix property ¤

suffix: str

__get_pydantic_core_schema__ classmethod ¤

__get_pydantic_core_schema__(
    source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema
Source code in src/bioimageio/spec/_internal/validated_string.py
31
32
33
34
35
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    return no_info_after_validator_function(cls, handler(str))

__get_pydantic_json_schema__ classmethod ¤

__get_pydantic_json_schema__(
    core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue
Source code in src/bioimageio/spec/_internal/validated_string.py
37
38
39
40
41
42
43
44
45
46
@classmethod
def __get_pydantic_json_schema__(
    cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    json_schema = cls.root_model.model_json_schema(mode=handler.mode)
    json_schema["title"] = cls.__name__.strip("_")
    if cls.__doc__:
        json_schema["description"] = cls.__doc__

    return json_schema

__new__ ¤

__new__(object: object)
Source code in src/bioimageio/spec/_internal/validated_string.py
21
22
23
24
25
def __new__(cls, object: object):
    _validated = cls.root_model.model_validate(object).root
    self = super().__new__(cls, _validated)
    self._validated = _validated
    return self._after_validator()

__truediv__ ¤

__truediv__(other: str) -> RootHttpUrl
Source code in src/bioimageio/spec/_internal/root_url.py
75
76
77
78
79
80
81
82
83
84
85
86
87
def __truediv__(self, other: str) -> RootHttpUrl:
    parsed = urlsplit(str(self))
    return RootHttpUrl(
        urlunsplit(
            (
                parsed.scheme,
                parsed.netloc,
                f"{parsed.path.strip('/')}/{other.strip('/')}",
                parsed.query,
                parsed.fragment,
            )
        )
    )

absolute ¤

absolute()

analog to absolute method of pathlib.

Source code in src/bioimageio/spec/_internal/root_url.py
19
20
21
def absolute(self):
    """analog to `absolute` method of pathlib."""
    return self

Sha256 ¤

Bases: ValidatedString


              flowchart TD
              bioimageio.spec.common.Sha256[Sha256]
              bioimageio.spec._internal.validated_string.ValidatedString[ValidatedString]

                              bioimageio.spec._internal.validated_string.ValidatedString --> bioimageio.spec.common.Sha256
                


              click bioimageio.spec.common.Sha256 href "" "bioimageio.spec.common.Sha256"
              click bioimageio.spec._internal.validated_string.ValidatedString href "" "bioimageio.spec._internal.validated_string.ValidatedString"
            

A SHA-256 hash value

Methods:

Name Description
__get_pydantic_core_schema__
__get_pydantic_json_schema__
__new__

Attributes:

Name Type Description
root_model type[RootModel[Any]]

the pydantic root model to validate the string

root_model class-attribute ¤

root_model: type[RootModel[Any]] = RootModel[
    Annotated[
        str,
        StringConstraints(
            strip_whitespace=True,
            to_lower=True,
            min_length=64,
            max_length=64,
        ),
    ]
]

the pydantic root model to validate the string

__get_pydantic_core_schema__ classmethod ¤

__get_pydantic_core_schema__(
    source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema
Source code in src/bioimageio/spec/_internal/validated_string.py
31
32
33
34
35
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    return no_info_after_validator_function(cls, handler(str))

__get_pydantic_json_schema__ classmethod ¤

__get_pydantic_json_schema__(
    core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue
Source code in src/bioimageio/spec/_internal/validated_string.py
37
38
39
40
41
42
43
44
45
46
@classmethod
def __get_pydantic_json_schema__(
    cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    json_schema = cls.root_model.model_json_schema(mode=handler.mode)
    json_schema["title"] = cls.__name__.strip("_")
    if cls.__doc__:
        json_schema["description"] = cls.__doc__

    return json_schema

__new__ ¤

__new__(object: object)
Source code in src/bioimageio/spec/_internal/validated_string.py
21
22
23
24
25
def __new__(cls, object: object):
    _validated = cls.root_model.model_validate(object).root
    self = super().__new__(cls, _validated)
    self._validated = _validated
    return self._after_validator()