diff --git a/arkindex_worker/models.py b/arkindex_worker/models.py index a29811db4132df5e0ac360245d2d5675c0471b09..ae6eb85fc1cb1a91fa0db9e06ed7b94175c6a913 100644 --- a/arkindex_worker/models.py +++ b/arkindex_worker/models.py @@ -5,7 +5,7 @@ Wrappers around API results to provide more convenient attribute access and IIIF import tempfile from contextlib import contextmanager -from typing import Generator, Optional +from typing import Generator, List, Optional from PIL import Image from requests import HTTPError @@ -93,6 +93,19 @@ class Element(MagicDict): url += "/" return "{}full/{}/0/default.jpg".format(url, size) + @property + def polygon(self) -> List[float]: + """ + Access an Element's polygon. + This is a shortcut to an Element's polygon, normally accessed via + its zone field via `zone.polygon`. This is mostly done + to facilitate access to this important field by matching + the [CachedElement][arkindex_worker.cache.CachedElement].polygon field. + """ + if not self.get("zone"): + raise ValueError("Element {} has no zone".format(self.id)) + return self.zone.polygon + @property def requires_tiles(self) -> bool: """ diff --git a/tests/test_element.py b/tests/test_element.py index 960d6eda79a5e1a22644cabac6b1347e6c4b27f2..e26e2973f57d2f2779e5426d7a6442ade986990c 100644 --- a/tests/test_element.py +++ b/tests/test_element.py @@ -2,6 +2,7 @@ import pytest from requests import HTTPError +from arkindex_worker.cache import CachedElement from arkindex_worker.models import Element @@ -402,3 +403,17 @@ def test_setattr_setitem(): element = Element({"name": "something"}) element.type = "page" assert dict(element) == {"name": "something", "type": "page"} + + +def test_element_polygon(): + polygon = [[0, 0], [181, 0], [181, 240], [0, 240], [0, 0]] + element = Element({"zone": {"polygon": polygon}}) + cached_element = CachedElement(polygon=polygon) + assert element.polygon == polygon + assert element.polygon == cached_element.polygon + + +def test_element_no_polygon(): + element = Element(id="element_id") + with pytest.raises(ValueError, match="Element element_id has no zone"): + _ = element.polygon