|
| 1 | +import pathlib |
| 2 | +from typing import Type |
| 3 | + |
| 4 | +from pyspark.ml import PipelineModel |
| 5 | + |
| 6 | +from flytekit import Blob, BlobMetadata, BlobType, FlyteContext, Literal, LiteralType, Scalar |
| 7 | +from flytekit.core.type_engine import TypeEngine |
| 8 | +from flytekit.extend import TypeTransformer |
| 9 | + |
| 10 | + |
| 11 | +class PySparkPipelineModelTransformer(TypeTransformer[PipelineModel]): |
| 12 | + _TYPE_INFO = BlobType(format="binary", dimensionality=BlobType.BlobDimensionality.MULTIPART) |
| 13 | + |
| 14 | + def __init__(self): |
| 15 | + super(PySparkPipelineModelTransformer, self).__init__(name="PySparkPipelineModel", t=PipelineModel) |
| 16 | + |
| 17 | + def get_literal_type(self, t: Type[PipelineModel]) -> LiteralType: |
| 18 | + return LiteralType(blob=self._TYPE_INFO) |
| 19 | + |
| 20 | + def to_literal( |
| 21 | + self, |
| 22 | + ctx: FlyteContext, |
| 23 | + python_val: PipelineModel, |
| 24 | + python_type: Type[PipelineModel], |
| 25 | + expected: LiteralType, |
| 26 | + ) -> Literal: |
| 27 | + local_path = ctx.file_access.get_random_local_path() |
| 28 | + pathlib.Path(local_path).parent.mkdir(parents=True, exist_ok=True) |
| 29 | + python_val.save(local_path) |
| 30 | + |
| 31 | + remote_dir = ctx.file_access.get_random_remote_directory() |
| 32 | + ctx.file_access.upload_directory(local_path, remote_dir) |
| 33 | + |
| 34 | + return Literal(scalar=Scalar(blob=Blob(uri=remote_dir, metadata=BlobMetadata(type=self._TYPE_INFO)))) |
| 35 | + |
| 36 | + def to_python_value( |
| 37 | + self, ctx: FlyteContext, lv: Literal, expected_python_type: Type[PipelineModel] |
| 38 | + ) -> PipelineModel: |
| 39 | + local_dir = ctx.file_access.get_random_local_directory() |
| 40 | + ctx.file_access.download_directory(lv.scalar.blob.uri, local_dir) |
| 41 | + |
| 42 | + return PipelineModel.load(local_dir) |
| 43 | + |
| 44 | + |
| 45 | +TypeEngine.register(PySparkPipelineModelTransformer()) |
0 commit comments