Skip to content

Element

arkindex_worker.worker.element

ElementsWorker methods for elements and element types.

Classes

ElementType

Bases: NamedTuple

Arkindex Type of an element

MissingTypeError

Bases: Exception

A required element type was not found in a corpus.

ElementMixin

Functions
create_required_types
create_required_types(element_types: list[ElementType])

Creates given element types in the corpus.

Parameters:

Name Type Description Default
element_types list[ElementType]

The missing element types to create.

required
Source code in arkindex_worker/worker/element.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@unsupported_cache
def create_required_types(self, element_types: list[ElementType]):
    """Creates given element types in the corpus.

    :param element_types: The missing element types to create.
    """
    for element_type in element_types:
        self.request(
            "CreateElementType",
            body={
                "slug": element_type.slug,
                "display_name": element_type.name,
                "folder": element_type.is_folder,
                "corpus": self.corpus_id,
            },
        )
        logger.info(f"Created a new element type with slug {element_type.slug}")
check_required_types
check_required_types(
    *type_slugs: str, create_missing: bool = False
) -> bool

Check that a corpus has a list of required element types, and raise an exception if any of them are missing.

Parameters:

Name Type Description Default
*type_slugs str

Type slugs to look for.

()
create_missing bool

Whether missing types should be created.

False

Returns:

Type Description
bool

Whether all of the specified type slugs have been found.

Raises:

Type Description
MissingTypeError

If any of the specified type slugs were not found.

Source code in arkindex_worker/worker/element.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def check_required_types(
    self, *type_slugs: str, create_missing: bool = False
) -> bool:
    """
    Check that a corpus has a list of required element types,
    and raise an exception if any of them are missing.

    :param *type_slugs: Type slugs to look for.
    :param create_missing: Whether missing types should be created.
    :returns: Whether all of the specified type slugs have been found.
    :raises MissingTypeError: If any of the specified type slugs were not found.
    """
    assert len(type_slugs), "At least one element type slug is required."
    assert all(
        isinstance(slug, str) for slug in type_slugs
    ), "Element type slugs must be strings."

    corpus = self.request("RetrieveCorpus", id=self.corpus_id)
    available_slugs = {element_type["slug"] for element_type in corpus["types"]}
    missing_slugs = set(type_slugs) - available_slugs

    if missing_slugs:
        if create_missing:
            self.create_required_types(
                element_types=[
                    ElementType(slug, slug, False) for slug in missing_slugs
                ],
            )
        else:
            raise MissingTypeError(
                f'Element type(s) {", ".join(sorted(missing_slugs))} were not found in the {corpus["name"]} corpus ({corpus["id"]}).'
            )

    return True
create_sub_element
create_sub_element(
    element: Element,
    type: str,
    name: str,
    polygon: list[list[int | float]] | None = None,
    confidence: float | None = None,
    image: str | None = None,
    slim_output: bool = True,
) -> str

Create a child element on the given element through the API.

Parameters:

Name Type Description Default
element Element

The parent element.

required
type str

Slug of the element type for this child element.

required
name str

Name of the child element.

required
polygon list[list[int | float]] | None

Optional polygon of the child element.

None
confidence float | None

Optional confidence score, between 0.0 and 1.0.

None
image str | None

Optional image ID of the child element.

None
slim_output bool

Whether to return the child ID or the full child.

True

Returns:

Type Description
str

UUID of the created element.

Source code in arkindex_worker/worker/element.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@unsupported_cache
def create_sub_element(
    self,
    element: Element,
    type: str,
    name: str,
    polygon: list[list[int | float]] | None = None,
    confidence: float | None = None,
    image: str | None = None,
    slim_output: bool = True,
) -> str:
    """
    Create a child element on the given element through the API.

    :param Element element: The parent element.
    :param type: Slug of the element type for this child element.
    :param name: Name of the child element.
    :param polygon: Optional polygon of the child element.
    :param confidence: Optional confidence score, between 0.0 and 1.0.
    :param image: Optional image ID of the child element.
    :param slim_output: Whether to return the child ID or the full child.
    :returns: UUID of the created element.
    """
    assert element and isinstance(
        element, Element
    ), "element shouldn't be null and should be of type Element"
    assert type and isinstance(
        type, str
    ), "type shouldn't be null and should be of type str"
    assert name and isinstance(
        name, str
    ), "name shouldn't be null and should be of type str"
    assert polygon is None or isinstance(
        polygon, list
    ), "polygon should be None or a list"
    if polygon is not None:
        assert len(polygon) >= 3, "polygon should have at least three points"
        assert all(
            isinstance(point, list) and len(point) == 2 for point in polygon
        ), "polygon points should be lists of two items"
        assert all(
            isinstance(coord, int | float) for point in polygon for coord in point
        ), "polygon points should be lists of two numbers"
    assert confidence is None or (
        isinstance(confidence, float) and 0 <= confidence <= 1
    ), "confidence should be None or a float in [0..1] range"
    assert image is None or isinstance(image, str), "image should be None or string"
    if image is not None:
        # Make sure it's a valid UUID
        try:
            UUID(image)
        except ValueError as e:
            raise ValueError("image is not a valid uuid.") from e
    if polygon and image is None:
        assert element.zone, "An image or a parent with an image is required to create an element with a polygon."
    assert isinstance(slim_output, bool), "slim_output should be of type bool"

    if self.is_read_only:
        logger.warning("Cannot create element as this worker is in read-only mode")
        return

    sub_element = self.request(
        "CreateElement",
        body={
            "type": type,
            "name": name,
            "image": image,
            "corpus": element.corpus.id,
            "polygon": polygon,
            "parent": element.id,
            "worker_run_id": self.worker_run_id,
            "confidence": confidence,
        },
    )

    return sub_element["id"] if slim_output else sub_element
create_elements
create_elements(
    parent: Element | CachedElement,
    elements: list[
        dict[
            str,
            str | list[list[int | float]] | float | None,
        ]
    ],
) -> list[dict[str, str]]

Create child elements on the given element in a single API request.

Parameters:

Name Type Description Default
parent Element | CachedElement

Parent element for all the new child elements. The parent must have an image and a polygon.

required
elements list[dict[str, str | list[list[int | float]] | float | None]]

List of dicts, one per element. Each dict can have the following keys: name (str) Required. Name of the element. type (str) Required. Slug of the element type for this element. polygon (list(list(int or float))) Required. Polygon for this child element. Must have at least three points, with each point having two non-negative coordinates and being inside of the parent element’s image. confidence (float or None) Optional confidence score, between 0.0 and 1.0.

required

Returns:

Type Description
list[dict[str, str]]

List of dicts, with each dict having a single key, id, holding the UUID of each created element.

Source code in arkindex_worker/worker/element.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def create_elements(
    self,
    parent: Element | CachedElement,
    elements: list[dict[str, str | list[list[int | float]] | float | None]],
) -> list[dict[str, str]]:
    """
    Create child elements on the given element in a single API request.

    :param parent: Parent element for all the new child elements. The parent must have an image and a polygon.
    :param elements: List of dicts, one per element. Each dict can have the following keys:

        name (str)
           Required. Name of the element.

        type (str)
           Required. Slug of the element type for this element.

        polygon (list(list(int or float)))
           Required. Polygon for this child element. Must have at least three points, with each point
           having two non-negative coordinates and being inside of the parent element's image.

        confidence (float or None)
            Optional confidence score, between 0.0 and 1.0.

    :return: List of dicts, with each dict having a single key, ``id``, holding the UUID of each created element.
    """
    if isinstance(parent, Element):
        assert parent.get(
            "zone"
        ), "create_elements cannot be used on parents without zones"
    elif isinstance(parent, CachedElement):
        assert (
            parent.image_id
        ), "create_elements cannot be used on parents without images"
    else:
        raise TypeError(
            "Parent element should be an Element or CachedElement instance"
        )

    assert elements and isinstance(
        elements, list
    ), "elements shouldn't be null and should be of type list"

    for index, element in enumerate(elements):
        assert isinstance(
            element, dict
        ), f"Element at index {index} in elements: Should be of type dict"

        name = element.get("name")
        assert (
            name and isinstance(name, str)
        ), f"Element at index {index} in elements: name shouldn't be null and should be of type str"

        type = element.get("type")
        assert (
            type and isinstance(type, str)
        ), f"Element at index {index} in elements: type shouldn't be null and should be of type str"

        polygon = element.get("polygon")
        assert (
            polygon and isinstance(polygon, list)
        ), f"Element at index {index} in elements: polygon shouldn't be null and should be of type list"
        assert (
            len(polygon) >= 3
        ), f"Element at index {index} in elements: polygon should have at least three points"
        assert all(
            isinstance(point, list) and len(point) == 2 for point in polygon
        ), f"Element at index {index} in elements: polygon points should be lists of two items"
        assert all(
            isinstance(coord, int | float) for point in polygon for coord in point
        ), f"Element at index {index} in elements: polygon points should be lists of two numbers"

        confidence = element.get("confidence")
        assert (
            confidence is None
            or (isinstance(confidence, float) and 0 <= confidence <= 1)
        ), f"Element at index {index} in elements: confidence should be None or a float in [0..1] range"

    if self.is_read_only:
        logger.warning("Cannot create elements as this worker is in read-only mode")
        return

    created_ids = self.request(
        "CreateElements",
        id=parent.id,
        body={
            "worker_run_id": self.worker_run_id,
            "elements": elements,
        },
    )

    if self.use_cache:
        # Create the image as needed and handle both an Element and a CachedElement
        if isinstance(parent, CachedElement):
            image_id = parent.image_id
        else:
            image_id = parent.zone.image.id
            CachedImage.get_or_create(
                id=parent.zone.image.id,
                defaults={
                    "width": parent.zone.image.width,
                    "height": parent.zone.image.height,
                    "url": parent.zone.image.url,
                },
            )

        # Store elements in local cache
        try:
            to_insert = [
                {
                    "id": created_ids[idx]["id"],
                    "parent_id": parent.id,
                    "type": element["type"],
                    "image_id": image_id,
                    "polygon": element["polygon"],
                    "worker_run_id": self.worker_run_id,
                    "confidence": element.get("confidence"),
                }
                for idx, element in enumerate(elements)
            ]
            CachedElement.insert_many(to_insert).execute()
        except IntegrityError as e:
            logger.warning(f"Couldn't save created elements in local cache: {e}")

    return created_ids
create_element_parent
create_element_parent(
    parent: Element, child: Element
) -> dict[str, str]

Link an element to a parent through the API.

Parameters:

Name Type Description Default
parent Element

Parent element.

required
child Element

Child element.

required

Returns:

Type Description
dict[str, str]

A dict from the CreateElementParent API endpoint.

Source code in arkindex_worker/worker/element.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
@unsupported_cache
def create_element_parent(
    self,
    parent: Element,
    child: Element,
) -> dict[str, str]:
    """
    Link an element to a parent through the API.

    :param parent: Parent element.
    :param child: Child element.
    :returns: A dict from the ``CreateElementParent`` API endpoint.
    """
    assert parent and isinstance(
        parent, Element
    ), "parent shouldn't be null and should be of type Element"
    assert child and isinstance(
        child, Element
    ), "child shouldn't be null and should be of type Element"

    if self.is_read_only:
        logger.warning("Cannot link elements as this worker is in read-only mode")
        return

    return self.request(
        "CreateElementParent",
        parent=parent.id,
        child=child.id,
    )
partial_update_element
partial_update_element(
    element: Element | CachedElement, **kwargs
) -> dict

Partially updates an element through the API.

Parameters:

Name Type Description Default
element Element | CachedElement

The element to update.

required
**kwargs
  • type (str): Optional slug type of the element. * name (str): Optional name of the element. * polygon (list): Optional polygon for this element * confidence (float): Optional confidence score of this element * rotation_angle (int): Optional rotation angle of this element * mirrored (bool): Optional mirror status of this element * image (UUID): Optional ID of the image of this element
{}

Returns:

Type Description
dict

A dict from the PartialUpdateElement API endpoint.

Source code in arkindex_worker/worker/element.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def partial_update_element(
    self, element: Element | CachedElement, **kwargs
) -> dict:
    """
    Partially updates an element through the API.

    :param element: The element to update.
    :param **kwargs:

        * *type* (``str``): Optional slug type of the element.
        * *name* (``str``): Optional name of the element.
        * *polygon* (``list``): Optional polygon for this element
        * *confidence* (``float``): Optional confidence score of this element
        * *rotation_angle* (``int``): Optional rotation angle of this element
        * *mirrored* (``bool``): Optional mirror status of this element
        * *image* (``UUID``): Optional ID of the image of this element


    :returns: A dict from the ``PartialUpdateElement`` API endpoint.
    """
    assert element and isinstance(
        element, Element | CachedElement
    ), "element shouldn't be null and should be an Element or CachedElement"

    if "type" in kwargs:
        assert isinstance(kwargs["type"], str), "type should be a str"

    if "name" in kwargs:
        assert isinstance(kwargs["name"], str), "name should be a str"

    if "polygon" in kwargs:
        polygon = kwargs["polygon"]
        assert isinstance(polygon, list), "polygon should be a list"
        assert len(polygon) >= 3, "polygon should have at least three points"
        assert all(
            isinstance(point, list) and len(point) == 2 for point in polygon
        ), "polygon points should be lists of two items"
        assert all(
            isinstance(coord, int | float) for point in polygon for coord in point
        ), "polygon points should be lists of two numbers"

    if "confidence" in kwargs:
        confidence = kwargs["confidence"]
        assert confidence is None or (
            isinstance(confidence, float) and 0 <= confidence <= 1
        ), "confidence should be None or a float in [0..1] range"

    if "rotation_angle" in kwargs:
        rotation_angle = kwargs["rotation_angle"]
        assert (
            isinstance(rotation_angle, int) and rotation_angle >= 0
        ), "rotation_angle should be a positive integer"

    if "mirrored" in kwargs:
        assert isinstance(kwargs["mirrored"], bool), "mirrored should be a boolean"

    if "image" in kwargs:
        image = kwargs["image"]
        assert isinstance(image, UUID), "image should be a UUID"
        # Cast to string
        kwargs["image"] = str(image)

    if self.is_read_only:
        logger.warning("Cannot update element as this worker is in read-only mode")
        return

    updated_element = self.request(
        "PartialUpdateElement",
        id=element.id,
        body=kwargs,
    )

    if self.use_cache:
        # Name is not present in CachedElement model
        kwargs.pop("name", None)

        # Stringify polygon if present
        if "polygon" in kwargs:
            kwargs["polygon"] = str(kwargs["polygon"])

        # Retrieve the right image
        if "image" in kwargs:
            kwargs["image"] = CachedImage.get_by_id(kwargs["image"])

        CachedElement.update(**kwargs).where(
            CachedElement.id == element.id
        ).execute()

    return updated_element
list_element_children
list_element_children(
    element: Element | CachedElement,
    folder: bool | None = None,
    name: str | None = None,
    recursive: bool | None = None,
    transcription_worker_version: str | bool | None = None,
    transcription_worker_run: str | bool | None = None,
    type: str | None = None,
    with_classes: bool | None = None,
    with_corpus: bool | None = None,
    with_metadata: bool | None = None,
    with_has_children: bool | None = None,
    with_zone: bool | None = None,
    worker_version: str | bool | None = None,
    worker_run: str | bool | None = None,
) -> Iterable[dict] | Iterable[CachedElement]

List children of an element.

Warns:

The following parameters are deprecated:

  • transcription_worker_version in favor of transcription_worker_run
  • worker_version in favor of worker_run

Parameters:

Name Type Description Default
element Element | CachedElement

Parent element to find children of.

required
folder bool | None

Restrict to or exclude elements with folder types. This parameter is not supported when caching is enabled.

None
name str | None

Restrict to elements whose name contain a substring (case-insensitive). This parameter is not supported when caching is enabled.

None
recursive bool | None

Look for elements recursively (grand-children, etc.) This parameter is not supported when caching is enabled.

None
transcription_worker_version str | bool | None

Deprecated Restrict to elements that have a transcription created by a worker version with this UUID. Set to False to look for elements that have a manual transcription. This parameter is not supported when caching is enabled.

None
transcription_worker_run str | bool | None

Restrict to elements that have a transcription created by a worker run with this UUID. Set to False to look for elements that have a manual transcription. This parameter is not supported when caching is enabled.

None
type str | None

Restrict to elements with a specific type slug This parameter is not supported when caching is enabled.

None
with_classes bool | None

Include each element’s classifications in the response. This parameter is not supported when caching is enabled.

None
with_corpus bool | None

Include each element’s corpus in the response. This parameter is not supported when caching is enabled.

None
with_has_children bool | None

Include the has_children attribute in the response, indicating if this element has child elements of its own. This parameter is not supported when caching is enabled.

None
with_metadata bool | None

Include each element’s metadata in the response. This parameter is not supported when caching is enabled.

None
with_zone bool | None

Include the zone attribute in the response, holding the element’s image and polygon. This parameter is not supported when caching is enabled.

None
worker_version str | bool | None

Deprecated Restrict to elements created by a worker version with this UUID.

None
worker_run str | bool | None

Restrict to elements created by a worker run with this UUID.

None

Returns:

Type Description
Iterable[dict] | Iterable[CachedElement]

An iterable of dicts from the ListElementChildren API endpoint, or an iterable of CachedElement when caching is enabled.

Source code in arkindex_worker/worker/element.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
def list_element_children(
    self,
    element: Element | CachedElement,
    folder: bool | None = None,
    name: str | None = None,
    recursive: bool | None = None,
    transcription_worker_version: str | bool | None = None,
    transcription_worker_run: str | bool | None = None,
    type: str | None = None,
    with_classes: bool | None = None,
    with_corpus: bool | None = None,
    with_metadata: bool | None = None,
    with_has_children: bool | None = None,
    with_zone: bool | None = None,
    worker_version: str | bool | None = None,
    worker_run: str | bool | None = None,
) -> Iterable[dict] | Iterable[CachedElement]:
    """
    List children of an element.

    Warns:
    ----
    The following parameters are **deprecated**:

    - `transcription_worker_version` in favor of `transcription_worker_run`
    - `worker_version` in favor of `worker_run`

    :param element: Parent element to find children of.
    :param folder: Restrict to or exclude elements with folder types.
       This parameter is not supported when caching is enabled.
    :param name: Restrict to elements whose name contain a substring (case-insensitive).
       This parameter is not supported when caching is enabled.
    :param recursive: Look for elements recursively (grand-children, etc.)
       This parameter is not supported when caching is enabled.
    :param transcription_worker_version: **Deprecated** Restrict to elements that have a transcription created by a worker version with this UUID. Set to False to look for elements that have a manual transcription.
       This parameter is not supported when caching is enabled.
    :param transcription_worker_run: Restrict to elements that have a transcription created by a worker run with this UUID. Set to False to look for elements that have a manual transcription.
       This parameter is not supported when caching is enabled.
    :param type: Restrict to elements with a specific type slug
       This parameter is not supported when caching is enabled.
    :param with_classes: Include each element's classifications in the response.
       This parameter is not supported when caching is enabled.
    :param with_corpus: Include each element's corpus in the response.
       This parameter is not supported when caching is enabled.
    :param with_has_children: Include the ``has_children`` attribute in the response,
       indicating if this element has child elements of its own.
       This parameter is not supported when caching is enabled.
    :param with_metadata: Include each element's metadata in the response.
       This parameter is not supported when caching is enabled.
    :param with_zone: Include the ``zone`` attribute in the response,
       holding the element's image and polygon.
       This parameter is not supported when caching is enabled.
    :param worker_version: **Deprecated** Restrict to elements created by a worker version with this UUID.
    :param worker_run: Restrict to elements created by a worker run with this UUID.
    :return: An iterable of dicts from the ``ListElementChildren`` API endpoint,
       or an iterable of [CachedElement][arkindex_worker.cache.CachedElement] when caching is enabled.
    """
    assert element and isinstance(
        element, Element | CachedElement
    ), "element shouldn't be null and should be an Element or CachedElement"
    query_params = {}
    if folder is not None:
        assert isinstance(folder, bool), "folder should be of type bool"
        query_params["folder"] = folder
    if name:
        assert isinstance(name, str), "name should be of type str"
        query_params["name"] = name
    if recursive is not None:
        assert isinstance(recursive, bool), "recursive should be of type bool"
        query_params["recursive"] = recursive
    if transcription_worker_version is not None:
        warn(
            "`transcription_worker_version` usage is deprecated. Consider using `transcription_worker_run` instead.",
            DeprecationWarning,
            stacklevel=1,
        )
        assert isinstance(
            transcription_worker_version, str | bool
        ), "transcription_worker_version should be of type str or bool"
        if isinstance(transcription_worker_version, bool):
            assert (
                transcription_worker_version is False
            ), "if of type bool, transcription_worker_version can only be set to False"
        query_params["transcription_worker_version"] = transcription_worker_version
    if transcription_worker_run is not None:
        assert isinstance(
            transcription_worker_run, str | bool
        ), "transcription_worker_run should be of type str or bool"
        if isinstance(transcription_worker_run, bool):
            assert (
                transcription_worker_run is False
            ), "if of type bool, transcription_worker_run can only be set to False"
        query_params["transcription_worker_run"] = transcription_worker_run
    if type:
        assert isinstance(type, str), "type should be of type str"
        query_params["type"] = type
    if with_classes is not None:
        assert isinstance(with_classes, bool), "with_classes should be of type bool"
        query_params["with_classes"] = with_classes
    if with_corpus is not None:
        assert isinstance(with_corpus, bool), "with_corpus should be of type bool"
        query_params["with_corpus"] = with_corpus
    if with_has_children is not None:
        assert isinstance(
            with_has_children, bool
        ), "with_has_children should be of type bool"
        query_params["with_has_children"] = with_has_children
    if with_metadata is not None:
        assert isinstance(
            with_metadata, bool
        ), "with_metadata should be of type bool"
        query_params["with_metadata"] = with_metadata
    if with_zone is not None:
        assert isinstance(with_zone, bool), "with_zone should be of type bool"
        query_params["with_zone"] = with_zone
    if worker_version is not None:
        warn(
            "`worker_version` usage is deprecated. Consider using `worker_run` instead.",
            DeprecationWarning,
            stacklevel=1,
        )
        assert isinstance(
            worker_version, str | bool
        ), "worker_version should be of type str or bool"
        if isinstance(worker_version, bool):
            assert (
                worker_version is False
            ), "if of type bool, worker_version can only be set to False"
        query_params["worker_version"] = worker_version
    if worker_run is not None:
        assert isinstance(
            worker_run, str | bool
        ), "worker_run should be of type str or bool"
        if isinstance(worker_run, bool):
            assert (
                worker_run is False
            ), "if of type bool, worker_run can only be set to False"
        query_params["worker_run"] = worker_run

    if self.use_cache:
        # Checking that we only received query_params handled by the cache
        assert (
            set(query_params.keys())
            <= {
                "type",
                "worker_version",
                "worker_run",
            }
        ), "When using the local cache, you can only filter by 'type' and/or 'worker_version' and/or 'worker_run'"

        query = CachedElement.select().where(CachedElement.parent_id == element.id)
        if type:
            query = query.where(CachedElement.type == type)
        if worker_version is not None:
            # If worker_version=False, filter by manual worker_version e.g. None
            worker_version_id = worker_version or None
            if worker_version_id:
                query = query.where(
                    CachedElement.worker_version_id == worker_version_id
                )
            else:
                query = query.where(CachedElement.worker_version_id.is_null())

        if worker_run is not None:
            # If worker_run=False, filter by manual worker_run e.g. None
            worker_run_id = worker_run or None
            if worker_run_id:
                query = query.where(CachedElement.worker_run_id == worker_run_id)
            else:
                query = query.where(CachedElement.worker_run_id.is_null())

        return query
    else:
        children = self.api_client.paginate(
            "ListElementChildren", id=element.id, **query_params
        )

    return children
list_element_parents
list_element_parents(
    element: Element | CachedElement,
    folder: bool | None = None,
    name: str | None = None,
    recursive: bool | None = None,
    transcription_worker_version: str | bool | None = None,
    transcription_worker_run: str | bool | None = None,
    type: str | None = None,
    with_classes: bool | None = None,
    with_corpus: bool | None = None,
    with_metadata: bool | None = None,
    with_has_children: bool | None = None,
    with_zone: bool | None = None,
    worker_version: str | bool | None = None,
    worker_run: str | bool | None = None,
) -> Iterable[dict] | Iterable[CachedElement]

List parents of an element.

Warns:

The following parameters are deprecated:

  • transcription_worker_version in favor of transcription_worker_run
  • worker_version in favor of worker_run

Parameters:

Name Type Description Default
element Element | CachedElement

Child element to find parents of.

required
folder bool | None

Restrict to or exclude elements with folder types. This parameter is not supported when caching is enabled.

None
name str | None

Restrict to elements whose name contain a substring (case-insensitive). This parameter is not supported when caching is enabled.

None
recursive bool | None

Look for elements recursively (grand-children, etc.) This parameter is not supported when caching is enabled.

None
transcription_worker_version str | bool | None

Deprecated Restrict to elements that have a transcription created by a worker version with this UUID. This parameter is not supported when caching is enabled.

None
transcription_worker_run str | bool | None

Restrict to elements that have a transcription created by a worker run with this UUID. This parameter is not supported when caching is enabled.

None
type str | None

Restrict to elements with a specific type slug This parameter is not supported when caching is enabled.

None
with_classes bool | None

Include each element’s classifications in the response. This parameter is not supported when caching is enabled.

None
with_corpus bool | None

Include each element’s corpus in the response. This parameter is not supported when caching is enabled.

None
with_has_children bool | None

Include the has_children attribute in the response, indicating if this element has child elements of its own. This parameter is not supported when caching is enabled.

None
with_metadata bool | None

Include each element’s metadata in the response. This parameter is not supported when caching is enabled.

None
with_zone bool | None

Include the zone attribute in the response, holding the element’s image and polygon. This parameter is not supported when caching is enabled.

None
worker_version str | bool | None

Deprecated Restrict to elements created by a worker version with this UUID.

None
worker_run str | bool | None

Restrict to elements created by a worker run with this UUID.

None

Returns:

Type Description
Iterable[dict] | Iterable[CachedElement]

An iterable of dicts from the ListElementParents API endpoint, or an iterable of CachedElement when caching is enabled.

Source code in arkindex_worker/worker/element.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
def list_element_parents(
    self,
    element: Element | CachedElement,
    folder: bool | None = None,
    name: str | None = None,
    recursive: bool | None = None,
    transcription_worker_version: str | bool | None = None,
    transcription_worker_run: str | bool | None = None,
    type: str | None = None,
    with_classes: bool | None = None,
    with_corpus: bool | None = None,
    with_metadata: bool | None = None,
    with_has_children: bool | None = None,
    with_zone: bool | None = None,
    worker_version: str | bool | None = None,
    worker_run: str | bool | None = None,
) -> Iterable[dict] | Iterable[CachedElement]:
    """
    List parents of an element.

    Warns:
    ----
    The following parameters are **deprecated**:

    - `transcription_worker_version` in favor of `transcription_worker_run`
    - `worker_version` in favor of `worker_run`

    :param element: Child element to find parents of.
    :param folder: Restrict to or exclude elements with folder types.
       This parameter is not supported when caching is enabled.
    :param name: Restrict to elements whose name contain a substring (case-insensitive).
       This parameter is not supported when caching is enabled.
    :param recursive: Look for elements recursively (grand-children, etc.)
       This parameter is not supported when caching is enabled.
    :param transcription_worker_version: **Deprecated** Restrict to elements that have a transcription created by a worker version with this UUID.
       This parameter is not supported when caching is enabled.
    :param transcription_worker_run: Restrict to elements that have a transcription created by a worker run with this UUID.
       This parameter is not supported when caching is enabled.
    :param type: Restrict to elements with a specific type slug
       This parameter is not supported when caching is enabled.
    :param with_classes: Include each element's classifications in the response.
       This parameter is not supported when caching is enabled.
    :param with_corpus: Include each element's corpus in the response.
       This parameter is not supported when caching is enabled.
    :param with_has_children: Include the ``has_children`` attribute in the response,
       indicating if this element has child elements of its own.
       This parameter is not supported when caching is enabled.
    :param with_metadata: Include each element's metadata in the response.
       This parameter is not supported when caching is enabled.
    :param with_zone: Include the ``zone`` attribute in the response,
       holding the element's image and polygon.
       This parameter is not supported when caching is enabled.
    :param worker_version: **Deprecated** Restrict to elements created by a worker version with this UUID.
    :param worker_run: Restrict to elements created by a worker run with this UUID.
    :return: An iterable of dicts from the ``ListElementParents`` API endpoint,
       or an iterable of [CachedElement][arkindex_worker.cache.CachedElement] when caching is enabled.
    """
    assert element and isinstance(
        element, Element | CachedElement
    ), "element shouldn't be null and should be an Element or CachedElement"
    query_params = {}
    if folder is not None:
        assert isinstance(folder, bool), "folder should be of type bool"
        query_params["folder"] = folder
    if name:
        assert isinstance(name, str), "name should be of type str"
        query_params["name"] = name
    if recursive is not None:
        assert isinstance(recursive, bool), "recursive should be of type bool"
        query_params["recursive"] = recursive
    if transcription_worker_version is not None:
        warn(
            "`transcription_worker_version` usage is deprecated. Consider using `transcription_worker_run` instead.",
            DeprecationWarning,
            stacklevel=1,
        )
        assert isinstance(
            transcription_worker_version, str | bool
        ), "transcription_worker_version should be of type str or bool"
        if isinstance(transcription_worker_version, bool):
            assert (
                transcription_worker_version is False
            ), "if of type bool, transcription_worker_version can only be set to False"
        query_params["transcription_worker_version"] = transcription_worker_version
    if transcription_worker_run is not None:
        assert isinstance(
            transcription_worker_run, str | bool
        ), "transcription_worker_run should be of type str or bool"
        if isinstance(transcription_worker_run, bool):
            assert (
                transcription_worker_run is False
            ), "if of type bool, transcription_worker_run can only be set to False"
        query_params["transcription_worker_run"] = transcription_worker_run
    if type:
        assert isinstance(type, str), "type should be of type str"
        query_params["type"] = type
    if with_classes is not None:
        assert isinstance(with_classes, bool), "with_classes should be of type bool"
        query_params["with_classes"] = with_classes
    if with_corpus is not None:
        assert isinstance(with_corpus, bool), "with_corpus should be of type bool"
        query_params["with_corpus"] = with_corpus
    if with_has_children is not None:
        assert isinstance(
            with_has_children, bool
        ), "with_has_children should be of type bool"
        query_params["with_has_children"] = with_has_children
    if with_metadata is not None:
        assert isinstance(
            with_metadata, bool
        ), "with_metadata should be of type bool"
        query_params["with_metadata"] = with_metadata
    if with_zone is not None:
        assert isinstance(with_zone, bool), "with_zone should be of type bool"
        query_params["with_zone"] = with_zone
    if worker_version is not None:
        warn(
            "`worker_version` usage is deprecated. Consider using `worker_run` instead.",
            DeprecationWarning,
            stacklevel=1,
        )
        assert isinstance(
            worker_version, str | bool
        ), "worker_version should be of type str or bool"
        if isinstance(worker_version, bool):
            assert (
                worker_version is False
            ), "if of type bool, worker_version can only be set to False"
        query_params["worker_version"] = worker_version
    if worker_run is not None:
        assert isinstance(
            worker_run, str | bool
        ), "worker_run should be of type str or bool"
        if isinstance(worker_run, bool):
            assert (
                worker_run is False
            ), "if of type bool, worker_run can only be set to False"
        query_params["worker_run"] = worker_run

    if self.use_cache:
        # Checking that we only received query_params handled by the cache
        assert (
            set(query_params.keys())
            <= {
                "type",
                "worker_version",
                "worker_run",
            }
        ), "When using the local cache, you can only filter by 'type' and/or 'worker_version' and/or 'worker_run'"

        parent_ids = CachedElement.select(CachedElement.parent_id).where(
            CachedElement.id == element.id
        )
        query = CachedElement.select().where(CachedElement.id.in_(parent_ids))
        if type:
            query = query.where(CachedElement.type == type)
        if worker_version is not None:
            # If worker_version=False, filter by manual worker_version e.g. None
            worker_version_id = worker_version or None
            if worker_version_id:
                query = query.where(
                    CachedElement.worker_version_id == worker_version_id
                )
            else:
                query = query.where(CachedElement.worker_version_id.is_null())

        if worker_run is not None:
            # If worker_run=False, filter by manual worker_run e.g. None
            worker_run_id = worker_run or None
            if worker_run_id:
                query = query.where(CachedElement.worker_run_id == worker_run_id)
            else:
                query = query.where(CachedElement.worker_run_id.is_null())

        return query
    else:
        parents = self.api_client.paginate(
            "ListElementParents", id=element.id, **query_params
        )

    return parents