Skip to content

summary ¤

CLASS DESCRIPTION
CondaEnv

Represenation of the content of a conda environment.yaml file

ErrorEntry

An error in a ValidationDetail

InstalledPackage
ValidationContextSummary

Summary of the validation context without internally used context fields.

ValidationDetail

a detail in a validation summary

ValidationEntry

Base of ErrorEntry and WarningEntry

ValidationSummary

Summarizes output of all bioimageio validations and tests

WarningEntry

A warning in a ValidationDetail

FUNCTION DESCRIPTION
_format_html_table

format rows as HTML table

_format_md_table

format rows as markdown table

_format_summary
format_loc

helper to format a location tuple loc

is_dict

to avoid Dict[Unknown, Unknown]

is_yaml_value
write_yaml
ATTRIBUTE DESCRIPTION
CONDA_CMD

Loc

location of error/warning in a nested data structure

VERSION

WARNING_LEVEL_TO_NAME

TYPE: Mapping[WarningLevel, WarningLevelName]

WARNING_NAME_TO_LEVEL

TYPE: Mapping[WarningLevelName, WarningLevel]

WARNING_SEVERITY_TO_NAME

TYPE: Mapping[WarningSeverity, WarningSeverityName]

WarningLevel

With warning level x validation warnings of severity >=x are raised.

WarningLevelName

WarningSeverity

WarningSeverityName

CONDA_CMD module-attribute ¤

CONDA_CMD = (
    "conda.bat"
    if platform.system() == "Windows"
    else "conda"
)

Loc module-attribute ¤

Loc = Tuple[Union[int, str], ...]

location of error/warning in a nested data structure

VERSION module-attribute ¤

VERSION = '0.5.6.0'

WARNING_LEVEL_TO_NAME module-attribute ¤

WARNING_LEVEL_TO_NAME: Mapping[
    WarningLevel, WarningLevelName
] = MappingProxyType(
    {
        INFO: INFO_NAME,
        WARNING: WARNING_NAME,
        ALERT: ALERT_NAME,
        ERROR: ERROR_NAME,
    }
)

WARNING_NAME_TO_LEVEL module-attribute ¤

WARNING_NAME_TO_LEVEL: Mapping[
    WarningLevelName, WarningLevel
] = MappingProxyType(
    {v: k for k, v in (WARNING_LEVEL_TO_NAME.items())}
)

WARNING_SEVERITY_TO_NAME module-attribute ¤

WARNING_SEVERITY_TO_NAME: Mapping[
    WarningSeverity, WarningSeverityName
] = MappingProxyType(
    {
        INFO: INFO_NAME,
        WARNING: WARNING_NAME,
        ALERT: ALERT_NAME,
    }
)

WarningLevel module-attribute ¤

WarningLevel = Literal[WarningSeverity, 50]

With warning level x validation warnings of severity >=x are raised. Highest warning level 50/error does not raise any validaiton warnings (only validation errors).

WarningLevelName module-attribute ¤

WarningLevelName = Literal[WarningSeverityName, 'error']

WarningSeverityName module-attribute ¤

WarningSeverityName = Literal['info', 'warning', 'alert']

CondaEnv pydantic-model ¤

Bases: BaseModel

Represenation of the content of a conda environment.yaml file

Show JSON schema:
{
  "$defs": {
    "PipDeps": {
      "description": "Pip dependencies to include in conda dependecies",
      "properties": {
        "pip": {
          "items": {
            "type": "string"
          },
          "title": "Pip",
          "type": "array"
        }
      },
      "title": "PipDeps",
      "type": "object"
    }
  },
  "description": "Represenation of the content of a conda environment.yaml file",
  "properties": {
    "name": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Name"
    },
    "channels": {
      "items": {
        "type": "string"
      },
      "title": "Channels",
      "type": "array"
    },
    "dependencies": {
      "items": {
        "anyOf": [
          {
            "type": "string"
          },
          {
            "$ref": "#/$defs/PipDeps"
          }
        ]
      },
      "title": "Dependencies",
      "type": "array"
    }
  },
  "title": "CondaEnv",
  "type": "object"
}

Fields:

Validators:

  • _ensure_valid_conda_env_namename

channels pydantic-field ¤

channels: List[str]

dependencies pydantic-field ¤

dependencies: List[Union[str, PipDeps]]

name pydantic-field ¤

name: Optional[str] = None

wo_name property ¤

wo_name

get_pip_deps ¤

get_pip_deps() -> List[str]

Get the pip dependencies of this conda env.

Source code in src/bioimageio/spec/conda_env.py
70
71
72
73
74
75
76
def get_pip_deps(self) -> List[str]:
    """Get the pip dependencies of this conda env."""
    for dep in self.dependencies:
        if isinstance(dep, PipDeps):
            return dep.pip

    return []

ErrorEntry pydantic-model ¤

Bases: ValidationEntry

An error in a ValidationDetail

Show JSON schema:
{
  "description": "An error in a `ValidationDetail`",
  "properties": {
    "loc": {
      "items": {
        "anyOf": [
          {
            "type": "integer"
          },
          {
            "type": "string"
          }
        ]
      },
      "title": "Loc",
      "type": "array"
    },
    "msg": {
      "title": "Msg",
      "type": "string"
    },
    "type": {
      "anyOf": [
        {
          "enum": [
            "no_such_attribute",
            "json_invalid",
            "json_type",
            "needs_python_object",
            "recursion_loop",
            "missing",
            "frozen_field",
            "frozen_instance",
            "extra_forbidden",
            "invalid_key",
            "get_attribute_error",
            "model_type",
            "model_attributes_type",
            "dataclass_type",
            "dataclass_exact_type",
            "none_required",
            "greater_than",
            "greater_than_equal",
            "less_than",
            "less_than_equal",
            "multiple_of",
            "finite_number",
            "too_short",
            "too_long",
            "iterable_type",
            "iteration_error",
            "string_type",
            "string_sub_type",
            "string_unicode",
            "string_too_short",
            "string_too_long",
            "string_pattern_mismatch",
            "enum",
            "dict_type",
            "mapping_type",
            "list_type",
            "tuple_type",
            "set_type",
            "set_item_not_hashable",
            "bool_type",
            "bool_parsing",
            "int_type",
            "int_parsing",
            "int_parsing_size",
            "int_from_float",
            "float_type",
            "float_parsing",
            "bytes_type",
            "bytes_too_short",
            "bytes_too_long",
            "bytes_invalid_encoding",
            "value_error",
            "assertion_error",
            "literal_error",
            "date_type",
            "date_parsing",
            "date_from_datetime_parsing",
            "date_from_datetime_inexact",
            "date_past",
            "date_future",
            "time_type",
            "time_parsing",
            "datetime_type",
            "datetime_parsing",
            "datetime_object_invalid",
            "datetime_from_date_parsing",
            "datetime_past",
            "datetime_future",
            "timezone_naive",
            "timezone_aware",
            "timezone_offset",
            "time_delta_type",
            "time_delta_parsing",
            "frozen_set_type",
            "is_instance_of",
            "is_subclass_of",
            "callable_type",
            "union_tag_invalid",
            "union_tag_not_found",
            "arguments_type",
            "missing_argument",
            "unexpected_keyword_argument",
            "missing_keyword_only_argument",
            "unexpected_positional_argument",
            "missing_positional_only_argument",
            "multiple_argument_values",
            "url_type",
            "url_parsing",
            "url_syntax_violation",
            "url_too_long",
            "url_scheme",
            "uuid_type",
            "uuid_parsing",
            "uuid_version",
            "decimal_type",
            "decimal_parsing",
            "decimal_max_digits",
            "decimal_max_places",
            "decimal_whole_digits",
            "complex_type",
            "complex_str_parsing"
          ],
          "type": "string"
        },
        {
          "type": "string"
        }
      ],
      "title": "Type"
    },
    "with_traceback": {
      "default": false,
      "title": "With Traceback",
      "type": "boolean"
    },
    "traceback_md": {
      "default": "",
      "title": "Traceback Md",
      "type": "string"
    },
    "traceback_html": {
      "default": "",
      "title": "Traceback Html",
      "type": "string"
    }
  },
  "required": [
    "loc",
    "msg",
    "type"
  ],
  "title": "ErrorEntry",
  "type": "object"
}

Fields:

loc pydantic-field ¤

loc: Loc

msg pydantic-field ¤

msg: str

traceback_html pydantic-field ¤

traceback_html: str = ''

traceback_md pydantic-field ¤

traceback_md: str = ''

traceback_rich property ¤

traceback_rich: Optional[rich.traceback.Traceback]

type pydantic-field ¤

type: Union[ErrorType, str]

with_traceback pydantic-field ¤

with_traceback: bool = False

model_post_init ¤

model_post_init(__context: Any)
Source code in src/bioimageio/spec/summary.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def model_post_init(self, __context: Any):
    if self.with_traceback and not (self.traceback_md or self.traceback_html):
        self._traceback_rich = rich.traceback.Traceback()
        console = rich.console.Console(
            record=True,
            file=open(os.devnull, "wt", encoding="utf-8"),
            color_system="truecolor",
            width=120,
            tab_size=4,
            soft_wrap=True,
        )
        console.print(self._traceback_rich)
        if not self.traceback_md:
            self.traceback_md = console.export_text(clear=False)

        if not self.traceback_html:
            self.traceback_html = console.export_html(clear=False)

InstalledPackage ¤

Bases: NamedTuple


              flowchart TD
              bioimageio.spec.summary.InstalledPackage[InstalledPackage]

              

              click bioimageio.spec.summary.InstalledPackage href "" "bioimageio.spec.summary.InstalledPackage"
            
ATTRIBUTE DESCRIPTION
build

TYPE: str

channel

TYPE: str

name

TYPE: str

version

TYPE: str

build class-attribute instance-attribute ¤

build: str = ''

channel class-attribute instance-attribute ¤

channel: str = ''

name instance-attribute ¤

name: str

version instance-attribute ¤

version: str

ValidationContextSummary dataclass ¤

ValidationContextSummary(
    file_name: Optional[FileName] = None,
    original_source_name: Optional[str] = None,
    perform_io_checks: bool = settings.perform_io_checks,
    known_files: Dict[str, Optional[Sha256]] = cast(
        Callable[[], Dict[str, Optional[Sha256]]], dict
    )(),
    update_hashes: bool = False,
    root: Union[
        RootHttpUrl, Path, Literal["in-memory"]
    ] = Path(),
)

Bases: ValidationContextBase


              flowchart TD
              bioimageio.spec.summary.ValidationContextSummary[ValidationContextSummary]
              bioimageio.spec._internal.validation_context.ValidationContextBase[ValidationContextBase]

                              bioimageio.spec._internal.validation_context.ValidationContextBase --> bioimageio.spec.summary.ValidationContextSummary
                


              click bioimageio.spec.summary.ValidationContextSummary href "" "bioimageio.spec.summary.ValidationContextSummary"
              click bioimageio.spec._internal.validation_context.ValidationContextBase href "" "bioimageio.spec._internal.validation_context.ValidationContextBase"
            

Summary of the validation context without internally used context fields.

ATTRIBUTE DESCRIPTION
__pydantic_config__

Pydantic config to include ValdationContextSummary in ValidationDetail.

file_name

File name of the bioimageio YAML file.

TYPE: Optional[FileName]

known_files

Allows to bypass download and hashing of referenced files.

TYPE: Dict[str, Optional[Sha256]]

original_source_name

Original source of the bioimageio resource description, e.g. a URL or file path.

TYPE: Optional[str]

perform_io_checks

Wether or not to perform validation that requires file io,

TYPE: bool

root

TYPE: Union[RootHttpUrl, Path, Literal['in-memory']]

update_hashes

Overwrite specified file hashes with values computed from the referenced file (instead of comparing them).

TYPE: bool

__pydantic_config__ class-attribute instance-attribute ¤

__pydantic_config__ = ConfigDict(extra='forbid')

Pydantic config to include ValdationContextSummary in ValidationDetail.

file_name class-attribute instance-attribute ¤

file_name: Optional[FileName] = None

File name of the bioimageio YAML file.

known_files class-attribute instance-attribute ¤

known_files: Dict[str, Optional[Sha256]] = field(
    default_factory=cast(
        Callable[[], Dict[str, Optional[Sha256]]], dict
    )
)

Allows to bypass download and hashing of referenced files.

original_source_name class-attribute instance-attribute ¤

original_source_name: Optional[str] = None

Original source of the bioimageio resource description, e.g. a URL or file path.

perform_io_checks class-attribute instance-attribute ¤

perform_io_checks: bool = settings.perform_io_checks

Wether or not to perform validation that requires file io, e.g. downloading a remote files.

Existence of local absolute file paths is still being checked.

root class-attribute instance-attribute ¤

root: Union[RootHttpUrl, Path, Literal["in-memory"]] = (
    Path()
)

update_hashes class-attribute instance-attribute ¤

update_hashes: bool = False

Overwrite specified file hashes with values computed from the referenced file (instead of comparing them). (Has no effect if perform_io_checks=False.)

ValidationDetail pydantic-model ¤

Bases: BaseModel

a detail in a validation summary

Show JSON schema:
{
  "$defs": {
    "CondaEnv": {
      "description": "Represenation of the content of a conda environment.yaml file",
      "properties": {
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Name"
        },
        "channels": {
          "items": {
            "type": "string"
          },
          "title": "Channels",
          "type": "array"
        },
        "dependencies": {
          "items": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "$ref": "#/$defs/PipDeps"
              }
            ]
          },
          "title": "Dependencies",
          "type": "array"
        }
      },
      "title": "CondaEnv",
      "type": "object"
    },
    "ErrorEntry": {
      "description": "An error in a `ValidationDetail`",
      "properties": {
        "loc": {
          "items": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "string"
              }
            ]
          },
          "title": "Loc",
          "type": "array"
        },
        "msg": {
          "title": "Msg",
          "type": "string"
        },
        "type": {
          "anyOf": [
            {
              "enum": [
                "no_such_attribute",
                "json_invalid",
                "json_type",
                "needs_python_object",
                "recursion_loop",
                "missing",
                "frozen_field",
                "frozen_instance",
                "extra_forbidden",
                "invalid_key",
                "get_attribute_error",
                "model_type",
                "model_attributes_type",
                "dataclass_type",
                "dataclass_exact_type",
                "none_required",
                "greater_than",
                "greater_than_equal",
                "less_than",
                "less_than_equal",
                "multiple_of",
                "finite_number",
                "too_short",
                "too_long",
                "iterable_type",
                "iteration_error",
                "string_type",
                "string_sub_type",
                "string_unicode",
                "string_too_short",
                "string_too_long",
                "string_pattern_mismatch",
                "enum",
                "dict_type",
                "mapping_type",
                "list_type",
                "tuple_type",
                "set_type",
                "set_item_not_hashable",
                "bool_type",
                "bool_parsing",
                "int_type",
                "int_parsing",
                "int_parsing_size",
                "int_from_float",
                "float_type",
                "float_parsing",
                "bytes_type",
                "bytes_too_short",
                "bytes_too_long",
                "bytes_invalid_encoding",
                "value_error",
                "assertion_error",
                "literal_error",
                "date_type",
                "date_parsing",
                "date_from_datetime_parsing",
                "date_from_datetime_inexact",
                "date_past",
                "date_future",
                "time_type",
                "time_parsing",
                "datetime_type",
                "datetime_parsing",
                "datetime_object_invalid",
                "datetime_from_date_parsing",
                "datetime_past",
                "datetime_future",
                "timezone_naive",
                "timezone_aware",
                "timezone_offset",
                "time_delta_type",
                "time_delta_parsing",
                "frozen_set_type",
                "is_instance_of",
                "is_subclass_of",
                "callable_type",
                "union_tag_invalid",
                "union_tag_not_found",
                "arguments_type",
                "missing_argument",
                "unexpected_keyword_argument",
                "missing_keyword_only_argument",
                "unexpected_positional_argument",
                "missing_positional_only_argument",
                "multiple_argument_values",
                "url_type",
                "url_parsing",
                "url_syntax_violation",
                "url_too_long",
                "url_scheme",
                "uuid_type",
                "uuid_parsing",
                "uuid_version",
                "decimal_type",
                "decimal_parsing",
                "decimal_max_digits",
                "decimal_max_places",
                "decimal_whole_digits",
                "complex_type",
                "complex_str_parsing"
              ],
              "type": "string"
            },
            {
              "type": "string"
            }
          ],
          "title": "Type"
        },
        "with_traceback": {
          "default": false,
          "title": "With Traceback",
          "type": "boolean"
        },
        "traceback_md": {
          "default": "",
          "title": "Traceback Md",
          "type": "string"
        },
        "traceback_html": {
          "default": "",
          "title": "Traceback Html",
          "type": "string"
        }
      },
      "required": [
        "loc",
        "msg",
        "type"
      ],
      "title": "ErrorEntry",
      "type": "object"
    },
    "PipDeps": {
      "description": "Pip dependencies to include in conda dependecies",
      "properties": {
        "pip": {
          "items": {
            "type": "string"
          },
          "title": "Pip",
          "type": "array"
        }
      },
      "title": "PipDeps",
      "type": "object"
    },
    "ValidationContextSummary": {
      "additionalProperties": false,
      "properties": {
        "file_name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "File Name"
        },
        "original_source_name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Original Source Name"
        },
        "perform_io_checks": {
          "default": true,
          "title": "Perform Io Checks",
          "type": "boolean"
        },
        "known_files": {
          "additionalProperties": {
            "anyOf": [
              {
                "description": "A SHA-256 hash value",
                "maxLength": 64,
                "minLength": 64,
                "title": "Sha256",
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "title": "Known Files",
          "type": "object"
        },
        "update_hashes": {
          "default": false,
          "title": "Update Hashes",
          "type": "boolean"
        },
        "root": {
          "anyOf": [
            {
              "description": "An untested HTTP URL, possibly a 'URL folder' or an invalid HTTP URL",
              "format": "uri",
              "maxLength": 2083,
              "minLength": 1,
              "title": "RootHttpUrl",
              "type": "string"
            },
            {
              "format": "path",
              "type": "string"
            },
            {
              "const": "in-memory",
              "type": "string"
            }
          ],
          "default": ".",
          "title": "Root"
        }
      },
      "title": "ValidationContextSummary",
      "type": "object"
    },
    "WarningEntry": {
      "description": "A warning in a `ValidationDetail`",
      "properties": {
        "loc": {
          "items": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "string"
              }
            ]
          },
          "title": "Loc",
          "type": "array"
        },
        "msg": {
          "title": "Msg",
          "type": "string"
        },
        "type": {
          "anyOf": [
            {
              "enum": [
                "no_such_attribute",
                "json_invalid",
                "json_type",
                "needs_python_object",
                "recursion_loop",
                "missing",
                "frozen_field",
                "frozen_instance",
                "extra_forbidden",
                "invalid_key",
                "get_attribute_error",
                "model_type",
                "model_attributes_type",
                "dataclass_type",
                "dataclass_exact_type",
                "none_required",
                "greater_than",
                "greater_than_equal",
                "less_than",
                "less_than_equal",
                "multiple_of",
                "finite_number",
                "too_short",
                "too_long",
                "iterable_type",
                "iteration_error",
                "string_type",
                "string_sub_type",
                "string_unicode",
                "string_too_short",
                "string_too_long",
                "string_pattern_mismatch",
                "enum",
                "dict_type",
                "mapping_type",
                "list_type",
                "tuple_type",
                "set_type",
                "set_item_not_hashable",
                "bool_type",
                "bool_parsing",
                "int_type",
                "int_parsing",
                "int_parsing_size",
                "int_from_float",
                "float_type",
                "float_parsing",
                "bytes_type",
                "bytes_too_short",
                "bytes_too_long",
                "bytes_invalid_encoding",
                "value_error",
                "assertion_error",
                "literal_error",
                "date_type",
                "date_parsing",
                "date_from_datetime_parsing",
                "date_from_datetime_inexact",
                "date_past",
                "date_future",
                "time_type",
                "time_parsing",
                "datetime_type",
                "datetime_parsing",
                "datetime_object_invalid",
                "datetime_from_date_parsing",
                "datetime_past",
                "datetime_future",
                "timezone_naive",
                "timezone_aware",
                "timezone_offset",
                "time_delta_type",
                "time_delta_parsing",
                "frozen_set_type",
                "is_instance_of",
                "is_subclass_of",
                "callable_type",
                "union_tag_invalid",
                "union_tag_not_found",
                "arguments_type",
                "missing_argument",
                "unexpected_keyword_argument",
                "missing_keyword_only_argument",
                "unexpected_positional_argument",
                "missing_positional_only_argument",
                "multiple_argument_values",
                "url_type",
                "url_parsing",
                "url_syntax_violation",
                "url_too_long",
                "url_scheme",
                "uuid_type",
                "uuid_parsing",
                "uuid_version",
                "decimal_type",
                "decimal_parsing",
                "decimal_max_digits",
                "decimal_max_places",
                "decimal_whole_digits",
                "complex_type",
                "complex_str_parsing"
              ],
              "type": "string"
            },
            {
              "type": "string"
            }
          ],
          "title": "Type"
        },
        "severity": {
          "default": 30,
          "enum": [
            20,
            30,
            35
          ],
          "title": "Severity",
          "type": "integer"
        }
      },
      "required": [
        "loc",
        "msg",
        "type"
      ],
      "title": "WarningEntry",
      "type": "object"
    }
  },
  "additionalProperties": true,
  "description": "a detail in a validation summary",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "status": {
      "enum": [
        "passed",
        "failed"
      ],
      "title": "Status",
      "type": "string"
    },
    "loc": {
      "default": [],
      "items": {
        "anyOf": [
          {
            "type": "integer"
          },
          {
            "type": "string"
          }
        ]
      },
      "title": "Loc",
      "type": "array"
    },
    "errors": {
      "items": {
        "$ref": "#/$defs/ErrorEntry"
      },
      "title": "Errors",
      "type": "array"
    },
    "warnings": {
      "items": {
        "$ref": "#/$defs/WarningEntry"
      },
      "title": "Warnings",
      "type": "array"
    },
    "context": {
      "anyOf": [
        {
          "$ref": "#/$defs/ValidationContextSummary"
        },
        {
          "type": "null"
        }
      ],
      "default": null
    },
    "recommended_env": {
      "anyOf": [
        {
          "$ref": "#/$defs/CondaEnv"
        },
        {
          "type": "null"
        }
      ],
      "default": null
    },
    "saved_conda_compare": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Saved Conda Compare"
    }
  },
  "required": [
    "name",
    "status"
  ],
  "title": "ValidationDetail",
  "type": "object"
}

Fields:

Validators:

  • _load_legacy

conda_compare property ¤

conda_compare: Optional[str]

context pydantic-field ¤

context: Optional[ValidationContextSummary] = None

errors pydantic-field ¤

errors: List[ErrorEntry]

loc pydantic-field ¤

loc: Loc = ()

location in the RDF that this detail applies to

name pydantic-field ¤

name: str

recommended_env pydantic-field ¤

recommended_env: Optional[CondaEnv] = None

recommended conda environemnt for this validation detail

saved_conda_compare pydantic-field ¤

saved_conda_compare: Optional[str] = None

output of conda compare <recommended env>

status pydantic-field ¤

status: Literal['passed', 'failed']

status_icon property ¤

status_icon: str

warnings pydantic-field ¤

warnings: List[WarningEntry]

ValidationEntry pydantic-model ¤

Bases: BaseModel

Base of ErrorEntry and WarningEntry

Show JSON schema:
{
  "description": "Base of `ErrorEntry` and `WarningEntry`",
  "properties": {
    "loc": {
      "items": {
        "anyOf": [
          {
            "type": "integer"
          },
          {
            "type": "string"
          }
        ]
      },
      "title": "Loc",
      "type": "array"
    },
    "msg": {
      "title": "Msg",
      "type": "string"
    },
    "type": {
      "anyOf": [
        {
          "enum": [
            "no_such_attribute",
            "json_invalid",
            "json_type",
            "needs_python_object",
            "recursion_loop",
            "missing",
            "frozen_field",
            "frozen_instance",
            "extra_forbidden",
            "invalid_key",
            "get_attribute_error",
            "model_type",
            "model_attributes_type",
            "dataclass_type",
            "dataclass_exact_type",
            "none_required",
            "greater_than",
            "greater_than_equal",
            "less_than",
            "less_than_equal",
            "multiple_of",
            "finite_number",
            "too_short",
            "too_long",
            "iterable_type",
            "iteration_error",
            "string_type",
            "string_sub_type",
            "string_unicode",
            "string_too_short",
            "string_too_long",
            "string_pattern_mismatch",
            "enum",
            "dict_type",
            "mapping_type",
            "list_type",
            "tuple_type",
            "set_type",
            "set_item_not_hashable",
            "bool_type",
            "bool_parsing",
            "int_type",
            "int_parsing",
            "int_parsing_size",
            "int_from_float",
            "float_type",
            "float_parsing",
            "bytes_type",
            "bytes_too_short",
            "bytes_too_long",
            "bytes_invalid_encoding",
            "value_error",
            "assertion_error",
            "literal_error",
            "date_type",
            "date_parsing",
            "date_from_datetime_parsing",
            "date_from_datetime_inexact",
            "date_past",
            "date_future",
            "time_type",
            "time_parsing",
            "datetime_type",
            "datetime_parsing",
            "datetime_object_invalid",
            "datetime_from_date_parsing",
            "datetime_past",
            "datetime_future",
            "timezone_naive",
            "timezone_aware",
            "timezone_offset",
            "time_delta_type",
            "time_delta_parsing",
            "frozen_set_type",
            "is_instance_of",
            "is_subclass_of",
            "callable_type",
            "union_tag_invalid",
            "union_tag_not_found",
            "arguments_type",
            "missing_argument",
            "unexpected_keyword_argument",
            "missing_keyword_only_argument",
            "unexpected_positional_argument",
            "missing_positional_only_argument",
            "multiple_argument_values",
            "url_type",
            "url_parsing",
            "url_syntax_violation",
            "url_too_long",
            "url_scheme",
            "uuid_type",
            "uuid_parsing",
            "uuid_version",
            "decimal_type",
            "decimal_parsing",
            "decimal_max_digits",
            "decimal_max_places",
            "decimal_whole_digits",
            "complex_type",
            "complex_str_parsing"
          ],
          "type": "string"
        },
        {
          "type": "string"
        }
      ],
      "title": "Type"
    }
  },
  "required": [
    "loc",
    "msg",
    "type"
  ],
  "title": "ValidationEntry",
  "type": "object"
}

Fields:

loc pydantic-field ¤

loc: Loc

msg pydantic-field ¤

msg: str

type pydantic-field ¤

type: Union[ErrorType, str]

ValidationSummary pydantic-model ¤

Bases: BaseModel

Summarizes output of all bioimageio validations and tests for one specific ResourceDescr instance.

Show JSON schema:
{
  "$defs": {
    "CondaEnv": {
      "description": "Represenation of the content of a conda environment.yaml file",
      "properties": {
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Name"
        },
        "channels": {
          "items": {
            "type": "string"
          },
          "title": "Channels",
          "type": "array"
        },
        "dependencies": {
          "items": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "$ref": "#/$defs/PipDeps"
              }
            ]
          },
          "title": "Dependencies",
          "type": "array"
        }
      },
      "title": "CondaEnv",
      "type": "object"
    },
    "ErrorEntry": {
      "description": "An error in a `ValidationDetail`",
      "properties": {
        "loc": {
          "items": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "string"
              }
            ]
          },
          "title": "Loc",
          "type": "array"
        },
        "msg": {
          "title": "Msg",
          "type": "string"
        },
        "type": {
          "anyOf": [
            {
              "enum": [
                "no_such_attribute",
                "json_invalid",
                "json_type",
                "needs_python_object",
                "recursion_loop",
                "missing",
                "frozen_field",
                "frozen_instance",
                "extra_forbidden",
                "invalid_key",
                "get_attribute_error",
                "model_type",
                "model_attributes_type",
                "dataclass_type",
                "dataclass_exact_type",
                "none_required",
                "greater_than",
                "greater_than_equal",
                "less_than",
                "less_than_equal",
                "multiple_of",
                "finite_number",
                "too_short",
                "too_long",
                "iterable_type",
                "iteration_error",
                "string_type",
                "string_sub_type",
                "string_unicode",
                "string_too_short",
                "string_too_long",
                "string_pattern_mismatch",
                "enum",
                "dict_type",
                "mapping_type",
                "list_type",
                "tuple_type",
                "set_type",
                "set_item_not_hashable",
                "bool_type",
                "bool_parsing",
                "int_type",
                "int_parsing",
                "int_parsing_size",
                "int_from_float",
                "float_type",
                "float_parsing",
                "bytes_type",
                "bytes_too_short",
                "bytes_too_long",
                "bytes_invalid_encoding",
                "value_error",
                "assertion_error",
                "literal_error",
                "date_type",
                "date_parsing",
                "date_from_datetime_parsing",
                "date_from_datetime_inexact",
                "date_past",
                "date_future",
                "time_type",
                "time_parsing",
                "datetime_type",
                "datetime_parsing",
                "datetime_object_invalid",
                "datetime_from_date_parsing",
                "datetime_past",
                "datetime_future",
                "timezone_naive",
                "timezone_aware",
                "timezone_offset",
                "time_delta_type",
                "time_delta_parsing",
                "frozen_set_type",
                "is_instance_of",
                "is_subclass_of",
                "callable_type",
                "union_tag_invalid",
                "union_tag_not_found",
                "arguments_type",
                "missing_argument",
                "unexpected_keyword_argument",
                "missing_keyword_only_argument",
                "unexpected_positional_argument",
                "missing_positional_only_argument",
                "multiple_argument_values",
                "url_type",
                "url_parsing",
                "url_syntax_violation",
                "url_too_long",
                "url_scheme",
                "uuid_type",
                "uuid_parsing",
                "uuid_version",
                "decimal_type",
                "decimal_parsing",
                "decimal_max_digits",
                "decimal_max_places",
                "decimal_whole_digits",
                "complex_type",
                "complex_str_parsing"
              ],
              "type": "string"
            },
            {
              "type": "string"
            }
          ],
          "title": "Type"
        },
        "with_traceback": {
          "default": false,
          "title": "With Traceback",
          "type": "boolean"
        },
        "traceback_md": {
          "default": "",
          "title": "Traceback Md",
          "type": "string"
        },
        "traceback_html": {
          "default": "",
          "title": "Traceback Html",
          "type": "string"
        }
      },
      "required": [
        "loc",
        "msg",
        "type"
      ],
      "title": "ErrorEntry",
      "type": "object"
    },
    "InstalledPackage": {
      "maxItems": 4,
      "minItems": 2,
      "prefixItems": [
        {
          "title": "Name",
          "type": "string"
        },
        {
          "title": "Version",
          "type": "string"
        },
        {
          "default": "",
          "title": "Build",
          "type": "string"
        },
        {
          "default": "",
          "title": "Channel",
          "type": "string"
        }
      ],
      "type": "array"
    },
    "PipDeps": {
      "description": "Pip dependencies to include in conda dependecies",
      "properties": {
        "pip": {
          "items": {
            "type": "string"
          },
          "title": "Pip",
          "type": "array"
        }
      },
      "title": "PipDeps",
      "type": "object"
    },
    "ValidationContextSummary": {
      "additionalProperties": false,
      "properties": {
        "file_name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "File Name"
        },
        "original_source_name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Original Source Name"
        },
        "perform_io_checks": {
          "default": true,
          "title": "Perform Io Checks",
          "type": "boolean"
        },
        "known_files": {
          "additionalProperties": {
            "anyOf": [
              {
                "description": "A SHA-256 hash value",
                "maxLength": 64,
                "minLength": 64,
                "title": "Sha256",
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "title": "Known Files",
          "type": "object"
        },
        "update_hashes": {
          "default": false,
          "title": "Update Hashes",
          "type": "boolean"
        },
        "root": {
          "anyOf": [
            {
              "description": "An untested HTTP URL, possibly a 'URL folder' or an invalid HTTP URL",
              "format": "uri",
              "maxLength": 2083,
              "minLength": 1,
              "title": "RootHttpUrl",
              "type": "string"
            },
            {
              "format": "path",
              "type": "string"
            },
            {
              "const": "in-memory",
              "type": "string"
            }
          ],
          "default": ".",
          "title": "Root"
        }
      },
      "title": "ValidationContextSummary",
      "type": "object"
    },
    "ValidationDetail": {
      "additionalProperties": true,
      "description": "a detail in a validation summary",
      "properties": {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "status": {
          "enum": [
            "passed",
            "failed"
          ],
          "title": "Status",
          "type": "string"
        },
        "loc": {
          "default": [],
          "items": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "string"
              }
            ]
          },
          "title": "Loc",
          "type": "array"
        },
        "errors": {
          "items": {
            "$ref": "#/$defs/ErrorEntry"
          },
          "title": "Errors",
          "type": "array"
        },
        "warnings": {
          "items": {
            "$ref": "#/$defs/WarningEntry"
          },
          "title": "Warnings",
          "type": "array"
        },
        "context": {
          "anyOf": [
            {
              "$ref": "#/$defs/ValidationContextSummary"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "recommended_env": {
          "anyOf": [
            {
              "$ref": "#/$defs/CondaEnv"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "saved_conda_compare": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Saved Conda Compare"
        }
      },
      "required": [
        "name",
        "status"
      ],
      "title": "ValidationDetail",
      "type": "object"
    },
    "WarningEntry": {
      "description": "A warning in a `ValidationDetail`",
      "properties": {
        "loc": {
          "items": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "string"
              }
            ]
          },
          "title": "Loc",
          "type": "array"
        },
        "msg": {
          "title": "Msg",
          "type": "string"
        },
        "type": {
          "anyOf": [
            {
              "enum": [
                "no_such_attribute",
                "json_invalid",
                "json_type",
                "needs_python_object",
                "recursion_loop",
                "missing",
                "frozen_field",
                "frozen_instance",
                "extra_forbidden",
                "invalid_key",
                "get_attribute_error",
                "model_type",
                "model_attributes_type",
                "dataclass_type",
                "dataclass_exact_type",
                "none_required",
                "greater_than",
                "greater_than_equal",
                "less_than",
                "less_than_equal",
                "multiple_of",
                "finite_number",
                "too_short",
                "too_long",
                "iterable_type",
                "iteration_error",
                "string_type",
                "string_sub_type",
                "string_unicode",
                "string_too_short",
                "string_too_long",
                "string_pattern_mismatch",
                "enum",
                "dict_type",
                "mapping_type",
                "list_type",
                "tuple_type",
                "set_type",
                "set_item_not_hashable",
                "bool_type",
                "bool_parsing",
                "int_type",
                "int_parsing",
                "int_parsing_size",
                "int_from_float",
                "float_type",
                "float_parsing",
                "bytes_type",
                "bytes_too_short",
                "bytes_too_long",
                "bytes_invalid_encoding",
                "value_error",
                "assertion_error",
                "literal_error",
                "date_type",
                "date_parsing",
                "date_from_datetime_parsing",
                "date_from_datetime_inexact",
                "date_past",
                "date_future",
                "time_type",
                "time_parsing",
                "datetime_type",
                "datetime_parsing",
                "datetime_object_invalid",
                "datetime_from_date_parsing",
                "datetime_past",
                "datetime_future",
                "timezone_naive",
                "timezone_aware",
                "timezone_offset",
                "time_delta_type",
                "time_delta_parsing",
                "frozen_set_type",
                "is_instance_of",
                "is_subclass_of",
                "callable_type",
                "union_tag_invalid",
                "union_tag_not_found",
                "arguments_type",
                "missing_argument",
                "unexpected_keyword_argument",
                "missing_keyword_only_argument",
                "unexpected_positional_argument",
                "missing_positional_only_argument",
                "multiple_argument_values",
                "url_type",
                "url_parsing",
                "url_syntax_violation",
                "url_too_long",
                "url_scheme",
                "uuid_type",
                "uuid_parsing",
                "uuid_version",
                "decimal_type",
                "decimal_parsing",
                "decimal_max_digits",
                "decimal_max_places",
                "decimal_whole_digits",
                "complex_type",
                "complex_str_parsing"
              ],
              "type": "string"
            },
            {
              "type": "string"
            }
          ],
          "title": "Type"
        },
        "severity": {
          "default": 30,
          "enum": [
            20,
            30,
            35
          ],
          "title": "Severity",
          "type": "integer"
        }
      },
      "required": [
        "loc",
        "msg",
        "type"
      ],
      "title": "WarningEntry",
      "type": "object"
    }
  },
  "additionalProperties": true,
  "description": "Summarizes output of all bioimageio validations and tests\nfor one specific `ResourceDescr` instance.",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "source_name": {
      "title": "Source Name",
      "type": "string"
    },
    "id": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Id"
    },
    "type": {
      "title": "Type",
      "type": "string"
    },
    "format_version": {
      "title": "Format Version",
      "type": "string"
    },
    "status": {
      "enum": [
        "passed",
        "valid-format",
        "failed"
      ],
      "title": "Status",
      "type": "string"
    },
    "metadata_completeness": {
      "default": 0.0,
      "maximum": 1,
      "minimum": 0,
      "title": "Metadata Completeness",
      "type": "number"
    },
    "details": {
      "items": {
        "$ref": "#/$defs/ValidationDetail"
      },
      "title": "Details",
      "type": "array"
    },
    "env": {
      "items": {
        "$ref": "#/$defs/InstalledPackage"
      },
      "title": "Env",
      "type": "array",
      "uniqueItems": true
    },
    "saved_conda_list": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Saved Conda List"
    }
  },
  "required": [
    "name",
    "source_name",
    "type",
    "format_version",
    "status",
    "details"
  ],
  "title": "ValidationSummary",
  "type": "object"
}

Fields:

Validators:

  • _convert_old_envenv

conda_list property ¤

conda_list: str

details pydantic-field ¤

details: List[ValidationDetail]

List of validation details

env pydantic-field ¤

env: Set[InstalledPackage]

List of selected, relevant package versions

errors property ¤

errors: List[ErrorEntry]

format_version pydantic-field ¤

format_version: str

Format version of the resource being validated

id pydantic-field ¤

id: Optional[str] = None

ID of the resource being validated

metadata_completeness pydantic-field ¤

metadata_completeness: float = 0.0

Estimate of completeness of the metadata in the resource description.

This completeness estimate may change with subsequent releases

and should be considered bioimageio.spec version specific.

name pydantic-field ¤

name: str

Name of the validation

saved_conda_list pydantic-field ¤

saved_conda_list: Optional[str] = None

source_name pydantic-field ¤

source_name: str

Source of the validated bioimageio description

status pydantic-field ¤

status: Literal['passed', 'valid-format', 'failed']

Overall status of the bioimageio validation

status_icon property ¤

status_icon: str

type pydantic-field ¤

type: str

Type of the resource being validated

warnings property ¤

warnings: List[WarningEntry]

add_detail ¤

add_detail(
    detail: ValidationDetail, update_status: bool = True
) -> None
Source code in src/bioimageio/spec/summary.py
391
392
393
394
395
396
397
398
399
400
401
def add_detail(self, detail: ValidationDetail, update_status: bool = True) -> None:
    if update_status:
        if self.status == "valid-format" and detail.status == "passed":
            # once status is 'valid-format' we can only improve to 'passed'
            self.status = "passed"
        elif self.status == "passed" and detail.status == "failed":
            # once status is 'passed' it can only degrade to 'valid-format'
            self.status = "valid-format"
        # once format is 'failed' it cannot improve

    self.details.append(detail)

display ¤

display(
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
    tab_size: int = 4,
    soft_wrap: bool = True,
) -> None
Source code in src/bioimageio/spec/summary.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def display(
    self,
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
    tab_size: int = 4,
    soft_wrap: bool = True,
) -> None:
    try:  # render as HTML in Jupyter notebook
        from IPython.core.getipython import get_ipython
        from IPython.display import (
            display_html,  # pyright: ignore[reportUnknownVariableType]
        )
    except ImportError:
        pass
    else:
        if get_ipython() is not None:
            _ = display_html(
                self.format_html(
                    width=width, include_conda_list=include_conda_list
                ),
                raw=True,
            )
            return

    # render with rich
    _ = self._format(
        target=rich.console.Console(
            width=width,
            tab_size=tab_size,
            soft_wrap=soft_wrap,
        ),
        width=width,
        include_conda_list=include_conda_list,
    )

format ¤

format(
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
) -> str

Format summary as Markdown string (alias to format_md)

Source code in src/bioimageio/spec/summary.py
322
323
324
325
326
327
328
329
def format(
    self,
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
) -> str:
    """Format summary as Markdown string (alias to `format_md`)"""
    return self.format_md(width=width, include_conda_list=include_conda_list)

format_html ¤

format_html(
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
) -> str
Source code in src/bioimageio/spec/summary.py
342
343
344
345
346
347
348
349
350
351
352
353
def format_html(
    self,
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
) -> str:
    md_with_html = self._format(
        target="html", width=width, include_conda_list=include_conda_list
    )
    return markdown.markdown(
        md_with_html, extensions=["tables", "fenced_code", "nl2br"]
    )

format_md ¤

format_md(
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
) -> str

Format summary as Markdown string

Source code in src/bioimageio/spec/summary.py
331
332
333
334
335
336
337
338
339
340
def format_md(
    self,
    *,
    width: Optional[int] = None,
    include_conda_list: bool = False,
) -> str:
    """Format summary as Markdown string"""
    return self._format(
        width=width, target="md", include_conda_list=include_conda_list
    )

load_json classmethod ¤

load_json(path: Path) -> Self

Load validation/test summary from a suitable JSON file

Source code in src/bioimageio/spec/summary.py
492
493
494
495
496
@classmethod
def load_json(cls, path: Path) -> Self:
    """Load validation/test summary from a suitable JSON file"""
    json_str = Path(path).read_text(encoding="utf-8")
    return cls.model_validate_json(json_str)

log ¤

log(
    to: Union[
        Literal["display"],
        Path,
        Sequence[Union[Literal["display"], Path]],
    ],
) -> List[Path]

Convenience method to display the validation summary in the terminal and/or save it to disk. See save for details.

Source code in src/bioimageio/spec/summary.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def log(
    self,
    to: Union[Literal["display"], Path, Sequence[Union[Literal["display"], Path]]],
) -> List[Path]:
    """Convenience method to display the validation summary in the terminal and/or
    save it to disk. See `save` for details."""
    if to == "display":
        display = True
        save_to = []
    elif isinstance(to, Path):
        display = False
        save_to = [to]
    else:
        display = "display" in to
        save_to = [p for p in to if p != "display"]

    if display:
        self.display()

    return self.save(save_to)

save ¤

save(
    path: Union[Path, Sequence[Path]] = Path(
        "{id}_summary_{now}"
    ),
) -> List[Path]

Save the validation/test summary in JSON, Markdown or HTML format.

RETURNS DESCRIPTION
List[Path]

List of file paths the summary was saved to.

Notes: - Format is chosen based on the suffix: .json, .md, .html. - If path has no suffix it is assumed to be a direcotry to which a summary.json, summary.md and summary.html are saved to.

Source code in src/bioimageio/spec/summary.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def save(
    self, path: Union[Path, Sequence[Path]] = Path("{id}_summary_{now}")
) -> List[Path]:
    """Save the validation/test summary in JSON, Markdown or HTML format.

    Returns:
        List of file paths the summary was saved to.

    Notes:
    - Format is chosen based on the suffix: `.json`, `.md`, `.html`.
    - If **path** has no suffix it is assumed to be a direcotry to which a
      `summary.json`, `summary.md` and `summary.html` are saved to.
    """
    if isinstance(path, (str, Path)):
        path = [Path(path)]

    # folder to file paths
    file_paths: List[Path] = []
    for p in path:
        if p.suffix:
            file_paths.append(p)
        else:
            file_paths.extend(
                [
                    p / "summary.json",
                    p / "summary.md",
                    p / "summary.html",
                ]
            )

    now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    for p in file_paths:
        p = Path(str(p).format(id=self.id or "bioimageio", now=now))
        if p.suffix == ".json":
            self.save_json(p)
        elif p.suffix == ".md":
            self.save_markdown(p)
        elif p.suffix == ".html":
            self.save_html(p)
        else:
            raise ValueError(f"Unknown summary path suffix '{p.suffix}'")

    return file_paths

save_html ¤

save_html(path: Path = Path('summary.html')) -> None

Save rendered validation/test summary as HTML file.

Source code in src/bioimageio/spec/summary.py
484
485
486
487
488
489
490
def save_html(self, path: Path = Path("summary.html")) -> None:
    """Save rendered validation/test summary as HTML file."""
    path.parent.mkdir(exist_ok=True, parents=True)

    html = self.format_html()
    _ = path.write_text(html, encoding="utf-8")
    logger.info("Saved HTML formatted summary to {}", path.absolute())

save_json ¤

save_json(
    path: Path = Path("summary.json"),
    *,
    indent: Optional[int] = 2,
) -> None

Save validation/test summary as JSON file.

Source code in src/bioimageio/spec/summary.py
468
469
470
471
472
473
474
475
def save_json(
    self, path: Path = Path("summary.json"), *, indent: Optional[int] = 2
) -> None:
    """Save validation/test summary as JSON file."""
    json_str = self.model_dump_json(indent=indent)
    path.parent.mkdir(exist_ok=True, parents=True)
    _ = path.write_text(json_str, encoding="utf-8")
    logger.info("Saved summary to {}", path.absolute())

save_markdown ¤

save_markdown(path: Path = Path('summary.md')) -> None

Save rendered validation/test summary as Markdown file.

Source code in src/bioimageio/spec/summary.py
477
478
479
480
481
482
def save_markdown(self, path: Path = Path("summary.md")) -> None:
    """Save rendered validation/test summary as Markdown file."""
    formatted = self.format_md()
    path.parent.mkdir(exist_ok=True, parents=True)
    _ = path.write_text(formatted, encoding="utf-8")
    logger.info("Saved Markdown formatted summary to {}", path.absolute())

WarningEntry pydantic-model ¤

Bases: ValidationEntry

A warning in a ValidationDetail

Show JSON schema:
{
  "description": "A warning in a `ValidationDetail`",
  "properties": {
    "loc": {
      "items": {
        "anyOf": [
          {
            "type": "integer"
          },
          {
            "type": "string"
          }
        ]
      },
      "title": "Loc",
      "type": "array"
    },
    "msg": {
      "title": "Msg",
      "type": "string"
    },
    "type": {
      "anyOf": [
        {
          "enum": [
            "no_such_attribute",
            "json_invalid",
            "json_type",
            "needs_python_object",
            "recursion_loop",
            "missing",
            "frozen_field",
            "frozen_instance",
            "extra_forbidden",
            "invalid_key",
            "get_attribute_error",
            "model_type",
            "model_attributes_type",
            "dataclass_type",
            "dataclass_exact_type",
            "none_required",
            "greater_than",
            "greater_than_equal",
            "less_than",
            "less_than_equal",
            "multiple_of",
            "finite_number",
            "too_short",
            "too_long",
            "iterable_type",
            "iteration_error",
            "string_type",
            "string_sub_type",
            "string_unicode",
            "string_too_short",
            "string_too_long",
            "string_pattern_mismatch",
            "enum",
            "dict_type",
            "mapping_type",
            "list_type",
            "tuple_type",
            "set_type",
            "set_item_not_hashable",
            "bool_type",
            "bool_parsing",
            "int_type",
            "int_parsing",
            "int_parsing_size",
            "int_from_float",
            "float_type",
            "float_parsing",
            "bytes_type",
            "bytes_too_short",
            "bytes_too_long",
            "bytes_invalid_encoding",
            "value_error",
            "assertion_error",
            "literal_error",
            "date_type",
            "date_parsing",
            "date_from_datetime_parsing",
            "date_from_datetime_inexact",
            "date_past",
            "date_future",
            "time_type",
            "time_parsing",
            "datetime_type",
            "datetime_parsing",
            "datetime_object_invalid",
            "datetime_from_date_parsing",
            "datetime_past",
            "datetime_future",
            "timezone_naive",
            "timezone_aware",
            "timezone_offset",
            "time_delta_type",
            "time_delta_parsing",
            "frozen_set_type",
            "is_instance_of",
            "is_subclass_of",
            "callable_type",
            "union_tag_invalid",
            "union_tag_not_found",
            "arguments_type",
            "missing_argument",
            "unexpected_keyword_argument",
            "missing_keyword_only_argument",
            "unexpected_positional_argument",
            "missing_positional_only_argument",
            "multiple_argument_values",
            "url_type",
            "url_parsing",
            "url_syntax_violation",
            "url_too_long",
            "url_scheme",
            "uuid_type",
            "uuid_parsing",
            "uuid_version",
            "decimal_type",
            "decimal_parsing",
            "decimal_max_digits",
            "decimal_max_places",
            "decimal_whole_digits",
            "complex_type",
            "complex_str_parsing"
          ],
          "type": "string"
        },
        {
          "type": "string"
        }
      ],
      "title": "Type"
    },
    "severity": {
      "default": 30,
      "enum": [
        20,
        30,
        35
      ],
      "title": "Severity",
      "type": "integer"
    }
  },
  "required": [
    "loc",
    "msg",
    "type"
  ],
  "title": "WarningEntry",
  "type": "object"
}

Fields:

loc pydantic-field ¤

loc: Loc

msg pydantic-field ¤

msg: str

severity pydantic-field ¤

severity: WarningSeverity = WARNING

severity_name property ¤

severity_name: WarningSeverityName

type pydantic-field ¤

type: Union[ErrorType, str]

_format_html_table ¤

_format_html_table(rows: List[List[str]]) -> str

format rows as HTML table

Source code in src/bioimageio/spec/summary.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
def _format_html_table(rows: List[List[str]]) -> str:
    """format `rows` as HTML table"""

    def get_line(cells: List[str], cell_tag: Literal["th", "td"] = "td"):
        return (
            ["  <tr>"]
            + [f"    <{cell_tag}>{c}</{cell_tag}>" for c in cells]
            + ["  </tr>"]
        )

    table = ["<table>"] + get_line(rows[0], cell_tag="th")
    for r in rows[1:]:
        table.extend(get_line(r))

    table.append("</table>")

    return "\n".join(table)

_format_md_table ¤

_format_md_table(rows: List[List[str]]) -> str

format rows as markdown table

Source code in src/bioimageio/spec/summary.py
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def _format_md_table(rows: List[List[str]]) -> str:
    """format `rows` as markdown table"""
    n_cols = len(rows[0])
    assert all(len(row) == n_cols for row in rows)
    col_widths = [max(max(len(row[i]) for row in rows), 3) for i in range(n_cols)]

    # fix new lines in table cell
    rows = [[line.replace("\n", "<br>") for line in r] for r in rows]

    lines = [" | ".join(rows[0][i].center(col_widths[i]) for i in range(n_cols))]
    lines.append(" | ".join("---".center(col_widths[i]) for i in range(n_cols)))
    lines.extend(
        [
            " | ".join(row[i].ljust(col_widths[i]) for i in range(n_cols))
            for row in rows[1:]
        ]
    )
    return "\n| " + " |\n| ".join(lines) + " |\n"

_format_summary ¤

_format_summary(
    summary: ValidationSummary,
    *,
    hide_tracebacks: bool = False,
    hide_source: bool = False,
    hide_env: bool = False,
    target: Union[
        rich.console.Console, Literal["html", "md"]
    ] = "md",
    include_conda_list: bool,
    width: int,
) -> str
Source code in src/bioimageio/spec/summary.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def _format_summary(
    summary: ValidationSummary,
    *,
    hide_tracebacks: bool = False,  # TODO: remove?
    hide_source: bool = False,  # TODO: remove?
    hide_env: bool = False,  # TODO: remove?
    target: Union[rich.console.Console, Literal["html", "md"]] = "md",
    include_conda_list: bool,
    width: int,
) -> str:
    parts: List[str] = []
    format_table = _format_html_table if target == "html" else _format_md_table
    details_below: Dict[str, Union[str, Tuple[str, rich.traceback.Traceback]]] = {}
    left_out_details: int = 0
    left_out_details_header = "Left out details"

    def add_part(part: str):
        parts.append(part)
        if isinstance(target, rich.console.Console):
            target.print(rich.markdown.Markdown(part))

    def add_section(header: str):
        if target == "md" or isinstance(target, rich.console.Console):
            add_part(f"\n### {header}\n")
        elif target == "html":
            parts.append(f'<h3 id="{header_to_tag(header)}">{header}</h3>')
        else:
            assert_never(target)

    def header_to_tag(header: str):
        return (
            header.replace("`", "")
            .replace("(", "")
            .replace(")", "")
            .replace(" ", "-")
            .lower()
        )

    def add_as_details_below(
        title: str, text: Union[str, Tuple[str, rich.traceback.Traceback]]
    ):
        """returns a header and its tag to link to details below"""

        def make_link(header: str):
            tag = header_to_tag(header)
            if target == "md":
                return f"[{header}](#{tag})"
            elif target == "html":
                return f'<a href="#{tag}">{header}</a>'
            elif isinstance(target, rich.console.Console):
                return f"{header} below"
            else:
                assert_never(target)

        for n in range(1, 4):
            header = f"{title} {n}"
            if header in details_below:
                if details_below[header] == text:
                    return make_link(header)
            else:
                details_below[header] = text
                return make_link(header)

        nonlocal left_out_details
        left_out_details += 1
        return make_link(left_out_details_header)

    @dataclass
    class CodeCell:
        text: str

    @dataclass
    class CodeRef:
        text: str

    def format_code(
        code: str,
        lang: str = "",
        title: str = "Details",
        cell_line_limit: int = 15,
        cell_width_limit: int = 120,
    ) -> Union[CodeRef, CodeCell]:
        if not code.strip():
            return CodeCell("")

        if target == "html":
            html_lang = f' lang="{lang}"' if lang else ""
            code = f"<pre{html_lang}>{code}</pre>"
            put_below = (
                code.count("\n") > cell_line_limit
                or max(map(len, code.split("\n"))) > cell_width_limit
            )
        else:
            put_below = True
            code = f"\n```{lang}\n{code}\n```\n"

        if put_below:
            link = add_as_details_below(title, code)
            return CodeRef(f"See {link}.")
        else:
            return CodeCell(code)

    def format_traceback(entry: ErrorEntry):
        if isinstance(target, rich.console.Console):
            if entry.traceback_rich is None:
                return format_code(entry.traceback_md, title="Traceback")
            else:
                link = add_as_details_below(
                    "Traceback", (entry.traceback_md, entry.traceback_rich)
                )
                return CodeRef(f"See {link}.")

        if target == "md":
            return format_code(entry.traceback_md, title="Traceback")
        elif target == "html":
            return format_code(entry.traceback_html, title="Traceback")
        else:
            assert_never(target)

    def format_text(text: str):
        if target == "html":
            return [f"<pre>{text}</pre>"]
        else:
            return text.split("\n")

    def get_info_table():
        info_rows = [
            [summary.status_icon, summary.name.strip(".").strip()],
            ["status", summary.status],
        ]
        if not hide_source:
            info_rows.append(["source", html.escape(summary.source_name)])

        if summary.id is not None:
            info_rows.append(["id", summary.id])

        info_rows.append(["format version", f"{summary.type} {summary.format_version}"])
        if not hide_env:
            info_rows.extend([[e.name, e.version] for e in sorted(summary.env)])

        if include_conda_list:
            info_rows.append(
                ["conda list", format_code(summary.conda_list, title="Conda List").text]
            )
        return format_table(info_rows)

    def get_details_table():
        details = [["", "Location", "Details"]]

        def append_detail(
            status: str, loc: Loc, text: str, code: Union[CodeRef, CodeCell, None]
        ):
            text_lines = format_text(text)
            status_lines = [""] * len(text_lines)
            loc_lines = [""] * len(text_lines)
            status_lines[0] = status
            loc_lines[0] = format_loc(loc, target)
            for s_line, loc_line, text_line in zip(status_lines, loc_lines, text_lines):
                details.append([s_line, loc_line, text_line])

            if code is not None:
                details.append(["", "", code.text])

        for d in summary.details:
            details.append([d.status_icon, format_loc(d.loc, target), d.name])

            for entry in d.errors:
                append_detail(
                    "❌",
                    entry.loc,
                    entry.msg,
                    None if hide_tracebacks else format_traceback(entry),
                )

            for entry in d.warnings:
                append_detail("⚠", entry.loc, entry.msg, None)

            if d.recommended_env is not None:
                rec_env = StringIO()
                json_env = d.recommended_env.model_dump(
                    mode="json", exclude_defaults=True
                )
                assert is_yaml_value(json_env)
                write_yaml(json_env, rec_env)
                append_detail(
                    "",
                    d.loc,
                    f"recommended conda environment ({d.name})",
                    format_code(
                        rec_env.getvalue(),
                        lang="yaml",
                        title="Recommended Conda Environment",
                    ),
                )

            if d.conda_compare:
                wrapped_conda_compare = "\n".join(
                    TextWrapper(width=width - 4).wrap(d.conda_compare)
                )
                append_detail(
                    "",
                    d.loc,
                    f"conda compare ({d.name})",
                    format_code(
                        wrapped_conda_compare,
                        title="Conda Environment Comparison",
                    ),
                )

        return format_table(details)

    add_part(get_info_table())
    add_part(get_details_table())

    for header, text in details_below.items():
        add_section(header)
        if isinstance(text, tuple):
            assert isinstance(target, rich.console.Console)
            text, rich_obj = text
            target.print(rich_obj)
            parts.append(f"{text}\n")
        else:
            add_part(f"{text}\n")

    if left_out_details:
        parts.append(
            f"\n{left_out_details_header}\nLeft out {left_out_details} more details for brevity.\n"
        )

    return "".join(parts)

format_loc ¤

format_loc(
    loc: Loc,
    target: Union[
        Literal["md", "html", "plain"], rich.console.Console
    ],
) -> str

helper to format a location tuple loc

Source code in src/bioimageio/spec/summary.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def format_loc(
    loc: Loc, target: Union[Literal["md", "html", "plain"], rich.console.Console]
) -> str:
    """helper to format a location tuple **loc**"""
    loc_str = ".".join(f"({x})" if x[0].isupper() else x for x in map(str, loc))

    # additional field validation can make the location information quite convoluted, e.g.
    # `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
    # therefore we remove the `.function-after[validate_url_ok(), url['http','https']]` here
    loc_str, *_ = loc_str.split(".function-after")
    if loc_str:
        if target == "md" or isinstance(target, rich.console.Console):
            start = "`"
            end = "`"
        elif target == "html":
            start = "<code>"
            end = "</code>"
        elif target == "plain":
            start = ""
            end = ""
        else:
            assert_never(target)

        return f"{start}{loc_str}{end}"
    else:
        return ""

is_dict ¤

is_dict(v: Any) -> TypeGuard[Dict[Any, Any]]

to avoid Dict[Unknown, Unknown]

Source code in src/bioimageio/spec/_internal/type_guards.py
12
13
14
def is_dict(v: Any) -> TypeGuard[Dict[Any, Any]]:
    """to avoid Dict[Unknown, Unknown]"""
    return isinstance(v, dict)

is_yaml_value ¤

is_yaml_value(value: Any) -> TypeGuard[YamlValue]
Source code in src/bioimageio/spec/_internal/io.py
501
502
def is_yaml_value(value: Any) -> TypeGuard[YamlValue]:
    return is_yaml_leaf_value(value) or is_yaml_list(value) or is_yaml_dict(value)

write_yaml ¤

write_yaml(
    content: Union[
        YamlValue, BioimageioYamlContentView, BaseModel
    ],
    /,
    file: Union[
        NewPath, FilePath, IO[str], IO[bytes], ZipPath
    ],
)
Source code in src/bioimageio/spec/_internal/io_utils.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def write_yaml(
    content: Union[YamlValue, BioimageioYamlContentView, BaseModel],
    /,
    file: Union[NewPath, FilePath, IO[str], IO[bytes], ZipPath],
):
    if isinstance(file, Path):
        cm = file.open("w", encoding="utf-8")
    else:
        cm = nullcontext(file)

    if isinstance(content, BaseModel):
        content = content.model_dump(mode="json")

    with cm as f:
        _yaml_dump.dump(content, f)