Skip to content

Commit 4718664

Browse files
committed
Print missing packages to install when no suitable ImageWriter is found
Fixes #7980. resolve_writer raised a generic OptionalImportError when no registered writer backend was available for the given extension, without telling users which optional dependency to install. - OptionalImportError now records the name of the missing package via the new pkg_name argument. - require_pkg passes the missing package name to OptionalImportError. For an installed package with an incompatible version, the recorded name carries the version constraint (e.g. 'torch>=10000'), since an unconstrained 'pip install' would be a no-op in that case. - resolve_writer collects the packages of the unavailable candidate writers and appends installation hints to the error message, e.g. 'No ImageWriter backend found for png. Please install the missing package(s): pillow (e.g. `pip install pillow`).' The PIL import name is translated to the installable pillow distribution; the generic message is kept when dependency details are unavailable. - tests added to tests/data/test_image_rw.py and tests/utils/test_require_pkg.py. Signed-off-by: Pushpak <[email protected]>
1 parent 8605065 commit 4718664

4 files changed

Lines changed: 119 additions & 6 deletions

File tree

‎monai/data/image_writer.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@
6363

6464
SUPPORTED_WRITERS: dict = {}
6565

66+
# import names of the writer dependencies that differ from their pip-installable distribution names
67+
_INSTALL_NAMES = {"PIL": "pillow"}
68+
6669

6770
def register_writer(ext_name, *im_writers):
6871
"""
@@ -99,24 +102,38 @@ def resolve_writer(ext_name, error_if_not_found=True) -> Sequence:
99102
As an indexing key it will be converted to a lower case string.
100103
error_if_not_found: whether to raise an error if no suitable image writer is found.
101104
if True , raise an ``OptionalImportError``, otherwise return an empty tuple. Default is ``True``.
105+
106+
Raises:
107+
OptionalImportError: When no suitable image writer is found and ``error_if_not_found`` is True.
108+
If the missing writers are known to require packages that are not installed,
109+
the error message additionally suggests the packages to install.
110+
102111
"""
103112
if not SUPPORTED_WRITERS:
104113
init()
105114
fmt = f"{ext_name}".lower()
106115
if fmt.startswith("."):
107116
fmt = fmt[1:]
108117
avail_writers = []
118+
missing_pkgs = []
109119
default_writers = SUPPORTED_WRITERS.get(EXT_WILDCARD, ())
110120
for _writer in look_up_option(fmt, SUPPORTED_WRITERS, default=default_writers):
111121
try:
112122
_writer() # this triggers `monai.utils.module.require_pkg` to check the system availability
113123
avail_writers.append(_writer)
114-
except OptionalImportError:
124+
except OptionalImportError as e:
125+
if e.pkg_name is not None and e.pkg_name not in missing_pkgs:
126+
missing_pkgs.append(e.pkg_name)
115127
continue
116128
except Exception: # other writer init errors indicating it exists
117129
avail_writers.append(_writer)
118130
if not avail_writers and error_if_not_found:
119-
raise OptionalImportError(f"No ImageWriter backend found for {fmt}.")
131+
err_msg = f"No ImageWriter backend found for {fmt}."
132+
if missing_pkgs:
133+
install_names = [_INSTALL_NAMES.get(pkg, pkg) for pkg in missing_pkgs]
134+
install_hints = " or ".join(f"`pip install {name}`" for name in install_names)
135+
err_msg += f" Please install the missing package(s): {' or '.join(install_names)} (e.g. {install_hints})."
136+
raise OptionalImportError(err_msg)
120137
writer_tuple = ensure_tuple(avail_writers)
121138
SUPPORTED_WRITERS[fmt] = writer_tuple
122139
return writer_tuple

‎monai/utils/module.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,8 +311,18 @@ def __init__(self, required_version, name):
311311
class OptionalImportError(ImportError):
312312
"""
313313
Could not import APIs from an optional dependency.
314+
315+
Args:
316+
msg: the error message.
317+
pkg_name: name of the missing package that caused the import error, if known.
318+
It is used to provide installation hints to the users. Defaults to ``None``.
319+
314320
"""
315321

322+
def __init__(self, msg: str = "", pkg_name: str | None = None):
323+
super().__init__(msg)
324+
self.pkg_name = pkg_name
325+
316326

317327
def optional_import(
318328
module: str,
@@ -464,6 +474,12 @@ def require_pkg(
464474
raise_error: if True, raise `OptionalImportError` error if the required package is not installed
465475
or the version doesn't match requirement, if False, print the error in a warning.
466476
477+
Raises:
478+
OptionalImportError: When ``raise_error`` is True and the required package is not installed or its
479+
version doesn't match the requirement. The error records the name of the package to install
480+
in ``pkg_name``: the plain package name if it is missing, or a name with the version
481+
constraint (e.g. ``itk>=5.2``) if an installed package has an incompatible version.
482+
467483
"""
468484

469485
def _decorator(obj):
@@ -476,7 +492,13 @@ def _wrapper(*args, **kwargs):
476492
if not has:
477493
err_msg = f"required package `{pkg_name}` is not installed or the version doesn't match requirement."
478494
if raise_error:
479-
raise OptionalImportError(err_msg)
495+
# an unconstrained `pip install` is a no-op for an installed package with an
496+
# incompatible version, so record the version constraint for installation hints;
497+
# `>=` is assumed for any `version_checker` other than `exact_version`
498+
name = pkg_name
499+
if version and optional_import(pkg_name)[1]:
500+
name = f"{pkg_name}{'==' if version_checker is exact_version else '>='}{version}"
501+
raise OptionalImportError(err_msg, pkg_name=name)
480502
else:
481503
warnings.warn(err_msg)
482504

‎tests/data/test_image_rw.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,21 @@ def test_rgb(self, reader, writer):
136136
self.png_rw(test_data, reader, writer, np.uint8, False)
137137

138138

139+
class UnavailableWriter:
140+
"""
141+
Simulates a registered writer whose backend dependency is not installed:
142+
``require_pkg``-decorated writers raise ``OptionalImportError`` on instantiation.
143+
"""
144+
145+
pkg_name: str | None = "test123"
146+
147+
def __init__(self):
148+
raise OptionalImportError(
149+
f"required package `{self.pkg_name}` is not installed or the version doesn't match requirement.",
150+
pkg_name=self.pkg_name,
151+
)
152+
153+
139154
class TestRegRes(unittest.TestCase):
140155
def test_0_default(self):
141156
self.assertTrue(len(resolve_writer(".png")) > 0, "has png writer")
@@ -150,6 +165,49 @@ def test_1_new(self):
150165
register_writer("new2", lambda x: x + 1)
151166
self.assertEqual(resolve_writer("new")[0](0), 1)
152167

168+
def test_2_install_hint(self):
169+
register_writer("unknown2", UnavailableWriter)
170+
with self.assertRaises(OptionalImportError) as cm:
171+
resolve_writer("unknown2")
172+
self.assertIn("pip install test123", str(cm.exception))
173+
174+
def test_3_install_hint_alias(self):
175+
# the `PIL` import name should be translated to the installable name `pillow`
176+
177+
class NoPillow(UnavailableWriter):
178+
pkg_name = "PIL"
179+
180+
register_writer("unknown3", NoPillow)
181+
with self.assertRaises(OptionalImportError) as cm:
182+
resolve_writer("unknown3")
183+
self.assertIn("pip install pillow", str(cm.exception))
184+
185+
def test_4_multiple_install_hints(self):
186+
187+
class NoItk(UnavailableWriter):
188+
pkg_name = "itk"
189+
190+
class NoNibabel(UnavailableWriter):
191+
pkg_name = "nibabel"
192+
193+
register_writer("unknown4", NoItk, NoNibabel)
194+
with self.assertRaises(OptionalImportError) as cm:
195+
resolve_writer("unknown4")
196+
self.assertIn("pip install itk", str(cm.exception))
197+
self.assertIn("pip install nibabel", str(cm.exception))
198+
199+
def test_5_no_install_hint(self):
200+
# a writer failing without package details keeps the generic message
201+
202+
class NoPkgName(UnavailableWriter):
203+
def __init__(self):
204+
raise OptionalImportError("some other reason")
205+
206+
register_writer("unknown5", NoPkgName)
207+
with self.assertRaises(OptionalImportError) as cm:
208+
resolve_writer("unknown5")
209+
self.assertEqual(str(cm.exception), "No ImageWriter backend found for unknown5.")
210+
153211

154212
@unittest.skipUnless(has_itk, "itk not installed")
155213
class TestLoadSaveNrrd(unittest.TestCase):

‎tests/utils/test_require_pkg.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
import unittest
1515

16-
from monai.utils import OptionalImportError, min_version, require_pkg
16+
from monai.utils import OptionalImportError, exact_version, min_version, require_pkg
1717

1818

1919
class TestRequirePkg(unittest.TestCase):
@@ -43,23 +43,39 @@ def test_func(x):
4343
test_func(x=None)
4444

4545
def test_class_exception(self):
46-
with self.assertRaises(OptionalImportError):
46+
with self.assertRaises(OptionalImportError) as cm:
4747

4848
@require_pkg(pkg_name="test123")
4949
class TestClass:
5050
pass
5151

5252
TestClass()
5353

54+
self.assertEqual(cm.exception.pkg_name, "test123")
55+
5456
def test_class_version_exception(self):
55-
with self.assertRaises(OptionalImportError):
57+
# the installed package is incompatible, so the recorded name carries the version constraint
58+
with self.assertRaises(OptionalImportError) as cm:
5659

5760
@require_pkg(pkg_name="torch", version="10000", version_checker=min_version)
5861
class TestClass:
5962
pass
6063

6164
TestClass()
6265

66+
self.assertEqual(cm.exception.pkg_name, "torch>=10000")
67+
68+
def test_func_exact_version_exception(self):
69+
with self.assertRaises(OptionalImportError) as cm:
70+
71+
@require_pkg(pkg_name="torch", version="10000", version_checker=exact_version)
72+
def test_func(x):
73+
return x
74+
75+
test_func(x=None)
76+
77+
self.assertEqual(cm.exception.pkg_name, "torch==10000")
78+
6379
def test_func_exception(self):
6480
with self.assertRaises(OptionalImportError):
6581

0 commit comments

Comments
 (0)