Coverage for src/bioimageio/spec/_internal/io_basics.py: 97%

94 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 16:20 +0000

1from __future__ import annotations 

2 

3import hashlib 

4import os 

5import zipfile 

6from contextlib import nullcontext 

7from functools import partial 

8from pathlib import Path 

9from typing import Annotated, Any, ClassVar, Protocol, runtime_checkable 

10from zipfile import ZipFile 

11 

12import pydantic 

13import zipp # pyright: ignore[reportMissingTypeStubs] 

14from annotated_types import Predicate 

15from pydantic import RootModel, StringConstraints 

16 

17from .root_url import RootHttpUrl 

18from .validated_string import ValidatedString 

19 

20FileName = str 

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

22AbsoluteDirectory = Annotated[ 

23 pydantic.DirectoryPath, 

24 Predicate(Path.is_absolute), 

25 pydantic.Field(title="AbsoluteDirectory"), 

26] 

27AbsoluteFilePath = Annotated[ 

28 pydantic.FilePath, 

29 Predicate(Path.is_absolute), 

30 pydantic.Field(title="AbsoluteFilePath"), 

31] 

32 

33BIOIMAGEIO_YAML = "bioimageio.yaml" 

34DEPRECATED_BIOIMAGEIO_YAML = "rdf.yaml" 

35ALTERNATIVE_BIOIMAGEIO_YAML_NAMES = ("model.yaml",) 

36ALL_BIOIMAGEIO_YAML_NAMES = ( 

37 BIOIMAGEIO_YAML, 

38 DEPRECATED_BIOIMAGEIO_YAML, 

39) + ALTERNATIVE_BIOIMAGEIO_YAML_NAMES 

40 

41ZipPath = zipp.Path # not zipfile.Path due to https://bugs.python.org/issue40564 

42 

43 

44class Sha256(ValidatedString): 

45 """A SHA-256 hash value""" 

46 

47 root_model: ClassVar[type[RootModel[Any]]] = RootModel[ 

48 Annotated[ 

49 str, 

50 StringConstraints( 

51 strip_whitespace=True, to_lower=True, min_length=64, max_length=64 

52 ), 

53 ] 

54 ] 

55 

56 

57class BytesReaderP(Protocol): 

58 def read(self, size: int = -1, /) -> bytes: ... 

59 

60 @property 

61 def closed(self) -> bool: ... 

62 

63 def readable(self) -> bool: ... 

64 

65 def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int: ... 

66 

67 def seekable(self) -> bool: ... 

68 

69 def tell(self) -> int: ... 

70 

71 

72@runtime_checkable 

73class BytesReaderIntoP(BytesReaderP, Protocol): 

74 def readinto(self, b: bytearray | memoryview) -> int: ... 

75 

76 

77Suffix = str 

78 

79 

80class BytesReader(BytesReaderP): 

81 def __init__( 

82 self, 

83 /, 

84 reader: BytesReaderP | BytesReaderIntoP, 

85 *, 

86 sha256: Sha256 | None, 

87 suffix: Suffix, 

88 original_file_name: FileName, 

89 original_root: RootHttpUrl | AbsoluteDirectory | ZipFile, 

90 is_zipfile: bool | None, 

91 ) -> None: 

92 self._reader = reader 

93 self._sha256 = sha256 

94 self._suffix = suffix 

95 self._original_file_name = original_file_name 

96 self._original_root = original_root 

97 self._is_zipfile = is_zipfile 

98 super().__init__() 

99 

100 @property 

101 def is_zipfile(self) -> bool: 

102 if self._is_zipfile is None: 

103 pos = self.tell() 

104 self._is_zipfile = zipfile.is_zipfile(self) 

105 _ = self.seek(pos) 

106 

107 return self._is_zipfile 

108 

109 @property 

110 def sha256(self) -> Sha256: 

111 if self._sha256 is None: 

112 pos = self._reader.tell() 

113 _ = self._reader.seek(0) 

114 self._sha256 = get_sha256(self._reader) 

115 _ = self._reader.seek(pos) 

116 

117 return self._sha256 

118 

119 @property 

120 def suffix(self) -> Suffix: 

121 return self._suffix 

122 

123 @property 

124 def original_file_name(self) -> FileName: 

125 return self._original_file_name 

126 

127 @property 

128 def original_root(self) -> RootHttpUrl | AbsoluteDirectory | ZipFile: 

129 return self._original_root 

130 

131 def read(self, size: int = -1, /) -> bytes: 

132 return self._reader.read(size) 

133 

134 def read_text(self, encoding: str = "utf-8") -> str: 

135 return self._reader.read().decode(encoding) 

136 

137 def readable(self) -> bool: 

138 return True 

139 

140 def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int: 

141 return self._reader.seek(offset, whence) 

142 

143 def seekable(self) -> bool: 

144 return True 

145 

146 def tell(self) -> int: 

147 return self._reader.tell() 

148 

149 @property 

150 def closed(self) -> bool: 

151 return self._reader.closed 

152 

153 

154def get_sha256(source: BytesReaderP | BytesReaderIntoP | Path) -> Sha256: 

155 chunksize = 128 * 1024 

156 h = hashlib.sha256() 

157 

158 if isinstance(source, BytesReaderIntoP): 

159 b = bytearray(chunksize) 

160 mv = memoryview(b) 

161 for n in iter(lambda: source.readinto(mv), 0): 

162 h.update(mv[:n]) 

163 else: 

164 if isinstance(source, Path): 

165 read_ctxt = source.open(mode="rb") 

166 else: 

167 read_ctxt = nullcontext(source) 

168 

169 with read_ctxt as r: 

170 for chunk in iter(partial(r.read, chunksize), b""): 

171 h.update(chunk) 

172 

173 sha = h.hexdigest() 

174 return Sha256(sha)