Coverage for src/bioimageio/spec/_description_impl.py: 92%
61 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
1"""implementation details for building a bioimage.io resource description"""
3from __future__ import annotations
5import collections.abc
6from collections.abc import Callable, Mapping
7from typing import Any, Literal, TypeVar
9from ._internal.common_nodes import InvalidDescr, ResourceDescrBase
10from ._internal.field_validation import issue_warning
11from ._internal.io import BioimageioYamlContentView
12from ._internal.types import FormatVersionPlaceholder
13from ._internal.validation_context import ValidationContext, get_validation_context
14from .summary import (
15 ErrorEntry,
16 ValidationDetail,
17)
19ResourceDescrT = TypeVar("ResourceDescrT", bound=ResourceDescrBase)
22DISCOVER: Literal["discover"] = "discover"
23"""placeholder for whatever format version an RDF specifies"""
26def get_rd_class_impl(
27 typ: Any,
28 format_version: Any,
29 descriptions_map: Mapping[str | None, Mapping[str, type[ResourceDescrT]]],
30 fallback_to_latest: bool,
31) -> type[ResourceDescrT]:
32 """get the resource description class for the given type and format version"""
33 assert None in descriptions_map
34 assert all("latest" in version_map for version_map in descriptions_map.values())
35 assert all(
36 fv == "latest" or fv.count(".") == 1
37 for version_map in descriptions_map.values()
38 for fv in version_map
39 )
40 if not isinstance(typ, str) or typ not in descriptions_map:
41 typ = None
43 format_version = str(format_version)
44 if format_version == "latest" or (ndots := format_version.count(".")) == 1:
45 use_format_version = format_version
46 elif ndots == 0:
47 use_format_version = format_version + ".0"
48 else:
49 assert ndots > 1
50 use_format_version = format_version[: format_version.rfind(".")]
52 descr_versions = descriptions_map[typ]
53 if use_format_version not in descr_versions:
54 if fallback_to_latest:
55 issue_warning(
56 "Unsupported format version '{value}' for type '{typ}'.",
57 value=format_version,
58 field="format_version",
59 log_depth=3,
60 msg_context={"typ": typ},
61 )
62 use_format_version = "latest"
63 else:
64 raise ValueError(
65 f"Unsupported format version '{format_version}' for type '{typ}'."
66 + " Supported format versions are: {', '.join(sorted(fv for fv in descr_versions))}"
67 )
69 return descr_versions[use_format_version]
72def build_description_impl(
73 content: BioimageioYamlContentView,
74 /,
75 *,
76 context: ValidationContext | None = None,
77 format_version: FormatVersionPlaceholder | str = DISCOVER,
78 get_rd_class: Callable[[Any, Any, bool], type[ResourceDescrT]],
79) -> ResourceDescrT | InvalidDescr:
80 context = context or get_validation_context()
81 errors: list[ErrorEntry] = []
82 if isinstance(content, collections.abc.Mapping):
83 for minimum in ("type", "format_version"):
84 if minimum not in content:
85 errors.append(
86 ErrorEntry(
87 loc=(minimum,), msg=f"Missing field '{minimum}'", type="error"
88 )
89 )
90 elif not isinstance(content[minimum], str):
91 errors.append(
92 ErrorEntry(
93 loc=(minimum,),
94 msg=f"Invalid type '{type(content[minimum])}'",
95 type="error",
96 )
97 )
98 else:
99 errors.append(
100 ErrorEntry(
101 loc=(), msg=f"Invalid content of type '{type(content)}'", type="error"
102 )
103 )
104 content = {}
106 if errors:
107 ret = InvalidDescr(**content) # pyright: ignore[reportArgumentType]
108 ret.validation_summary.add_detail(
109 ValidationDetail(
110 name="extract fields to chose description class",
111 status="failed",
112 errors=errors,
113 context=context.summary,
114 )
115 )
116 assert ret.validation_summary.status == "failed", (
117 "expected invalid description to have a failed validation summary status"
118 )
119 return ret
121 typ = content["type"]
122 # check format_version argument before loading as 'discover'
123 # to throw an exception for an invalid format_version early
124 if str(format_version).lower() != DISCOVER:
125 as_rd_class = get_rd_class(typ, format_version, False)
126 else:
127 as_rd_class = None
128 # always load with discovered format_version first
129 rd_class = get_rd_class(typ, content["format_version"], True)
130 rd = rd_class.load(content, context=context)
132 if as_rd_class is not None and as_rd_class is not rd_class:
133 # load with requested format_version
134 discover_details = rd.validation_summary.details
135 rd = as_rd_class.load(content, context=context)
136 assert rd.validation_summary is not None
137 rd.validation_summary.details[:0] = discover_details
139 return rd