Skip to content

Pillow

zenml.integrations.pillow

Initialization of the Pillow integration.

Attributes

PILLOW = 'pillow' module-attribute

Classes

Integration

Base class for integration in ZenML.

Functions
activate() -> None classmethod

Abstract method to activate the integration.

Source code in src/zenml/integrations/integration.py
140
141
142
@classmethod
def activate(cls) -> None:
    """Abstract method to activate the integration."""
check_installation() -> bool classmethod

Method to check whether the required packages are installed.

Returns:

Type Description
bool

True if all required packages are installed, False otherwise.

Source code in src/zenml/integrations/integration.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@classmethod
def check_installation(cls) -> bool:
    """Method to check whether the required packages are installed.

    Returns:
        True if all required packages are installed, False otherwise.
    """
    for requirement in cls.get_requirements():
        parsed_requirement = Requirement(requirement)

        if not requirement_installed(parsed_requirement):
            logger.debug(
                "Requirement '%s' for integration '%s' is not installed "
                "or installed with the wrong version.",
                requirement,
                cls.NAME,
            )
            return False

        dependencies = get_dependencies(parsed_requirement)

        for dependency in dependencies:
            if not requirement_installed(dependency):
                logger.debug(
                    "Requirement '%s' for integration '%s' is not "
                    "installed or installed with the wrong version.",
                    dependency,
                    cls.NAME,
                )
                return False

    logger.debug(
        f"Integration '{cls.NAME}' is installed correctly with "
        f"requirements {cls.get_requirements()}."
    )
    return True
flavors() -> List[Type[Flavor]] classmethod

Abstract method to declare new stack component flavors.

Returns:

Type Description
List[Type[Flavor]]

A list of new stack component flavors.

Source code in src/zenml/integrations/integration.py
144
145
146
147
148
149
150
151
@classmethod
def flavors(cls) -> List[Type[Flavor]]:
    """Abstract method to declare new stack component flavors.

    Returns:
        A list of new stack component flavors.
    """
    return []
get_requirements(target_os: Optional[str] = None, python_version: Optional[str] = None) -> List[str] classmethod

Method to get the requirements for the integration.

Parameters:

Name Type Description Default
target_os Optional[str]

The target operating system to get the requirements for.

None
python_version Optional[str]

The Python version to use for the requirements.

None

Returns:

Type Description
List[str]

A list of requirements.

Source code in src/zenml/integrations/integration.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@classmethod
def get_requirements(
    cls,
    target_os: Optional[str] = None,
    python_version: Optional[str] = None,
) -> List[str]:
    """Method to get the requirements for the integration.

    Args:
        target_os: The target operating system to get the requirements for.
        python_version: The Python version to use for the requirements.

    Returns:
        A list of requirements.
    """
    return cls.REQUIREMENTS
get_uninstall_requirements(target_os: Optional[str] = None) -> List[str] classmethod

Method to get the uninstall requirements for the integration.

Parameters:

Name Type Description Default
target_os Optional[str]

The target operating system to get the requirements for.

None

Returns:

Type Description
List[str]

A list of requirements.

Source code in src/zenml/integrations/integration.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
@classmethod
def get_uninstall_requirements(
    cls, target_os: Optional[str] = None
) -> List[str]:
    """Method to get the uninstall requirements for the integration.

    Args:
        target_os: The target operating system to get the requirements for.

    Returns:
        A list of requirements.
    """
    ret = []
    for each in cls.get_requirements(target_os=target_os):
        is_ignored = False
        for ignored in cls.REQUIREMENTS_IGNORED_ON_UNINSTALL:
            if each.startswith(ignored):
                is_ignored = True
                break
        if not is_ignored:
            ret.append(each)
    return ret
plugin_flavors() -> List[Type[BasePluginFlavor]] classmethod

Abstract method to declare new plugin flavors.

Returns:

Type Description
List[Type[BasePluginFlavor]]

A list of new plugin flavors.

Source code in src/zenml/integrations/integration.py
153
154
155
156
157
158
159
160
@classmethod
def plugin_flavors(cls) -> List[Type["BasePluginFlavor"]]:
    """Abstract method to declare new plugin flavors.

    Returns:
        A list of new plugin flavors.
    """
    return []

PillowIntegration

Bases: Integration

Definition of Pillow integration for ZenML.

Functions
activate() -> None classmethod

Activates the integration.

Source code in src/zenml/integrations/pillow/__init__.py
26
27
28
29
@classmethod
def activate(cls) -> None:
    """Activates the integration."""
    from zenml.integrations.pillow import materializers  # noqa

Modules

materializers

Initialization of the Pillow materializer.

Classes
Modules
pillow_image_materializer

Materializer for Pillow Image objects.

Classes
PillowImageMaterializer(uri: str, artifact_store: Optional[BaseArtifactStore] = None)

Bases: BaseMaterializer

Materializer for Image.Image objects.

This materializer takes a PIL image object and returns a PIL image object. It handles all the source image formats supported by PIL as listed here: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html.

Source code in src/zenml/materializers/base_materializer.py
125
126
127
128
129
130
131
132
133
134
135
def __init__(
    self, uri: str, artifact_store: Optional[BaseArtifactStore] = None
):
    """Initializes a materializer with the given URI.

    Args:
        uri: The URI where the artifact data will be stored.
        artifact_store: The artifact store used to store this artifact.
    """
    self.uri = uri
    self._artifact_store = artifact_store
Functions
extract_metadata(image: Image.Image) -> Dict[str, MetadataType]

Extract metadata from the given Image object.

Parameters:

Name Type Description Default
image Image

The Image object to extract metadata from.

required

Returns:

Type Description
Dict[str, MetadataType]

The extracted metadata as a dictionary.

Source code in src/zenml/integrations/pillow/materializers/pillow_image_materializer.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def extract_metadata(
    self, image: Image.Image
) -> Dict[str, "MetadataType"]:
    """Extract metadata from the given `Image` object.

    Args:
        image: The `Image` object to extract metadata from.

    Returns:
        The extracted metadata as a dictionary.
    """
    metadata = {
        "width": image.width,
        "height": image.height,
        "mode": str(image.mode),
    }
    if hasattr(image, "filename"):
        metadata["original_filename"] = str(image.filename)
    return metadata  # type: ignore[return-value]
load(data_type: Type[Image.Image]) -> Image.Image

Read from artifact store.

Parameters:

Name Type Description Default
data_type Type[Image]

An Image.Image type.

required

Returns:

Type Description
Image

An Image.Image object.

Source code in src/zenml/integrations/pillow/materializers/pillow_image_materializer.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def load(self, data_type: Type[Image.Image]) -> Image.Image:
    """Read from artifact store.

    Args:
        data_type: An Image.Image type.

    Returns:
        An Image.Image object.
    """
    files = io_utils.find_files(self.uri, f"{DEFAULT_IMAGE_FILENAME}.*")
    filepath = [file for file in files if not fileio.isdir(file)][0]

    with self.get_temporary_directory(delete_at_exit=False) as temp_dir:
        temp_file = os.path.join(
            temp_dir,
            f"{DEFAULT_IMAGE_FILENAME}{os.path.splitext(filepath)[1]}",
        )

        # copy from artifact store to temporary file
        fileio.copy(filepath, temp_file)
        return Image.open(temp_file)
save(image: Image.Image) -> None

Write to artifact store.

Parameters:

Name Type Description Default
image Image

An Image.Image object.

required
Source code in src/zenml/integrations/pillow/materializers/pillow_image_materializer.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def save(self, image: Image.Image) -> None:
    """Write to artifact store.

    Args:
        image: An Image.Image object.
    """
    with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
        file_extension = image.format or DEFAULT_IMAGE_EXTENSION
        full_filename = f"{DEFAULT_IMAGE_FILENAME}.{file_extension}"
        temp_image_path = os.path.join(temp_dir, full_filename)

        # save the image in a temporary directory
        image.save(temp_image_path)

        # copy the saved image to the artifact store
        artifact_store_path = os.path.join(self.uri, full_filename)
        io_utils.copy(temp_image_path, artifact_store_path, overwrite=True)  # type: ignore[attr-defined]
save_visualizations(image: Image.Image) -> Dict[str, VisualizationType]

Finds and saves the given image as a visualization.

Parameters:

Name Type Description Default
image Image

The image to save as a visualization.

required

Returns:

Type Description
Dict[str, VisualizationType]

A dictionary of visualization URIs and their types.

Source code in src/zenml/integrations/pillow/materializers/pillow_image_materializer.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def save_visualizations(
    self, image: Image.Image
) -> Dict[str, VisualizationType]:
    """Finds and saves the given image as a visualization.

    Args:
        image: The image to save as a visualization.

    Returns:
        A dictionary of visualization URIs and their types.
    """
    file_extension = image.format or DEFAULT_IMAGE_EXTENSION
    full_filename = f"{DEFAULT_IMAGE_FILENAME}.{file_extension}"
    artifact_store_path = os.path.join(self.uri, full_filename)
    artifact_store_path = artifact_store_path.replace("\\", "/")
    return {artifact_store_path: VisualizationType.IMAGE}
Functions Modules