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 ( 11 AbsoluteDirectory, 12 AbsoluteFilePath, 13 FileName, 14 Sha256, 15 ZipPath, 16) 17from ._internal.root_url import RootHttpUrl 18from ._internal.types import ( 19 FilePath, 20 FileSource, 21 PermissiveFileSource, 22 RelativeFilePath, 23) 24from ._internal.url import HttpUrl 25 26__all__ = [ 27 "AbsoluteDirectory", 28 "AbsoluteFilePath", 29 "BioimageioYamlContent", 30 "BioimageioYamlSource", 31 "FileDescr", 32 "FileName", 33 "FilePath", 34 "FileSource", 35 "HttpUrl", 36 "InvalidDescr", 37 "PermissiveFileSource", 38 "RelativeFilePath", 39 "RootHttpUrl", 40 "Sha256", 41 "ValidationError", 42 "YamlValue", 43 "ZipPath", 44]
AbsoluteDirectory =
typing.Annotated[pathlib.Path, PathType(path_type='dir'), Predicate(is_absolute), FieldInfo(annotation=NoneType, required=True, title='AbsoluteDirectory')]
AbsoluteFilePath =
typing.Annotated[pathlib.Path, PathType(path_type='file'), Predicate(is_absolute), FieldInfo(annotation=NoneType, required=True, title='AbsoluteFilePath')]
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, title='FilePath')]], 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]]
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)
source: Annotated[Union[HttpUrl, RelativeFilePath, Annotated[pathlib.Path, PathType(path_type='file'), FieldInfo(annotation=NoneType, required=True, title='FilePath')]], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')]), AfterValidator(func=<function wo_special_file_name at 0x7fec152e3740>), PlainSerializer(func=<function _package at 0x7fec152e2a20>, return_type=PydanticUndefined, when_used='unless-none')]
∈📦 file source
@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
Inherited Members
FileName =
<class 'str'>
FilePath =
typing.Annotated[pathlib.Path, PathType(path_type='file'), FieldInfo(annotation=NoneType, required=True, title='FilePath')]
FileSource =
typing.Annotated[typing.Union[HttpUrl, RelativeFilePath, typing.Annotated[pathlib.Path, PathType(path_type='file'), FieldInfo(annotation=NoneType, required=True, title='FilePath')]], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]
118class HttpUrl(RootHttpUrl): 119 """A URL with the HTTP or HTTPS scheme.""" 120 121 root_model: ClassVar[Type[RootModel[Any]]] = RootModel[pydantic.HttpUrl] 122 _exists: Optional[bool] = None 123 124 def _after_validator(self): 125 self = super()._after_validator() 126 context = validation_context_var.get() 127 if ( 128 context.perform_io_checks 129 and str(self._validated) not in context.known_files 130 ): 131 self._validated = _validate_url(self._validated) 132 self._exists = True 133 134 return self 135 136 def exists(self): 137 """True if URL is available""" 138 if self._exists is None: 139 try: 140 self._validated = _validate_url(self._validated) 141 except Exception as e: 142 logger.info(e) 143 self._exists = False 144 else: 145 self._exists = True 146 147 return self._exists
A URL with the HTTP or HTTPS scheme.
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):
136 def exists(self): 137 """True if URL is available""" 138 if self._exists is None: 139 try: 140 self._validated = _validate_url(self._validated) 141 except Exception as e: 142 logger.info(e) 143 self._exists = False 144 else: 145 self._exists = True 146 147 return self._exists
True if URL is available
431class InvalidDescr( 432 ResourceDescrBase, 433 extra="allow", 434 title="An invalid resource description", 435): 436 """A representation of an invalid resource description""" 437 438 type: Any = "unknown" 439 format_version: Any = "unknown" 440 fields_to_set_explicitly: ClassVar[FrozenSet[LiteralString]] = frozenset()
A representation of an invalid resource description
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'
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, title='FilePath')]], 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), FieldInfo(annotation=NoneType, required=True, title='AbsoluteFilePath')], 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
Inherited Members
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
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 )
33class Sha256(ValidatedString): 34 """A SHA-256 hash value""" 35 36 root_model: ClassVar[Type[RootModel[Any]]] = RootModel[ 37 Annotated[ 38 str, 39 StringConstraints( 40 strip_whitespace=True, to_lower=True, min_length=64, max_length=64 41 ), 42 ] 43 ]
A SHA-256 hash value
class
ValidationError(builtins.ValueError):
Inappropriate argument value (of correct type).
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')]]
ZipPath =
<class 'zipp.Path'>