Coverage for src/bioimageio/spec/summary.py: 100%
397 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"""Utilities for summarizing and formatting BioImage.IO validation results.
3This module defines data structures to capture validation errors, warnings,
4and summaries for BioImage.IO resource descriptions, along with helpers to
5format these results as plain text, Markdown, or HTML for reporting and
6diagnostics.
7"""
9from __future__ import annotations
11import html
12import platform
13import subprocess
14from collections.abc import Callable, Mapping, Sequence
15from dataclasses import dataclass
16from datetime import datetime, timezone
17from io import StringIO
18from itertools import chain
19from pathlib import Path
20from tempfile import TemporaryDirectory
21from textwrap import TextWrapper
22from types import MappingProxyType
23from typing import (
24 Annotated,
25 Any,
26 Literal,
27 NamedTuple,
28 cast,
29)
31import annotated_types
32import markdown
33import rich.console
34import rich.markdown
35import rich.traceback
36from loguru import logger
37from pydantic import (
38 BaseModel,
39 Field,
40 field_serializer,
41 field_validator,
42 model_validator,
43)
44from pydantic_core.core_schema import ErrorType
45from typing_extensions import Self, assert_never
47from ._internal.io import is_yaml_value
48from ._internal.io_utils import write_yaml
49from ._internal.type_guards import is_dict
50from ._internal.validation_context import ValidationContextSummary
51from ._internal.version_type import Version
52from ._internal.warning_levels import (
53 ALERT,
54 ALERT_NAME,
55 ERROR,
56 ERROR_NAME,
57 INFO,
58 INFO_NAME,
59 WARNING,
60 WARNING_NAME,
61 WarningLevel,
62 WarningSeverity,
63)
64from ._version import VERSION
65from .conda_env import CondaEnv
67CONDA_CMD = "conda.bat" if platform.system() == "Windows" else "conda"
69Loc = tuple[int | str, ...]
70"""location of error/warning in a nested data structure"""
72WarningSeverityName = Literal["info", "warning", "alert"]
73WarningLevelName = Literal[WarningSeverityName, "error"]
75WARNING_SEVERITY_TO_NAME: Mapping[WarningSeverity, WarningSeverityName] = (
76 MappingProxyType({INFO: INFO_NAME, WARNING: WARNING_NAME, ALERT: ALERT_NAME})
77)
78WARNING_LEVEL_TO_NAME: Mapping[WarningLevel, WarningLevelName] = MappingProxyType(
79 {INFO: INFO_NAME, WARNING: WARNING_NAME, ALERT: ALERT_NAME, ERROR: ERROR_NAME}
80)
81WARNING_NAME_TO_LEVEL: Mapping[WarningLevelName, WarningLevel] = MappingProxyType(
82 {v: k for k, v in WARNING_LEVEL_TO_NAME.items()}
83)
86class ValidationEntry(BaseModel):
87 """Base of `ErrorEntry` and `WarningEntry`"""
89 loc: Loc
90 msg: str
91 type: ErrorType | str
94class ErrorEntry(ValidationEntry):
95 """An error in a `ValidationDetail`"""
97 with_traceback: bool = False
98 traceback_md: str = ""
99 traceback_html: str = ""
100 # private rich traceback that is not serialized
101 _traceback_rich: rich.traceback.Traceback | None = None
103 @property
104 def traceback_rich(self) -> rich.traceback.Traceback | None:
105 return self._traceback_rich
107 def model_post_init(self, __context: Any, /):
108 if self.with_traceback and not (self.traceback_md or self.traceback_html):
109 self._traceback_rich = rich.traceback.Traceback()
110 console = rich.console.Console(
111 record=True,
112 file=StringIO(),
113 color_system="truecolor",
114 width=120,
115 tab_size=4,
116 soft_wrap=True,
117 )
118 console.print(self._traceback_rich)
119 if not self.traceback_md:
120 self.traceback_md = console.export_text(clear=False)
122 if not self.traceback_html:
123 self.traceback_html = console.export_html(clear=False)
126class WarningEntry(ValidationEntry):
127 """A warning in a `ValidationDetail`"""
129 severity: WarningSeverity = WARNING
131 @property
132 def severity_name(self) -> WarningSeverityName:
133 return WARNING_SEVERITY_TO_NAME[self.severity]
136def format_loc(
137 loc: Loc, target: Literal["md", "html", "plain"] | rich.console.Console
138) -> str:
139 """helper to format a location tuple **loc**"""
140 loc_str = ".".join(f"({x})" if x[0].isupper() else x for x in map(str, loc))
142 # additional field validation can make the location information quite convoluted, e.g.
143 # `weights.pytorch_state_dict.dependencies.source.function-after[validate_url_ok(), url['http','https']]` Input should be a valid URL, relative URL without a base
144 # therefore we remove the `.function-after[validate_url_ok(), url['http','https']]` here
145 loc_str, *_ = loc_str.split(".function-after")
146 if loc_str:
147 if target == "md" or isinstance(target, rich.console.Console):
148 start = "`"
149 end = "`"
150 elif target == "html":
151 start = "<code>"
152 end = "</code>"
153 elif target == "plain":
154 start = ""
155 end = ""
156 else:
157 assert_never(target)
159 return f"{start}{loc_str}{end}"
160 else:
161 return ""
164class InstalledPackage(NamedTuple):
165 name: str
166 version: str
167 build: str = ""
168 channel: str = ""
171class ValidationDetail(BaseModel, extra="allow"):
172 """a detail in a validation summary"""
174 name: str
175 status: Literal["passed", "failed"]
176 loc: Loc = ()
177 """location in the RDF that this detail applies to"""
178 errors: list[ErrorEntry] = Field(
179 default_factory=cast(Callable[[], list[ErrorEntry]], list)
180 )
181 warnings: list[WarningEntry] = Field(
182 default_factory=cast(Callable[[], list[WarningEntry]], list)
183 )
185 context: ValidationContextSummary | None = None
187 recommended_env: CondaEnv | None = None
188 """recommended conda environemnt for this validation detail"""
190 saved_conda_compare: str | None = None
191 """output of `conda compare <recommended env>`"""
193 @field_serializer("saved_conda_compare")
194 def _save_conda_compare(self, value: str | None):
195 return self.conda_compare
197 @model_validator(mode="before")
198 def _load_legacy(cls, data: Any):
199 if is_dict(data):
200 field_name = "conda_compare"
201 if (
202 field_name in data
203 and (saved_field_name := f"saved_{field_name}") not in data
204 ):
205 data[saved_field_name] = data.pop(field_name)
207 return data
209 @property
210 def conda_compare(self) -> str | None:
211 if self.recommended_env is None:
212 return None
214 if self.saved_conda_compare is None:
215 dumped_env = self.recommended_env.model_dump(mode="json")
216 if is_yaml_value(dumped_env):
217 with TemporaryDirectory() as d:
218 path = Path(d) / "env.yaml"
219 with path.open("w", encoding="utf-8") as f:
220 write_yaml(dumped_env, f)
222 try:
223 compare_proc = subprocess.run(
224 [CONDA_CMD, "compare", str(path)],
225 stdout=subprocess.PIPE,
226 stderr=subprocess.STDOUT,
227 shell=False,
228 text=True,
229 check=False,
230 )
231 except Exception as e:
232 self.saved_conda_compare = f"Failed to run `conda compare`: {e}"
233 else:
234 self.saved_conda_compare = (
235 compare_proc.stdout
236 or f"`conda compare` exited with {compare_proc.returncode}"
237 )
238 else:
239 self.saved_conda_compare = (
240 "Failed to dump recommended env to valid yaml"
241 )
243 return self.saved_conda_compare
245 @property
246 def status_icon(self) -> str:
247 if self.status == "passed":
248 return "✔️"
249 else:
250 return "❌"
253class ValidationSummary(BaseModel, extra="allow"):
254 """Summarizes output of all bioimageio validations and tests
255 for one specific `ResourceDescr` instance."""
257 name: str
258 """Name of the validation"""
260 source_name: str
261 """Source of the validated bioimageio description"""
263 id: str | None = None
264 """ID of the validated resource"""
266 version: Version | None = None
267 """Version of the validated resource"""
269 type: str
270 """Type of the validated resource"""
272 format_version: str
273 """Format version of the validated resource"""
275 status: Literal["passed", "valid-format", "failed"]
276 """Overall status of the bioimageio validation"""
278 metadata_completeness: Annotated[float, annotated_types.Interval(ge=0, le=1)] = 0.0
279 """Estimate of completeness of the metadata in the resource description.
281 Note: This completeness estimate may change with subsequent releases
282 and should be considered bioimageio.spec version specific.
283 """
285 details: list[ValidationDetail]
286 """List of validation details"""
287 env: set[InstalledPackage] = Field(
288 default_factory=lambda: {
289 InstalledPackage(
290 name="bioimageio.spec",
291 version=VERSION,
292 )
293 }
294 )
295 """List of selected, relevant package versions"""
297 saved_conda_list: str | None = None
299 @field_serializer("saved_conda_list")
300 def _save_conda_list(self, value: str | None):
301 return self.conda_list
303 @property
304 def conda_list(self) -> str:
305 if self.saved_conda_list is None:
306 try:
307 p = subprocess.run(
308 [CONDA_CMD, "list"],
309 stdout=subprocess.PIPE,
310 stderr=subprocess.STDOUT,
311 shell=False,
312 text=True,
313 check=False,
314 )
315 except Exception as e:
316 self.saved_conda_list = f"Failed to run `conda list`: {e}"
317 else:
318 self.saved_conda_list = (
319 p.stdout or f"`conda list` exited with {p.returncode}"
320 )
322 return self.saved_conda_list
324 @property
325 def status_icon(self) -> str:
326 if self.status == "passed":
327 return "✔️"
328 elif self.status == "valid-format":
329 return "🟡"
330 else:
331 return "❌"
333 @property
334 def errors(self) -> list[ErrorEntry]:
335 return list(chain.from_iterable(d.errors for d in self.details))
337 @property
338 def warnings(self) -> list[WarningEntry]:
339 return list(chain.from_iterable(d.warnings for d in self.details))
341 def format(
342 self,
343 *,
344 width: int | None = None,
345 include_conda_list: bool = False,
346 ) -> str:
347 """Format summary as Markdown string (alias to `format_md`)"""
348 return self.format_md(width=width, include_conda_list=include_conda_list)
350 def format_md(
351 self,
352 *,
353 width: int | None = None,
354 include_conda_list: bool = False,
355 ) -> str:
356 """Format summary as Markdown string"""
357 return self._format(
358 width=width, target="md", include_conda_list=include_conda_list
359 )
361 def format_html(
362 self,
363 *,
364 width: int | None = None,
365 include_conda_list: bool = False,
366 ) -> str:
367 md_with_html = self._format(
368 target="html", width=width, include_conda_list=include_conda_list
369 )
370 return markdown.markdown(
371 md_with_html, extensions=["tables", "fenced_code", "nl2br"]
372 )
374 def display(
375 self,
376 *,
377 width: int | None = None,
378 include_conda_list: bool = False,
379 tab_size: int = 4,
380 soft_wrap: bool = True,
381 ) -> None:
382 try: # render as HTML in Jupyter notebook
383 from IPython.core.getipython import get_ipython
384 from IPython.display import (
385 display_html, # pyright: ignore[reportUnknownVariableType]
386 )
387 except ImportError:
388 pass
389 else:
390 if get_ipython() is not None:
391 _ = display_html(
392 self.format_html(
393 width=width, include_conda_list=include_conda_list
394 ),
395 raw=True,
396 )
397 return
399 # render with rich
400 _ = self._format(
401 target=rich.console.Console(
402 width=width,
403 tab_size=tab_size,
404 soft_wrap=soft_wrap,
405 ),
406 width=width,
407 include_conda_list=include_conda_list,
408 )
410 def add_detail(
411 self,
412 detail: ValidationDetail,
413 update_status: bool = True,
414 ) -> None:
415 """add a validation detail to the summary and, if `update_status` is True,
416 possibly downgrade the overall status from "passed" to "valid-format"
417 """
418 if detail in self.details:
419 return
421 # An overall status 'passed' can degrade to 'valid-format'
422 # The status can not be upgraded here as we do not know if it has been downgraded before or not yet tested.
423 # Once status is 'failed' it cannot change anymore.
424 if update_status and self.status == "passed" and detail.status == "failed":
425 # "passed" -> "valid-format"
426 self.status = "valid-format"
428 self.details.append(detail)
430 def log(
431 self,
432 to: Literal["display"] | Path | Sequence[Literal["display"] | Path],
433 ) -> list[Path]:
434 """Convenience method to display the validation summary in the terminal and/or
435 save it to disk. See `save` for details."""
436 if to == "display":
437 display = True
438 save_to = []
439 elif isinstance(to, Path):
440 display = False
441 save_to = [to]
442 else:
443 display = "display" in to
444 save_to = [p for p in to if p != "display"]
446 if display:
447 self.display()
449 return self.save(save_to)
451 def save(
452 self, path: Path | Sequence[Path] = Path("{id}_summary_{now}")
453 ) -> list[Path]:
454 """Save the validation/test summary in JSON, Markdown or HTML format.
456 Returns:
457 List of file paths the summary was saved to.
459 Notes:
460 - Format is chosen based on the suffix: `.json`, `.md`, `.html`.
461 - If **path** has no suffix it is assumed to be a direcotry to which a
462 `summary.json`, `summary.md` and `summary.html` are saved to.
463 """
464 if isinstance(path, (str, Path)):
465 path = [Path(path)]
467 # folder to file paths
468 file_paths: list[Path] = []
469 for p in path:
470 if p.suffix:
471 file_paths.append(p)
472 else:
473 file_paths.extend(
474 [
475 p / "summary.json",
476 p / "summary.md",
477 p / "summary.html",
478 ]
479 )
481 now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
482 for p in file_paths:
483 p = Path(str(p).format(id=self.id or "bioimageio", now=now))
484 if p.suffix == ".json":
485 self.save_json(p)
486 elif p.suffix == ".md":
487 self.save_markdown(p)
488 elif p.suffix == ".html":
489 self.save_html(p)
490 else:
491 raise ValueError(f"Unknown summary path suffix '{p.suffix}'")
493 return file_paths
495 def save_json(
496 self, path: Path = Path("summary.json"), *, indent: int | None = 2
497 ) -> None:
498 """Save validation/test summary as JSON file."""
499 json_str = self.model_dump_json(indent=indent)
500 path.parent.mkdir(exist_ok=True, parents=True)
501 _ = path.write_text(json_str, encoding="utf-8")
502 logger.info("Saved summary to {}", path.absolute())
504 def save_markdown(self, path: Path = Path("summary.md")) -> None:
505 """Save rendered validation/test summary as Markdown file."""
506 formatted = self.format_md()
507 path.parent.mkdir(exist_ok=True, parents=True)
508 _ = path.write_text(formatted, encoding="utf-8")
509 logger.info("Saved Markdown formatted summary to {}", path.absolute())
511 def save_html(self, path: Path = Path("summary.html")) -> None:
512 """Save rendered validation/test summary as HTML file."""
513 path.parent.mkdir(exist_ok=True, parents=True)
515 html = self.format_html()
516 _ = path.write_text(html, encoding="utf-8")
517 logger.info("Saved HTML formatted summary to {}", path.absolute())
519 @classmethod
520 def load_json(cls, path: Path) -> Self:
521 """Load validation/test summary from a suitable JSON file"""
522 json_str = Path(path).read_text(encoding="utf-8")
523 return cls.model_validate_json(json_str)
525 @field_validator("env", mode="before")
526 def _convert_old_env(cls, value: list[list[str] | dict[str, str]]):
527 """convert old style dict values of `env` for backwards compatibility"""
528 if isinstance(value, list):
529 return [
530 (
531 (v["name"], v["version"], v.get("build", ""), v.get("channel", ""))
532 if isinstance(v, dict) and "name" in v and "version" in v
533 else v
534 )
535 for v in value
536 ]
537 else:
538 return value
540 def _format(
541 self,
542 *,
543 target: rich.console.Console | Literal["html", "md"],
544 width: int | None,
545 include_conda_list: bool,
546 ) -> str:
547 return _format_summary(
548 self,
549 target=target,
550 width=width or 100,
551 include_conda_list=include_conda_list,
552 )
555def _format_summary(
556 summary: ValidationSummary,
557 *,
558 hide_tracebacks: bool = False, # TODO: remove?
559 hide_source: bool = False, # TODO: remove?
560 hide_env: bool = False, # TODO: remove?
561 target: rich.console.Console | Literal["html", "md"] = "md",
562 include_conda_list: bool,
563 width: int,
564) -> str:
565 parts: list[str] = []
566 format_table = _format_html_table if target == "html" else _format_md_table
567 details_below: dict[str, str | tuple[str, rich.traceback.Traceback]] = {}
568 left_out_details: int = 0
569 left_out_details_header = "Left out details"
571 def add_part(part: str):
572 parts.append(part)
573 if isinstance(target, rich.console.Console):
574 target.print(rich.markdown.Markdown(part))
576 def add_section(header: str):
577 if target == "md" or isinstance(target, rich.console.Console):
578 add_part(f"\n### {header}\n")
579 elif target == "html":
580 parts.append(f'<h3 id="{header_to_tag(header)}">{header}</h3>')
581 else:
582 assert_never(target)
584 def header_to_tag(header: str):
585 return (
586 header.replace("`", "")
587 .replace("(", "")
588 .replace(")", "")
589 .replace(" ", "-")
590 .lower()
591 )
593 def add_as_details_below(
594 title: str, text: str | tuple[str, rich.traceback.Traceback]
595 ):
596 """returns a header and its tag to link to details below"""
598 def make_link(header: str):
599 tag = header_to_tag(header)
600 if target == "md":
601 return f"[{header}](#{tag})"
602 elif target == "html":
603 return f'<a href="#{tag}">{header}</a>'
604 elif isinstance(target, rich.console.Console):
605 return f"{header} below"
606 else:
607 assert_never(target)
609 for n in range(1, 4):
610 header = f"{title} {n}"
611 if header in details_below:
612 if details_below[header] == text:
613 return make_link(header)
614 else:
615 details_below[header] = text
616 return make_link(header)
618 nonlocal left_out_details
619 left_out_details += 1
620 return make_link(left_out_details_header)
622 @dataclass
623 class CodeCell:
624 text: str
626 @dataclass
627 class CodeRef:
628 text: str
630 def format_code(
631 code: str,
632 lang: str = "",
633 title: str = "Details",
634 cell_line_limit: int = 15,
635 cell_width_limit: int = 120,
636 ) -> CodeRef | CodeCell:
637 if not code.strip():
638 return CodeCell("")
640 if target == "html":
641 html_lang = f' lang="{lang}"' if lang else ""
642 code = f"<pre{html_lang}>{code}</pre>"
643 put_below = (
644 code.count("\n") > cell_line_limit
645 or max(map(len, code.split("\n"))) > cell_width_limit
646 )
647 else:
648 put_below = True
649 code = f"\n```{lang}\n{code}\n```\n"
651 if put_below:
652 link = add_as_details_below(title, code)
653 return CodeRef(f"See {link}.")
654 else:
655 return CodeCell(code)
657 def format_traceback(entry: ErrorEntry):
658 if isinstance(target, rich.console.Console):
659 if entry.traceback_rich is None:
660 return format_code(entry.traceback_md, title="Traceback")
661 else:
662 link = add_as_details_below(
663 "Traceback", (entry.traceback_md, entry.traceback_rich)
664 )
665 return CodeRef(f"See {link}.")
667 if target == "md":
668 return format_code(entry.traceback_md, title="Traceback")
669 elif target == "html":
670 return format_code(entry.traceback_html, title="Traceback")
671 else:
672 assert_never(target)
674 def format_text(text: str):
675 if target == "html":
676 return [f"<pre>{text}</pre>"]
677 else:
678 return text.split("\n")
680 def get_info_table():
681 info_rows = [
682 [summary.status_icon, summary.name.strip(".").strip()],
683 ["status", summary.status],
684 ]
685 if not hide_source:
686 info_rows.append(["source", html.escape(summary.source_name)])
688 if summary.id is not None:
689 info_rows.append(["id", summary.id])
691 if summary.version is not None:
692 info_rows.append(["version", str(summary.version)])
694 info_rows.append(["applied format", f"{summary.type} {summary.format_version}"])
695 if not hide_env:
696 info_rows.extend([[e.name, e.version] for e in sorted(summary.env)])
698 if include_conda_list:
699 info_rows.append(
700 ["conda list", format_code(summary.conda_list, title="Conda List").text]
701 )
702 return format_table(info_rows)
704 def get_details_table():
705 details = [["", "Location", "Details"]]
707 def append_detail(
708 status: str, loc: Loc, text: str, code: CodeRef | CodeCell | None
709 ):
710 text_lines = format_text(text)
711 status_lines = [""] * len(text_lines)
712 loc_lines = [""] * len(text_lines)
713 status_lines[0] = status
714 loc_lines[0] = format_loc(loc, target)
715 for s_line, loc_line, text_line in zip(status_lines, loc_lines, text_lines):
716 details.append([s_line, loc_line, text_line])
718 if code is not None:
719 details.append(["", "", code.text])
721 for d in summary.details:
722 details.append([d.status_icon, format_loc(d.loc, target), d.name])
724 for entry in d.errors:
725 append_detail(
726 "❌",
727 entry.loc,
728 entry.msg,
729 None if hide_tracebacks else format_traceback(entry),
730 )
732 for entry in d.warnings:
733 append_detail(
734 "⚠" if entry.severity > INFO else "ℹ", entry.loc, entry.msg, None
735 )
737 if d.recommended_env is not None:
738 rec_env = StringIO()
739 json_env = d.recommended_env.model_dump(
740 mode="json", exclude_defaults=True
741 )
742 assert is_yaml_value(json_env)
743 write_yaml(json_env, rec_env)
744 append_detail(
745 "",
746 d.loc,
747 f"recommended conda environment ({d.name})",
748 format_code(
749 rec_env.getvalue(),
750 lang="yaml",
751 title="Recommended Conda Environment",
752 ),
753 )
755 if d.conda_compare:
756 wrapped_conda_compare = "\n".join(
757 TextWrapper(width=width - 4).wrap(d.conda_compare)
758 )
759 append_detail(
760 "",
761 d.loc,
762 f"conda compare ({d.name})",
763 format_code(
764 wrapped_conda_compare,
765 title="Conda Environment Comparison",
766 ),
767 )
769 return format_table(details)
771 add_part(get_info_table())
772 add_part(get_details_table())
774 for header, text in details_below.items():
775 add_section(header)
776 if isinstance(text, tuple):
777 assert isinstance(target, rich.console.Console)
778 text, rich_obj = text
779 target.print(rich_obj)
780 parts.append(f"{text}\n")
781 else:
782 add_part(f"{text}\n")
784 if left_out_details:
785 parts.append(
786 f"\n{left_out_details_header}\nLeft out {left_out_details} more details for brevity.\n"
787 )
789 return "".join(parts)
792def _format_md_table(rows: list[list[str]]) -> str:
793 """format `rows` as markdown table"""
794 n_cols = len(rows[0])
795 assert all(len(row) == n_cols for row in rows)
796 col_widths = [max(max(len(row[i]) for row in rows), 3) for i in range(n_cols)]
798 # fix new lines in table cell
799 rows = [[line.replace("\n", "<br>") for line in r] for r in rows]
801 lines = [" | ".join(rows[0][i].center(col_widths[i]) for i in range(n_cols))]
802 lines.append(" | ".join("---".center(col_widths[i]) for i in range(n_cols)))
803 lines.extend(
804 [
805 " | ".join(row[i].ljust(col_widths[i]) for i in range(n_cols))
806 for row in rows[1:]
807 ]
808 )
809 return "\n| " + " |\n| ".join(lines) + " |\n"
812def _format_html_table(rows: list[list[str]]) -> str:
813 """format `rows` as HTML table"""
815 def get_line(cells: list[str], cell_tag: Literal["th", "td"] = "td"):
816 return (
817 [" <tr>"]
818 + [
819 f' <{cell_tag} style="text-align:{"center" if cell_tag == "th" else "left"}">{c}</{cell_tag}>'
820 for c in cells
821 ]
822 + [" </tr>"]
823 )
825 table = ["<table>"] + get_line(rows[0], cell_tag="th")
826 for r in rows[1:]:
827 table.extend(get_line(r))
829 table.append("</table>")
831 return "\n".join(table)