Jupyter-ITVitae/cats.ipynb
2024-03-07 10:06:58 +01:00

4.2 KiB

None <html lang="en"> <head> gitea_input3498499277 </head>
In [4]:
from collections.abc import Generator
from io import BytesIO

import requests
from PIL import Image


class Cat:
    """Cat object storing the request data and image file from the cat API."""

    def __init__(self, id, url, width, height):
        self.id = id
        self.url = url
        self.width = width
        self.height = height
        self._image = get_cat_image(url)

    def get_image(self) -> Image:
        """Return the image of the cat object, cropped correctly if the width and height are changed.

        Returns:
            Image: Image object that has been edited by the crop function.
        """
        if (self.width, self.height) != self._image.size:
            return self._image.resize((self.width, self.height))
        return self._image

    def save_image(self, path: str) -> bool:
        """Save image in cat to disk

        Args:
            path (str): the path to save the cat picture to.

        Returns:
            bool: return if the function executed correctly, passthrough of the save function of Image.
        """
        return self.get_image().save(f"{path}/{self.id}.png")


def get_cat_data(count: int = 1) -> list[dict]:
    """Fetch a cat from the cat API, return a parsed JSON object.

    Args:
        count (int): the amount of cats to return.

    Returns:
        list[dict]: Returns the parsed data, the cat API returns a list with length 1 with a dict in it.
    """
    response = requests.get(f"https://api.thecatapi.com/v1/images/search?limit={count}")
    if response.status_code != 200:
        return None
    return response.json()


def get_cats(cat_json: list[dict]) -> Generator[Cat]:
    """Create a cat image from a JSON object formatted like the cat API

    Args:
        cat_json (list[dict]): Expects a list with a length > 1 with dicts in it that contains at least the fields:
        (str) id
        (str) url
        (str) width
        (str) height

    Returns:
        Generator[Cat]: A Generator object creating cat objects from the JSON object.
    """

    for cat in cat_json:
        yield Cat(
            cat.get("id"),
            cat.get("url"),
            cat.get("width"),
            cat.get("height"),
        )


def get_cat_image(url: str) -> Image:
    """Fetch an image url of the cat provided, returns an image file.

    Args:
        url (str): the amount of cats to return.

    Returns:
        Image: An image file parsed with the PIL library, read from a bytestream from the cats API.
    """
    cr = requests.get(url)
    if cr.status_code != 200:
        print(f"Error fetching cat image, error code {cr.status_code}")
        return None
    return Image.open(BytesIO(cr.content))


cats = get_cats(get_cat_data(count=5))
for cat in cats:
    cat.height = 720
    cat.width = 1080
    cat.save_image("./cats")
</html>