Jupyter-ITVitae/assignment.ipynb

7.6 KiB

None <html lang="en"> <head> gitea_input3939135531 </head>
In [2]:
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")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/home/lillian/Coding/jupyter/assignment.ipynb Cell 1 line 7
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=68'>69</a>     for cat in cat_json:
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=69'>70</a>         yield Cat(
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=70'>71</a>             cat.get("id"),
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=71'>72</a>             cat.get("url"),
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=72'>73</a>             cat.get("width"),
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=73'>74</a>             cat.get("height"),
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=74'>75</a>         )
---> <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=77'>78</a> def get_cat_image(url: String) -> Image:
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=78'>79</a>     """Fetch an image url of the cat provided, returns an image file.
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=79'>80</a> 
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=80'>81</a>     Args:
   (...)
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=84'>85</a>         Image: An image file parsed with the PIL library, read from a bytestream from the cats API.
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=85'>86</a>     """
     <a href='vscode-notebook-cell:/home/lillian/Coding/jupyter/assignment.ipynb#W0sZmlsZQ%3D%3D?line=86'>87</a>     cr = requests.get(url)

NameError: name 'String' is not defined
</html>