From eb0abab639682e728dfbba698fa56ec9fb613092 Mon Sep 17 00:00:00 2001 From: Yoann Schneider <yschneider@teklia.com> Date: Mon, 3 Oct 2022 13:10:17 +0000 Subject: [PATCH] Add element polygon shortcut as a property --- arkindex_worker/models.py | 15 ++++++++++++++- tests/test_element.py | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/arkindex_worker/models.py b/arkindex_worker/models.py index a29811db..ae6eb85f 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 960d6eda..e26e2973 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 -- GitLab