diff --git a/src/machinevisiontoolbox/ImageIO.py b/src/machinevisiontoolbox/ImageIO.py index 7ae900c5..9363754e 100644 --- a/src/machinevisiontoolbox/ImageIO.py +++ b/src/machinevisiontoolbox/ImageIO.py @@ -57,7 +57,9 @@ def Read( :param rgb: force color image to be in RGB order, defaults to True :type rgb: bool, optional :param kwargs: options applied to image frames, see :func:`~machinevisiontoolbox.base.imageio.convert` - :raises ValueError: file not found, or no file selected in browser + :raises FileNotFoundError: file is neither in the current folder nor in + the mvtb-data ``images`` folder + :raises ValueError: no file selected in browser :raises ImportError: ``filename`` omitted but tkinter is unavailable :return: image from file :rtype: :class:`Image` @@ -69,6 +71,11 @@ def Read( If ``filename`` is omitted a native file-browser dialogue is opened, initially showing the ``images`` folder of the ``mvtb_data`` package. + .. versionchanged:: 2.5.0 + A file that cannot be found raises :class:`FileNotFoundError`, with + a short traceback and the names of similar files, instead of + :class:`ValueError`. + .. rubric:: Examples .. runblock:: pycon @@ -98,7 +105,11 @@ def Read( raise ValueError("expecting a string or path") # read the image - data = iread(filename, rgb=rgb, alpha=alpha, **kwargs) + try: + data = iread(filename, rgb=rgb, alpha=alpha, **kwargs) + except FileNotFoundError as exc: + # raise afresh, so the traceback is one frame and not four + raise FileNotFoundError(*exc.args) from None # result is a tuple(image, filename) or a list of tuples diff --git a/src/machinevisiontoolbox/Sources.py b/src/machinevisiontoolbox/Sources.py index 45dd57ea..3455fe8d 100644 --- a/src/machinevisiontoolbox/Sources.py +++ b/src/machinevisiontoolbox/Sources.py @@ -3434,7 +3434,7 @@ def _open_reader(self) -> Any: # exists locally, otherwise searches the mvtb-data companion package. try: path = str(mvtb_path_to_datafile("data", path)) - except (ValueError, ModuleNotFoundError): + except (FileNotFoundError, ValueError, ModuleNotFoundError): pass # fall through; rosbags will raise a clear error on open self._is_ros2 = _BagPath(path).is_dir() diff --git a/src/machinevisiontoolbox/base/data.py b/src/machinevisiontoolbox/base/data.py index 4ed40fd8..e93710c2 100644 --- a/src/machinevisiontoolbox/base/data.py +++ b/src/machinevisiontoolbox/base/data.py @@ -5,6 +5,7 @@ from __future__ import annotations +import difflib import importlib import importlib.resources from pathlib import Path @@ -111,6 +112,33 @@ def mvtb_load_data(filename: str, handler: Callable[..., Any], **kwargs: Any) -> return handler(path, **kwargs) +def _not_found_message(filename: tuple[str | Path, ...], root: Path) -> str: + """Readable message for a file that is neither local nor in mvtbdata + + The message names the file as the caller wrote it, without the folder + inside ``mvtbdata`` that was added to the search, and suggests files with + similar names if there are any. + """ + folder = root.joinpath(*filename[:-1]) + where = "mvtbdata" + if len(filename) > 1: + where += f"/{Path(*filename[:1])}" + name = Path(*filename[1:]) + else: + name = Path(filename[0]) + msg = f"file {str(name)!r} not found in the current folder or in {where}" + if folder.is_dir(): + # best matches first, ties in alphabetical order + names = sorted(p.name for p in folder.iterdir() if not p.name.startswith(".")) + score = {n: difflib.SequenceMatcher(None, name.name, n).ratio() for n in names} + close = sorted((n for n in names if score[n] >= 0.6), key=lambda n: -score[n])[ + :3 + ] + if close: + msg += "; did you mean " + ", ".join(close) + "?" + return msg + + def mvtb_path_to_datafile( *filename: str | Path, local: bool = True, string: bool = False ) -> Path | str: @@ -123,7 +151,7 @@ def mvtb_path_to_datafile( :type local: bool :param string: return as string, default False :type string: bool - :raises FileNotFoundError: File does not exist + :raises FileNotFoundError: File is neither local nor in the mvtbdata package :return: Absolute path :rtype: Path or str @@ -163,7 +191,7 @@ def mvtb_path_to_datafile( else: return path else: - raise ValueError(f"file {filename} not found locally") + raise FileNotFoundError(f"file {str(path)!r} not found") # file is either local or in mvtbdata path = Path(filename[-1]).expanduser() @@ -192,4 +220,4 @@ def mvtb_path_to_datafile( else: return path else: - raise ValueError(f"file {filename} not found locally or in mvtbdata ({root})") + raise FileNotFoundError(_not_found_message(filename, root)) diff --git a/src/machinevisiontoolbox/base/imageio.py b/src/machinevisiontoolbox/base/imageio.py index 06afb9c0..8d831411 100644 --- a/src/machinevisiontoolbox/base/imageio.py +++ b/src/machinevisiontoolbox/base/imageio.py @@ -53,7 +53,7 @@ def _pick_imagefile() -> Path: """ try: initialdir = mvtb_path_to_datafile("images") - except (ModuleNotFoundError, ValueError): + except (ModuleNotFoundError, FileNotFoundError, ValueError): initialdir = Path.home() try: @@ -1111,6 +1111,8 @@ def iread( :type args: tuple :param kwargs: key word arguments passed to :func:`convert` :type kwargs: dict + :raises FileNotFoundError: the file is neither in the current folder nor in + the ``images`` folder of the mvtb-data package :return: image and filename :rtype: tuple (ndarray, str) or list of tuples, image is a 2D or 3D NumPy ndarray @@ -1132,6 +1134,11 @@ def iread( correction, image decimation or region of interest windowing. Details are given at :func:`convert`. + .. versionchanged:: 2.5.0 + A file that cannot be found raises :class:`FileNotFoundError`, with a + short traceback and the names of similar files, instead of + :class:`ValueError`. + .. rubric:: Examples .. runblock:: pycon @@ -1208,6 +1215,9 @@ def iread( return next(iterator) except StopIteration as exc: raise ValueError(f"invalid filename, got {filename!r}") from exc + except FileNotFoundError as exc: + # raise afresh, so the traceback stops here and not in the helpers + raise FileNotFoundError(*exc.args) from None def iread_iter( diff --git a/src/machinevisiontoolbox/bin/imtool.py b/src/machinevisiontoolbox/bin/imtool.py index c512c5cb..e6575132 100755 --- a/src/machinevisiontoolbox/bin/imtool.py +++ b/src/machinevisiontoolbox/bin/imtool.py @@ -241,7 +241,7 @@ def main(): try: img = Image.Read(file, alpha=args.alpha) print(img) - except ValueError: + except (FileNotFoundError, ValueError): print(f"File {file} not found") if i == len(args.files) - 1: diff --git a/src/machinevisiontoolbox/bin/ocrtool.py b/src/machinevisiontoolbox/bin/ocrtool.py index 6d2c9c8b..60104cdc 100755 --- a/src/machinevisiontoolbox/bin/ocrtool.py +++ b/src/machinevisiontoolbox/bin/ocrtool.py @@ -94,7 +94,7 @@ def main(): for i, file in enumerate(args.files): try: img = Image.Read(file, rgb=False) - except ValueError: + except (FileNotFoundError, ValueError): print(f"File {file} not found") continue diff --git a/src/machinevisiontoolbox/bin/tagtool.py b/src/machinevisiontoolbox/bin/tagtool.py index ebe4a12c..c7f71daa 100755 --- a/src/machinevisiontoolbox/bin/tagtool.py +++ b/src/machinevisiontoolbox/bin/tagtool.py @@ -269,7 +269,7 @@ def main(): for i, file in enumerate(args.files): try: img = Image.Read(file, rgb=False) - except ValueError: + except (FileNotFoundError, ValueError): print(f"File {file} not found") continue diff --git a/tests/base/test_data.py b/tests/base/test_data.py index ed8613d2..e663700f 100644 --- a/tests/base/test_data.py +++ b/tests/base/test_data.py @@ -18,7 +18,7 @@ class TestDataFiles(unittest.TestCase): def test_datafile_local(self): # test for exception if file not found # test that exception raised if not present - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): mvtb_path_to_datafile("notthere.png") # create a local test image file @@ -32,15 +32,56 @@ def test_datafile_mvtb(self): path = mvtb_path_to_datafile("images", "shark1.png") self.assertTrue(os.path.isfile(path)) - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): mvtb_path_to_datafile("images", "__shark100.png") path = mvtb_path_to_datafile("data", "bunny.ply") self.assertTrue(os.path.isfile(path)) - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): mvtb_path_to_datafile("data", "__bunny100.png") + def test_missing_file_message(self): + with self.assertRaises(FileNotFoundError) as cm: + mvtb_path_to_datafile("images", "flowers.png") + msg = str(cm.exception) + # names the file as written, not as a tuple of path components + self.assertTrue(msg.startswith("file 'flowers.png' not found"), msg) + self.assertNotIn("PosixPath", msg) + self.assertIn("mvtbdata/images", msg) + # suggests the similar files that do exist + self.assertIn("did you mean flowers1.png, flowers2.png, flowers3.png?", msg) + + def test_missing_file_no_suggestion(self): + with self.assertRaises(FileNotFoundError) as cm: + mvtb_path_to_datafile("images", "qqqqqqqqqq.png") + self.assertNotIn("did you mean", str(cm.exception)) + + def test_read_missing_file_traceback(self): + import traceback + + from machinevisiontoolbox import Image + + # assertRaises discards the traceback, so catch the error by hand + try: + Image.Read("flowers.png") + except FileNotFoundError as exc: + error = exc + else: + self.fail("FileNotFoundError not raised") + # one frame in the toolbox, not a chain of helper calls + frames = traceback.extract_tb(error.__traceback__) + self.assertEqual([f.name for f in frames][-1], "Read") + self.assertEqual(len(frames), 2, [f.name for f in frames]) # test + Read + self.assertIsNone(error.__cause__) + self.assertTrue(error.__suppress_context__) + + def test_iread_missing_file(self): + from machinevisiontoolbox import iread + + with self.assertRaises(FileNotFoundError): + iread("flowers.png") + def tearDown(self): # remove the test image file try: @@ -59,7 +100,7 @@ def test_matfile_in_mvtbdata(self): self.assertEqual(data["bunny"].ndim, 2) def test_matfile_missing_raises(self): - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): mvtb_load_matfile("data/__not_there__.mat") def test_matfile_struct_becomes_namedtuple(self): @@ -100,7 +141,7 @@ def test_jsonfile(self): self.assertEqual(data, {"name": "cube", "n": [1, 2, 3]}) def test_jsonfile_missing_raises(self): - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): mvtb_load_jsonfile("__not_there__.json") @@ -115,7 +156,7 @@ def test_absolute_path(self): ) # an absolute path that does not exist is an error, with no search of mvtbdata - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): mvtb_path_to_datafile(Path(tmp) / "gone.dat") def test_string_result(self): diff --git a/tests/base/test_file_picker.py b/tests/base/test_file_picker.py index 64d9595b..8de35117 100644 --- a/tests/base/test_file_picker.py +++ b/tests/base/test_file_picker.py @@ -21,7 +21,12 @@ def picker(monkeypatch): @pytest.mark.parametrize( - "error", [ModuleNotFoundError("mvtbdata"), ValueError("missing images")] + "error", + [ + ModuleNotFoundError("mvtbdata"), + FileNotFoundError("missing images"), + ValueError("missing images"), + ], ) def test_missing_data_uses_home(monkeypatch, picker, error): monkeypatch.setattr(imageio, "mvtb_path_to_datafile", Mock(side_effect=error)) diff --git a/tests/base/test_io.py b/tests/base/test_io.py index 20a7c624..2dbce833 100644 --- a/tests/base/test_io.py +++ b/tests/base/test_io.py @@ -282,7 +282,7 @@ def test_iread_with_dtype(self): def test_iread_invalid_file(self): """Test iread with non-existent file""" - with self.assertRaises(ValueError): + with self.assertRaises(FileNotFoundError): iread("nonexistent_file_12345.png") def test_iread_file_path(self): diff --git a/tests/test_image_sources.py b/tests/test_image_sources.py index 2ee55225..1e75764d 100644 --- a/tests/test_image_sources.py +++ b/tests/test_image_sources.py @@ -55,7 +55,7 @@ def _has_file(*args): try: mvtb_path_to_datafile(*args) return True - except ValueError: + except FileNotFoundError: return False