Coverage for src/bioimageio/spec/_internal/common_nodes.py: 87%

206 statements  

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

1from __future__ import annotations 

2 

3from abc import ABC 

4from collections.abc import Callable, Iterable, Mapping 

5from inspect import signature 

6from io import BytesIO 

7from pathlib import Path 

8from types import MappingProxyType 

9from typing import ( 

10 IO, 

11 TYPE_CHECKING, 

12 Any, 

13 ClassVar, 

14 Literal, 

15 Protocol, 

16 TypeVar, 

17) 

18from zipfile import ZipFile 

19 

20import pydantic 

21from pydantic import DirectoryPath, PrivateAttr, model_validator 

22from pydantic_core import PydanticUndefined 

23from typing_extensions import ParamSpec, Self 

24 

25from ..summary import ( 

26 WARNING_LEVEL_TO_NAME, 

27 ErrorEntry, 

28 ValidationDetail, 

29 ValidationSummary, 

30 WarningEntry, 

31) 

32from .field_warning import issue_warning 

33from .io import ( 

34 BioimageioYamlContent, 

35 FileDescr, 

36 IncompleteDescr, 

37 IncompleteDescrView, 

38 deepcopy_incomplete_descr, 

39 extract_file_descrs, 

40 populate_cache, 

41) 

42from .io_basics import BIOIMAGEIO_YAML, FileName 

43from .io_utils import write_content_to_zip 

44from .node import Node 

45from .packaging_context import PackagingContext 

46from .root_url import RootHttpUrl 

47from .type_guards import is_dict 

48from .utils import get_format_version_tuple 

49from .validation_context import ValidationContext, get_validation_context 

50from .warning_levels import ALERT, ERROR, INFO 

51 

52 

53class NodeWithExplicitlySetFields(Node): 

54 _fields_to_set_explicitly: ClassVar[Mapping[str, Any]] 

55 

56 @classmethod 

57 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: 

58 explict_fields: dict[str, Any] = {} 

59 for attr in dir(cls): 

60 if attr.startswith("implemented_"): 

61 field_name = attr.replace("implemented_", "") 

62 if field_name not in cls.model_fields: 

63 continue 

64 

65 assert ( 

66 cls.model_fields[field_name].get_default() is PydanticUndefined 

67 ), field_name 

68 default = getattr(cls, attr) 

69 explict_fields[field_name] = default 

70 

71 cls._fields_to_set_explicitly = MappingProxyType(explict_fields) 

72 return super().__pydantic_init_subclass__(**kwargs) 

73 

74 @model_validator(mode="before") 

75 @classmethod 

76 def _set_fields_explicitly(cls, data: Any | dict[str, Any]) -> Any | dict[str, Any]: 

77 if isinstance(data, dict): 

78 for name, default in cls._fields_to_set_explicitly.items(): 

79 if name not in data: 

80 data[name] = default 

81 

82 return data # pyright: ignore[reportUnknownVariableType] 

83 

84 

85if TYPE_CHECKING: 

86 

87 class _ResourceDescrBaseAbstractFieldsProtocol(Protocol): 

88 """workaround to add "abstract" fields to ResourceDescrBase""" 

89 

90 # TODO: implement as proper abstract fields of ResourceDescrBase 

91 

92 type: Any # should be LiteralString 

93 format_version: Any # should be LiteralString 

94 implemented_type: ClassVar[Any] 

95 implemented_format_version: ClassVar[Any] 

96 

97else: 

98 

99 class _ResourceDescrBaseAbstractFieldsProtocol: 

100 pass 

101 

102 

103P = ParamSpec("P") 

104T = TypeVar("T") 

105 

106 

107class ResourceDescrBase( 

108 NodeWithExplicitlySetFields, ABC, _ResourceDescrBaseAbstractFieldsProtocol 

109): 

110 """base class for all resource descriptions""" 

111 

112 _validation_summary: ValidationSummary | None = None 

113 

114 implemented_format_version_tuple: ClassVar[tuple[int, int, int]] 

115 

116 # @field_validator("format_version", mode="before", check_fields=False) 

117 # field_validator on "format_version" is not possible, because we want to use 

118 # "format_version" in a descriminated Union higher up 

119 # (PydanticUserError: Cannot use a mode='before' validator in the discriminator 

120 # field 'format_version' of Model 'CollectionDescr') 

121 @model_validator(mode="before") 

122 @classmethod 

123 def _ignore_future_patch(cls, data: Any, /) -> Any: 

124 if ( 

125 cls.implemented_format_version == "unknown" 

126 or not is_dict(data) 

127 or "format_version" not in data 

128 ): 

129 return data 

130 

131 value = data["format_version"] 

132 fv = get_format_version_tuple(value) 

133 if fv is None: 

134 return data 

135 if ( 

136 fv[0] == cls.implemented_format_version_tuple[0] 

137 and fv[1:] > cls.implemented_format_version_tuple[1:] 

138 ): 

139 issue_warning( 

140 "future format_version '{value}' treated as '{implemented}'", 

141 value=value, 

142 msg_context={"implemented": cls.implemented_format_version}, 

143 severity=ALERT, 

144 ) 

145 data["format_version"] = cls.implemented_format_version 

146 

147 return data 

148 

149 @model_validator(mode="after") 

150 def _set_init_validation_summary(self) -> Self: 

151 context = get_validation_context() 

152 

153 self._validation_summary = ValidationSummary( 

154 name="bioimageio format validation", 

155 source_name=context.source_name, 

156 id=getattr(self, "id", None), 

157 version=getattr(self, "version", None), 

158 type=self.type, 

159 format_version=self.format_version, 

160 status="failed" if isinstance(self, InvalidDescr) else "valid-format", 

161 metadata_completeness=self._get_metadata_completeness(), 

162 details=( 

163 [] 

164 if isinstance(self, InvalidDescr) 

165 else [ 

166 ValidationDetail( 

167 name=f"Successfully created `{self.__class__.__name__}` instance.", 

168 status="passed", 

169 context=context.summary, 

170 ) 

171 ] 

172 ), 

173 ) 

174 return self 

175 

176 @property 

177 def validation_summary(self) -> ValidationSummary: 

178 assert self._validation_summary is not None, "access only after initialization" 

179 return self._validation_summary 

180 

181 _root: RootHttpUrl | DirectoryPath | ZipFile = PrivateAttr( 

182 default_factory=lambda: get_validation_context().root 

183 ) 

184 

185 _file_name: FileName | None = PrivateAttr( 

186 default_factory=lambda: get_validation_context().file_name 

187 ) 

188 

189 @property 

190 def root(self) -> RootHttpUrl | DirectoryPath | ZipFile: 

191 """The URL/Path prefix to resolve any relative paths with.""" 

192 return self._root 

193 

194 @property 

195 def file_name(self) -> FileName | None: 

196 """File name of the bioimageio.yaml file the description was loaded from.""" 

197 return self._file_name 

198 

199 @classmethod 

200 def __pydantic_init_subclass__(cls, **kwargs: Any): 

201 super().__pydantic_init_subclass__(**kwargs) 

202 # set classvar implemented_format_version_tuple 

203 if "format_version" in cls.model_fields: 

204 if "." not in cls.implemented_format_version: 

205 cls.implemented_format_version_tuple = (0, 0, 0) 

206 else: 

207 fv_tuple = get_format_version_tuple(cls.implemented_format_version) 

208 assert fv_tuple is not None, ( 

209 f"failed to cast '{cls.implemented_format_version}' to tuple" 

210 ) 

211 cls.implemented_format_version_tuple = fv_tuple 

212 

213 @classmethod 

214 def load_from_kwargs( 

215 cls: Callable[P, T], 

216 context: ValidationContext | None = None, 

217 *args: P.args, 

218 **kwargs: P.kwargs, 

219 ) -> T | InvalidDescr: 

220 sig = signature(cls) 

221 bound = sig.bind_partial(*args, **kwargs) 

222 return cls.load(dict(bound.arguments), context=context) # pyright: ignore[reportFunctionMemberAccess] 

223 

224 @classmethod 

225 def load( 

226 cls, 

227 data: IncompleteDescrView, 

228 context: ValidationContext | None = None, 

229 ) -> Self | InvalidDescr: 

230 """factory method to create a resource description object""" 

231 

232 context = context or get_validation_context() 

233 if context.perform_io_checks: 

234 file_descrs = extract_file_descrs(data) 

235 populate_cache(file_descrs) # TODO: add progress bar 

236 

237 with context.replace(log_warnings=context.warning_level <= INFO): 

238 rd, errors, val_warnings = cls._load_impl(deepcopy_incomplete_descr(data)) 

239 

240 if context.warning_level > INFO: 

241 all_warnings_context = context.replace( 

242 warning_level=INFO, log_warnings=False, raise_errors=False 

243 ) 

244 # raise all validation warnings by reloading 

245 with all_warnings_context: 

246 _, _, val_warnings = cls._load_impl(deepcopy_incomplete_descr(data)) 

247 

248 format_status = "failed" if errors else "passed" 

249 rd.validation_summary.add_detail( 

250 ValidationDetail( 

251 errors=errors, 

252 name=( 

253 "bioimageio.spec format validation" 

254 f" {rd.type} {cls.implemented_format_version}" 

255 ), 

256 status=format_status, 

257 warnings=val_warnings, 

258 ), 

259 update_status=False, # this special validation detail needs manual format updating below 

260 ) 

261 assert format_status != "failed" or isinstance(rd, InvalidDescr) 

262 

263 return rd 

264 

265 def _get_metadata_completeness(self) -> float: 

266 if isinstance(self, InvalidDescr): 

267 return 0.0 

268 

269 given = self.model_dump(mode="json", exclude_unset=True, exclude_defaults=False) 

270 full = self.model_dump(mode="json", exclude_unset=False, exclude_defaults=False) 

271 

272 def extract_flat_keys(d: dict[Any, Any], key: str = "") -> Iterable[str]: 

273 for k, v in d.items(): 

274 if is_dict(v): 

275 yield from extract_flat_keys(v, key=f"{key}.{k}" if key else k) 

276 

277 yield f"{key}.{k}" if key else k 

278 

279 given_keys = set(extract_flat_keys(given)) 

280 full_keys = set(extract_flat_keys(full)) 

281 assert len(full_keys) >= len(given_keys) 

282 return len(given_keys) / len(full_keys) if full_keys else 0.0 

283 

284 @classmethod 

285 def _load_impl( 

286 cls, data: IncompleteDescr 

287 ) -> tuple[Self | InvalidDescr, list[ErrorEntry], list[WarningEntry]]: 

288 rd: Self | InvalidDescr | None = None 

289 val_errors: list[ErrorEntry] = [] 

290 val_warnings: list[WarningEntry] = [] 

291 

292 context = get_validation_context() 

293 try: 

294 rd = cls.model_validate(data) 

295 except pydantic.ValidationError as e: 

296 for ee in e.errors(include_url=False): 

297 if (severity := ee.get("ctx", {}).get("severity", ERROR)) < ERROR: 

298 val_warnings.append( 

299 WarningEntry( 

300 loc=ee["loc"], 

301 msg=ee["msg"], 

302 type=ee["type"], 

303 severity=severity, 

304 ) 

305 ) 

306 elif context.raise_errors: 

307 raise 

308 else: 

309 val_errors.append( 

310 ErrorEntry(loc=ee["loc"], msg=ee["msg"], type=ee["type"]) 

311 ) 

312 

313 if len(val_errors) == 0: # FIXME is this reduntant? 

314 val_errors.append( 

315 ErrorEntry( 

316 loc=(), 

317 msg=( 

318 f"Encountered {len(val_warnings)} more severe than warning" 

319 " level " 

320 f"'{WARNING_LEVEL_TO_NAME[context.warning_level]}'" 

321 ), 

322 type="severe_warnings", 

323 ) 

324 ) 

325 except Exception as e: 

326 if context.raise_errors: 

327 raise 

328 

329 try: 

330 msg = str(e) 

331 except Exception: 

332 msg = e.__class__.__name__ + " encountered" 

333 

334 val_errors.append( 

335 ErrorEntry( 

336 loc=(), 

337 msg=msg, 

338 type=type(e).__name__, 

339 with_traceback=True, 

340 ) 

341 ) 

342 

343 if rd is None: 

344 try: 

345 rd = InvalidDescr.model_validate(data) 

346 except Exception: 

347 if context.raise_errors: 

348 raise 

349 resource_type = cls.model_fields["type"].default 

350 format_version = cls.implemented_format_version 

351 rd = InvalidDescr(type=resource_type, format_version=format_version) 

352 if context.raise_errors: 

353 raise ValueError(rd) 

354 

355 return rd, val_errors, val_warnings 

356 

357 def package( 

358 self, 

359 dest: ZipFile | IO[bytes] | Path | str | None = None, 

360 /, 

361 local_files_only: bool = False, 

362 ) -> ZipFile: 

363 """package the described resource as a zip archive 

364 

365 Args: 

366 dest: (path/bytes stream of) destination zipfile 

367 """ 

368 if dest is None: 

369 dest = BytesIO() 

370 

371 if isinstance(dest, ZipFile): 

372 zip = dest 

373 if "r" in zip.mode: 

374 raise ValueError( 

375 f"zip file {dest} opened in '{zip.mode}' mode," 

376 + " but write access is needed for packaging." 

377 ) 

378 else: 

379 zip = ZipFile(dest, mode="w") 

380 

381 if zip.filename is None: 

382 zip.filename = ( 

383 str(getattr(self, "id", getattr(self, "name", "bioimageio"))) + ".zip" 

384 ) 

385 

386 content = self.get_package_content(local_files_only=local_files_only) 

387 write_content_to_zip(content, zip) 

388 return zip 

389 

390 def get_package_content( 

391 self, local_files_only: bool = False 

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

393 """Returns package content without creating the package.""" 

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

395 with PackagingContext( 

396 bioimageio_yaml_file_name=BIOIMAGEIO_YAML, 

397 file_sources=content, 

398 local_files_only=local_files_only, 

399 ): 

400 rdf_content: BioimageioYamlContent = self.model_dump( 

401 mode="json", exclude_unset=True 

402 ) 

403 

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

405 

406 return {**content, BIOIMAGEIO_YAML: rdf_content} 

407 

408 

409class InvalidDescr( 

410 ResourceDescrBase, 

411 extra="allow", 

412 title="An invalid resource description", 

413): 

414 """A representation of an invalid resource description""" 

415 

416 implemented_type: ClassVar[Literal["unknown"]] = "unknown" 

417 if TYPE_CHECKING: # see NodeWithExplicitlySetFields 

418 type: Any = "unknown" 

419 else: 

420 type: Any 

421 

422 implemented_format_version: ClassVar[Literal["unknown"]] = "unknown" 

423 if TYPE_CHECKING: # see NodeWithExplicitlySetFields 

424 format_version: Any = "unknown" 

425 else: 

426 format_version: Any 

427 

428 def get_reason(self) -> str | None: 

429 """Get the reason why the description is invalid, if available.""" 

430 reasons: list[str] = [] 

431 if self.validation_summary and self.validation_summary.details: 

432 for detail in self.validation_summary.details: 

433 if detail.status == "failed" and detail.errors: 

434 reasons.extend( 

435 f"{loc}: {msg}" 

436 for loc, msg in ( 

437 ( 

438 ".".join(map(str, error.loc)), 

439 error.msg.replace("\n", " "), 

440 ) 

441 for error in detail.errors 

442 ) 

443 ) 

444 

445 return "\n- ".join(reasons) if reasons else None 

446 

447 

448class KwargsNode(Node): 

449 def get(self, item: str, default: Any = None) -> Any: 

450 return self[item] if item in self else default # ruff: ignore[SIM401] 

451 

452 def __getitem__(self, item: str) -> Any: 

453 if item in self.__class__.model_fields: 

454 return getattr(self, item) 

455 else: 

456 raise KeyError(item) 

457 

458 def __contains__(self, item: str) -> bool: 

459 return item in self.__class__.model_fields