Coverage for src/bioimageio/spec/_package.py: 83%

96 statements  

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

1from __future__ import annotations 

2 

3import collections.abc 

4import shutil 

5from collections.abc import Sequence 

6from io import BytesIO 

7from pathlib import Path 

8from tempfile import NamedTemporaryFile, mkdtemp 

9from typing import IO, Literal 

10from zipfile import ZIP_DEFLATED 

11 

12from loguru import logger 

13from pydantic import DirectoryPath, FilePath, NewPath 

14 

15from ._description import InvalidDescr, ResourceDescr, build_description 

16from ._internal.common_nodes import ResourceDescrBase 

17from ._internal.io import ( 

18 BioimageioYamlContent, 

19 BioimageioYamlSource, 

20 FileDescr, 

21 RelativeFilePath, 

22 ensure_is_valid_bioimageio_yaml_name, 

23) 

24from ._internal.io_basics import ( 

25 BIOIMAGEIO_YAML, 

26 AbsoluteFilePath, 

27 BytesReader, 

28 FileName, 

29 ZipPath, 

30) 

31from ._internal.io_utils import open_bioimageio_yaml, write_yaml, write_zip 

32from ._internal.packaging_context import PackagingContext 

33from ._internal.url import HttpUrl 

34from ._internal.utils import get_os_friendly_file_name 

35from ._internal.validation_context import get_validation_context 

36from ._internal.warning_levels import ERROR 

37from ._io import load_description 

38from .model.v0_4 import WeightsFormat 

39 

40 

41def get_resource_package_content( 

42 rd: ResourceDescr, 

43 /, 

44 *, 

45 bioimageio_yaml_file_name: FileName = BIOIMAGEIO_YAML, 

46 weights_priority_order: Sequence[WeightsFormat] | None = None, # model only 

47) -> dict[FileName, HttpUrl | AbsoluteFilePath | BioimageioYamlContent | ZipPath]: 

48 """DEPRECATED in favor of get_package_content: Get the content of a bioimage.io resource package.""" 

49 ret: dict[ 

50 FileName, HttpUrl | AbsoluteFilePath | BioimageioYamlContent | ZipPath 

51 ] = {} 

52 for k, v in get_package_content( 

53 rd, 

54 bioimageio_yaml_file_name=bioimageio_yaml_file_name, 

55 weights_priority_order=weights_priority_order, 

56 ).items(): 

57 if isinstance(v, FileDescr): 

58 if isinstance(v.source, (Path, RelativeFilePath)): 

59 ret[k] = v.source.absolute() 

60 else: 

61 ret[k] = v.source 

62 

63 else: 

64 ret[k] = v 

65 

66 return ret 

67 

68 

69def get_package_content( 

70 rd: ResourceDescr, 

71 /, 

72 *, 

73 bioimageio_yaml_file_name: FileName = BIOIMAGEIO_YAML, 

74 weights_priority_order: Sequence[WeightsFormat] | None = None, # model only 

75 local_files_only: bool = False, 

76) -> dict[FileName, FileDescr | BioimageioYamlContent]: 

77 """ 

78 Args: 

79 rd: resource description 

80 bioimageio_yaml_file_name: RDF file name 

81 weights_priority_order: (for model resources only) 

82 If given, only the first weights format present in the model is included. 

83 If none of the prioritized weights formats is found a ValueError is raised. 

84 local_files_only: If True, only local files are included in the package content. If False, remote files are also included. 

85 """ 

86 os_friendly_name = get_os_friendly_file_name(rd.name) 

87 bioimageio_yaml_file_name = bioimageio_yaml_file_name.format( 

88 name=os_friendly_name, type=rd.type 

89 ) 

90 

91 bioimageio_yaml_file_name = ensure_is_valid_bioimageio_yaml_name( 

92 bioimageio_yaml_file_name 

93 ) 

94 content: dict[FileName, FileDescr] = {} 

95 with PackagingContext( 

96 bioimageio_yaml_file_name=bioimageio_yaml_file_name, 

97 file_sources=content, 

98 weights_priority_order=weights_priority_order, 

99 local_files_only=local_files_only, 

100 ): 

101 rdf_content: BioimageioYamlContent = rd.model_dump( 

102 mode="json", exclude_unset=True 

103 ) 

104 

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

106 

107 return {**content, bioimageio_yaml_file_name: rdf_content} 

108 

109 

110def _prepare_resource_package( 

111 source: BioimageioYamlSource | ResourceDescr, 

112 /, 

113 *, 

114 weights_priority_order: Sequence[WeightsFormat] | None = None, 

115 local_files_only: bool = False, 

116) -> dict[FileName, BioimageioYamlContent | BytesReader]: 

117 """Prepare to package a resource description; downloads all required files. 

118 

119 Args: 

120 source: A bioimage.io resource description (as file, raw YAML content or description class) 

121 context: validation context 

122 weights_priority_order: If given only the first weights format present in the model is included. 

123 If none of the prioritized weights formats is found all are included. 

124 local_files_only: If True, only local files are included in the package. If False, remote files are also included. 

125 """ 

126 context = get_validation_context() 

127 bioimageio_yaml_file_name = context.file_name 

128 if isinstance(source, ResourceDescrBase): 

129 descr = source 

130 elif isinstance(source, collections.abc.Mapping): 

131 descr = build_description(source) 

132 else: 

133 opened = open_bioimageio_yaml(source) 

134 bioimageio_yaml_file_name = opened.original_file_name 

135 context = context.replace( 

136 root=opened.original_root, file_name=opened.original_file_name 

137 ) 

138 with context: 

139 descr = build_description(opened.content) 

140 

141 if isinstance(descr, InvalidDescr): 

142 raise ValueError(f"Resource description is invalid:\n{descr.get_reason()}") 

143 

144 with context: 

145 package_content = get_package_content( 

146 descr, 

147 bioimageio_yaml_file_name=bioimageio_yaml_file_name or BIOIMAGEIO_YAML, 

148 weights_priority_order=weights_priority_order, 

149 local_files_only=local_files_only, 

150 ) 

151 

152 return { 

153 k: v if isinstance(v, collections.abc.Mapping) else v.get_reader() 

154 for k, v in package_content.items() 

155 } 

156 

157 

158def save_bioimageio_package_as_folder( 

159 source: BioimageioYamlSource | ResourceDescr, 

160 /, 

161 *, 

162 output_path: NewPath | DirectoryPath | None = None, 

163 weights_priority_order: Sequence[ 

164 Literal[ 

165 "keras_hdf5", 

166 "onnx", 

167 "pytorch_state_dict", 

168 "tensorflow_js", 

169 "tensorflow_saved_model_bundle", 

170 "torchscript", 

171 ] 

172 ] 

173 | None = None, 

174 local_files_only: bool = False, 

175) -> DirectoryPath: 

176 """Write the content of a bioimage.io resource package to a folder. 

177 

178 Args: 

179 source: bioimageio resource description 

180 output_path: file path to write package to 

181 weights_priority_order: If given only the first weights format present in the model is included. 

182 If none of the prioritized weights formats is found all are included. 

183 local_files_only: If True, only local files are included in the package. If False, remote files are also included. 

184 

185 Returns: 

186 directory path to bioimageio package folder 

187 """ 

188 package_content = _prepare_resource_package( 

189 source, 

190 weights_priority_order=weights_priority_order, 

191 local_files_only=local_files_only, 

192 ) 

193 if output_path is None: 

194 output_path = Path(mkdtemp()) 

195 else: 

196 output_path = Path(output_path) 

197 

198 output_path.mkdir(exist_ok=True, parents=True) 

199 for name, src in package_content.items(): 

200 if not name: 

201 raise ValueError("got empty file name in package content") 

202 

203 if isinstance(src, collections.abc.Mapping): 

204 write_yaml(src, output_path / name) 

205 elif ( 

206 isinstance(src.original_root, Path) 

207 and src.original_root / src.original_file_name 

208 == (output_path / name).resolve() 

209 ): 

210 logger.debug( 

211 f"Not copying {src.original_root / src.original_file_name} to itself." 

212 ) 

213 else: 

214 if isinstance(src.original_root, Path): 

215 logger.debug( 

216 f"Copying from path {src.original_root / src.original_file_name} to {output_path / name}." 

217 ) 

218 else: 

219 logger.debug( 

220 f"Copying {src.original_root}/{src.original_file_name} to {output_path / name}." 

221 ) 

222 with (output_path / name).open("wb") as dest: 

223 _ = shutil.copyfileobj(src, dest) 

224 

225 return output_path 

226 

227 

228def save_bioimageio_package( 

229 source: BioimageioYamlSource | ResourceDescr, 

230 /, 

231 *, 

232 compression: int = ZIP_DEFLATED, 

233 compression_level: int = 1, 

234 output_path: NewPath | FilePath | None = None, 

235 weights_priority_order: Sequence[ 

236 Literal[ 

237 "keras_hdf5", 

238 "onnx", 

239 "pytorch_state_dict", 

240 "tensorflow_js", 

241 "tensorflow_saved_model_bundle", 

242 "torchscript", 

243 ] 

244 ] 

245 | None = None, 

246 allow_invalid: bool = False, 

247 local_files_only: bool = False, 

248) -> FilePath: 

249 """Package a bioimageio resource as a zip file. 

250 

251 Args: 

252 source: bioimageio resource description 

253 compression: The numeric constant of compression method. 

254 compression_level: Compression level to use when writing files to the archive. 

255 See https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile 

256 output_path: file path to write package to 

257 weights_priority_order: If given only the first weights format present in the model is included. 

258 If none of the prioritized weights formats is found all are included. 

259 allow_invalid: If True, do not raise an error if the exported package is invalid, but log an error instead. 

260 local_files_only: If True, only local files are included in the package. If False, remote files are also included. 

261 

262 Returns: 

263 path to zipped bioimageio package 

264 """ 

265 package_content = _prepare_resource_package( 

266 source, 

267 weights_priority_order=weights_priority_order, 

268 local_files_only=local_files_only, 

269 ) 

270 if output_path is None: 

271 output_path = Path( 

272 NamedTemporaryFile(suffix=".bioimageio.zip", delete=False).name # ruff: ignore[SIM115] 

273 ) 

274 else: 

275 output_path = Path(output_path) 

276 

277 write_zip( 

278 output_path, 

279 package_content, 

280 compression=compression, 

281 compression_level=compression_level, 

282 ) 

283 with get_validation_context().replace(warning_level=ERROR): 

284 if isinstance((exported := load_description(output_path)), InvalidDescr): 

285 msg = f"Exported package at '{output_path}' is invalid:\n{exported.get_reason()}" 

286 if allow_invalid: 

287 logger.error(msg) 

288 else: 

289 raise ValueError(msg) 

290 

291 return output_path 

292 

293 

294def save_bioimageio_package_to_stream( 

295 source: BioimageioYamlSource | ResourceDescr, 

296 /, 

297 *, 

298 compression: int = ZIP_DEFLATED, 

299 compression_level: int = 1, 

300 output_stream: IO[bytes] | None = None, 

301 weights_priority_order: Sequence[ 

302 Literal[ 

303 "keras_hdf5", 

304 "onnx", 

305 "pytorch_state_dict", 

306 "tensorflow_js", 

307 "tensorflow_saved_model_bundle", 

308 "torchscript", 

309 ] 

310 ] 

311 | None = None, 

312 local_files_only: bool = False, 

313) -> IO[bytes]: 

314 """Package a bioimageio resource into a stream. 

315 

316 Args: 

317 source: bioimageio resource description 

318 compression: The numeric constant of compression method. 

319 compression_level: Compression level to use when writing files to the archive. 

320 See https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile 

321 output_stream: stream to write package to 

322 weights_priority_order: If given only the first weights format present in the model is included. 

323 If none of the prioritized weights formats is found all are included. 

324 local_files_only: If True, only local files are included in the package. If False, remote files are also included. 

325 

326 Note: this function bypasses safety checks and does not load/validate the model after writing. 

327 

328 Returns: 

329 stream of zipped bioimageio package 

330 """ 

331 if output_stream is None: 

332 output_stream = BytesIO() 

333 

334 package_content = _prepare_resource_package( 

335 source, 

336 weights_priority_order=weights_priority_order, 

337 local_files_only=local_files_only, 

338 ) 

339 

340 write_zip( 

341 output_stream, 

342 package_content, 

343 compression=compression, 

344 compression_level=compression_level, 

345 ) 

346 

347 return output_stream