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
23 changes: 13 additions & 10 deletions src/machinevisiontoolbox/Sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -4444,6 +4444,12 @@ class LabelMeReader:

:param filename: path to LabelMe JSON file, or an ``http(s)://`` URL
:type filename: str
:raises OSError: if the file cannot be opened or the URL cannot be fetched
:raises json.JSONDecodeError: if the content is not valid JSON

.. versionchanged:: 2.5.0
An unreadable file or invalid JSON now raises, where it used to return an
incompletely initialised reader.

LabelMe is a popular annotation tool that saves annotations in a JSON format. This
class reads the JSON file and extracts the image, polygonal shapes, and associated
Expand Down Expand Up @@ -4492,17 +4498,14 @@ class reads the JSON file and extracts the image, polygonal shapes, and associat
def __init__(self, filename: str) -> None:
self.filename = filename

try:
if str(filename).startswith(("http://", "https://")):
import urllib.request
if str(filename).startswith(("http://", "https://")):
import urllib.request

with urllib.request.urlopen(filename) as response: # noqa: S310
self.data = json.loads(response.read().decode("utf-8"))
else:
with open(self.filename, "r", encoding="utf-8") as f:
self.data = json.load(f)
except (OSError, json.JSONDecodeError, TypeError, ValueError):
return None
with urllib.request.urlopen(filename) as response: # noqa: S310
self.data = json.loads(response.read().decode("utf-8"))
else:
with open(self.filename, "r", encoding="utf-8") as f:
self.data = json.load(f)
self._nshapes = len(self.data.get("shapes", []))
self._version = self.data.get("version")

Expand Down
21 changes: 21 additions & 0 deletions tests/test_image_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,27 @@ def test_labelme_read(self):
self.assertEqual(shapes[1].flags, {"hard": False})


class TestLabelMeReaderErrors(unittest.TestCase):
"""A LabelMe file that cannot be read raises, it does not return a half-built reader."""

def test_missing_file_raises(self):
from machinevisiontoolbox import LabelMeReader

with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(FileNotFoundError):
LabelMeReader(os.path.join(tmp, "missing.json"))

def test_invalid_json_raises(self):
from machinevisiontoolbox import LabelMeReader

with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "bad.json")
with open(path, "w", encoding="utf-8") as f:
f.write("{ this is not json")
with self.assertRaises(json.JSONDecodeError):
LabelMeReader(path)


class TestEarthViewKey(unittest.TestCase):
"""How EarthView finds its API key (no network access needed)."""

Expand Down
Loading