Coverage for src/bioimageio/spec/_description.py: 92%

52 statements  

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

1from __future__ import annotations 

2 

3from types import MappingProxyType 

4from typing import Annotated, Any, Literal, TypeAlias, TypeVar, overload 

5 

6from pydantic import Discriminator 

7 

8from ._description_impl import DISCOVER, build_description_impl, get_rd_class_impl 

9from ._internal.common_nodes import InvalidDescr 

10from ._internal.io import BioimageioYamlContent, BioimageioYamlContentView 

11from ._internal.types import FormatVersionPlaceholder 

12from ._internal.validation_context import ValidationContext, get_validation_context 

13from .application import ( 

14 AnyApplicationDescr, 

15 ApplicationDescr, 

16 ApplicationDescr_v0_2, 

17 ApplicationDescr_v0_3, 

18) 

19from .dataset import AnyDatasetDescr, DatasetDescr, DatasetDescr_v0_2, DatasetDescr_v0_3 

20from .generic import AnyGenericDescr, GenericDescr, GenericDescr_v0_2, GenericDescr_v0_3 

21from .model import AnyModelDescr, ModelDescr, ModelDescr_v0_4, ModelDescr_v0_5 

22from .notebook import ( 

23 AnyNotebookDescr, 

24 NotebookDescr, 

25 NotebookDescr_v0_2, 

26 NotebookDescr_v0_3, 

27) 

28from .summary import ValidationSummary 

29 

30LATEST: Literal["latest"] = "latest" 

31"""placeholder for the latest available format version""" 

32 

33 

34LatestResourceDescr: TypeAlias = ( 

35 Annotated[ 

36 ApplicationDescr | DatasetDescr | ModelDescr | NotebookDescr, 

37 Discriminator("type"), 

38 ] 

39 | GenericDescr 

40) 

41"""A resource description following the latest specification format""" 

42 

43 

44SpecificResourceDescr: TypeAlias = Annotated[ 

45 AnyApplicationDescr | AnyDatasetDescr | AnyModelDescr | AnyNotebookDescr, 

46 Discriminator("type"), 

47] 

48"""Any of the implemented, non-generic resource descriptions""" 

49 

50ResourceDescr: TypeAlias = SpecificResourceDescr | AnyGenericDescr 

51"""Any of the implemented resource descriptions""" 

52 

53 

54def dump_description( 

55 rd: ResourceDescr | InvalidDescr, 

56 /, 

57 *, 

58 exclude_unset: bool = True, 

59 exclude_defaults: bool = False, 

60) -> BioimageioYamlContent: 

61 """Converts a resource to a dictionary containing only simple types that can directly be serialzed to YAML. 

62 

63 Args: 

64 rd: bioimageio resource description 

65 exclude_unset: Exclude fields that have not explicitly be set. 

66 exclude_defaults: Exclude fields that have the default value (even if set explicitly). 

67 """ 

68 return rd.model_dump( 

69 mode="json", exclude_unset=exclude_unset, exclude_defaults=exclude_defaults 

70 ) 

71 

72 

73RD = TypeVar("RD", bound=ResourceDescr) 

74 

75 

76LATEST_DESCRIPTIONS_MAP = MappingProxyType( 

77 { 

78 None: GenericDescr, 

79 "generic": GenericDescr, 

80 "application": ApplicationDescr, 

81 "dataset": DatasetDescr, 

82 "notebook": NotebookDescr, 

83 "model": ModelDescr, 

84 } 

85) 

86DESCRIPTIONS_MAP = MappingProxyType( 

87 { 

88 None: MappingProxyType( 

89 { 

90 "0.2": GenericDescr_v0_2, 

91 "0.3": GenericDescr_v0_3, 

92 "latest": GenericDescr, 

93 } 

94 ), 

95 "generic": MappingProxyType( 

96 { 

97 "0.2": GenericDescr_v0_2, 

98 "0.3": GenericDescr_v0_3, 

99 "latest": GenericDescr, 

100 } 

101 ), 

102 "application": MappingProxyType( 

103 { 

104 "0.2": ApplicationDescr_v0_2, 

105 "0.3": ApplicationDescr_v0_3, 

106 "latest": ApplicationDescr, 

107 } 

108 ), 

109 "dataset": MappingProxyType( 

110 { 

111 "0.2": DatasetDescr_v0_2, 

112 "0.3": DatasetDescr_v0_3, 

113 "latest": DatasetDescr, 

114 } 

115 ), 

116 "notebook": MappingProxyType( 

117 { 

118 "0.2": NotebookDescr_v0_2, 

119 "0.3": NotebookDescr_v0_3, 

120 "latest": NotebookDescr, 

121 } 

122 ), 

123 "model": MappingProxyType( 

124 { 

125 "0.3": ModelDescr_v0_4, 

126 "0.4": ModelDescr_v0_4, 

127 "0.5": ModelDescr_v0_5, 

128 "latest": ModelDescr, 

129 } 

130 ), 

131 } 

132) 

133"""A mapping to determine the appropriate Description class 

134 for a given **type** and **format_version**.""" 

135 

136 

137def _get_rd_class(typ: Any, format_version: Any, fallback_to_latest: bool): 

138 return get_rd_class_impl( 

139 typ, format_version, DESCRIPTIONS_MAP, fallback_to_latest=fallback_to_latest 

140 ) 

141 

142 

143@overload 

144def build_description( 

145 content: BioimageioYamlContentView, 

146 /, 

147 *, 

148 context: ValidationContext | None = None, 

149 format_version: Literal["latest"], 

150) -> LatestResourceDescr | InvalidDescr: ... 

151 

152 

153@overload 

154def build_description( 

155 content: BioimageioYamlContentView, 

156 /, 

157 *, 

158 context: ValidationContext | None = None, 

159 format_version: FormatVersionPlaceholder | str = DISCOVER, 

160) -> ResourceDescr | InvalidDescr: ... 

161 

162 

163def build_description( 

164 content: BioimageioYamlContentView, 

165 /, 

166 *, 

167 context: ValidationContext | None = None, 

168 format_version: FormatVersionPlaceholder | str = DISCOVER, 

169) -> ResourceDescr | InvalidDescr: 

170 """build a bioimage.io resource description from an RDF's content. 

171 

172 Use `load_description` if you want to build a resource description from an rdf.yaml 

173 or bioimage.io zip-package. 

174 

175 Args: 

176 content: loaded rdf.yaml file (loaded with YAML, not bioimageio.spec) 

177 context: validation context to use during validation 

178 format_version: 

179 (optional) use this argument to load the resource and 

180 convert its metadata to a higher format_version. 

181 Note: 

182 - Use "latest" to convert to the latest available format version. 

183 - Use "discover" to use the format version specified in the RDF. 

184 - Only considers major.minor format version, ignores patch version. 

185 - Conversion to lower format versions is not supported. 

186 

187 Returns: 

188 An object holding all metadata of the bioimage.io resource 

189 

190 """ 

191 

192 return build_description_impl( 

193 content, 

194 context=context, 

195 format_version=format_version, 

196 get_rd_class=_get_rd_class, 

197 ) 

198 

199 

200def validate_format( 

201 data: BioimageioYamlContent, 

202 /, 

203 *, 

204 format_version: Literal["discover", "latest"] | str = DISCOVER, 

205 context: ValidationContext | None = None, 

206) -> ValidationSummary: 

207 """Validate a dictionary holding a bioimageio description. 

208 See `bioimagieo.spec.load_description_and_validate_format_only` 

209 to validate a file source. 

210 

211 Args: 

212 data: Dictionary holding the raw bioimageio.yaml content. 

213 format_version: 

214 Format version to (update to and) use for validation. 

215 Note: 

216 - Use "latest" to convert to the latest available format version. 

217 - Use "discover" to use the format version specified in the RDF. 

218 - Only considers major.minor format version, ignores patch version. 

219 - Conversion to lower format versions is not supported. 

220 context: Validation context, see `bioimagieo.spec.ValidationContext` 

221 

222 Note: 

223 Use `bioimagieo.spec.load_description_and_validate_format_only` to validate a 

224 file source instead of loading the YAML content and creating the appropriate 

225 `ValidationContext`. 

226 

227 Alternatively you can use `bioimagieo.spec.load_description` and access the 

228 `validation_summary` attribute of the returned object. 

229 """ 

230 with context or get_validation_context(): 

231 rd = build_description(data, format_version=format_version) 

232 

233 assert rd.validation_summary is not None 

234 return rd.validation_summary 

235 

236 

237def ensure_description_is_model( 

238 rd: InvalidDescr | ResourceDescr, 

239) -> AnyModelDescr: 

240 """ 

241 Raises: 

242 ValueError: for invalid or non-model resources 

243 """ 

244 if isinstance(rd, InvalidDescr): 

245 raise ValueError(f"Invalid {rd.type} description:\n{rd.get_reason()}") 

246 

247 if rd.type != "model": 

248 raise ValueError( 

249 f"Expected a model resource, but got resource type '{rd.type}'" 

250 ) 

251 

252 assert not isinstance( 

253 rd, 

254 ( 

255 GenericDescr_v0_2, 

256 GenericDescr_v0_3, 

257 ), 

258 ) 

259 

260 return rd 

261 

262 

263def ensure_description_is_dataset( 

264 rd: InvalidDescr | ResourceDescr, 

265) -> AnyDatasetDescr: 

266 if isinstance(rd, InvalidDescr): 

267 raise ValueError(f"Invalid {rd.type} description:\n{rd.get_reason()}") 

268 

269 if rd.type != "dataset": 

270 raise ValueError( 

271 f"Expected a dataset resource, but got resource type '{rd.type}'" 

272 ) 

273 

274 assert not isinstance( 

275 rd, 

276 ( 

277 GenericDescr_v0_2, 

278 GenericDescr_v0_3, 

279 ), 

280 ) 

281 

282 return rd