Skip to content

Commit

Permalink
Print what package should be installed when suitable writer is missing
Browse files Browse the repository at this point in the history
Fixes Project-MONAI#7980

Signed-off-by: ytl0623 <[email protected]>
  • Loading branch information
ytl0623 committed Aug 7, 2024
1 parent 6c23fd0 commit 08523ce
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion monai/utils/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from pydoc import locate
from re import match
from types import FunctionType, ModuleType
from typing import Any, Iterable, cast
from typing import Any, Iterable, cast, Dict, List

import torch

Expand Down Expand Up @@ -60,6 +60,16 @@
"pytorch_after",
]

WRITER_PACKAGE_MAP: Dict[str, List[str]] = {
"png": ["pillow"],
"jpg": ["pillow"],
"jpeg": ["pillow"],
"nii": ["nibabel"],
"nii.gz": ["nibabel"],
"dcm": ["pydicom"],
# Add more mappings as needed
}


def look_up_option(
opt_str: Hashable,
Expand Down Expand Up @@ -334,6 +344,20 @@ class OptionalImportError(ImportError):
"""
Could not import APIs from an optional dependency.
"""

def __init__(self, msg: str = "") -> None:
super().__init__(msg)
self.msg = msg

def __str__(self) -> str:
original_msg = super().__str__()
if "ImageWriter" in original_msg and "backend found for" in original_msg:
ext = original_msg.split("for ")[-1].strip(".")
suggested_packages = WRITER_PACKAGE_MAP.get(ext, [])
if suggested_packages:
package_list = ", ".join(suggested_packages)
return f"{original_msg} Please install one of the following packages: {package_list}"
return original_msg


def optional_import(
Expand Down

0 comments on commit 08523ce

Please sign in to comment.