Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/machinevisiontoolbox/ImageIO.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/Sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
34 changes: 31 additions & 3 deletions src/machinevisiontoolbox/base/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from __future__ import annotations

import difflib
import importlib
import importlib.resources
from pathlib import Path
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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))
12 changes: 11 additions & 1 deletion src/machinevisiontoolbox/base/imageio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/bin/imtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/bin/ocrtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/bin/tagtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
53 changes: 47 additions & 6 deletions tests/base/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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):
Expand Down Expand Up @@ -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")


Expand All @@ -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):
Expand Down
7 changes: 6 additions & 1 deletion tests/base/test_file_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion tests/base/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_image_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _has_file(*args):
try:
mvtb_path_to_datafile(*args)
return True
except ValueError:
except FileNotFoundError:
return False


Expand Down
Loading