Coverage for src/bioimageio/spec/_internal/io_utils.py: 77%

200 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 io 

5import shutil 

6import zipfile 

7from collections.abc import Callable, Mapping 

8from contextlib import nullcontext 

9from difflib import get_close_matches 

10from pathlib import Path 

11from types import MappingProxyType 

12from typing import IO, Any, cast 

13from zipfile import ZipFile 

14 

15import httpx 

16import numpy 

17import pydantic 

18from loguru import logger 

19from numpy.typing import NDArray 

20from pydantic import BaseModel, FilePath, NewPath, RootModel 

21from ruyaml import YAML 

22from typing_extensions import Unpack 

23 

24from ._settings import settings 

25from .io import ( 

26 BIOIMAGEIO_YAML, 

27 BioimageioYamlContent, 

28 BioimageioYamlContentView, 

29 FileDescr, 

30 HashKwargs, 

31 LightHttpFileDescr, 

32 OpenedBioimageioYaml, 

33 RelativeFilePath, 

34 YamlValue, 

35 extract_file_name, 

36 find_bioimageio_yaml_file_name, 

37 get_reader, 

38 identify_bioimageio_yaml_file_name, 

39 interprete_file_source, 

40) 

41from .io_basics import AbsoluteDirectory, BytesReader, FileName, ZipPath 

42from .progress import ProgressbarLike 

43from .root_url import RootHttpUrl 

44from .types import PermissiveFileSource 

45from .url import HttpUrl 

46from .utils import cache 

47from .validation_context import ValidationContext, get_validation_context 

48 

49_yaml_load = YAML(typ="safe") 

50 

51_yaml_dump = YAML() 

52_yaml_dump.version = (1, 2) # pyright: ignore[reportAttributeAccessIssue] 

53_yaml_dump.default_flow_style = False 

54_yaml_dump.indent(mapping=2, sequence=4, offset=2) 

55_yaml_dump.width = 88 # pyright: ignore[reportAttributeAccessIssue] 

56 

57 

58def read_yaml( 

59 file: FilePath | ZipPath | IO[str] | IO[bytes] | BytesReader | str, 

60) -> YamlValue: 

61 if isinstance(file, (ZipPath, Path)): 

62 data = file.read_text(encoding="utf-8") 

63 else: 

64 data = file 

65 

66 content: YamlValue = _yaml_load.load(data) 

67 return content 

68 

69 

70def write_yaml( 

71 content: YamlValue | BioimageioYamlContentView | BaseModel, 

72 /, 

73 file: NewPath | FilePath | IO[str] | IO[bytes] | ZipPath, 

74): 

75 if isinstance(file, Path): 

76 cm = file.open("w", encoding="utf-8") 

77 else: 

78 cm = nullcontext(file) 

79 

80 if isinstance(content, BaseModel): 

81 content = content.model_dump(mode="json") 

82 

83 with cm as f: 

84 _yaml_dump.dump(content, f) 

85 

86 

87def _sanitize_bioimageio_yaml(content: YamlValue) -> BioimageioYamlContent: 

88 if not isinstance(content, dict): 

89 raise ValueError( 

90 f"Expected {BIOIMAGEIO_YAML} content to be a mapping (got {type(content)})." 

91 ) 

92 

93 for key in content: 

94 if not isinstance(key, str): 

95 raise ValueError( 

96 f"Expected all keys (field names) in a {BIOIMAGEIO_YAML} " 

97 + f"to be strings (got '{key}' of type {type(key)})." 

98 ) 

99 

100 return cast(BioimageioYamlContent, content) 

101 

102 

103def _open_bioimageio_rdf_in_zip( 

104 path: ZipPath, 

105 *, 

106 original_root: AbsoluteDirectory | RootHttpUrl | ZipFile, 

107 original_source_name: str, 

108) -> OpenedBioimageioYaml: 

109 with path.open("rb") as f: 

110 assert not isinstance(f, io.TextIOWrapper) 

111 unparsed_content = f.read().decode(encoding="utf-8") 

112 

113 content = _sanitize_bioimageio_yaml(read_yaml(io.StringIO(unparsed_content))) 

114 

115 return OpenedBioimageioYaml( 

116 content, 

117 original_root=original_root, 

118 original_file_name=extract_file_name(path), 

119 original_source_name=original_source_name, 

120 unparsed_content=unparsed_content, 

121 ) 

122 

123 

124def _open_bioimageio_zip( 

125 source: ZipFile, 

126 *, 

127 original_source_name: str, 

128) -> OpenedBioimageioYaml: 

129 rdf_name = identify_bioimageio_yaml_file_name( 

130 [info.filename for info in source.filelist] 

131 ) 

132 return _open_bioimageio_rdf_in_zip( 

133 ZipPath(source, rdf_name), 

134 original_root=source, 

135 original_source_name=original_source_name, 

136 ) 

137 

138 

139def open_bioimageio_yaml( 

140 source: PermissiveFileSource | ZipFile | ZipPath, 

141 /, 

142 progressbar: bool | ProgressbarLike | Callable[[], ProgressbarLike] | None = None, 

143 **kwargs: Unpack[HashKwargs], 

144) -> OpenedBioimageioYaml: 

145 if ( 

146 isinstance(source, str) 

147 and source.startswith("huggingface/") 

148 and source.count("/") >= 2 

149 ): 

150 if source.count("/") == 2: 

151 # huggingface/{user_or_org}/{repo_name} 

152 repo_id = source[len("huggingface/") :] 

153 branch = "main" 

154 else: 

155 # huggingface/{user_or_org}/{repo_id}/ 

156 # huggingface/{user_or_org}/{repo_id}/version 

157 repo_id, version = source[len("huggingface/") :].rsplit("/", 1) 

158 if len(version) == 0: 

159 branch = "main" 

160 elif version[0].isdigit(): 

161 branch = f"v{version}" 

162 else: 

163 branch = version 

164 

165 source = HttpUrl( 

166 settings.huggingface_http_pattern.format(repo_id=repo_id, branch=branch) 

167 ) 

168 

169 if isinstance(source, RelativeFilePath): 

170 source = source.absolute() 

171 

172 if isinstance(source, ZipFile): 

173 return _open_bioimageio_zip(source, original_source_name=str(source)) 

174 elif isinstance(source, ZipPath): 

175 return _open_bioimageio_rdf_in_zip( 

176 source, original_root=source.root, original_source_name=str(source) 

177 ) 

178 

179 try: 

180 if isinstance(source, (FileDescr, ZipPath)): 

181 src = source 

182 elif isinstance(source, (Path, str)) and (source_dir := Path(source)).is_dir(): 

183 # open bioimageio yaml from a folder 

184 src = source_dir / find_bioimageio_yaml_file_name(source_dir) 

185 elif isinstance(source, (str, pydantic.AnyUrl)): 

186 src = interprete_file_source(source) 

187 else: 

188 src = source 

189 

190 reader = get_reader(src, progressbar=progressbar, **kwargs) 

191 

192 except Exception as e: 

193 # check if `source` is a collection id 

194 if not isinstance(source, str): 

195 raise 

196 

197 collection_patterns = settings.collection_http_pattern 

198 if isinstance(collection_patterns, str): 

199 collection_patterns = (collection_patterns,) if collection_patterns else () 

200 

201 collection_pattern_errors: list[str] = [] 

202 for pattern in collection_patterns: 

203 with ValidationContext(perform_io_checks=False): 

204 url = HttpUrl(pattern.format(bioimageio_id=source)) 

205 

206 try: 

207 r = httpx.get(url, follow_redirects=True) 

208 _ = r.raise_for_status() 

209 unparsed_content = r.content.decode(encoding="utf-8") 

210 content = _sanitize_bioimageio_yaml(read_yaml(unparsed_content)) 

211 except Exception as e_coll_pattern: 

212 error_msg = f"BIOIMAGEIO_COLLECTION_HTTP_PATTERN: Failed to get bioimageio.yaml from {url}: {e_coll_pattern}" 

213 logger.warning(error_msg) 

214 collection_pattern_errors.append(error_msg) 

215 else: 

216 logger.info("loaded {} from {}", source, url) 

217 original_file_name = ( 

218 "rdf.yaml" if url.path is None else url.path.split("/")[-1] 

219 ) 

220 return OpenedBioimageioYaml( 

221 content=content, 

222 original_root=url.parent, 

223 original_file_name=original_file_name, 

224 original_source_name=url, 

225 unparsed_content=unparsed_content, 

226 ) 

227 

228 collection_pattern_error_msg = "".join( 

229 f"\n{error}" for error in collection_pattern_errors 

230 ) 

231 

232 if not isinstance(settings.id_map, str) or "/" not in settings.id_map: 

233 raise ValueError( 

234 f"BIOIMAGEIO_ID_MAP: Invalid id map url {settings.id_map}.{collection_pattern_error_msg}" 

235 ) from e 

236 

237 id_map = get_id_map() 

238 if not id_map: 

239 raise ValueError( 

240 f"BIOIMAGEIO_ID_MAP: Empty (or unavailable) id map from {settings.id_map}.{collection_pattern_error_msg}" 

241 ) from e 

242 

243 if id_map and source not in id_map: 

244 close_matches = get_close_matches(source, id_map) 

245 if len(close_matches) == 0: 

246 raise ValueError( 

247 f"BIOIMAGEIO_ID_MAP: '{source}' not found in {settings.id_map}.{collection_pattern_error_msg}" 

248 ) from e 

249 

250 if len(close_matches) == 1: 

251 did_you_mean = f" Did you mean '{close_matches[0]}'?" 

252 else: 

253 did_you_mean = f" Did you mean any of {close_matches}?" 

254 

255 raise ValueError( 

256 f"BIOIMAGEIO_ID_MAP: '{source}' not found in {settings.id_map}.{did_you_mean}{collection_pattern_error_msg}" 

257 ) from e 

258 

259 entry = id_map[source] 

260 logger.info("loading {} from {}", source, entry.source) 

261 reader = entry.get_reader(progressbar=progressbar) 

262 with get_validation_context().replace(perform_io_checks=False): 

263 src = HttpUrl(entry.source) 

264 

265 if reader.is_zipfile: 

266 return _open_bioimageio_zip(ZipFile(reader), original_source_name=str(src)) 

267 

268 unparsed_content = reader.read().decode(encoding="utf-8") 

269 content = _sanitize_bioimageio_yaml(read_yaml(unparsed_content)) 

270 

271 if isinstance(src, RelativeFilePath): 

272 src = src.absolute() 

273 

274 if isinstance(src, ZipPath): 

275 root = src.root 

276 elif isinstance(src, FileDescr): 

277 file_source = src.source.absolute() 

278 if isinstance(file_source, ZipPath): 

279 root = file_source.root 

280 else: 

281 root = file_source.parent 

282 else: 

283 root = src.parent 

284 

285 return OpenedBioimageioYaml( 

286 content, 

287 original_root=root, 

288 original_source_name=str(src), 

289 original_file_name=extract_file_name(src), 

290 unparsed_content=unparsed_content, 

291 ) 

292 

293 

294_IdMap = RootModel[dict[str, LightHttpFileDescr]] 

295 

296 

297def _get_id_map_impl(url: str) -> dict[str, LightHttpFileDescr]: 

298 if not isinstance(url, str) or "/" not in url: 

299 logger.opt(depth=1).error("invalid id map url: {}", url) 

300 try: 

301 id_map_raw: Any = httpx.get( 

302 url, timeout=settings.http_timeout, follow_redirects=True 

303 ).json() 

304 except Exception as e: 

305 logger.opt(depth=1).error("failed to get {}: {}", url, e) 

306 return {} 

307 

308 id_map = _IdMap.model_validate(id_map_raw) 

309 return id_map.root 

310 

311 

312@cache 

313def get_id_map() -> Mapping[str, LightHttpFileDescr]: 

314 try: 

315 if settings.resolve_draft: 

316 ret = _get_id_map_impl(settings.id_map_draft) 

317 else: 

318 ret = {} 

319 

320 ret.update(_get_id_map_impl(settings.id_map)) 

321 

322 except Exception as e: 

323 logger.error("failed to get resource id map: {}", e) 

324 ret = {} 

325 

326 return MappingProxyType(ret) 

327 

328 

329def write_content_to_zip( 

330 content: Mapping[ 

331 FileName, 

332 str | FilePath | ZipPath | BioimageioYamlContentView | FileDescr | BytesReader, 

333 ], 

334 zip: zipfile.ZipFile, 

335): 

336 """write strings as text, dictionaries as yaml and files to a ZipFile 

337 Args: 

338 content: dict mapping archive names to local file paths, 

339 strings (for text files), or dict (for yaml files). 

340 zip: ZipFile 

341 """ 

342 for arc_name, file in content.items(): 

343 if isinstance(file, collections.abc.Mapping): 

344 buf = io.StringIO() 

345 write_yaml(file, buf) 

346 file = buf.getvalue() 

347 

348 if isinstance(file, str): 

349 zip.writestr(arc_name, file.encode("utf-8")) 

350 else: 

351 if isinstance(file, BytesReader): 

352 reader = file 

353 else: 

354 reader = get_reader(file) 

355 

356 if ( 

357 isinstance(reader.original_root, ZipFile) 

358 and reader.original_root is zip 

359 ): 

360 logger.debug( 

361 f"Not copying {reader.original_file_name} in " 

362 + ( 

363 "zip file" 

364 if reader.original_root.filename is None 

365 else reader.original_root.filename 

366 ) 

367 + " to itself." 

368 ) 

369 continue 

370 

371 with zip.open(arc_name, "w", force_zip64=True) as dest: 

372 shutil.copyfileobj(reader, dest, 1024 * 8) 

373 

374 

375def write_zip( 

376 path: FilePath | IO[bytes], 

377 content: Mapping[ 

378 FileName, str | FilePath | ZipPath | BioimageioYamlContentView | BytesReader 

379 ], 

380 *, 

381 compression: int, 

382 compression_level: int, 

383) -> None: 

384 """Write a zip archive. 

385 

386 Args: 

387 path: output path to write to. 

388 content: dict mapping archive names to local file paths, strings (for text files), or dict (for yaml files). 

389 compression: The numeric constant of compression method. 

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

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

392 

393 """ 

394 if isinstance(path, Path): 

395 path.parent.mkdir(parents=True, exist_ok=True) 

396 

397 with ZipFile( 

398 path, "w", compression=compression, compresslevel=compression_level 

399 ) as zip: 

400 write_content_to_zip(content, zip) 

401 

402 

403def load_array(source: PermissiveFileSource) -> NDArray[Any]: 

404 """load a numpy ndarray from a .npy file""" 

405 reader = get_reader(source) 

406 if settings.allow_pickle: 

407 logger.warning("Loading numpy array with `allow_pickle=True`.") 

408 

409 return numpy.load(reader, allow_pickle=settings.allow_pickle) 

410 

411 

412def save_array(path: Path | ZipPath, array: NDArray[Any]) -> None: 

413 """save a numpy ndarray to a .npy file""" 

414 with path.open(mode="wb") as f: 

415 assert not isinstance(f, io.TextIOWrapper) 

416 return numpy.save(f, array, allow_pickle=False)