~homeworkprod/byceps

ref: bcef32cd2dc329bcf81057794883008f5c040ac8 byceps/byceps/services/image/service.py -rw-r--r-- 1.3 KiB
bcef32cd — Jochen Kupperschmidt Work around Jinja 3.0.0 bug with `for` inside of `set` block 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
byceps.services.image.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from typing import BinaryIO, FrozenSet, Iterable

from ...util.image import read_dimensions
from ...util.image.models import Dimensions, ImageType
from ...util.image.typeguess import guess_type


class ImageTypeProhibited(ValueError):
    pass


def get_image_type_names(types: Iterable[ImageType]) -> FrozenSet[str]:
    """Return the names of the image types."""
    return frozenset(t.name.upper() for t in types)


def determine_image_type(
    stream: BinaryIO, allowed_types: set[ImageType]
) -> ImageType:
    """Extract image type from stream."""
    image_type = guess_type(stream)

    if image_type not in allowed_types:
        allowed_type_names = get_image_type_names(allowed_types)
        allowed_type_names_string = ', '.join(sorted(allowed_type_names))

        raise ImageTypeProhibited(
            'Image is not one of the allowed types '
            f'({allowed_type_names_string}).'
        )

    return image_type


def determine_dimensions(stream: BinaryIO) -> Dimensions:
    """Extract image dimensions from stream."""
    dimensions = read_dimensions(stream)
    stream.seek(0)
    return dimensions