Classes related to the validation API¶
DICOM Edition reader¶
- class dicom_validator.validator.dicom_info.DicomInfo(dictionary: dict[str, dict[str, str]], iods: dict[str, dict[str, dict]], modules: dict[str, dict[str, dict]])¶
Holds DICOM standard information as read from the JSON cache files.
- dictionary¶
The DICOM dictionary from PS3.6
- Type:
dict[str, dict[str, str]]
- iods¶
The IOD descriptions for each SOP Class from PS3.3 and PS3.4
- Type:
dict[str, dict[str, dict]]
- modules¶
The attribute descriptions for each module extracted from PS3.3
- Type:
dict[str, dict[str, dict]]
- class dicom_validator.spec_reader.edition_reader.EditionReader(path: str | Path | None = None)¶
- editions_path() → Path¶
Return the path to the JSON file containing the identifiers of all found DICOM editions as a comma separated list.
- docbook_path(edition: str) → Path¶
Return the local path where docbook XML files for an edition reside.
- Parameters:
edition (str) – Edition identifier (e.g. ‘2025c’).
- Returns:
Directory path to the docbook sources for the given edition.
- Return type:
Path
- json_path(edition: str) → Path¶
Return the local path where JSON cache files are stored that contain the processed information for a DICOM edition.
- Parameters:
edition (str) – Edition identifier (e.g. ‘2025c’).
- Returns:
Directory path to the JSON cache for the given edition.
- Return type:
Path
- version_path(edition: str) → Path¶
Return the path of the file that stores the version string of the dicom-validator version used to create the JSON cache files.
- Parameters:
edition (str) – Edition identifier (e.g. ‘2025c’).
- Returns:
Path to the version file within the JSON cache directory.
- Return type:
Path
- update_edition() → None¶
Fetch the list of available DICOM editions and cache it locally.
Notes
Writes editions.html as downloaded, and editions.json as created from the HTML file under the base path. Logs a warning if the retrieval of the editions file failed.
- retrieve(html_path: Path) → None¶
Download the editions HTML page to the given path.
- Parameters:
html_path (pathlib.Path) – Destination path for the downloaded editions.html.
- get_editions(update: bool = True) → list[str] | None¶
Return available DICOM edition identifiers, updating the cache if needed.
- Parameters:
update (bool, optional) – If True, refresh the local cache when it is older than ~30 days or missing. If False, only read from the cache, creating it only if empty.
- Returns:
Sorted list of edition identifiers (e.g., ‘2025c’), or None if unavailable.
- Return type:
list[str] | None
- read_from_html() → list[str]¶
Parse the downloaded editions HTML and extract edition identifiers.
- Returns:
List of edition identifiers found in the HTML.
- Return type:
list[str]
- write_to_json() → None¶
Write the parsed editions list to the JSON cache file.
- get_edition(edition_str: str) → str | None¶
Resolve an edition selector to a concrete edition identifier, updating the available editions if needed.
- Parameters:
edition_str (str) – One of: - Exact edition name (e.g., ‘2025c’) - Year (e.g., ‘2025’) to select the latest available revision of that year - ‘current’ for the latest published edition - ‘local’ for the latest locally available edition
- Returns:
The resolved edition identifier or None if it cannot be determined.
- Return type:
str | None
- is_current(edition_str: str) → bool¶
Check whether the given selector refers to the current edition.
- Parameters:
edition_str (str) – Edition selector as accepted by get_edition.
- Returns:
True if it resolves to the latest edition, otherwise False.
- Return type:
bool
- get_edition_and_path(edition_str: str) → tuple[str | None, Path | None]¶
Resolve an edition selector and return its local base path.
- Parameters:
edition_str (str) – Edition selector as accepted by get_edition.
- Returns:
The resolved edition and its local base directory, or (None, None) if it cannot be resolved.
- Return type:
tuple[str | None, Path | None]
- get_chapter(edition: str, chapter: int) → bool¶
Ensure the DocBook file for a given part is present locally, downloading it if needed.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
chapter (int) – DICOM standard part number (e.g., 3, 4, or 6).
- Returns:
True if the file exists locally or is downloaded successfully, otherwise False.
- Return type:
bool
- load_info(edition: str, info_json: str) → dict¶
Load a JSON info file for the given edition.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
info_json (str) – File name within the edition’s JSON directory.
- Returns:
Parsed JSON content.
- Return type:
dict
- load_dicom_info(edition: str) → DicomInfo¶
Load all DICOM info JSON files and build a DicomInfo instance.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
- Returns:
Aggregated information from dictionary, IOD, and module JSON.
- Return type:
- dicom_info_for_edition(edition: str) → DicomInfo¶
Looks up the edition, downloads and processes the DICOM files if needed, and returns the existing or newly created DICOM info object.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’ or ‘current’).
- Raises:
InvalidEditionError – If the edition argument has an invalid format or value.
EditionLoadError – If the edition could not be loaded. This could be due to a download error, or an error while parsing the DICOM files.
- json_files_exist(edition: str) → bool¶
Check if all expected JSON files exist for the given edition.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
- Returns:
True if all JSON files are present; otherwise False.
- Return type:
bool
- static dump_description(description: dict) → str¶
Serialize a description dictionary to a pretty-printed JSON string.
- Parameters:
description (dict) – Dictionary structure to serialize.
- Returns:
Pretty-printed JSON string.
- Return type:
str
- create_json_files(edition: str) → None¶
Parse DocBook sources and (re)create all JSON cache files.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
- get_edition_path(edition_str: str, recreate_json: bool = False, create_json: bool = True) → Path | None¶
Prepare local files for an edition and return its base path.
- Parameters:
edition_str (str) – Edition selector as accepted by get_edition.
recreate_json (bool, optional) – If True, force re-creating the JSON cache files regardless of their age. Defaults to False.
create_json (bool, optional) – If True, create JSON cache files if missing or outdated. Defaults to True.
- Returns:
Local base directory of the edition, or None on failure.
- Return type:
Path | None
- is_current_version(edition: str) → bool¶
Check whether the local JSON cache matches this package version exactly. We want an exact match as the format is not guaranteed to be downwards compatible.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
- Returns:
True if the stored version is equal to this package’s __version__.
- Return type:
bool
- write_current_version(edition: str) → None¶
Write this package’s version string into the edition’s cache.
- Parameters:
edition (str) – Edition identifier (e.g., ‘2025c’).
Validation Logic¶
- class dicom_validator.validator.iod_validator.IODValidator(dataset: Dataset, dicom_info: DicomInfo, *, log_level: int = 20, suppress_vr_warnings: bool = False, error_handler: ValidationResultHandler | None = None, file_path: str = '')¶
Performs the actual IOD validation of a single DICOM dataset.
- __init__(dataset: Dataset, dicom_info: DicomInfo, *, log_level: int = 20, suppress_vr_warnings: bool = False, error_handler: ValidationResultHandler | None = None, file_path: str = '') → None¶
Create an IODValidator instance.
- Parameters:
dataset (Dataset) – The dataset to be validated.
dicom_info (dict) – The DICOM information as extracted from the standard.
log_level (int) – The log level of the logger, if using the default error handler.
suppress_vr_warnings (bool) – If True, skip the VR validation of DICOM tags.
error_handler (ValidationResultHandler) – Handles errors found during validation. Defaults to a handler that logs all errors to the console.
- validate() → ValidationResult¶
Validates current dataset. All errors are contained in the ValidationResult object after execution. By default, e.g. if no other handler has been set, all errors are logged to the console.
- class dicom_validator.validator.dicom_file_validator.DicomFileValidator(dicom_info: DicomInfo, log_level: int = 20, force_read: bool = False, suppress_vr_warnings: bool = False, error_handler: ValidationResultHandler | None = None)¶
Validates a single DICOM file or all DICOM files in a directory.
- __init__(dicom_info: DicomInfo, log_level: int = 20, force_read: bool = False, suppress_vr_warnings: bool = False, error_handler: ValidationResultHandler | None = None) → None¶
Initializes a DicomFileValidator object.
- Parameters:
dicom_info (DicomInfo) – DICOM information as read from the JSON files created from the standard
log_level (int) – The log level to use with the default error handler
force_read (bool) – If True, the DICOM file is tried to read even if it may not be valid
suppress_vr_warnings (bool) – By default, values not valid for the given VR are reported, using the pydicom validation. If set to True, this validation is not performed.
error_handler (ValidationResultHandler or None) – If set, this handler will be used to handle the validation result, otherwise the default handler is used that logs errors to the console.
- validate(path: str | PathLike) → dict[str, ValidationResult]¶
Validate a single DICOM file or all files under a directory.
- Parameters:
path (str | os.PathLike) – Path to a DICOM file or a directory containing DICOM files.
- Returns:
A mapping from file path to its validation result.
- Return type:
dict[str, ValidationResult]
- validate_dir(dir_path: str) → dict[str, ValidationResult]¶
Validate all DICOM files contained in a directory tree.
- Parameters:
dir_path (str) – Path to a directory that will be traversed recursively.
- Returns:
A mapping from file path to its validation result for all files found.
- Return type:
dict[str, ValidationResult]
- validate_file(file_path: str) → dict[str, ValidationResult]¶
Validate a single DICOM file.
- Parameters:
file_path (str) – Path to a DICOM file.
- Returns:
A mapping containing exactly one entry for the given file.
- Return type:
dict[str, ValidationResult]
Validation result¶
- class dicom_validator.validator.validation_result.ErrorCode(*values)¶
Defines the kind of error found for a DICOM tag in a module.
- TagMissing = 1¶
Mandatory tag is missing from a module
- TagEmpty = 2¶
Type 1 or 1C tag is empty
- TagUnexpected = 3¶
Tag is not in any allowed module
- TagNotAllowed = 4¶
Tag not allowed by a condition
- EnumValueNotAllowed = 5¶
Value not in the list of allowed enum values
- InvalidValue = 6¶
The value failed the VR validation
- class dicom_validator.validator.validation_result.ErrorScope(*values)¶
Defines the scope of an error found for a DICOM tag in a module. Some errors are specific to functional groups while having the same error code as errors unrelated to functional groups.
- General = 0¶
Tag not inside a functional group sequence
- SharedFuncGroup = 1¶
Tag inside the shared the functional group sequence
- PerFrameFuncGroup = 2¶
Tag inside the per-frame the functional group sequence
- BothFuncGroups = 3¶
Tag in both shared and per-frame functional group sequences
- class dicom_validator.validator.validation_result.TagType(*values)¶
The DICOM tag type used in a specific module.
- Type1 = '1'¶
Tag must exist and not be empty
- Type1C = '1C'¶
Tag must exist and not be empty if the condition is fulfilled
- Type2 = '2'¶
Tag must exist
- Type2C = '2C'¶
Tag must exist if the condition is fulfilled
- Type3 = '3'¶
Tag is optional
- class dicom_validator.validator.validation_result.Status(*values)¶
The result state after validation.
- Passed = 0¶
No errors found in validation
- Failed = 1¶
Some violations found in validation
- MissingFile = 2¶
File to be validated is missing
- InvalidFile = 3¶
File to be validated is invalid DICOM
- MissingSOPClassUID = 4¶
File to be validated has no SOP Class UID
- UnknownSOPClassUID = 5¶
The SOP Class UID in the file to be validated is unknown
- class dicom_validator.validator.validation_result.DicomTag(tag: int, parents: list[int] | None = None)¶
Represents a DICOM tag together with parent sequences, if any.
- tag¶
The DICOM tag ID
- Type:
pydicom.tag.BaseTag
- parents¶
List of parent DICOM tag IDs if the tag is inside a sequence, or None
- Type:
list[pydicom.tag.BaseTag] | None
- class dicom_validator.validator.validation_result.TagError(type: TagType = TagType.Undefined, code: ErrorCode = ErrorCode.NoError, scope: ErrorScope = ErrorScope.General, context: dict | None = None)¶
Represents the error found for a specific DICOM tag.
- type¶
Type of tag (1, 1C, 2, 2C, 3)
- code¶
Error code of the tag error
- scope¶
Scope (root or functional groups) where the tag error occurred
- context¶
Contains additional information for some errors
- Type:
dict | None
- class dicom_validator.validator.validation_result.ValidationResult(sop_class_uid: str = '', file_path: str = '', status: Status = Status.Passed, errors: int = 0, module_errors: dict[str, dict[DicomTag, TagError]] | None = None)¶
The validation result for a specific DICOM dataset.
- sop_class_uid¶
The SOP Class UID of the dataset
- Type:
str
- file_path¶
The path of the DICOM file if known
- Type:
str
- status¶
Status of the validation
- errors¶
Number of validation errors found
- Type:
int
- module_errors¶
Tag errors per module, where module name is the key, and a dictionary with errors per DICOM tag ID is the value
- Type:
dict[str, dict[dicom_validator.validator.validation_result.DicomTag, dicom_validator.validator.validation_result.TagError]] | None
Error handling¶
Base classes¶
- class dicom_validator.validator.error_handler.ValidationResultHandler(*args, **kwargs)¶
Protocol to be implemented by any validation result handler passed to the IODValidator.
- abstractmethod handle_validation_start(result: ValidationResult)¶
Called before the validation has started. Only the SOP Class UID is set at this point.
- abstractmethod handle_validation_result(result: ValidationResult)¶
Called after the validation has finished. All found errors are recorded in the validation result.
- class dicom_validator.validator.error_handler.ValidationResultHandlerBase(*args, **kwargs)¶
Provides a skeleton implementation for a result handler. An easy way to implement another handler is to derive from this class and implement the actual handling in some or all placeholder methods.
- handle_validation_start(result: ValidationResult) → None¶
Placeholder method. Called before the validation has started. Only the SOP Class UID is set at this point.
- handle_validation_result(result: ValidationResult) → None¶
Called after the validation has finished. All found errors are recorded in the validation result. Only calls other methods that may contain the actual handling.
- handle_failed_validation_start(result: ValidationResult) → None¶
Placeholder method. Called in case the validation could not be started. Only the error code is set in the result. The validation is aborted after this call.
- handle_validation_result_start(validation_result: ValidationResult) → None¶
Placeholder method. Called after the validation result is available and before the result handling starts.
- handle_validation_result_end(validation_result: ValidationResult) → None¶
Placeholder method. Called after the validation result have been handled.
- handle_module_errors(module_name: str, tag_errors: dict[DicomTag, TagError]) → None¶
Called to handle the errors in a single module. Only calls other methods that may contain the actual handling.
- handle_module_errors_start(module_name: str, tag_errors: dict[DicomTag, TagError]) → None¶
Placeholder method. Called before the errors for a single module are handled.
- handle_module_errors_end(module_name: str, tag_errors: dict[DicomTag, TagError]) → None¶
Placeholder method. Called after the errors for a single module are handled.
- handle_tag_error(tag_id: DicomTag, error: TagError) → None¶
Placeholder method. Called to handle a single tag error. The actual error handling (logging, recording) shall be implemented here.
- handle_tag_parents_start(parents: list[BaseTag]) → None¶
Placeholder method. Called to handle parent sequence tags. Is called once for one or more tag errors with the same parent sequences.
- handle_tag_parents_end(parents: list[BaseTag]) → None¶
Placeholder method. Called to handle parent sequence tags. Is called once after one or more tag errors with the same parent sequences appeared.
Default error handler¶
- class dicom_validator.validator.error_handler.LoggingResultHandler(dicom_info: DicomInfo, logger: Logger)¶
Handles the result of the validation of a single DICOM file by logging all errors.
- handle_validation_start(result: ValidationResult) → None¶
Placeholder method. Called before the validation has started. Only the SOP Class UID is set at this point.
- handle_module_errors_start(module_name: str, tag_errors: dict[DicomTag, TagError]) → None¶
Placeholder method. Called before the errors for a single module are handled.
- handle_tag_parents_start(parents: list[BaseTag]) → None¶
Placeholder method. Called to handle parent sequence tags. Is called once for one or more tag errors with the same parent sequences.
- handle_tag_error(tag_id: DicomTag, error: TagError) → None¶
Placeholder method. Called to handle a single tag error. The actual error handling (logging, recording) shall be implemented here.
- handle_validation_result_start(validation_result: ValidationResult) → None¶
Placeholder method. Called after the validation result is available and before the result handling starts.
- handle_validation_result_end(validation_result: ValidationResult) → None¶
Placeholder method. Called after the validation result have been handled.
- handle_failed_validation_start(result: ValidationResult) → None¶
Placeholder method. Called in case the validation could not be started. Only the error code is set in the result. The validation is aborted after this call.
Example error handler¶
- class dicom_validator.validator.html_error_handler.HtmlErrorHandler(dicom_info: DicomInfo)¶
An example error handler that writes DICOM errors to a simple HTML page, adding links to each affected module.
- handle_validation_result_start(result: ValidationResult) → None¶
Start a new HTML section for a validation result.
- handle_validation_result_end(result: ValidationResult) → None¶
Finalize the HTML output for a validation result.
- static url_for_ref(ref) → str¶
We always refer to the latest standard. This could be adapted to check for the documentation of a specific edition of the standard.
- static url_exists(url)¶
Check whether a URL is reachable via an HTTP HEAD request.
- Parameters:
url (str) – Fully-qualified URL.
- Returns:
True if the server responds with a status code < 400.
- Return type:
bool
- valid_url_for_ref(ref: str) → str | None¶
Return a valid URL to the referenced PS3.3 section if it exists.
- Parameters:
ref (str) – Section reference label (e.g., ‘C.7.6.1’).
- Returns:
URL to the best-matching PS3.3 HTML section, or None if not found.
- Return type:
str | None
- handle_module_errors_start(module_name: str, tag_errors: dict[DicomTag, TagError]) → None¶
Start a new HTML list for errors in a specific module.
- handle_module_errors_end(module_name: str, tag_errors: dict[DicomTag, TagError]) → None¶
Close the HTML list for the current module’s errors.
- static error_message(error: TagError) → str¶
Return a human-readable message fragment for a tag error.
- Parameters:
error (TagError) – The error to be rendered.
- Returns:
A short message starting with a space to append after the tag name.
- Return type:
str
- tag_name(tag_id: BaseTag) → str¶
Return a human-readable name for a tag, including its ID.
- Parameters:
tag_id (BaseTag) – DICOM tag identifier.
- Returns:
A string like ‘Patient Name (0010,0010)’ when known, otherwise the tag ID string.
- Return type:
str
- handle_tag_error(tag_id: DicomTag, error: TagError) → None¶
Append a single tag error as an HTML list item.
- handle_tag_parents_start(parents: list[BaseTag]) → None¶
Start a new section header listing parent sequence tags.