Coverage for src/bioimageio/spec/generic/v0_3.py: 92%

198 statements  

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

1from __future__ import annotations 

2 

3import string 

4from collections.abc import Callable, Sequence 

5from typing import ( 

6 TYPE_CHECKING, 

7 Annotated, 

8 Any, 

9 ClassVar, 

10 Literal, 

11 TypeVar, 

12 cast, 

13 get_args, 

14) 

15 

16import annotated_types 

17from annotated_types import Len, LowerCase, MaxLen, MinLen 

18from pydantic import Field, RootModel, ValidationInfo, field_validator, model_validator 

19 

20from .._internal.common_nodes import Node, ResourceDescrBase 

21from .._internal.constants import TAG_CATEGORIES 

22from .._internal.field_validation import validate_github_user 

23from .._internal.field_warning import as_warning, issue_warning, warn 

24from .._internal.io import ( 

25 BioimageioYamlContent, 

26 FileDescr, 

27 WithSuffix, 

28 is_yaml_value, 

29) 

30from .._internal.io_basics import Sha256 

31from .._internal.io_packaging import FileDescr_package 

32from .._internal.license_id import DeprecatedLicenseId, LicenseId 

33from .._internal.node_converter import Converter 

34from .._internal.type_guards import is_dict 

35from .._internal.types import FAIR, NotEmpty, RelativeFilePath 

36from .._internal.url import HttpUrl 

37from .._internal.validated_string import ValidatedString 

38from .._internal.validator_annotations import ( 

39 Predicate, 

40 RestrictCharacters, 

41) 

42from .._internal.version_type import Version 

43from .._internal.warning_levels import ALERT, INFO 

44from ._v0_3_converter import convert_from_older_format 

45from .v0_2 import Author as _Author_v0_2 

46from .v0_2 import BadgeDescr, Doi, OrcidId, Uploader 

47from .v0_2 import Maintainer as _Maintainer_v0_2 

48 

49__all__ = [ 

50 "KNOWN_SPECIFIC_RESOURCE_TYPES", 

51 "VALID_COVER_IMAGE_EXTENSIONS", 

52 "Author", 

53 "BadgeDescr", 

54 "CiteEntry", 

55 "DeprecatedLicenseId", 

56 "Doi", 

57 "FileDescr", 

58 "GenericDescr", 

59 "HttpUrl", 

60 "LicenseId", 

61 "LinkedResource", 

62 "Maintainer", 

63 "OrcidId", 

64 "RelativeFilePath", 

65 "ResourceId", 

66 "Sha256", 

67 "Uploader", 

68 "Version", 

69] 

70 

71KNOWN_SPECIFIC_RESOURCE_TYPES = ( 

72 "application", 

73 "collection", 

74 "dataset", 

75 "model", 

76 "notebook", 

77) 

78VALID_COVER_IMAGE_EXTENSIONS = ( 

79 ".gif", 

80 ".jpeg", 

81 ".jpg", 

82 ".png", 

83 ".svg", 

84) 

85 

86 

87FileDescr_documentation = Annotated[ 

88 FileDescr_package, 

89 WithSuffix(".md", case_sensitive=True), 

90 Field( 

91 examples=[ 

92 {"source": "README.md"}, 

93 ], 

94 ), 

95] 

96 

97 

98class ResourceId(ValidatedString): 

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

100 Annotated[ 

101 NotEmpty[str], 

102 RestrictCharacters(string.ascii_lowercase + string.digits + "_-/."), 

103 annotated_types.Predicate( 

104 lambda s: not (s.startswith("/") or s.endswith("/")) 

105 ), 

106 ] 

107 ] 

108 

109 

110def _has_no_slash(s: str) -> bool: 

111 return "/" not in s and "\\" not in s 

112 

113 

114class Author(_Author_v0_2): 

115 name: Annotated[str, Predicate(_has_no_slash)] 

116 github_user: str | None = None 

117 

118 @field_validator("github_user", mode="after") 

119 def _validate_github_user(cls, value: str | None): 

120 if value is None: 

121 return None 

122 else: 

123 return validate_github_user(value) 

124 

125 

126class _AuthorConv(Converter[_Author_v0_2, Author]): 

127 def _convert( 

128 self, src: _Author_v0_2, tgt: type[Author | dict[str, Any]] 

129 ) -> Author | dict[str, Any]: 

130 return tgt( 

131 name=src.name, 

132 github_user=src.github_user, 

133 affiliation=src.affiliation, 

134 email=src.email, 

135 orcid=src.orcid, 

136 ) 

137 

138 

139_author_conv = _AuthorConv(_Author_v0_2, Author) 

140 

141 

142class Maintainer(_Maintainer_v0_2): 

143 name: Annotated[str, Predicate(_has_no_slash)] | None = None 

144 github_user: str 

145 

146 @field_validator("github_user", mode="after") 

147 def validate_github_user(cls, value: str): 

148 return validate_github_user(value) 

149 

150 

151class _MaintainerConv(Converter[_Maintainer_v0_2, Maintainer]): 

152 def _convert( 

153 self, src: _Maintainer_v0_2, tgt: type[Maintainer | dict[str, Any]] 

154 ) -> Maintainer | dict[str, Any]: 

155 return tgt( 

156 name=src.name, 

157 github_user=src.github_user, 

158 affiliation=src.affiliation, 

159 email=src.email, 

160 orcid=src.orcid, 

161 ) 

162 

163 

164_maintainer_conv = _MaintainerConv(_Maintainer_v0_2, Maintainer) 

165 

166 

167class CiteEntry(Node): 

168 """A citation that should be referenced in work using this resource.""" 

169 

170 text: str 

171 """free text description""" 

172 

173 doi: Doi | None = None 

174 """A digital object identifier (DOI) is the prefered citation reference. 

175 See https://www.doi.org/ for details. 

176 Note: 

177 Either **doi** or **url** have to be specified. 

178 """ 

179 

180 url: HttpUrl | None = None 

181 """URL to cite (preferably specify a **doi** instead/also). 

182 Note: 

183 Either **doi** or **url** have to be specified. 

184 """ 

185 

186 @model_validator(mode="after") 

187 def _check_doi_or_url(self): 

188 if not self.doi and not self.url: 

189 raise ValueError("Either 'doi' or 'url' is required") 

190 

191 return self 

192 

193 

194class LinkedResourceBase(Node): 

195 @model_validator(mode="before") 

196 def _remove_version_number(cls, value: Any): 

197 if is_dict(value): 

198 vn = value.pop("version_number", None) 

199 if vn is not None and value.get("version") is None: 

200 value["version"] = vn 

201 

202 return value 

203 

204 version: Version | None = None 

205 """The version of the linked resource following SemVer 2.0.""" 

206 

207 

208class LinkedResource(LinkedResourceBase): 

209 """Reference to a bioimage.io resource""" 

210 

211 id: ResourceId 

212 """A valid resource `id` from the official bioimage.io collection.""" 

213 

214 

215class BioimageioConfig(Node, extra="allow"): 

216 """bioimage.io internal metadata.""" 

217 

218 

219class Config(Node, extra="allow"): 

220 """A place to store additional metadata (often tool specific). 

221 

222 Such additional metadata is typically set programmatically by the respective tool 

223 or by people with specific insights into the tool. 

224 If you want to store additional metadata that does not match any of the other 

225 fields, think of a key unlikely to collide with anyone elses use-case/tool and save 

226 it here. 

227 

228 Please consider creating [an issue in the bioimageio.spec repository](https://github.com/bioimage-io/spec-bioimage-io/issues/new?template=Blank+issue) 

229 if you are not sure if an existing field could cover your use case 

230 or if you think such a field should exist. 

231 """ 

232 

233 bioimageio: BioimageioConfig = Field(default_factory=BioimageioConfig) 

234 """bioimage.io internal metadata.""" 

235 

236 @model_validator(mode="after") 

237 def _validate_extra_fields(self): 

238 if self.model_extra: 

239 for k, v in self.model_extra.items(): 

240 if not isinstance(v, Node) and not is_yaml_value(v): 

241 raise ValueError( 

242 f"config.{k} is not a valid YAML value or `Node` instance" 

243 ) 

244 

245 return self 

246 

247 def __getitem__(self, key: str) -> Any: 

248 """Allows to access the config as a dictionary.""" 

249 return getattr(self, key) 

250 

251 def __setitem__(self, key: str, value: Any) -> None: 

252 """Allows to set the config as a dictionary.""" 

253 setattr(self, key, value) 

254 

255 

256_FileDescr_cover = Annotated[ 

257 FileDescr_package, 

258 WithSuffix(VALID_COVER_IMAGE_EXTENSIONS, case_sensitive=False), 

259] 

260 

261 

262class GenericModelDescrBase(ResourceDescrBase): 

263 """Base for all resource descriptions including of model descriptions""" 

264 

265 name: Annotated[ 

266 Annotated[ 

267 str, RestrictCharacters(string.ascii_letters + string.digits + "_+- ()") 

268 ], 

269 MinLen(5), 

270 MaxLen(128), 

271 warn(Annotated[str, MaxLen(64)], "Name longer than 64 characters.", INFO), 

272 ] 

273 """A human-friendly name of the resource description. 

274 May only contains letters, digits, underscore, minus, parentheses and spaces.""" 

275 

276 description: FAIR[ 

277 Annotated[ 

278 str, 

279 MaxLen(1024), 

280 warn( 

281 Annotated[str, MaxLen(512)], "Description longer than 512 characters." 

282 ), 

283 ] 

284 ] = "" 

285 """A string containing a brief description.""" 

286 

287 covers: list[_FileDescr_cover] = Field( 

288 default_factory=cast(Callable[[], list[_FileDescr_cover]], list), 

289 description=( 

290 "Cover images. Please use an image smaller than 500KB and an aspect" 

291 " ratio width to height of 2:1 or 1:1.\nThe supported image formats" 

292 f" are: {VALID_COVER_IMAGE_EXTENSIONS}" 

293 ), 

294 examples=[[{"source": "cover.png"}]], 

295 ) 

296 """Cover images.""" 

297 

298 documentation: FAIR[FileDescr_documentation | None] = None 

299 """Additional model documentation. 

300 The recommended documentation source file name is `README.md`. An `.md` suffix is mandatory.""" 

301 

302 @classmethod 

303 def convert_from_old_format_wo_validation(cls, data: BioimageioYamlContent) -> None: 

304 """Convert metadata following an older format version to this classes' format 

305 without validating the result. 

306 """ 

307 convert_from_older_format(data) 

308 

309 id_emoji: ( 

310 Annotated[str, Len(min_length=1, max_length=2), Field(examples=["🦈", "🦥"])] 

311 | None 

312 ) = None 

313 """UTF-8 emoji for display alongside the `id`.""" 

314 

315 authors: FAIR[list[Author]] = Field( 

316 default_factory=cast(Callable[[], list[Author]], list) 

317 ) 

318 """The authors are the creators of this resource description and the primary points of contact.""" 

319 

320 attachments: list[FileDescr_package] = Field( 

321 default_factory=cast(Callable[[], list[FileDescr]], list) 

322 ) 

323 """file attachments""" 

324 

325 cite: FAIR[list[CiteEntry]] = Field( 

326 default_factory=cast(Callable[[], list[CiteEntry]], list) 

327 ) 

328 """citations""" 

329 

330 license: FAIR[ 

331 Annotated[ 

332 LicenseId | DeprecatedLicenseId | None | FileDescr_package, 

333 Field( 

334 union_mode="left_to_right", examples=["CC0-1.0", "MIT", "BSD-2-Clause"] 

335 ), 

336 ] 

337 ] = None 

338 """A [SPDX license identifier](https://spdx.org/licenses/) or a custom license file.""" 

339 

340 @field_validator("license", mode="after") 

341 @classmethod 

342 def _check_license(cls, value: Any) -> Any: 

343 if isinstance(value, FileDescr): 

344 issue_warning( 

345 "Custom license file provided. Consider using a standard SPDX license identifier for better FAIR" 

346 + " compliance instead of pointing to {value}.", 

347 value=value.source, 

348 ) 

349 elif value in get_args(DeprecatedLicenseId): 

350 issue_warning( 

351 "License '{value}' is deprecated. Consider using a non-deprecated SPDX license identifier for better" 

352 + " FAIR compliance.", 

353 value=value, 

354 ) 

355 

356 return value 

357 

358 git_repo: Annotated[ 

359 HttpUrl | None, 

360 Field( 

361 examples=[ 

362 "https://github.com/bioimage-io/spec-bioimage-io/tree/main/example_descriptions/models/unet2d_nuclei_broad" 

363 ], 

364 ), 

365 ] = None 

366 """A URL to the Git repository where the resource is being developed.""" 

367 

368 icon: Annotated[str, Len(min_length=1, max_length=2)] | FileDescr_package | None = ( 

369 None 

370 ) 

371 """An icon for illustration, e.g. on bioimage.io""" 

372 

373 links: Annotated[ 

374 list[str], 

375 Field( 

376 examples=[ 

377 ( 

378 "ilastik/ilastik", 

379 "deepimagej/deepimagej", 

380 "zero/notebook_u-net_3d_zerocostdl4mic", 

381 ) 

382 ], 

383 ), 

384 ] = Field(default_factory=list) 

385 """IDs of other bioimage.io resources""" 

386 

387 uploader: Uploader | None = None 

388 """The person who uploaded the model (e.g. to bioimage.io)""" 

389 

390 maintainers: list[Maintainer] = Field( 

391 default_factory=cast(Callable[[], list[Maintainer]], list) 

392 ) 

393 """Maintainers of this resource. 

394 If not specified, `authors` are maintainers and at least some of them has to specify their `github_user` name""" 

395 

396 @model_validator(mode="after") 

397 def _check_maintainers_exist(self): 

398 if ( 

399 not self.maintainers 

400 and self.authors 

401 and all(a.github_user is None for a in self.authors) 

402 ): 

403 issue_warning( 

404 "Missing `maintainers` or any author in `authors` with a specified" 

405 + " `github_user` name.", 

406 value=self.authors, 

407 field="authors", 

408 severity=ALERT, 

409 ) 

410 

411 return self 

412 

413 tags: FAIR[ 

414 Annotated[ 

415 list[str], 

416 Field( 

417 examples=[("unet2d", "pytorch", "nucleus", "segmentation", "dsb2018")] 

418 ), 

419 ] 

420 ] = Field(default_factory=list) 

421 """Associated tags""" 

422 

423 @as_warning 

424 @field_validator("tags") 

425 @classmethod 

426 def warn_about_tag_categories( 

427 cls, value: list[str], info: ValidationInfo 

428 ) -> list[str]: 

429 categories = TAG_CATEGORIES.get(info.data["type"], {}) 

430 missing_categories: list[dict[str, Sequence[str]]] = [] 

431 for cat, entries in categories.items(): 

432 if not any(e in value for e in entries): 

433 missing_categories.append({cat: entries}) 

434 

435 if missing_categories: 

436 raise ValueError( 

437 f"Missing tags from bioimage.io categories: {missing_categories}" 

438 ) 

439 

440 return value 

441 

442 version: Version | None = None 

443 """The version of the resource following SemVer 2.0.""" 

444 

445 @model_validator(mode="before") 

446 def _remove_version_number(cls, value: Any): 

447 if is_dict(value): 

448 vn = value.pop("version_number", None) 

449 if vn is not None and value.get("version") is None: 

450 value["version"] = vn 

451 

452 return value 

453 

454 version_comment: Annotated[str, MaxLen(512)] | None = None 

455 """A comment on the version of the resource.""" 

456 

457 

458class GenericDescrBase(GenericModelDescrBase): 

459 """Base for all resource descriptions except for the model descriptions""" 

460 

461 implemented_format_version: ClassVar[Literal["0.3.4"]] = "0.3.4" 

462 if TYPE_CHECKING: 

463 format_version: Literal["0.3.4"] = "0.3.4" 

464 else: 

465 format_version: Literal["0.3.4"] 

466 """The **format** version of this resource specification""" 

467 

468 @model_validator(mode="before") 

469 @classmethod 

470 def _convert_from_older_format( 

471 cls, data: BioimageioYamlContent, / 

472 ) -> BioimageioYamlContent: 

473 cls.convert_from_old_format_wo_validation(data) 

474 return data 

475 

476 badges: list[BadgeDescr] = Field( # pyright: ignore[reportUnknownVariableType] 

477 default_factory=list 

478 ) 

479 """badges associated with this resource""" 

480 

481 config: Config = Field(default_factory=Config.model_construct) 

482 """A field for custom configuration that can contain any keys not present in the RDF spec. 

483 This means you should not store, for example, a GitHub repo URL in `config` since there is a `git_repo` field. 

484 Keys in `config` may be very specific to a tool or consumer software. To avoid conflicting definitions, 

485 it is recommended to wrap added configuration into a sub-field named with the specific domain or tool name, 

486 for example: 

487 ```yaml 

488 config: 

489 giraffe_neckometer: # here is the domain name 

490 length: 3837283 

491 address: 

492 home: zoo 

493 imagej: # config specific to ImageJ 

494 macro_dir: path/to/macro/file 

495 ``` 

496 If possible, please use [`snake_case`](https://en.wikipedia.org/wiki/Snake_case) for keys in `config`. 

497 You may want to list linked files additionally under `attachments` to include them when packaging a resource. 

498 (Packaging a resource means downloading/copying important linked files and creating a ZIP archive that contains 

499 an altered rdf.yaml file with local references to the downloaded files.)""" 

500 

501 

502ResourceDescrType = TypeVar("ResourceDescrType", bound=GenericDescrBase) 

503 

504 

505class GenericDescr(GenericDescrBase, extra="ignore"): 

506 """Specification of the fields used in a generic bioimage.io-compliant resource description file (RDF). 

507 

508 An RDF is a YAML file that describes a resource such as a model, a dataset, or a notebook. 

509 Note that those resources are described with a type-specific RDF. 

510 Use this generic resource description, if none of the known specific types matches your resource. 

511 """ 

512 

513 implemented_type: ClassVar[Literal["generic"]] = "generic" 

514 if TYPE_CHECKING: 

515 type: Annotated[str, LowerCase] = "generic" 

516 """The resource type assigns a broad category to the resource.""" 

517 else: 

518 type: Annotated[str, LowerCase] 

519 """The resource type assigns a broad category to the resource.""" 

520 

521 id: ( 

522 Annotated[ResourceId, Field(examples=["affable-shark", "ambitious-sloth"])] 

523 | None 

524 ) = None 

525 """bioimage.io-wide unique resource identifier 

526 assigned by bioimage.io; version **un**specific.""" 

527 

528 parent: ResourceId | None = None 

529 """The description from which this one is derived""" 

530 

531 source: HttpUrl | None = None 

532 """The primary source of the resource""" 

533 

534 @field_validator("type", mode="after") 

535 @classmethod 

536 def check_specific_types(cls, value: str) -> str: 

537 if value in KNOWN_SPECIFIC_RESOURCE_TYPES: 

538 raise ValueError( 

539 f"Use the {value} description instead of this generic description for" 

540 + f" your '{value}' resource." 

541 ) 

542 

543 return value