Coverage for src / bioimageio / spec / _internal / json_schema.py: 30%
33 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-08 13:52 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-08 13:52 +0000
1import difflib
2import re
3from typing import Any, Dict, Optional, Tuple
5from loguru import logger
6from pydantic import ConfigDict
8from .._description import DESCRIPTIONS_MAP, SpecificResourceDescr
9from .._version import VERSION
10from .type_guards import is_dict, is_list
13def _patch_desccription(
14 json_schema: Dict[str, Any], path: Tuple[str, ...] = ()
15) -> None:
16 """Patch descriptions:
18 - replace mkdocstrings cross-reference syntax [object][] by `object`
19 """
20 if isinstance(descr := json_schema.get("description"), str) and descr:
21 # Replace markdown link references like [object][] with `object`
22 new_descr = re.sub(r"\[([^\]]+)\]\[\]", r"`\1`", descr)
23 if descr != new_descr:
24 diff = difflib.Differ().compare(descr.splitlines(), new_descr.splitlines())
25 logger.debug(f"updated {'.'.join(path)}:\n" + "\n".join(diff))
26 json_schema["description"] = new_descr
28 for k, v in json_schema.items():
29 if is_dict(v):
30 _patch_desccription(v, path + (str(k),))
31 elif is_list(v):
32 for index, item in enumerate(v):
33 if is_dict(item):
34 _patch_desccription(item, path + (str(k), str(index)))
37def generate_json_schema(
38 type_format: Optional[Tuple[str, str]] = None,
39) -> Dict[str, Any]:
40 """generate the bioimageio specification as a JSON schema"""
41 from pydantic import TypeAdapter
43 spec_format_version = ".".join(VERSION.split(".")[:3]) # strip library version
44 if type_format is None:
45 adapter: TypeAdapter[Any] = TypeAdapter(
46 SpecificResourceDescr,
47 config=ConfigDict(
48 title=f"bioimage.io resource description {spec_format_version}"
49 ),
50 )
51 else:
52 typ, format_version = type_format
53 rd_class = DESCRIPTIONS_MAP[typ][format_version]
54 adapter = TypeAdapter(rd_class)
56 json_schema = adapter.json_schema()
57 _patch_desccription(json_schema)
58 return json_schema