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 4ef1785 commit 45aa9a6
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 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,15 @@
"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 @@ -335,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(
module: str,
Expand Down

0 comments on commit 45aa9a6

Please sign in to comment.