Skip to content

Commit 4bd8c11

Browse files
authored
chore: raise file not found for images (#19)
When trying to open an image in the from_image_file method, trying to open an empty filename would produce some non-helpful error, when ideally it should raise FileNotFoundError. This PR ensures that a FileNotFoundError is raised.
1 parent 02f7c25 commit 4bd8c11

File tree

4 files changed

+22
-4
lines changed

4 files changed

+22
-4
lines changed

CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
## 0.2.4-dev0
1+
## 0.2.4-dev1
22

3-
* Requirements bumps (delete this line with first real CHANGELOG cahnge)
3+
* Clarify error when trying to open file that doesn't exist as an image
44

55
## 0.2.3
66

test_unstructured_inference/inference/test_layout.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import pytest
2+
import tempfile
23
from unittest.mock import patch, mock_open
34

45
import layoutparser as lp
@@ -267,3 +268,13 @@ def mock_get_elements(self, *args, **kwargs):
267268
.elements
268269
)
269270
assert elements[0] == mock_page_layout
271+
272+
273+
def test_from_image_file_raises_with_empty_fn():
274+
with pytest.raises(FileNotFoundError):
275+
layout.DocumentLayout.from_image_file("")
276+
277+
278+
def test_from_image_file_raises_isadirectoryerror_with_dir():
279+
with tempfile.TemporaryDirectory() as tempdir, pytest.raises(IsADirectoryError):
280+
layout.DocumentLayout.from_image_file(tempdir)
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "0.2.4-dev0" # pragma: no cover
1+
__version__ = "0.2.4-dev1" # pragma: no cover

unstructured_inference/inference/layout.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22
from dataclasses import dataclass
3+
import os
34
import re
45
import tempfile
56
from typing import List, Optional, Tuple, Union, BinaryIO
@@ -76,7 +77,13 @@ def from_file(cls, filename: str, model: Optional[Detectron2LayoutModel] = None)
7677
def from_image_file(cls, filename: str, model: Optional[Detectron2LayoutModel] = None):
7778
"""Creates a DocumentLayout from an image file."""
7879
logger.info(f"Reading image file: {filename} ...")
79-
image = Image.open(filename)
80+
try:
81+
image = Image.open(filename)
82+
except Exception as e:
83+
if os.path.isdir(filename) or os.path.isfile(filename):
84+
raise e
85+
else:
86+
raise FileNotFoundError(f'File "{filename}" not found!') from e
8087
page = PageLayout(number=0, image=image, layout=None, model=model)
8188
page.get_elements()
8289
return cls.from_pages([page])

0 commit comments

Comments
 (0)