Coverage for src/bioimageio/spec/_internal/io.py: 75%
525 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
1from __future__ import annotations
3import collections.abc
4import hashlib
5import sys
6import warnings
7import zipfile
8from abc import abstractmethod
9from collections.abc import Callable, Iterable, Mapping, Sequence
10from contextlib import nullcontext
11from copy import deepcopy
12from dataclasses import dataclass, field
13from datetime import date as _date
14from datetime import datetime as _datetime
15from functools import partial
16from io import TextIOWrapper
17from pathlib import Path, PurePath, PurePosixPath
18from tempfile import mkdtemp
19from typing import (
20 TYPE_CHECKING,
21 Annotated,
22 Any,
23 Generic,
24 Literal,
25 TypeAlias,
26 TypedDict,
27 TypeGuard,
28 TypeVar,
29 overload,
30)
31from urllib.parse import urlparse, urlsplit, urlunsplit
32from zipfile import ZipFile
34import httpx
35import pydantic
36from exceptiongroup import ExceptionGroup
37from genericache import NoopCache
38from genericache.digest import ContentDigest, UrlDigest
39from pydantic import (
40 DirectoryPath,
41 Field,
42 GetCoreSchemaHandler,
43 PrivateAttr,
44 RootModel,
45 TypeAdapter,
46 model_serializer,
47 model_validator,
48)
49from pydantic_core import core_schema
50from tqdm import tqdm
51from typing_extensions import (
52 LiteralString,
53 NotRequired,
54 Self,
55 Unpack,
56 assert_never,
57)
58from typing_extensions import TypeAliasType as _TypeAliasType
60from ._settings import settings
61from .io_basics import (
62 ALL_BIOIMAGEIO_YAML_NAMES,
63 ALTERNATIVE_BIOIMAGEIO_YAML_NAMES,
64 BIOIMAGEIO_YAML,
65 AbsoluteDirectory,
66 AbsoluteFilePath,
67 BytesReader,
68 FileName,
69 FilePath,
70 Sha256,
71 ZipPath,
72 get_sha256,
73)
74from .node import Node
75from .progress import ProgressbarLike
76from .root_url import FtpUrl, RootHttpUrl
77from .type_guards import is_dict, is_list, is_mapping, is_sequence
78from .url import HttpUrl
79from .validation_context import get_validation_context
80from .version_type import Version
82AbsolutePathT = TypeVar(
83 "AbsolutePathT",
84 bound=HttpUrl | AbsoluteDirectory | AbsoluteFilePath | ZipPath,
85)
88class LightHttpFileDescr(Node):
89 """http source with sha256 value (minimal validation)"""
91 source: pydantic.HttpUrl
92 """file source"""
94 sha256: Sha256
95 """SHA256 checksum of the source file"""
97 def get_reader(
98 self,
99 *,
100 progressbar: ProgressbarLike
101 | Callable[[], ProgressbarLike]
102 | bool
103 | None = None,
104 ) -> BytesReader:
105 """open the file source (download if needed)"""
106 return get_reader(self.source, sha256=self.sha256, progressbar=progressbar)
108 download = get_reader
109 """alias for get_reader() method"""
112class RelativePathBase(RootModel[PurePath], Generic[AbsolutePathT], frozen=True):
113 _absolute: AbsolutePathT = PrivateAttr()
115 @property
116 def path(self) -> PurePath:
117 return self.root
119 @property
120 def suffix(self):
121 return self.root.suffix
123 def absolute( # method not property analog to `pathlib.Path.absolute()`
124 self,
125 ) -> AbsolutePathT:
126 """get the absolute path/url
128 (resolved at time of initialization with the root of the ValidationContext)
129 """
130 return self._absolute
132 def model_post_init(self, __context: Any, /) -> None:
133 """set `_absolute` property with validation context at creation time. @private"""
134 if self.root.is_absolute():
135 raise ValueError(f"{self.root} is an absolute path.")
137 if self.root.parts and self.root.parts[0] in ("http:", "https:"):
138 raise ValueError(f"{self.root} looks like an http url.")
140 self._absolute = ( # pyright: ignore[reportAttributeAccessIssue]
141 self.get_absolute(get_validation_context().root)
142 )
143 super().model_post_init(__context)
145 def __str__(self) -> str:
146 return self.root.as_posix()
148 def __repr__(self) -> str:
149 return f"RelativePath('{self}')"
151 @model_serializer()
152 def format(self) -> str:
153 return str(self)
155 @abstractmethod
156 def get_absolute(
157 self, root: RootHttpUrl | AbsoluteDirectory | pydantic.AnyUrl | ZipFile
158 ) -> AbsolutePathT: ...
160 def _get_absolute_impl(
161 self, root: RootHttpUrl | AbsoluteDirectory | pydantic.AnyUrl | ZipFile
162 ) -> Path | HttpUrl | ZipPath:
163 if isinstance(root, Path):
164 return (root / self.root).absolute()
166 rel_path = self.root.as_posix().strip("/")
167 if isinstance(root, ZipFile):
168 return ZipPath(root, rel_path)
170 parsed = urlsplit(str(root))
171 path = list(parsed.path.strip("/").split("/"))
172 if (
173 parsed.netloc == "zenodo.org"
174 and parsed.path.startswith("/api/records/")
175 and parsed.path.endswith("/content")
176 ):
177 path.insert(-1, rel_path)
178 else:
179 path.append(rel_path)
181 return HttpUrl(
182 urlunsplit(
183 (
184 parsed.scheme,
185 parsed.netloc,
186 "/".join(path),
187 parsed.query,
188 parsed.fragment,
189 )
190 )
191 )
193 @classmethod
194 def _validate(cls, value: PurePath | str):
195 if isinstance(value, str) and value.startswith(("https://", "http://")):
196 raise ValueError(f"{value} looks like a URL, not a relative path")
198 return cls(PurePath(value))
201class RelativeFilePath(
202 RelativePathBase[AbsoluteFilePath | HttpUrl | ZipPath], frozen=True
203):
204 """A path relative to the `rdf.yaml` file (also if the RDF source is a URL)."""
206 def model_post_init(self, __context: Any, /) -> None:
207 """add validation @private"""
208 if not self.root.parts: # an empty path can only be a directory
209 raise ValueError(f"{self.root} is not a valid file path.")
211 super().model_post_init(__context)
213 def get_absolute(
214 self, root: RootHttpUrl | Path | pydantic.AnyUrl | ZipFile
215 ) -> AbsoluteFilePath | HttpUrl | ZipPath:
216 absolute = self._get_absolute_impl(root)
217 if (
218 isinstance(absolute, Path)
219 and (context := get_validation_context()).perform_io_checks
220 and str(self.root) not in context.known_files
221 and not absolute.is_file()
222 ):
223 raise ValueError(f"{absolute} does not point to an existing file")
225 return absolute
227 @property
228 def parent(self) -> RelativeDirectory:
229 return RelativeDirectory(self.root.parent)
232class RelativeDirectory(
233 RelativePathBase[AbsoluteDirectory | HttpUrl | ZipPath], frozen=True
234):
235 def get_absolute(
236 self, root: RootHttpUrl | Path | pydantic.AnyUrl | ZipFile
237 ) -> AbsoluteDirectory | HttpUrl | ZipPath:
238 absolute = self._get_absolute_impl(root)
239 if (
240 isinstance(absolute, Path)
241 and get_validation_context().perform_io_checks
242 and not absolute.is_dir()
243 ):
244 raise ValueError(f"{absolute} does not point to an existing directory")
246 return absolute
248 @property
249 def parent(self) -> RelativeDirectory:
250 return RelativeDirectory(self.root.parent)
253@dataclass(frozen=True, slots=True)
254class WithSuffix:
255 suffix: LiteralString | tuple[LiteralString, ...]
256 case_sensitive: bool
257 allow_any_parent_suffix: bool = False
258 """Considers the suffix of any parent directory as well, e.g. for `foo.zarr/bar` or `foo.zarr/bar/buz`"""
260 def __get_pydantic_core_schema__(
261 self, source: type[Any], handler: GetCoreSchemaHandler
262 ):
263 if not self.suffix:
264 raise ValueError("suffix may not be empty")
266 schema = handler(source)
267 return core_schema.no_info_after_validator_function(
268 self.validate,
269 schema,
270 )
272 def validate(self, value: FileSource | FileDescr) -> FileSource | FileDescr:
273 return validate_suffix(value, self.suffix, case_sensitive=self.case_sensitive)
276ZarrPath = Annotated[
277 pydantic.DirectoryPath,
278 pydantic.Field(title="ZarrPath"),
279 WithSuffix(".zarr", case_sensitive=True),
280]
281RelativeZarrPath = Annotated[
282 RelativeDirectory,
283 pydantic.Field(title="RelativeZarrPath"),
284 WithSuffix(".zarr", case_sensitive=True),
285]
287ZarrUrl: TypeAlias = Annotated[
288 RootHttpUrl | FtpUrl,
289 pydantic.Field(title="ZarrUrl"),
290 WithSuffix(".zarr", case_sensitive=True, allow_any_parent_suffix=True),
291]
292"""An untested HTTP/FTP URL to a zarr (sub) directory"""
295FileSource: TypeAlias = Annotated[
296 HttpUrl | RelativeFilePath | FilePath,
297 Field(title="FileSource", union_mode="left_to_right"),
298]
299ZarrSource: TypeAlias = Annotated[
300 ZarrUrl | RelativeZarrPath | ZarrPath,
301 Field(title="ZarrSource", union_mode="left_to_right"),
302]
305class FileDescr(Node):
306 """A file description"""
308 source: FileSource
309 """File source"""
311 sha256: Sha256 | None = None
312 """SHA256 hash value of the **source** file."""
314 @model_validator(mode="after")
315 def _validate_sha256(self) -> Self:
316 self.validate_sha256()
317 return self
319 def validate_sha256(self, force_recompute: bool = False) -> None:
320 """validate the sha256 hash value of the **source** file"""
321 context = get_validation_context()
322 src_str = str(self.source)
323 if force_recompute:
324 actual_sha = None
325 else:
326 actual_sha = context.known_files.get(src_str)
328 if actual_sha is None:
329 if context.perform_io_checks or force_recompute:
330 reader = get_reader(self.source, sha256=self.sha256)
331 if force_recompute:
332 actual_sha = get_sha256(reader)
333 else:
334 actual_sha = reader.sha256
336 context.known_files[src_str] = actual_sha
337 elif context.known_files and src_str not in context.known_files:
338 # perform_io_checks is False, but known files were given,
339 # so we expect all file references to be in there
340 raise ValueError(f"File {src_str} not found in `known_files`.")
342 if actual_sha is None or self.sha256 == actual_sha:
343 return
344 elif self.sha256 is None or context.update_hashes:
345 self.sha256 = actual_sha
346 elif self.sha256 != actual_sha:
347 raise ValueError(
348 f"Sha256 mismatch for {self.source}. Expected {self.sha256}, got "
349 + f"{actual_sha}. Update expected `sha256` or point to the matching "
350 + "file."
351 )
353 def get_reader(
354 self,
355 *,
356 progressbar: ProgressbarLike
357 | Callable[[], ProgressbarLike]
358 | bool
359 | None = None,
360 ):
361 """open the file source (download if needed)"""
362 return get_reader(self.source, progressbar=progressbar, sha256=self.sha256)
364 def download(
365 self,
366 *,
367 progressbar: ProgressbarLike
368 | Callable[[], ProgressbarLike]
369 | bool
370 | None = None,
371 ):
372 """alias for `.get_reader`"""
373 return get_reader(self.source, progressbar=progressbar, sha256=self.sha256)
375 @property
376 def suffix(self) -> str:
377 return self.source.suffix
380PermissiveFileSource: TypeAlias = (
381 FileSource | str | pydantic.HttpUrl | FileDescr | ZipPath
382)
385path_or_url_adapter: TypeAdapter[FilePath | DirectoryPath | HttpUrl] = TypeAdapter(
386 FilePath | DirectoryPath | HttpUrl
387)
390def wo_special_file_name(src: F) -> F:
391 if has_valid_bioimageio_yaml_name(src):
392 raise ValueError(
393 f"'{src}' not allowed here as its filename is reserved to identify"
394 + f" '{BIOIMAGEIO_YAML}' (or equivalent) files."
395 )
397 return src
400def has_valid_bioimageio_yaml_name(
401 src: ZarrSource | FileSource | FileDescr,
402) -> bool:
403 return is_valid_bioimageio_yaml_name(extract_file_name(src))
406def is_valid_bioimageio_yaml_name(file_name: FileName) -> bool:
407 for bioimageio_name in ALL_BIOIMAGEIO_YAML_NAMES:
408 if file_name == bioimageio_name or file_name.endswith("." + bioimageio_name):
409 return True
411 return False
414def identify_bioimageio_yaml_file_name(file_names: Iterable[FileName]) -> FileName:
415 file_names = sorted(file_names)
416 for bioimageio_name in ALL_BIOIMAGEIO_YAML_NAMES:
417 for file_name in file_names:
418 if file_name == bioimageio_name or file_name.endswith(
419 "." + bioimageio_name
420 ):
421 return file_name
423 raise ValueError(
424 f"No {BIOIMAGEIO_YAML} found in {file_names}. (Looking for '{BIOIMAGEIO_YAML}'"
425 + " or or any of the alterntive file names:"
426 + f" {ALTERNATIVE_BIOIMAGEIO_YAML_NAMES}, or any file with an extension of"
427 + f" those, e.g. 'anything.{BIOIMAGEIO_YAML}')."
428 )
431def find_bioimageio_yaml_file_name(path: Path | ZipFile) -> FileName:
432 if isinstance(path, ZipFile):
433 file_names = path.namelist()
434 elif path.is_file():
435 if not zipfile.is_zipfile(path):
436 return path.name
438 with ZipFile(path, "r") as f:
439 file_names = f.namelist()
440 else:
441 file_names = [p.name for p in path.iterdir() if p.is_file()]
443 return identify_bioimageio_yaml_file_name(file_names)
446def ensure_has_valid_bioimageio_yaml_name(src: FileSource) -> FileSource:
447 if not has_valid_bioimageio_yaml_name(src):
448 raise ValueError(
449 f"'{src}' does not have a valid filename to identify"
450 + f" '{BIOIMAGEIO_YAML}' (or equivalent) files."
451 )
453 return src
456def ensure_is_valid_bioimageio_yaml_name(file_name: FileName) -> FileName:
457 if not is_valid_bioimageio_yaml_name(file_name):
458 raise ValueError(
459 f"'{file_name}' is not a valid filename to identify"
460 + f" '{BIOIMAGEIO_YAML}' (or equivalent) files."
461 )
463 return file_name
466# types as loaded from YAML 1.2 (with ruyaml)
467YamlLeafValue: TypeAlias = (
468 bool | _date | _datetime | int | float | str | None
469) # note: order relevant for deserializing
470# YAML Arrays are cast to tuples if used as key in mappings, nesting is not allowed though
471YamlKey: TypeAlias = YamlLeafValue | tuple[YamlLeafValue, ...]
472if TYPE_CHECKING:
473 YamlValue: TypeAlias = (
474 YamlLeafValue | list["YamlValue"] | dict[YamlKey, "YamlValue"]
475 )
476 YamlValueView: TypeAlias = (
477 YamlLeafValue | Sequence["YamlValueView"] | Mapping[YamlKey, "YamlValueView"]
478 )
479else:
480 # for pydantic validation we need to use `TypeAliasType`,
481 # see https://docs.pydantic.dev/latest/concepts/types/#named-recursive-types
482 # however this results in a partially unknown type with the current pyright 1.1.388
483 YamlValue: TypeAlias = _TypeAliasType(
484 "YamlValue",
485 YamlLeafValue | list["YamlValue"] | dict[YamlKey, "YamlValue"],
486 )
487 YamlValueView: TypeAlias = _TypeAliasType(
488 "YamlValueView",
489 YamlLeafValue | Sequence["YamlValueView"] | Mapping[YamlKey, "YamlValueView"],
490 )
493BioimageioYamlContent = dict[str, YamlValue]
494BioimageioYamlContentView = Mapping[str, YamlValueView]
496IncompleteDescrLeaf = Node | YamlValue | PermissiveFileSource | Version
497"""Leaf value of a partial description"""
499IncompleteDescrInner = (
500 IncompleteDescrLeaf
501 | list["IncompleteDescrInner"]
502 | dict[YamlKey, "IncompleteDescrInner"]
503)
505"""An inner node of an incomplete resource description --- YAML values and description nodes mixed."""
507IncompleteDescr = dict[str, IncompleteDescrInner]
508"""An incomplete resource description --- YAML values and description nodes mixed."""
511IncompleteDescrLeafView = Node | YamlValueView | PermissiveFileSource | Version
512"""Non-editable leaf value of an incomplete description"""
514IncompleteDescrInnerView = (
515 IncompleteDescrLeafView
516 | Sequence["IncompleteDescrInnerView"]
517 | Mapping[YamlKey, "IncompleteDescrInnerView"]
518)
519"""A inner node of a non-editable incomplete resource description --- YAML value views and Node instances mixed."""
521IncompleteDescrView = Mapping[str, IncompleteDescrInnerView]
522"""A non-editable incomplete resource description --- YAML mappings and Node instances mixed."""
525BioimageioYamlSource: TypeAlias = (
526 PermissiveFileSource | ZipFile | BioimageioYamlContent | BioimageioYamlContentView
527)
530@overload
531def deepcopy_yaml_value(value: BioimageioYamlContentView) -> BioimageioYamlContent: ...
534@overload
535def deepcopy_yaml_value(value: YamlValueView) -> YamlValue: ...
538def deepcopy_yaml_value(
539 value: BioimageioYamlContentView | YamlValueView,
540) -> BioimageioYamlContent | YamlValue:
541 if isinstance(value, collections.abc.Mapping):
542 return {key: deepcopy_yaml_value(val) for key, val in value.items()}
543 elif isinstance(value, collections.abc.Sequence):
544 return [deepcopy_yaml_value(val) for val in value]
545 else:
546 return value
549def deepcopy_incomplete_descr(data: IncompleteDescrView) -> IncompleteDescr:
550 return {k: _deepcopy_incomplete_descr_impl(v) for k, v in data.items()}
553def _deepcopy_incomplete_descr_impl(
554 data: IncompleteDescrInnerView,
555) -> IncompleteDescrInner:
556 if isinstance(data, Node):
557 return deepcopy(data)
558 elif isinstance(data, str):
559 return data
560 elif isinstance(data, collections.abc.Mapping):
561 return {k: _deepcopy_incomplete_descr_impl(v) for k, v in data.items()}
562 elif isinstance(data, collections.abc.Sequence):
563 return [_deepcopy_incomplete_descr_impl(v) for v in data]
564 elif isinstance(
565 data,
566 (
567 HttpUrl,
568 Path,
569 PurePath,
570 RelativeFilePath,
571 RelativeDirectory,
572 Version,
573 _date,
574 _datetime,
575 bool,
576 float,
577 int,
578 pydantic.HttpUrl,
579 type(None),
580 ZipPath,
581 ),
582 ):
583 return data
584 else:
585 assert_never(data)
588def is_yaml_leaf_value(value: Any) -> TypeGuard[YamlLeafValue]:
589 return isinstance(value, (bool, _date, _datetime, int, float, str, type(None)))
592def is_yaml_list(value: Any) -> TypeGuard[list[YamlValue]]:
593 return is_list(value) and all(is_yaml_value(item) for item in value)
596def is_yaml_sequence(value: Any) -> TypeGuard[list[YamlValueView]]:
597 return is_sequence(value) and all(is_yaml_value(item) for item in value)
600def is_yaml_dict(value: Any) -> TypeGuard[BioimageioYamlContent]:
601 return is_dict(value) and all(
602 isinstance(key, str) and is_yaml_value(val) for key, val in value.items()
603 )
606def is_yaml_mapping(value: Any) -> TypeGuard[BioimageioYamlContentView]:
607 return is_mapping(value) and all(
608 isinstance(key, str) and is_yaml_value_read_only(val)
609 for key, val in value.items()
610 )
613def is_yaml_value(value: Any) -> TypeGuard[YamlValue]:
614 return is_yaml_leaf_value(value) or is_yaml_list(value) or is_yaml_dict(value)
617def is_yaml_value_read_only(value: Any) -> TypeGuard[YamlValueView]:
618 return (
619 is_yaml_leaf_value(value) or is_yaml_sequence(value) or is_yaml_mapping(value)
620 )
623@dataclass(frozen=True, slots=True)
624class OpenedBioimageioYaml:
625 content: BioimageioYamlContent = field(repr=False)
626 original_root: AbsoluteDirectory | RootHttpUrl | ZipFile
627 original_source_name: str | None
628 original_file_name: FileName
629 unparsed_content: str = field(repr=False)
632@dataclass(frozen=True, slots=True)
633class LocalFile:
634 path: FilePath
635 original_root: AbsoluteDirectory | RootHttpUrl | ZipFile
636 original_file_name: FileName
639@dataclass(frozen=True, slots=True)
640class FileInZip:
641 path: ZipPath
642 original_root: RootHttpUrl | ZipFile
643 original_file_name: FileName
646class HashKwargs(TypedDict):
647 sha256: NotRequired[Sha256 | None]
650_file_source_adapter: TypeAdapter[FileSource] = TypeAdapter(FileSource)
651_zarr_source_adapter: TypeAdapter[ZarrSource] = TypeAdapter(ZarrSource)
654@overload
655def interprete_file_source(
656 file_source: str | pydantic.AnyUrl, allow_zarr: Literal[False] = False
657) -> FileSource: ...
660@overload
661def interprete_file_source(
662 file_source: str | pydantic.AnyUrl, allow_zarr: Literal[True] = True
663) -> FileSource | ZarrSource: ...
666def interprete_file_source(
667 file_source: str | pydantic.AnyUrl, allow_zarr: bool = False
668) -> FileSource | ZarrSource:
669 file_source = str(file_source)
670 with get_validation_context().replace(perform_io_checks=False):
671 try:
672 strict = _file_source_adapter.validate_python(file_source)
673 except Exception as e1:
674 if allow_zarr:
675 try:
676 strict = _zarr_source_adapter.validate_python(file_source)
677 except Exception as e2:
678 raise ExceptionGroup(
679 f"Could not interpret {file_source} as a file source or zarr source.",
680 (e1, e2),
681 )
682 else:
683 raise
685 return strict
688def interprete_zarr_source(
689 zarr_source: str | pydantic.AnyUrl,
690) -> ZarrSource:
691 zarr_source = str(zarr_source)
692 with get_validation_context().replace(perform_io_checks=False):
693 strict = _zarr_source_adapter.validate_python(zarr_source)
695 return strict
698def extract(
699 source: FilePath | ZipFile | ZipPath,
700 folder: DirectoryPath | None = None,
701 overwrite: bool = False,
702) -> DirectoryPath:
703 extract_member = None
704 if isinstance(source, ZipPath):
705 extract_member = source.at
706 source = source.root
708 if isinstance(source, ZipFile):
709 zip_context = nullcontext(source)
710 if folder is None:
711 if source.filename is None:
712 folder = Path(mkdtemp())
713 else:
714 zip_path = Path(source.filename)
715 folder = zip_path.with_suffix(zip_path.suffix + ".unzip")
716 else:
717 zip_context = ZipFile(source, "r")
718 if folder is None:
719 folder = source.with_suffix(source.suffix + ".unzip")
721 if overwrite and folder.exists():
722 warnings.warn(f"Overwriting existing unzipped archive at {folder}")
724 with zip_context as f:
725 if extract_member is not None:
726 extracted_file_path = folder / extract_member
727 if extracted_file_path.exists() and not overwrite:
728 warnings.warn(f"Found unzipped {extracted_file_path}.")
729 else:
730 _ = f.extract(extract_member, folder)
732 return folder
734 elif overwrite or not folder.exists():
735 f.extractall(folder)
736 return folder
738 found_content = {p.relative_to(folder).as_posix() for p in folder.glob("*")}
739 expected_content = {info.filename for info in f.filelist}
740 if expected_missing := expected_content - found_content:
741 parts = folder.name.split("_")
742 nr, *suffixes = parts[-1].split(".")
743 if nr.isdecimal():
744 nr = str(int(nr) + 1)
745 else:
746 nr = f"1.{nr}"
748 parts[-1] = ".".join([nr, *suffixes])
749 out_path_new = folder.with_name("_".join(parts))
750 warnings.warn(
751 f"Unzipped archive at {folder} is missing expected files"
752 + f" {expected_missing}."
753 + f" Unzipping to {out_path_new} instead to avoid overwriting."
754 )
755 return extract(f, out_path_new, overwrite=overwrite)
756 else:
757 warnings.warn(
758 f"Found unzipped archive with all expected files at {folder}."
759 )
760 return folder
763def get_reader(
764 source: PermissiveFileSource | FileDescr | ZipPath,
765 /,
766 progressbar: ProgressbarLike | Callable[[], ProgressbarLike] | bool | None = None,
767 **kwargs: Unpack[HashKwargs],
768) -> BytesReader:
769 """Open a file `source` (download if needed)"""
770 if isinstance(source, FileDescr):
771 if "sha256" not in kwargs:
772 kwargs["sha256"] = source.sha256
774 source = source.source
775 elif isinstance(source, str):
776 source = interprete_file_source(source)
778 if isinstance(source, RelativeDirectory):
779 raise ValueError(f"{source} is not a file source, but a directory")
780 elif isinstance(source, RelativeFilePath):
781 source = source.absolute()
782 elif isinstance(source, (pydantic.AnyUrl, RootHttpUrl)):
783 with get_validation_context().replace(perform_io_checks=False):
784 source = HttpUrl(source)
786 if isinstance(source, FtpUrl):
787 raise NotImplementedError(
788 "FTP URLs are not supported yet. Please use HTTP(S) URLs instead."
789 )
791 if isinstance(source, HttpUrl):
792 return _open_url(source, progressbar=progressbar, **kwargs)
794 if isinstance(source, ZipPath):
795 if not source.exists():
796 raise FileNotFoundError(source.filename)
798 f = source.open(mode="rb")
799 assert not isinstance(f, TextIOWrapper)
800 root = source.root
801 elif isinstance(source, Path):
802 if source.is_dir():
803 raise FileNotFoundError(f"{source} is a directory, not a file")
805 if not source.exists():
806 raise FileNotFoundError(source)
808 f = source.open("rb")
809 root = source.parent
810 else:
811 assert_never(source)
813 expected_sha = kwargs.get("sha256")
814 if expected_sha is None:
815 sha = None
816 else:
817 sha = get_sha256(f)
818 _ = f.seek(0)
819 if sha != expected_sha:
820 raise ValueError(
821 f"SHA256 mismatch for {source}. Expected {expected_sha}, got {sha}."
822 )
824 return BytesReader(
825 f,
826 sha256=sha,
827 suffix=source.suffix,
828 original_file_name=source.name,
829 original_root=root,
830 is_zipfile=None,
831 )
834download = get_reader
837def _open_url(
838 source: HttpUrl,
839 /,
840 progressbar: ProgressbarLike | Callable[[], ProgressbarLike] | bool | None,
841 **kwargs: Unpack[HashKwargs],
842) -> BytesReader:
843 cache = (
844 NoopCache[RootHttpUrl](url_hasher=UrlDigest.from_str)
845 if get_validation_context().disable_cache
846 else settings.disk_cache
847 )
848 sha = kwargs.get("sha256")
849 force_refetch = True if sha is None else ContentDigest.parse(hexdigest=sha)
850 source_path = PurePosixPath(
851 source.path
852 or sha
853 or hashlib.sha256(str(source).encode(encoding="utf-8")).hexdigest()
854 )
856 reader = cache.fetch(
857 source,
858 fetcher=partial(_fetch_url, progressbar=progressbar),
859 force_refetch=force_refetch,
860 )
861 return BytesReader(
862 reader,
863 suffix=source_path.suffix,
864 sha256=sha,
865 original_file_name=source_path.name,
866 original_root=source.parent,
867 is_zipfile=None,
868 )
871def _fetch_url(
872 source: RootHttpUrl,
873 *,
874 progressbar: ProgressbarLike | Callable[[], ProgressbarLike] | bool | None,
875):
876 if source.scheme not in ("http", "https"):
877 raise NotImplementedError(source.scheme)
879 if progressbar is None:
880 # chose progressbar option from validation context
881 progressbar = get_validation_context().progressbar
883 if progressbar is None:
884 # default to no progressbar in CI environments
885 progressbar = not settings.CI
887 if callable(progressbar):
888 progressbar = progressbar()
890 if isinstance(progressbar, bool) and progressbar:
891 progressbar = tqdm(
892 ncols=79,
893 ascii=bool(sys.platform == "win32"),
894 unit="B",
895 unit_scale=True,
896 leave=True,
897 )
899 if progressbar is not False:
900 progressbar.set_description(f"Downloading {extract_file_name(source)}")
902 headers: dict[str, str] = {}
903 if settings.user_agent is not None:
904 headers["User-Agent"] = settings.user_agent
905 elif settings.CI:
906 headers["User-Agent"] = "ci"
908 r = httpx.get(
909 str(source),
910 follow_redirects=True,
911 headers=headers,
912 timeout=settings.http_timeout,
913 )
914 _ = r.raise_for_status()
916 # set progressbar.total
917 total = r.headers.get("content-length")
918 if total is not None and not isinstance(total, int):
919 try:
920 total = int(total)
921 except Exception:
922 total = None
924 if progressbar is not False:
925 if total is None:
926 progressbar.total = 0
927 else:
928 progressbar.total = total
930 def iter_content():
931 for chunk in r.iter_bytes(chunk_size=4096):
932 yield chunk
933 if progressbar is not False:
934 _ = progressbar.update(len(chunk))
936 # Make sure the progress bar gets filled even if the actual number
937 # is chunks is smaller than expected. This happens when streaming
938 # text files that are compressed by the server when sending (gzip).
939 # Binary files don't experience this.
940 # (adapted from pooch.HttpDownloader)
941 if progressbar is not False:
942 progressbar.reset()
943 if total is not None:
944 _ = progressbar.update(total)
946 progressbar.close()
948 return iter_content()
951def extract_file_name(
952 src: ZarrSource | FileSource | FileDescr | ZipPath,
953) -> FileName:
954 if isinstance(src, FileDescr):
955 src = src.source
957 if isinstance(src, ZipPath):
958 return src.name or src.root.filename or "bioimageio.zip"
959 elif isinstance(src, (RelativeFilePath, RelativeDirectory)):
960 return src.path.name
961 elif isinstance(src, PurePath):
962 return src.name
963 else:
964 url = urlparse(str(src))
965 if (
966 url.scheme == "https"
967 and url.hostname == "zenodo.org"
968 and url.path.startswith("/api/records/")
969 and url.path.endswith("/content")
970 ):
971 return url.path.split("/")[-2]
972 else:
973 return url.path.split("/")[-1]
976def extract_file_descrs(
977 data: IncompleteDescrView,
978) -> list[FileDescr]:
979 collected: list[FileDescr] = []
980 with get_validation_context().replace(perform_io_checks=False, log_warnings=False):
981 _extract_file_descrs_impl(data, collected)
983 return collected
986def _extract_file_descrs_impl(
987 data: IncompleteDescrView | IncompleteDescrInnerView,
988 collected: list[FileDescr],
989) -> None:
990 if isinstance(data, FileDescr):
991 collected.append(data)
992 elif isinstance(data, Node):
993 for _, v in data:
994 _extract_file_descrs_impl(v, collected)
995 elif isinstance(data, collections.abc.Mapping):
996 if "source" in data and "sha256" in data:
997 try:
998 fd = FileDescr.model_validate(
999 {"source": data["source"], "sha256": data["sha256"]}
1000 )
1001 except Exception:
1002 warnings.warn(
1003 "Found mapping with 'source' and 'sha256' keys, but could not parse it as a FileDescr. Ignoring `sha256`."
1004 )
1005 try:
1006 fd = FileDescr.model_validate({"source": data["source"]})
1007 except Exception:
1008 warnings.warn(
1009 f"Found mapping with 'source' and `sha256' keys , but could not parse it as a FileDescr, evning when ignoring 'sha256'. Ignoring `source`: {data['source']}."
1010 )
1011 else:
1012 collected.append(fd)
1013 else:
1014 collected.append(fd)
1016 for v in data.values():
1017 _extract_file_descrs_impl(v, collected)
1018 elif not isinstance(data, (str, Path, RelativeFilePath)) and isinstance(
1019 data, collections.abc.Sequence
1020 ):
1021 for v in data:
1022 _extract_file_descrs_impl(v, collected)
1025F = TypeVar("F", bound=ZarrSource | FileSource | FileDescr)
1028def validate_suffix(
1029 value: F,
1030 suffix: str | Sequence[str],
1031 *,
1032 case_sensitive: bool,
1033 allow_any_parent_suffix: bool = False,
1034) -> F:
1035 """check final suffix"""
1036 if isinstance(suffix, str):
1037 suffixes = [suffix]
1038 else:
1039 suffixes = suffix
1041 assert len(suffixes) > 0, "no suffix given"
1042 assert all(suff.startswith(".") for suff in suffixes), (
1043 "expected suffixes to start with '.'"
1044 )
1045 o_value = value
1046 if isinstance(value, FileDescr):
1047 strict = value.source
1048 elif isinstance(value, (str, pydantic.AnyUrl)):
1049 strict = interprete_file_source(value)
1050 else:
1051 strict = value
1053 if isinstance(strict, (HttpUrl, pydantic.AnyUrl, RootHttpUrl, FtpUrl)):
1054 if strict.path is None or "." not in (path := strict.path):
1055 actual_suffixes = []
1056 else:
1057 if (
1058 strict.host == "zenodo.org"
1059 and path.startswith("/api/records/")
1060 and path.endswith("/content")
1061 ):
1062 # Zenodo API URLs have a "/content" suffix that should be ignored
1063 path = path[: -len("/content")]
1065 actual_suffixes = [f".{path.split('.')[-1]}"]
1067 elif isinstance(strict, PurePath):
1068 actual_suffixes = strict.suffixes
1069 elif isinstance(strict, (RelativeFilePath, RelativeDirectory)):
1070 actual_suffixes = strict.path.suffixes
1071 else:
1072 assert_never(strict)
1074 if actual_suffixes:
1075 actual_suffix = actual_suffixes[-1]
1076 else:
1077 actual_suffix = "no suffix"
1079 if (
1080 case_sensitive
1081 and actual_suffix not in suffixes
1082 or not case_sensitive
1083 and actual_suffix.lower() not in [s.lower() for s in suffixes]
1084 ):
1085 if allow_any_parent_suffix and strict != strict.parent:
1086 try:
1087 _ = validate_suffix(
1088 strict.parent,
1089 suffix,
1090 case_sensitive=case_sensitive,
1091 allow_any_parent_suffix=allow_any_parent_suffix,
1092 )
1093 except ValueError:
1094 pass
1095 else:
1096 return o_value
1098 if len(suffixes) == 1:
1099 raise ValueError(f"Expected suffix {suffixes[0]}, but got {actual_suffix}")
1100 else:
1101 raise ValueError(
1102 f"Expected a suffix from {suffixes}, but got {actual_suffix}"
1103 )
1105 return o_value
1108def populate_cache(sources: Sequence[FileDescr | LightHttpFileDescr]):
1109 unique: set[str] = set()
1110 for src in sources:
1111 if src.sha256 is None:
1112 continue # not caching without known SHA
1114 if isinstance(src.source, (HttpUrl, pydantic.AnyUrl)):
1115 url = str(src.source)
1116 elif isinstance(src.source, RelativeFilePath):
1117 if isinstance(absolute := src.source.absolute(), HttpUrl):
1118 url = str(absolute)
1119 else:
1120 continue # not caching local paths
1121 elif isinstance(src.source, Path):
1122 continue # not caching local paths
1123 elif isinstance(src.source, (RootHttpUrl, RelativeDirectory)):
1124 continue # not caching directories
1125 elif isinstance(src.source, FtpUrl):
1126 continue # not caching FTP URLs
1127 else:
1128 assert_never(src.source)
1130 if url in unique:
1131 continue # skip duplicate URLs
1133 unique.add(url)
1134 _ = src.download()