Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add image transformer #1901

Merged
merged 8 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dev-requirements.in
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ torch<=1.12.1; python_version<'3.11'
# pytorch 2 supports python 3.11
torch<=2.0.0; python_version>='3.11' or platform_system!='Windows'

pillow
scikit-learn
types-protobuf
types-croniter
Expand Down
2 changes: 2 additions & 0 deletions flytekit/core/type_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,8 @@
register_bigquery_handlers()
if is_imported("numpy"):
from flytekit.types import numpy # noqa: F401
if is_imported("PIL"):
from flytekit.types.file import image # noqa: F401

Check warning on line 878 in flytekit/core/type_engine.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/type_engine.py#L878

Added line #L878 was not covered by tests

@classmethod
def to_literal_type(cls, python_type: Type) -> LiteralType:
Expand Down
2 changes: 1 addition & 1 deletion flytekit/experimental/eager_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ async def wrapper(*args, **kws):
return task(
wrapper,
secret_requests=secret_requests,
disable_deck=False,
enable_deck=True,
execution_mode=PythonFunctionTask.ExecutionBehavior.EAGER,
**kwargs,
)
Expand Down
82 changes: 82 additions & 0 deletions flytekit/types/file/image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import pathlib
import typing
from typing import Type

Check warning on line 3 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L1-L3

Added lines #L1 - L3 were not covered by tests

import PIL.Image

Check warning on line 5 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L5

Added line #L5 was not covered by tests

from flytekit.core.context_manager import FlyteContext
from flytekit.core.type_engine import TypeEngine, TypeTransformer, TypeTransformerFailedError
from flytekit.models.core import types as _core_types
from flytekit.models.literals import Blob, BlobMetadata, Literal, Scalar
from flytekit.models.types import LiteralType

Check warning on line 11 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L7-L11

Added lines #L7 - L11 were not covered by tests

T = typing.TypeVar("T")

Check warning on line 13 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L13

Added line #L13 was not covered by tests


class PILImageTransformer(TypeTransformer[T]):

Check warning on line 16 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L16

Added line #L16 was not covered by tests
"""
TypeTransformer that supports PIL.Image as a native type.
"""

FILE_FORMAT = "PIL.Image"

Check warning on line 21 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L21

Added line #L21 was not covered by tests

def __init__(self):
super().__init__(name="PIL.Image", t=PIL.Image.Image)

Check warning on line 24 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L23-L24

Added lines #L23 - L24 were not covered by tests

def get_literal_type(self, t: Type[T]) -> LiteralType:
return LiteralType(

Check warning on line 27 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L26-L27

Added lines #L26 - L27 were not covered by tests
blob=_core_types.BlobType(
format=self.FILE_FORMAT, dimensionality=_core_types.BlobType.BlobDimensionality.SINGLE
)
)

def to_literal(

Check warning on line 33 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L33

Added line #L33 was not covered by tests
self, ctx: FlyteContext, python_val: PIL.Image.Image, python_type: Type[T], expected: LiteralType
) -> Literal:

meta = BlobMetadata(

Check warning on line 37 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L37

Added line #L37 was not covered by tests
type=_core_types.BlobType(
format=self.FILE_FORMAT, dimensionality=_core_types.BlobType.BlobDimensionality.SINGLE
)
)

local_path = ctx.file_access.get_random_local_path() + ".png"
pathlib.Path(local_path).parent.mkdir(parents=True, exist_ok=True)
python_val.save(local_path)

Check warning on line 45 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L43-L45

Added lines #L43 - L45 were not covered by tests
eapolinario marked this conversation as resolved.
Show resolved Hide resolved

remote_path = ctx.file_access.get_random_remote_path(local_path)
ctx.file_access.put_data(local_path, remote_path, is_multipart=False)
return Literal(scalar=Scalar(blob=Blob(metadata=meta, uri=remote_path)))

Check warning on line 49 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L47-L49

Added lines #L47 - L49 were not covered by tests

def to_python_value(self, ctx: FlyteContext, lv: Literal, expected_python_type: Type[T]) -> PIL.Image.Image:
try:
uri = lv.scalar.blob.uri
except AttributeError:
raise TypeTransformerFailedError(f"Cannot convert from {lv} to {expected_python_type}")

Check warning on line 55 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L51-L55

Added lines #L51 - L55 were not covered by tests

local_path = ctx.file_access.get_random_local_path()
ctx.file_access.get_data(uri, local_path, is_multipart=False)

Check warning on line 58 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L57-L58

Added lines #L57 - L58 were not covered by tests

return PIL.Image.open(local_path)

Check warning on line 60 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L60

Added line #L60 was not covered by tests

def guess_python_type(self, literal_type: LiteralType) -> Type[T]:

Check warning on line 62 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L62

Added line #L62 was not covered by tests
if (
literal_type.blob is not None
and literal_type.blob.dimensionality == _core_types.BlobType.BlobDimensionality.SINGLE
and literal_type.blob.format == self.FILE_FORMAT
):
return PIL.Image.Image

Check warning on line 68 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L68

Added line #L68 was not covered by tests

raise ValueError(f"Transformer {self} cannot reverse {literal_type}")

Check warning on line 70 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L70

Added line #L70 was not covered by tests

def to_html(self, ctx: FlyteContext, python_val: PIL.Image.Image, expected_python_type: Type[T]) -> str:
import base64
from io import BytesIO

Check warning on line 74 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L72-L74

Added lines #L72 - L74 were not covered by tests

buffered = BytesIO()
python_val.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
return f'<img src="data:image/png;base64,{img_base64}" alt="Rendered Image" />'

Check warning on line 79 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L76-L79

Added lines #L76 - L79 were not covered by tests


TypeEngine.register(PILImageTransformer())

Check warning on line 82 in flytekit/types/file/image.py

View check run for this annotation

Codecov / codecov/patch

flytekit/types/file/image.py#L82

Added line #L82 was not covered by tests
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
if TYPE_CHECKING:
import markdown
import pandas as pd
import PIL
import PIL.Image

Check warning on line 9 in plugins/flytekit-deck-standard/flytekitplugins/deck/renderer.py

View check run for this annotation

Codecov / codecov/patch

plugins/flytekit-deck-standard/flytekitplugins/deck/renderer.py#L9

Added line #L9 was not covered by tests
eapolinario marked this conversation as resolved.
Show resolved Hide resolved
import plotly.express as px
else:
pd = lazy_module("pandas")
Expand Down
2 changes: 1 addition & 1 deletion plugins/flytekit-kf-pytorch/tests/test_elastic_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def test_deck(start_method: str) -> None:

@task(
task_config=Elastic(nnodes=1, nproc_per_node=world_size, start_method=start_method),
disable_deck=False,
enable_deck=True,
)
def train():
import os
Expand Down
2 changes: 1 addition & 1 deletion plugins/flytekit-mlflow/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ from flytekit import task, workflow
from flytekitplugins.mlflow import mlflow_autolog
import mlflow

@task(disable_deck=False)
@task(enable_deck=True)
@mlflow_autolog(framework=mlflow.keras)
def train_model():
...
Expand Down
2 changes: 1 addition & 1 deletion plugins/flytekit-mlflow/tests/test_mlflow_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from flytekit import task


@task(disable_deck=False)
@task(enable_deck=True)
@mlflow_autolog(framework=mlflow.keras)
def train_model(epochs: int):
fashion_mnist = tf.keras.datasets.fashion_mnist
Expand Down
22 changes: 22 additions & 0 deletions tests/flytekit/unit/types/file/test_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import PIL.Image

from flytekit import task, workflow


@task(enable_deck=True)
def t1() -> PIL.Image.Image:
return PIL.Image.new("L", (100, 100), "black")


@task
def t2(im: PIL.Image.Image) -> PIL.Image.Image:
return im


@workflow
def wf():
t2(im=t1())


def test_image_transformer():
wf()
Loading