bioimageio.spec.common

 1from pydantic import ValidationError
 2
 3from ._internal.common_nodes import InvalidDescr
 4from ._internal.io import (
 5    BioimageioYamlContent,
 6    BioimageioYamlSource,
 7    FileDescr,
 8    YamlValue,
 9)
10from ._internal.io_basics import AbsoluteDirectory, AbsoluteFilePath, FileName, Sha256
11from ._internal.root_url import RootHttpUrl
12from ._internal.types import FileSource, PermissiveFileSource, RelativeFilePath
13from ._internal.url import HttpUrl
14
15__all__ = [
16    "AbsoluteDirectory",
17    "AbsoluteFilePath",
18    "BioimageioYamlContent",
19    "BioimageioYamlSource",
20    "FileDescr",
21    "FileName",
22    "FileSource",
23    "HttpUrl",
24    "InvalidDescr",
25    "PermissiveFileSource",
26    "RelativeFilePath",
27    "RootHttpUrl",
28    "Sha256",
29    "ValidationError",
30    "YamlValue",
31]
AbsoluteDirectory = typing.Annotated[pathlib.Path, PathType(path_type='dir'), Predicate(is_absolute)]
AbsoluteFilePath = typing.Annotated[pathlib.Path, PathType(path_type='file'), Predicate(is_absolute)]
BioimageioYamlContent = typing.Dict[str, YamlValue]
BioimageioYamlSource = typing.Union[typing.Annotated[typing.Union[HttpUrl, RelativeFilePath, typing.Annotated[pathlib.Path, PathType(path_type='file')]], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], str, typing.Annotated[pydantic_core._pydantic_core.Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'], host_required=None, default_host=None, default_port=None, default_path=None)], typing.Dict[str, YamlValue]]
class FileDescr(bioimageio.spec._internal.node.Node):
768class FileDescr(Node):
769    source: ImportantFileSource
770    """∈📦 file source"""
771
772    sha256: Optional[Sha256] = None
773    """SHA256 checksum of the source file"""
774
775    @model_validator(mode="after")
776    def validate_sha256(self) -> Self:
777        context = validation_context_var.get()
778        if not context.perform_io_checks:
779            return self
780        elif (src_str := str(self.source)) in context.known_files:
781            actual_sha = context.known_files[src_str]
782        else:
783            local_source = download(self.source, sha256=self.sha256).path
784            actual_sha = get_sha256(local_source)
785            context.known_files[str(self.source)] = actual_sha
786
787        if self.sha256 is None:
788            self.sha256 = actual_sha
789        elif self.sha256 != actual_sha:
790            raise ValueError(
791                f"Sha256 mismatch for {self.source}. Expected {self.sha256}, got "
792                + f"{actual_sha}. Update expected `sha256` or point to the matching "
793                + "file."
794            )
795
796        return self
797
798    def download(self):
799
800        return download(self.source, sha256=self.sha256)

Subpart of a resource description

source: Annotated[Union[HttpUrl, RelativeFilePath, Annotated[pathlib.Path, PathType(path_type='file')]], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')]), AfterValidator(func=<function wo_special_file_name at 0x7f9a7f3b8ea0>), PlainSerializer(func=<function _package at 0x7f9a7f3b9620>, return_type=PydanticUndefined, when_used='unless-none')]

∈📦 file source

sha256: Optional[Sha256]

SHA256 checksum of the source file

@model_validator(mode='after')
def validate_sha256(self) -> Self:
775    @model_validator(mode="after")
776    def validate_sha256(self) -> Self:
777        context = validation_context_var.get()
778        if not context.perform_io_checks:
779            return self
780        elif (src_str := str(self.source)) in context.known_files:
781            actual_sha = context.known_files[src_str]
782        else:
783            local_source = download(self.source, sha256=self.sha256).path
784            actual_sha = get_sha256(local_source)
785            context.known_files[str(self.source)] = actual_sha
786
787        if self.sha256 is None:
788            self.sha256 = actual_sha
789        elif self.sha256 != actual_sha:
790            raise ValueError(
791                f"Sha256 mismatch for {self.source}. Expected {self.sha256}, got "
792                + f"{actual_sha}. Update expected `sha256` or point to the matching "
793                + "file."
794            )
795
796        return self
def download(self):
798    def download(self):
799
800        return download(self.source, sha256=self.sha256)
FileName = <class 'str'>
FileSource = typing.Annotated[typing.Union[HttpUrl, RelativeFilePath, typing.Annotated[pathlib.Path, PathType(path_type='file')]], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]
class HttpUrl(bioimageio.spec.common.RootHttpUrl):
118class HttpUrl(RootHttpUrl):
119    root_model: ClassVar[Type[RootModel[Any]]] = RootModel[pydantic.HttpUrl]
120    _exists: Optional[bool] = None
121
122    @model_validator(mode="after")
123    def _validate_url(self):
124        url = self._validated
125        context = validation_context_var.get()
126        if context.perform_io_checks and str(url) not in context.known_files:
127            self._validated = _validate_url(url)
128            self._exists = True
129
130        return self
131
132    def exists(self):
133        """True if URL is available"""
134        if self._exists is None:
135            try:
136                self._validated = _validate_url(self._validated)
137            except Exception as e:
138                logger.info(e)
139                self._exists = False
140            else:
141                self._exists = True
142
143        return self._exists

A 'URL folder', possibly an invalid http URL

root_model: ClassVar[Type[pydantic.root_model.RootModel[Any]]] = <class 'pydantic.root_model.RootModel[Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'], host_required=None, default_host=None, default_port=None, default_path=None)]]'>

the pydantic root model to validate the string

def exists(self):
132    def exists(self):
133        """True if URL is available"""
134        if self._exists is None:
135            try:
136                self._validated = _validate_url(self._validated)
137            except Exception as e:
138                logger.info(e)
139                self._exists = False
140            else:
141                self._exists = True
142
143        return self._exists

True if URL is available

class InvalidDescr(bioimageio.spec._internal.common_nodes.ResourceDescrBase):
514class InvalidDescr(
515    ResourceDescrBase,
516    extra="allow",
517    title="An invalid resource description",
518):
519    """A representation of an invalid resource description"""
520
521    type: Any = "unknown"
522    format_version: Any = "unknown"
523    fields_to_set_explicitly: ClassVar[FrozenSet[LiteralString]] = frozenset()

A representation of an invalid resource description

type: Any
format_version: Any
fields_to_set_explicitly: ClassVar[FrozenSet[LiteralString]] = frozenset()

set set these fields explicitly with their default value if they are not set, such that they are always included even when dumping with 'exlude_unset'

implemented_format_version: ClassVar[str] = 'unknown'
implemented_format_version_tuple: ClassVar[Tuple[int, int, int]] = (0, 0, 0)
def model_post_init(self: pydantic.main.BaseModel, context: Any, /) -> None:
124                    def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None:
125                        """We need to both initialize private attributes and call the user-defined model_post_init
126                        method.
127                        """
128                        init_private_attributes(self, context)
129                        original_model_post_init(self, context)

We need to both initialize private attributes and call the user-defined model_post_init method.

PermissiveFileSource = typing.Union[typing.Annotated[typing.Union[HttpUrl, RelativeFilePath, typing.Annotated[pathlib.Path, PathType(path_type='file')]], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], str, typing.Annotated[pydantic_core._pydantic_core.Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'], host_required=None, default_host=None, default_port=None, default_path=None)]]
class RelativeFilePath(pydantic.root_model.RootModel[PurePath], typing.Generic[~AbsolutePathT]):
186class RelativeFilePath(
187    RelativePathBase[Union[AbsoluteFilePath, HttpUrl, ZipPath]], frozen=True
188):
189    """A path relative to the `rdf.yaml` file (also if the RDF source is a URL)."""
190
191    def model_post_init(self, __context: Any) -> None:
192        """add validation @private"""
193        if not self.root.parts:  # an empty path can only be a directory
194            raise ValueError(f"{self.root} is not a valid file path.")
195
196        super().model_post_init(__context)
197
198    def get_absolute(
199        self, root: "RootHttpUrl | Path | AnyUrl | ZipFile"
200    ) -> "AbsoluteFilePath | HttpUrl | ZipPath":
201        absolute = self._get_absolute_impl(root)
202        if (
203            isinstance(absolute, Path)
204            and (context := validation_context_var.get()).perform_io_checks
205            and str(self.root) not in context.known_files
206            and not absolute.is_file()
207        ):
208            raise ValueError(f"{absolute} does not point to an existing file")
209
210        return absolute

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

def model_post_init(self: pydantic.main.BaseModel, context: Any, /) -> None:
124                    def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None:
125                        """We need to both initialize private attributes and call the user-defined model_post_init
126                        method.
127                        """
128                        init_private_attributes(self, context)
129                        original_model_post_init(self, context)

We need to both initialize private attributes and call the user-defined model_post_init method.

def get_absolute( self, root: RootHttpUrl | pathlib.Path | pydantic_core._pydantic_core.Url | zipfile.ZipFile) -> Union[Annotated[pathlib.Path, PathType(path_type='file'), Predicate(is_absolute)], HttpUrl, zipp.Path]:
198    def get_absolute(
199        self, root: "RootHttpUrl | Path | AnyUrl | ZipFile"
200    ) -> "AbsoluteFilePath | HttpUrl | ZipPath":
201        absolute = self._get_absolute_impl(root)
202        if (
203            isinstance(absolute, Path)
204            and (context := validation_context_var.get()).perform_io_checks
205            and str(self.root) not in context.known_files
206            and not absolute.is_file()
207        ):
208            raise ValueError(f"{absolute} does not point to an existing file")
209
210        return absolute
class RootHttpUrl(bioimageio.spec._internal.validated_string.ValidatedString):
13class RootHttpUrl(ValidatedString):
14    """A 'URL folder', possibly an invalid http URL"""
15
16    root_model: ClassVar[Type[RootModel[Any]]] = RootModel[pydantic.HttpUrl]
17    _validated: pydantic.HttpUrl
18
19    def absolute(self):
20        """analog to `absolute` method of pathlib."""
21        return self
22
23    @property
24    def scheme(self) -> str:
25        return self._validated.scheme
26
27    @property
28    def host(self) -> Optional[str]:
29        return self._validated.host
30
31    @property
32    def path(self) -> Optional[str]:
33        return self._validated.path
34
35    @property
36    def parent(self) -> RootHttpUrl:
37        parsed = urlsplit(str(self))
38        path = list(parsed.path.split("/"))
39        if (
40            parsed.netloc == "zenodo.org"
41            and parsed.path.startswith("/api/records/")
42            and parsed.path.endswith("/content")
43        ):
44            path[-2:-1] = []
45        else:
46            path = path[:-1]
47
48        return RootHttpUrl(
49            urlunsplit(
50                (
51                    parsed.scheme,
52                    parsed.netloc,
53                    "/".join(path),
54                    parsed.query,
55                    parsed.fragment,
56                )
57            )
58        )

A 'URL folder', possibly an invalid http URL

root_model: ClassVar[Type[pydantic.root_model.RootModel[Any]]] = <class 'pydantic.root_model.RootModel[Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'], host_required=None, default_host=None, default_port=None, default_path=None)]]'>

the pydantic root model to validate the string

def absolute(self):
19    def absolute(self):
20        """analog to `absolute` method of pathlib."""
21        return self

analog to absolute method of pathlib.

scheme: str
23    @property
24    def scheme(self) -> str:
25        return self._validated.scheme
host: Optional[str]
27    @property
28    def host(self) -> Optional[str]:
29        return self._validated.host
path: Optional[str]
31    @property
32    def path(self) -> Optional[str]:
33        return self._validated.path
parent: RootHttpUrl
35    @property
36    def parent(self) -> RootHttpUrl:
37        parsed = urlsplit(str(self))
38        path = list(parsed.path.split("/"))
39        if (
40            parsed.netloc == "zenodo.org"
41            and parsed.path.startswith("/api/records/")
42            and parsed.path.endswith("/content")
43        ):
44            path[-2:-1] = []
45        else:
46            path = path[:-1]
47
48        return RootHttpUrl(
49            urlunsplit(
50                (
51                    parsed.scheme,
52                    parsed.netloc,
53                    "/".join(path),
54                    parsed.query,
55                    parsed.fragment,
56                )
57            )
58        )
class Sha256(bioimageio.spec._internal.validated_string.ValidatedString):
23class Sha256(ValidatedString):
24    """SHA-256 hash value"""
25
26    root_model: ClassVar[Type[RootModel[Any]]] = RootModel[
27        Annotated[
28            str,
29            StringConstraints(
30                strip_whitespace=True, to_lower=True, min_length=64, max_length=64
31            ),
32        ]
33    ]

SHA-256 hash value

root_model: ClassVar[Type[pydantic.root_model.RootModel[Any]]] = <class 'pydantic.root_model.RootModel[Annotated[str, StringConstraints]]'>

the pydantic root model to validate the string

class ValidationError(builtins.ValueError):

Inappropriate argument value (of correct type).

def from_exception_data(title, line_errors, input_type='python', hide_input=False):
def error_count(self, /):
def errors( self, /, *, include_url=True, include_context=True, include_input=True):
def json( self, /, *, indent=None, include_url=True, include_context=True, include_input=True):
title
type YamlValue = Union[bool, datetime.date, datetime.datetime, int, float, str, NoneType, List[ForwardRef('YamlValue')], Dict[Union[bool, datetime.date, datetime.datetime, int, float, str, NoneType, Tuple[Union[bool, datetime.date, datetime.datetime, int, float, str, NoneType], ...]], ForwardRef('YamlValue')]]