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

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
YamlValue
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 = Union[
    YamlLeafValue,
    List["YamlValue"],
    Dict[YamlKey, "YamlValue"],
]

BytesReader ¤

BytesReader(
    reader: Union[BytesReaderP, BytesReaderIntoP],
    *,
    sha256: Optional[Sha256],
    suffix: Suffix,
    original_file_name: FileName,
    original_root: Union[
        RootHttpUrl, AbsoluteDirectory, ZipFile
    ],
    is_zipfile: Optional[bool],
)

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 Union[RootHttpUrl, AbsoluteDirectory, ZipFile]
sha256 Sha256
suffix Suffix
Source code in src/bioimageio/spec/_internal/io_basics.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def __init__(
    self,
    /,
    reader: Union[BytesReaderP, BytesReaderIntoP],
    *,
    sha256: Optional[Sha256],
    suffix: Suffix,
    original_file_name: FileName,
    original_root: Union[RootHttpUrl, AbsoluteDirectory, ZipFile],
    is_zipfile: Optional[bool],
) -> 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: Union[
    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
126
127
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
129
130
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
132
133
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
135
136
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
138
139
def seekable(self) -> bool:
    return True

tell ¤

tell() -> int
Source code in src/bioimageio/spec/_internal/io_basics.py
141
142
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: Optional[Sha256] = None

SHA256 hash value of the source file.

source pydantic-field ¤

source: FileSource

File source

suffix property ¤

suffix: str

download ¤

download(
    *,
    progressbar: Union[
        Progressbar, Callable[[], Progressbar], bool, None
    ] = None,
)

alias for .get_reader

Source code in src/bioimageio/spec/_internal/io.py
310
311
312
313
314
315
316
def download(
    self,
    *,
    progressbar: Union[Progressbar, Callable[[], Progressbar], bool, None] = None,
):
    """alias for `.get_reader`"""
    return get_reader(self.source, progressbar=progressbar, sha256=self.sha256)

get_reader ¤

get_reader(
    *,
    progressbar: Union[
        Progressbar, Callable[[], Progressbar], bool, None
    ] = None,
)

open the file source (download if needed)

Source code in src/bioimageio/spec/_internal/io.py
302
303
304
305
306
307
308
def get_reader(
    self,
    *,
    progressbar: Union[Progressbar, Callable[[], Progressbar], 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: Union[Any, Mapping[str, Any]],
    *,
    strict: Optional[bool] = None,
    extra: Optional[
        Literal["allow", "ignore", "forbid"]
    ] = None,
    from_attributes: Optional[bool] = None,
    context: Union[
        ValidationContext, Mapping[str, Any], None
    ] = None,
    by_alias: Optional[bool] = None,
    by_name: Optional[bool] = None,
) -> Self

Validate a pydantic model instance.

Parameters:

Name Type Description Default

obj ¤

Union[Any, Mapping[str, Any]]

The object to validate.

required

strict ¤

Optional[bool]

Whether to raise an exception on invalid fields.

None

from_attributes ¤

Optional[bool]

Whether to extract data from object attributes.

None

context ¤

Union[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
45
46
47
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
@classmethod
def model_validate(
    cls,
    obj: Union[Any, Mapping[str, Any]],
    *,
    strict: Optional[bool] = None,
    extra: Optional[Literal["allow", "ignore", "forbid"]] = None,
    from_attributes: Optional[bool] = None,
    context: Union[ValidationContext, Mapping[str, Any], None] = None,
    by_alias: Optional[bool] = None,
    by_name: Optional[bool] = 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
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
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 not force_recompute and src_str in context.known_files:
        actual_sha = context.known_files[src_str]
    else:
        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

    if actual_sha is None:
        return
    elif self.sha256 == actual_sha:
        pass
    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__
absolute

analog to absolute method of pathlib.

exists

True if URL is available

Attributes:

Name Type Description
host Optional[str]
parent RootHttpUrl
parents Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path Optional[str]
root_model Type[RootModel[Any]]

the pydantic root model to validate the string

scheme str
suffix str

host property ¤

host: Optional[str]

parent property ¤

parent: RootHttpUrl

parents property ¤

parents: Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path property ¤

path: Optional[str]

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
29
30
31
32
33
@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
35
36
37
38
39
40
41
42
43
44
@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
19
20
21
22
23
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()

absolute ¤

absolute()

analog to absolute method of pathlib.

Source code in src/bioimageio/spec/_internal/root_url.py
18
19
20
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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: Optional[FileName]

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: Union[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
200
201
202
203
204
205
206
207
208
209
210
211
212
@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

get_package_content ¤

get_package_content() -> Dict[
    FileName, Union[FileDescr, BioimageioYamlContent]
]

Returns package content without creating the package.

Source code in src/bioimageio/spec/_internal/common_nodes.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def get_package_content(
    self,
) -> Dict[FileName, Union[FileDescr, BioimageioYamlContent]]:
    """Returns package content without creating the package."""
    content: Dict[FileName, FileDescr] = {}
    with PackagingContext(
        bioimageio_yaml_file_name=BIOIMAGEIO_YAML,
        file_sources=content,
    ):
        rdf_content: BioimageioYamlContent = self.model_dump(
            mode="json", exclude_unset=True
        )

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

    return {**content, BIOIMAGEIO_YAML: rdf_content}

load classmethod ¤

load(
    data: BioimageioYamlContentView,
    context: Optional[ValidationContext] = None,
) -> Union[Self, InvalidDescr]

factory method to create a resource description object

Source code in src/bioimageio/spec/_internal/common_nodes.py
214
215
216
217
218
219
220
221
222
223
224
225
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
@classmethod
def load(
    cls,
    data: BioimageioYamlContentView,
    context: Optional[ValidationContext] = None,
) -> Union[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({k: v for k, v in data.items()})
        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_yaml_value(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_yaml_value(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,  # avoid updating status from 'valid-format' to 'passed', but ...
    )
    if format_status == "failed":
        # ... update status in case of failure
        rd.validation_summary.status = "failed"

    return rd

model_validate classmethod ¤

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

Validate a pydantic model instance.

Parameters:

Name Type Description Default

obj ¤

Union[Any, Mapping[str, Any]]

The object to validate.

required

strict ¤

Optional[bool]

Whether to raise an exception on invalid fields.

None

from_attributes ¤

Optional[bool]

Whether to extract data from object attributes.

None

context ¤

Union[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
45
46
47
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
@classmethod
def model_validate(
    cls,
    obj: Union[Any, Mapping[str, Any]],
    *,
    strict: Optional[bool] = None,
    extra: Optional[Literal["allow", "ignore", "forbid"]] = None,
    from_attributes: Optional[bool] = None,
    context: Union[ValidationContext, Mapping[str, Any], None] = None,
    by_alias: Optional[bool] = None,
    by_name: Optional[bool] = 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: Optional[
        Union[ZipFile, IO[bytes], Path, str]
    ] = None,
) -> ZipFile

package the described resource as a zip archive

Parameters:

Name Type Description Default

dest ¤

Optional[Union[ZipFile, IO[bytes], Path, str]]

(path/bytes stream of) destination zipfile

None
Source code in src/bioimageio/spec/_internal/common_nodes.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def package(
    self, dest: Optional[Union[ZipFile, IO[bytes], Path, str]] = None, /
) -> 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()
    write_content_to_zip(content, zip)
    return zip

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
148
149
def __repr__(self) -> str:
    return f"RelativePath('{self}')"

__str__ ¤

__str__() -> str
Source code in src/bioimageio/spec/_internal/io.py
145
146
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
123
124
125
126
127
128
129
130
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
151
152
153
@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
215
216
217
218
219
220
221
222
223
224
225
226
227
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
208
209
210
211
212
213
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__
absolute

analog to absolute method of pathlib.

Attributes:

Name Type Description
host Optional[str]
parent RootHttpUrl
parents Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path Optional[str]
root_model Type[RootModel[Any]]

the pydantic root model to validate the string

scheme str

host property ¤

host: Optional[str]

parent property ¤

parent: RootHttpUrl

parents property ¤

parents: Iterable[RootHttpUrl]

iterate over all URL parents (max 100)

path property ¤

path: Optional[str]

root_model class-attribute ¤

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

the pydantic root model to validate the string

scheme property ¤

scheme: 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
29
30
31
32
33
@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
35
36
37
38
39
40
41
42
43
44
@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
19
20
21
22
23
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()

absolute ¤

absolute()

analog to absolute method of pathlib.

Source code in src/bioimageio/spec/_internal/root_url.py
18
19
20
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
29
30
31
32
33
@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
35
36
37
38
39
40
41
42
43
44
@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
19
20
21
22
23
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()